branch_name
stringclasses
22 values
content
stringlengths
18
81.8M
directory_id
stringlengths
40
40
languages
listlengths
1
36
num_files
int64
1
7.38k
repo_language
stringclasses
151 values
repo_name
stringlengths
7
101
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>csellis/ghostjs-casper<file_sep>/partials/home-blog.hbs <article class="mt-8 pb-8 "> <!-- Tailwind UI components require Tailwind CSS v1.8 and the @tailwindcss/ui plugin. Read the documentation to get started: https://tailwindui.com/documentation --> <div class="relative bg-gray-50 pt-16 pb-20 px-4 sm:px-6 lg:pt-24 lg:pb-28 lg:px-8"> <div class="absolute inset-0"> <div class="bg-white h-1/3 sm:h-2/3"></div> </div> <div class="relative max-w-7xl mx-auto"> <div class="text-center"> <h2 class="text-3xl leading-9 tracking-tight font-extrabold text-gray-900 sm:text-4xl sm:leading-10"> I write Articles </h2> <p class="mt-3 max-w-2xl mx-auto text-xl leading-7 text-gray-500 sm:mt-4"> </p> </div> <div class="mt-12 grid gap-5 max-w-lg mx-auto lg:grid-cols-3 lg:max-w-none"> {{#get "posts" include="tags" limit="6"}} {{#foreach posts}} {{^has tag="#projects, #hero, #videos"}} {{!-- Filter out extras --}} {{> home-projects-card}} {{/has}} {{/foreach}} {{/get}} </div> <div class="mt-12 flex justify-end"> <a href=""> More Articles &rarr; </a> </div> </div> </div> </article><file_sep>/partials/post-card copy.hbs <article> <h1>Tailwind Kitchen Sink</h1> <h2>Font Sizes</h2> <p class="text-xs ...">The quick brown fox ...</p> <p class="text-sm ...">The quick brown fox ...</p> <p class="text-base ...">The quick brown fox ...</p> <p class="text-lg ...">The quick brown fox ...</p> <p class="text-xl ...">The quick brown fox ...</p> <p class="text-2xl ...">The quick brown fox ...</p> <p class="text-3xl ...">The quick brown fox ...</p> <p class="text-4xl ...">The quick brown fox ...</p> <p class="text-5xl ...">The quick brown fox ...</p> <p class="text-6xl ...">The quick brown fox ...</p> </article><file_sep>/partials/home-hero.hbs <article class="mt-32 pb-8"> <section class="post-full-content"> <div class="post-content"> {{content}} </div> </section> </article><file_sep>/partials/home-projects-card.hbs <div class="flex flex-col rounded-lg shadow-lg overflow-hidden"> <div class="flex-shrink-0"> {{#if feature_image}} <a href="{{url}}"> <img class="h-48 w-full object-cover" srcset="{{img_url feature_image size="s"}} 300w, {{img_url feature_image size="m"}} 600w, {{img_url feature_image size="l"}} 1000w, {{img_url feature_image size="xl"}} 2000w" sizes="(max-width: 1000px) 400px, 700px" loading="lazy" src="{{img_url feature_image size="m"}}" alt="{{title}}" /> </a> {{/if}} </div> <div class="flex-1 bg-white p-6 flex flex-col justify-between"> <div class="flex-1"> {{#if primary_tag}} {{#primary_tag}} <p class="text-sm leading-5 font-medium text-indigo-600"> <a href="#" class="hover:underline"> {{name}} </a> </p> {{/primary_tag}} {{/if}} <a href="{{url}}" class="block"> <h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900"> {{title}} </h3> <p class="mt-3 text-base leading-6 text-gray-500"> {{excerpt words="33"}} </p> </a> </div> <div class="mt-6 flex items-center"> {{#foreach authors}} <div class="flex-shrink-0"> <a href="#"> {{#if profile_image}} <img class="h-10 w-10 rounded-full" src="{{img_url profile_image size="xs"}}" alt=" {{name}}'s Profile Image"> {{else}} <a href="{{url}}" class="static-avatar author-profile-image">{{> "icons/avatar"}}</a> {{/if}} </a> <p class="text-sm leading-5 font-medium text-gray-900"> <a href="#" class="hover:underline"> {{name}} </a> </p> </div> {{/foreach}} <div class="ml-3"> <div class="flex text-sm leading-5 text-gray-500"> <time datetime="{{date format="YYYY-MM-DD"}}"> {{date format="D MMM YYYY"}} </time> <span class="mx-1"> &middot; </span> <span> {{reading_time}} </span> </div> </div> </div> </div> </div>
7581abf0956c88481cc41a79c01ae37d517c5de6
[ "Handlebars" ]
4
Handlebars
csellis/ghostjs-casper
e93266e293f74b8d7fb051e17eec322cbf9227dc
6688cb91229c5ea73415d8e36158792d765e4cd1
refs/heads/main
<repo_name>MenalKour/C97<file_sep>/PythonProjects/NumberGame.py import random print("HELLO! LET'S PALY A NUMBER GUESSING GAME") num=random.randint(1,9) chances=0 print("GUESS ANY NUMBER BETWEEN 1 TO 9") while chances<5: guess=int(input("ENTER YOUR GUESS")) if guess == num: print("CORRECT") print("YOU WON!CONGRATULATIONS") print("👍😃") break elif guess < num: print("YOUR GUESS IS TOO LOW") print("GUESS A NUMBER HIGHER THAN THIS") else: print("YOUR GUESS IS TOO HIGH") print("GUESS A NUMBER LOWER THAN THIS") chances+=1 if chances==5 and guess!=num: print("YOU LOST") print("THE NUMBER WAS ",num) print("👎😪")
7e2f02a405653a82dc3934679ee21e826747ea96
[ "Python" ]
1
Python
MenalKour/C97
912eb9209e4bccfa2ea4930dc003850ca6ee0aae
78ed957efca1c1c32763f212a09927ab12989dbd
refs/heads/master
<repo_name>pankajkcodes/ImageToPdf<file_sep>/README.md # ImageToPdf ![Screenshot_1628400998](https://user-images.githubusercontent.com/74593517/128633006-4339b462-1db0-4f01-8040-50a69795a343.png)
010ab01a8179b0bf67590ea8ce90b4e140012517
[ "Markdown" ]
1
Markdown
pankajkcodes/ImageToPdf
2f72f13d62cc25ba381672cbcd75910cefba866b
89908dac03a3dfa0aecad025fecb6c1d7f63965b
refs/heads/main
<file_sep>#exoGena2212 * Ecrivez une fonction minutesTillMidnight(heure), où heure est sous la forme "HH:MM". * Cette fonction renvoie le nombre de minutes qui séparent heure de minuit.
542cf43048a60e93357a4604931e19ba68c4d113
[ "Markdown" ]
1
Markdown
Greg-Beaucaire/exoGena2212
73a3dde905cb4f2511ff2da8e356d1db4335bfbf
3a59f818ea1626f67f823d312187a97d71e6f358
refs/heads/master
<repo_name>subham-pal/Java-Codes<file_sep>/HotelReservation/src/main/java/com/subham/hotelreservation/models/Request.java package com.subham.hotelreservation.models; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.ArrayList; @Getter @AllArgsConstructor public class Request { ArrayList<Day> dayList; CustomerType type; public int dayListSize(){ return dayList.size(); } public Day getDay(int index){ return dayList.get(index); } } <file_sep>/HotelReservation/src/main/java/com/subham/hotelreservation/models/Hotel.java package com.subham.hotelreservation.models; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.HashMap; @AllArgsConstructor @Getter public class Hotel { private String hotelName; private Integer rating; private HashMap<Category, Integer> rateCard; } <file_sep>/HotelReservation/src/main/java/com/subham/hotelreservation/models/HotelSortArgument.java package com.subham.hotelreservation.models; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public class HotelSortArgument { private Integer amount; private Hotel hotel; }<file_sep>/HotelReservation/src/test/java/HotelTests.java import com.subham.hotelreservation.service.HotelFinder; import com.subham.hotelreservation.models.*; import com.subham.hotelreservation.utils.Comp; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; public class HotelTests { private static HotelList myHotels = new HotelList(); private static Category category1 = new Category(Day.WEEKDAY, CustomerType.REGULAR); private static Category category2 = new Category(Day.WEEKDAY, CustomerType.REWARD); private static Category category3 = new Category(Day.WEEKEND, CustomerType.REGULAR); private static Category category4 = new Category(Day.WEEKEND, CustomerType.REWARD); @BeforeClass public static void setDefaultHotels(){ HashMap<Category, Integer> rateMap1 = new HashMap<Category, Integer>(); rateMap1.put(category1, 110); rateMap1.put(category2, 80); rateMap1.put(category3, 90); rateMap1.put(category4, 80); Hotel hotel1 = new Hotel("Lakewood", 2, rateMap1); myHotels.addHotel(hotel1); HashMap<Category, Integer> rateMap2 = new HashMap<Category, Integer>(); rateMap2.put(category1, 160); rateMap2.put(category2, 110); rateMap2.put(category3, 60); rateMap2.put(category4, 50); Hotel hotel2 = new Hotel("Bridgewood", 3, rateMap2); myHotels.addHotel(hotel2); HashMap<Category, Integer> rateMap3 = new HashMap<Category, Integer>(); rateMap3.put(category1, 220); rateMap3.put(category2, 100); rateMap3.put(category3, 150); rateMap3.put(category4, 40); Hotel hotel3 = new Hotel("Ridgewood", 4, rateMap3); myHotels.addHotel(hotel3); } @Test public void mainTest1() { ArrayList<Day> daylist = new ArrayList<Day>(); daylist.add(Day.WEEKDAY); daylist.add(Day.WEEKDAY); daylist.add(Day.WEEKEND); Request request = new Request(daylist, CustomerType.REGULAR); HotelFinder finder = new HotelFinder(); Hotel res = finder.find(myHotels, request); Assert.assertEquals("Lakewood", res.getHotelName()); } @Test public void mainTest2() { ArrayList<Day> daylist = new ArrayList<Day>(); daylist.add(Day.WEEKDAY); daylist.add(Day.WEEKDAY); daylist.add(Day.WEEKEND); Request request = new Request(daylist, CustomerType.REWARD); HotelFinder finder = new HotelFinder(); Hotel res = finder.find(myHotels, request); Assert.assertEquals("Ridgewood", res.getHotelName()); } @Test public void hashCodeTestNotEquals1(){ Category category1 = new Category(Day.WEEKDAY, CustomerType.REGULAR); Category category2 = new Category(Day.WEEKEND, CustomerType.REGULAR); Assert.assertNotEquals(category1.hashCode(), category2.hashCode()); } @Test public void hashCodeTestNotEquals2(){ Category category1 = new Category(Day.WEEKDAY, CustomerType.REGULAR); Category category2 = new Category(Day.WEEKDAY, CustomerType.REWARD); Assert.assertNotEquals(category1.hashCode(), category2.hashCode()); } @Test public void hashCodeTestEquals1(){ Category category1 = new Category(Day.WEEKDAY, CustomerType.REGULAR); Category category2 = new Category(Day.WEEKDAY, CustomerType.REGULAR); Assert.assertEquals(category1.hashCode(), category2.hashCode()); } @Test public void hotelListSizeTest(){ Assert.assertEquals(myHotels.count(), 3); } @Test public void addHotelTest(){ HashMap<Category, Integer> rateMap4 = new HashMap<Category, Integer>(); rateMap4.put(category1, 220); rateMap4.put(category2, 100); rateMap4.put(category3, 150); rateMap4.put(category4, 40); Hotel hotel = new Hotel("Palwood", 4, rateMap4); myHotels.addHotel(hotel); Boolean res = myHotels.contains("Palwood"); Assert.assertEquals(res, true); } @Test public void removeHotelTest(){ HashMap<Category, Integer> rateMap4 = new HashMap<Category, Integer>(); rateMap4.put(category1, 220); rateMap4.put(category2, 100); rateMap4.put(category3, 150); rateMap4.put(category4, 40); Hotel hotel = new Hotel("Donwood", 4, rateMap4); myHotels.addHotel(hotel); myHotels.removeHotel(hotel); Boolean res = myHotels.contains("Donwood"); Assert.assertEquals(res, false); } } <file_sep>/HotelReservation/src/main/java/com/subham/hotelreservation/models/Category.java package com.subham.hotelreservation.models; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Category { private Day day; private CustomerType type; } <file_sep>/HotelReservation/src/main/java/com/subham/hotelreservation/utils/Comp.java package com.subham.hotelreservation.utils; import com.subham.hotelreservation.models.HotelSortArgument; import com.subham.hotelreservation.models.Request; import java.util.Comparator; public class Comp implements Comparator<HotelSortArgument> { public int compare(HotelSortArgument hotelSortArgument, HotelSortArgument t1) { if(hotelSortArgument.getAmount() < t1.getAmount()){ return -1; } else if(hotelSortArgument.getAmount() > t1.getAmount()){ return 1; } else{ if(hotelSortArgument.getHotel().getRating() > t1.getHotel().getRating()){ return -1; } return 0; } } } <file_sep>/README.md # Java Codes * Practice codes and assignments for java. * Programming is done in Intellij-IDEA IDE. * Used Maven Project. * Used Lombok plugin. * Junit Testing ## 1. Hotel Reservation A system which returns the cheapest available hotel according to user requirements. The features of java used in project are : * Comparators * Arraylist ## 2. Maths Operation * An object oriented maths operations calculator. It works only for binary operations.
a2352948281cbda6724e79d1c2ac53b20d24f667
[ "Java", "Markdown" ]
7
Java
subham-pal/Java-Codes
e1183204532ed27c7b3d9fd49b8b125a86801347
6182540136b706783ead1d960e0bd72b14b89f85
refs/heads/master
<repo_name>hespinoza01/hespinoza01.github.io<file_sep>/README.md # hespinoza01.github.io<file_sep>/js/building-site.js document.getElementById('main').innerHTML = ` <section class="building-site"> <p class="building-site--title">EN<br>CONSTRUCCIÓN</p> <p class="building-site--subtitle">EL SITIO ESTARÁ LISTO PRONTO</p> <div class="building-site--progress"><div class="building-site--progress-value"></div></div> <div class="building-site--progress-indicator"><span>10%</span><span>100%</span></div> <div class="building-site--social-icons"> <a href="https://twitter.com/@hespinoza__" target="_blank" title="Twitter" class="link-icon i-twitter"><svg class="icon"><use xlink:href="#icon-twitter"></use></svg></a> <a href="https://www.linkedin.com/in/harold-espinoza-b64a9a115" target="_blank" title="Linkedin" class="link-icon i-linkedin"><svg class="icon"><use xlink:href="#icon-linkedin"></use></svg></a> <a href="https://github.com/hespinoza01" target="_blank" title="Github" class="link-icon i-github"><svg class="icon"><use xlink:href="#icon-github"></use></svg></a> <a href="https://www.instagram.com/hespinoza__" target="_blank" title="Instagram" class="link-icon i-instagram"><svg class="icon"><use xlink:href="#icon-instagram"></use></svg></a> <a href="mailto:<EMAIL>" target="_blank" title="<EMAIL>" class="link-icon i-email"><svg class="icon"><use xlink:href="#icon-email"></use></svg></a> <a href="https://api.whatsapp.com/send?phone=50581966620" target="_blank" title="Whatsapp" class="link-icon i-whatsapp"><svg class="icon"><use xlink:href="#icon-whatsapp"></use></svg></a> <a href="https://facebook.com/hespinoza97" target="_blank" title="Facebook" class="link-icon i-facebook"><svg class="icon"><use xlink:href="#icon-facebook"></use></svg></a> </div> <footer class="building-site--footer">&#169; 2019. Hecho por <NAME></footer> </section> `; <file_sep>/js/main.js addEventListener('animationend', (e) => { if(e.animationName === 'out-loader') e.target.remove(); });
3c9bcf980a33f983e419aa6249aca742643d646a
[ "Markdown", "JavaScript" ]
3
Markdown
hespinoza01/hespinoza01.github.io
eeaeb34dbefe2a880b2d986661dc76900cd3e92b
79af68a81f65df1db589a4a82f9cb10915ce5adc
refs/heads/master
<file_sep>### This file includes the functions for building models from keras.models import * from keras.layers import * # from keras.models import Sequential, load_model # from keras.layers import Dense, Activation, Dropout,Convolution2D, MaxPooling2D, Flatten,BatchNormalization,UpSampling2D from keras.optimizers import Adam,SGD from keras.utils import np_utils from keras.callbacks import ModelCheckpoint def DenseModel(optimizer='sgd'): """ build model for Q3 Simple classification """ model = Sequential([Dense(3, input_shape=(5184,), activation='softmax')]) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model def CNN_ClassModel(input_shape=(1, 72, 72),n_class=3,lr=0.001): """ build model for Q5 a more difficult classification problem """ model=Sequential() model.add(Convolution2D(filters=16,nb_row=5,nb_col=5, # kernel_size=5,strides=1, padding='same',data_format='channels_first', input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same',data_format='channels_first')) model.add(Dropout(0.9)) model.add(Flatten()) model.add(Dense(200)) model.add(Activation('relu')) model.add(Dense(n_class)) model.add(Activation('softmax')) adam=Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=False) model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy']) return model def CNN_RegModel(input_shape=(1,72,72),output_dim=6,lr=0.0008,model_path='model.h5'): """ build model for Q6 regression problem """ model=Sequential() model.add(Convolution2D(filters=16,nb_row=5,nb_col=5, padding='same',data_format='channels_first',input_shape=input_shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same',data_format='channels_first')) model.add(Convolution2D(filters=32,nb_row=5,nb_col=5, padding='same',data_format='channels_first')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same',data_format='channels_first')) model.add(Convolution2D(filters=64,nb_row=5,nb_col=5, padding='same',data_format='channels_first')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same',data_format='channels_first')) model.add(Convolution2D(filters=128,nb_row=5,nb_col=5, padding='same',data_format='channels_first')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same',data_format='channels_first')) model.add(Flatten()) model.add(Dense(5184)) model.add(Activation('relu')) model.add(Dense(500)) model.add(Activation('relu')) model.add(Dense(100)) model.add(Activation('relu')) model.add(Dense(output_dim)) model.add(Activation('tanh')) adam=Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=False) model.compile(loss='mse',optimizer=adam,metrics=['acc']) # define the checkpoint filepath = model_path checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min') callbacks_list = [checkpoint] # print(model.summary()) return model, callbacks_list def autoencoder(input_shape=(72,72,1),lr=0.001): model = Sequential() model.add(Convolution2D(32, (5, 5), padding='same', data_format='channels_last', input_shape=input_shape)) model.add(BatchNormalization(axis=3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2), padding='same', data_format='channels_last')) model.add(UpSampling2D(size=(2, 2), data_format='channels_last')) model.add(Convolution2D(32, (5, 5), padding='same', data_format='channels_last')) model.add(BatchNormalization(axis=3)) model.add(Activation('relu')) # model4.add(UpSampling2D(size=(2, 2),data_format='channels_first')) model.add(Convolution2D(1, (5, 5), padding='same', data_format='channels_last')) model.add(Activation('sigmoid')) adam = Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=False) model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['accuracy']) return model def hourglass(input_shape=(72,72,1),lr=0.001): """ build model for Q7 Image denoising """ k_size = (3,3) input = Input(shape=input_shape) _x = Convolution2D(32, kernel_size=k_size, strides=(2, 2), data_format='channels_last',padding='same') (input) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = Convolution2D(32, k_size, padding='same', data_format='channels_last')(_x) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x_branch = MaxPooling2D(pool_size=(2, 2), padding='same', data_format='channels_last')(_x) _x = Convolution2D(128, k_size, padding='same', data_format='channels_last')(_x_branch) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = Convolution2D(128, k_size, padding='same', data_format='channels_last')(_x) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = MaxPooling2D(pool_size=(2, 2), padding='same', data_format='channels_last')(_x) _x = UpSampling2D(size=(2, 2), data_format='channels_last')(_x) _x = Convolution2D(64, k_size, padding='same', data_format='channels_last')(_x) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = Convolution2D(64, k_size, padding='same', data_format='channels_last')(_x) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = concatenate([_x,_x_branch],axis=3) _x = UpSampling2D(size=(2, 2), data_format='channels_last')(_x) _x = Convolution2D(32, k_size, padding='same', data_format='channels_last')(_x) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = UpSampling2D(size=(2, 2), data_format='channels_last')(_x) _x = Convolution2D(32, k_size, padding='same', data_format='channels_last')(_x) _x = BatchNormalization(axis=3)(_x) _x = Activation('relu')(_x) _x = Convolution2D(1, k_size, padding='same', data_format='channels_last')(_x) _x = Activation('sigmoid')(_x) model = Model(inputs=input, outputs=_x) adam = Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=False) model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['accuracy']) return model <file_sep># Deep_learning_MVA The mini project for the course Deep Learning <file_sep># Instructions #### For implementing the main file, please download all the files in the directory mp1 and run DL_mp1.ipynb. #### The python files inside the directory mp1 include the functions used in DL_mp1.ipynb #### Sepically, the functions for building models are listed in model_mp1.py <file_sep>### This file includes the functions for plotting import matplotlib.pyplot as plt import matplotlib.cm as cm def plot_acc_loss(his1,his2,legend1='adm',legend2='sgd',title1='Linear classifier accuracy',title2='Linear classifier loss'): plt.clf() plt.subplot(121) plt.subplots_adjust(top=1.2, bottom=0.08, left=0.10, right=3.0, hspace=0.2, wspace=0.15) plt.plot(his1.history['acc']) plt.plot(his2.history['acc']) plt.title(title1, fontsize=20) plt.ylabel('accuracy', fontsize=20) plt.xlabel('epoch', fontsize=20) plt.legend([legend1, legend2], loc='upper left', fontsize=20) # plt.savefig('Acc1.jpg') plt.subplot(122) plt.plot(his1.history['loss']) plt.plot(his2.history['loss']) plt.title(title2, fontsize=20) plt.ylabel('loss', fontsize=20) plt.xlabel('epoch', fontsize=20) plt.legend([legend1, legend2], loc='upper left', fontsize=20) # plt.savefig('Loss1.jpg') plt.subplots_adjust(top=1.2, bottom=0.08, left=0.10, right=3.0, hspace=0.15, wspace=0.15) def plot_trainval(his): plt.subplot(121) plt.plot(his.history['acc']) plt.plot(his.history['val_acc']) plt.title('model accuracy', fontsize=20) plt.ylabel('accuracy', fontsize=20) plt.xlabel('epoch', fontsize=20) plt.legend(['train', 'test'], loc='upper left', fontsize=20) plt.subplot(122) plt.plot(his.history['loss']) plt.plot(his.history['val_loss']) plt.title('model loss', fontsize=20) plt.ylabel('loss', fontsize=20) plt.xlabel('epoch', fontsize=20) plt.legend(['train', 'test'], loc='upper left', fontsize=20) plt.subplots_adjust(top=1.2, bottom=0.08, left=0.10, right=3.0, hspace=0.15,wspace=0.15) def visual_solution(solution): plt.clf() fig = plt.figure(figsize=(15,4)) ax1 = fig.add_subplot(131) ax1.imshow(solution[:,0].reshape(72,72),aspect='auto', cmap = cm.Greys) ax1.set_title('Rectangle') ax2 = fig.add_subplot(132) ax2.imshow(solution[:,1].reshape(72,72),aspect='auto', cmap = cm.Greys) ax2.set_title('Disk') ax3 = fig.add_subplot(133) ax3.set_title('Triangle') ax3.imshow(solution[:,2].reshape(72,72),aspect='auto', cmap = cm.Greys) <file_sep>### This file includes the functions for preprocessing, visualization, ### and generating dataset in 'Image Denosing Problem' import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from mp1 import generate_dataset_regression def normalize_perim(y): #print(y) U=y[[0,2,4]] V=y[[1,3,5]] order=np.argsort(V) U_sort=U[order] V_sort=V[order] return [U_sort[0], V_sort[0], U_sort[1], V_sort[1], U_sort[2], V_sort[2]] def custom_visual_pred(x, y, y_predict, str): fig, ax = plt.subplots(figsize=(5, 5)) I = x.reshape((72, 72)) ax.imshow(I, extent=[-0.15, 1.15, -0.15, 1.15], cmap='gray') ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) xy = y.reshape(3, 2) tri = patches.Polygon(xy, closed=True, fill=False, edgecolor='r', linewidth=5, alpha=0.5) ax.add_patch(tri) xy_predict = y_predict.reshape(3, 2) tri_predict = patches.Polygon(xy_predict, closed=True, fill=False, edgecolor='g', linewidth=5, alpha=0.5) ax.add_patch(tri_predict) plt.legend(['original vertex', 'predicted vertex'], loc='upper left') plt.savefig(str) plt.show() def vertex_predict(index,model,X_test,Y_test,x_test): y_tp_1 = model.predict(x_test[index][:, np.newaxis]) custom_visual_pred(X_test[index], Y_test[index], y_tp_1, 'vertex_{}'.format(index)) def generate_test_set_regression(): np.random.seed(42) [X_test, Y_test] = generate_dataset_regression(300, 20) return [X_test, Y_test] def generate_a_drawing(figsize, U, V, noise=0.0): fig = plt.figure(figsize=(figsize,figsize)) ax = plt.subplot(111) plt.axis('Off') ax.set_xlim(0,figsize) ax.set_ylim(0,figsize) ax.fill(U, V, "k") fig.canvas.draw() imdata = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)[::3].astype(np.float32) imdata = imdata + noise * np.random.random(imdata.size) plt.close(fig) return imdata def generate_a_rectangle(noise=0.0, free_location=False): figsize = 1.0 U = np.zeros(4) V = np.zeros(4) if free_location: corners = np.random.random(4) top = max(corners[0], corners[1]) bottom = min(corners[0], corners[1]) left = min(corners[2], corners[3]) right = max(corners[2], corners[3]) else: side = (0.3 + 0.7 * np.random.random()) * figsize top = figsize/2 + side/2 bottom = figsize/2 - side/2 left = bottom right = top U[0] = U[1] = top U[2] = U[3] = bottom V[0] = V[3] = left V[1] = V[2] = right picture_noise=generate_a_drawing(figsize, U, V, noise) picture=generate_a_drawing(figsize, U, V) return [picture_noise,picture] def generate_a_disk(noise=0.0, free_location=False): figsize = 1.0 if free_location: center = np.random.random(2) else: center = (figsize/2, figsize/2) radius = (0.3 + 0.7 * np.random.random()) * figsize/2 N = 50 U = np.zeros(N) V = np.zeros(N) i = 0 for t in np.linspace(0, 2*np.pi, N): U[i] = center[0] + np.cos(t) * radius V[i] = center[1] + np.sin(t) * radius i = i + 1 picture_noise=generate_a_drawing(figsize, U, V, noise) picture=generate_a_drawing(figsize, U, V) return [picture_noise,picture] def generate_a_triangle(noise=0.0, free_location=False): figsize = 1.0 if free_location: U = np.random.random(3) V = np.random.random(3) else: size = (0.3 + 0.7 * np.random.random())*figsize/2 middle = figsize/2 U = (middle, middle+size, middle-size) V = (middle+size, middle-size, middle-size) picture_noise = generate_a_drawing(figsize, U, V, noise) picture=generate_a_drawing(figsize, U, V) return [picture_noise,picture] def generate_dataset_denoising(nb_samples, noise_low,noise_high,free_location=False): # Getting im_size: im_size = generate_a_rectangle()[0].shape[0] X = np.zeros([nb_samples,im_size]) Y = np.zeros([nb_samples,im_size]) #print('Creating data:') for i in range(nb_samples): noise=np.random.uniform(noise_low,noise_high) category = np.random.randint(3) if category == 0: [X[i], Y[i]] = generate_a_rectangle(noise, free_location) elif category == 1: [X[i], Y[i]] = generate_a_disk(noise, free_location) else: [X[i], Y[i]] = generate_a_triangle(noise, free_location) X = (X + noise) / (255 + 2 * noise) Y = Y/255.0 return [X, Y] def generate_testset_denoising(noise_low,noise_high): # Getting im_size: np.random.seed(42) [X_test, Y_test] = generate_dataset_denoising(300,noise_low,noise_high, True) return [X_test, Y_test] def visualize_predhourglass(x,str): fig, ax = plt.subplots(figsize=(5, 5)) I = x.reshape((72,72)) ax.imshow(I, extent=[-0.15,1.15,-0.15,1.15],cmap='gray') ax.set_xlim([0,1]) ax.set_ylim([0,1]) plt.savefig(str) plt.show()
7cd215f6cc213a9452ef34edcd25a200513db763
[ "Markdown", "Python" ]
5
Markdown
fern35/Deep_learning_MVA
45dad94a46cf88f8b7194365e611337004a031e0
a704e7de4b4f071919c1514946469b96fe62b4fb
refs/heads/main
<file_sep># Unefficient way to import metrics from Prometheus to InfluxDB. # TODO: need to refact to use less memory import sys import os import logging import json from datetime import datetime from influxdb import InfluxDBClient from argparse import ArgumentParser from multiprocessing import Queue, queues import queue from threading import Thread import time global gtimeout gtimeout = 30 qMaxSize = 1000000 class TSDB(object): def __init__(self, dbHost=os.getenv("INFLUXDB_HOST", "influxdb"), dbPort=8086): self.dbHost = dbHost self.dbPort = dbPort self.dbc = self.init_TSDB() self.batch_size = qMaxSize self.queue = Queue(maxsize=qMaxSize) self.qThread = Thread( target=self.writer ) self.qThread.start() self.qmThread = Thread(target=self.queue_monitor) self.qmThread.start() def init_TSDB(self): try: return InfluxDBClient(host=self.dbHost, port=self.dbPort, ssl=False, verify_ssl=False, timeout=gtimeout) except: return None def use(self, dbname): self.dbc.switch_database(dbname) def _write_data_points(self, json_body, batch_size=0): #print("Writing...") return self.dbc.write_points(json_body, batch_size=batch_size, time_precision='s') def write_data_points(self, json_body, batch_size=0): #logging.info(f"Writing data points [{len(json_body)}]...") self._write_data_points(json_body, batch_size=batch_size) def queue_get_batch(self, batch_size=1000, timeout=gtimeout): """ Get batch objects from the queue """ result = [] try: result = [self.queue.get(timeout=gtimeout)] while len(result) < batch_size: result.append(self.queue.get(block=False, timeout=gtimeout)) except queue.Empty: pass except Exception as e: logging.error(e) pass return result def writer(self): try: while True: self.write_data_points(self.queue_get_batch()) except KeyboardInterrupt: pass def queue_monitor(self): try: while True: logging.info(f"Queue Size: {self.queue.qsize()} ({sys.getsizeof(self.queue)})") time.sleep(30) except KeyboardInterrupt: pass def prom_query_to_influxdb(self, series): """ Make InfluxDB payload and write to DB. /api/v1/query will return a vector """ influx_body = [] try: for s in series: if "metric" not in s: continue dpoint = { "measurement": s['metric']['__name__'], "tags": {}, "fields": {} } #del s['metric']['__name__'] for mk in s['metric']: dpoint['tags'][mk] = s['metric'][mk] dpoint['time'] = datetime.fromtimestamp(s['value'][0]).isoformat('T', 'seconds') dpoint['fields']['value'] = float(s['value'][1]) #influx_body.append(dpoint) self.write_data_points(dpoint) except Exception as e: logging.error("ERR prom_query_to_influxdb(): {}".format(e)) pass return influx_body def prom_range_to_influxdb(self, series): """ Make InfluxDB payload and write to DB. /api/v1/query_range will return a matrix """ influx_body = [] # now is dummy try: for s in series: # could be processed in paralllel if "metric" not in s: continue name = s['metric']['__name__'] #del s['metric']['__name__'] tags = {} for mk in s['metric']: tags[mk] = s['metric'][mk] for v in s['values']: dpoint = { "measurement": name, "tags": tags, "fields": {} } dpoint['time'] = datetime.fromtimestamp(v[0]).isoformat('T', 'seconds') dpoint['fields']['value'] = float(v[1]) #influx_body.append(dpoint) self.queue.put(dpoint) except Exception as e: logging.error("ERR prom_range_to_influxdb(): {}".format(e)) pass return influx_body def parser(self, series, resultType=None): try: try: if resultType == "vector": series_influx = self.prom_query_to_influxdb(series) elif resultType == "matrix": series_influx = self.prom_range_to_influxdb(series) else: print(f"Unable to parse. resultType not found on payload: {resultType}") return #self.write_data_points(series_influx) except Exception as e: logging.error("# ERR 2: ", e) return { "status": "error", "errCode": "parser2", "message": e } raise e except KeyboardInterrupt: return { "status": "calceled" } except Exception as e: logging.error("# ERR 1: ", e) return { "status": "error", "errCode": "parser1", "message": e } pass return { "status": "success", "totalMetricsReceived": len(series), "totalPointsSaved": len(series_influx) } if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') parser = ArgumentParser(description='Metrics path.') parser.add_argument('-i', '--in', dest='arg_in' , required=True, help='Input file or directory') args = parser.parse_args() if os.path.isfile(args.arg_in): files = [args.arg_in] else: path = args.arg_in files = ['{}/{}'.format(path, f) \ for f in os.listdir(path) \ if os.path.isfile(os.path.join(path, f)) \ ] db = TSDB() db.use('prometheus') for metric_file in files: logging.info(f"Loading metric file: {metric_file}") with open(metric_file, 'r') as f: # TODO: very low performance, should stream the messages to the processor data = json.loads(f.read()) db.parser(data['data']['result'], resultType=data['data']['resultType']) #print(json.dumps(resp, indent=4)) logging.info(f"Qlen: {db.queue.qsize()}") time.sleep(gtimeout) logging.info("Pausing...") db.qThread.join() db.qmThread.join() logging.info(f"Finish...wait {gtimeout}s") time.sleep(gtimeout) <file_sep># must-gather-data (Collector) Collect monitoring information from the OpenShift cluster, monitoring stackm [using must-gather](https://github.com/openshift/must-gather). Currently the must-gather-monitoring is build-in [WIP on upstream](https://github.com/openshift/must-gather/pull/214), so it could be a plugin depending how complex or specific it would be. When it is not merged, the build images with must-gather-monitoring scripts is available on [quay.io](https://quay.io/repository/rhn_support_mrbraga/must-gather?tab=tags). ## Config Variables `GATHER_MONIT_START_DATE`: start date string (rendered by `date -d`) `GATHER_MONIT_END_DATE`: end date string (rendered by `date -d`) `GATHER_MONIT_QUERY_STEP`: metric resolution to get from Prometheus. Default: "1m". `GATHER_PROM_QUERIES_RANGE`: list of valid queries to collect range of data points, based on `start` and `end` variables `GATHER_PROM_QUERIES`: list of valid queries to collect instant data points `GATHER_PROM_QUERIES_RANGE_PREFIX`: list of valid metric prefixes to be discovery and collected a query range. (TODO) `GATHER_MONIT_DISCOVERY_GRAFANA`: manage Grafana metrics discovery, 'no' is disabled. Default: != 'no' ## Usage - Create the optional ConfigMap configuration NOTE: See [samples](#Samples) to check variables to set ~~~bash oc create configmap must-gather-env -n openshift-monitoring --from-file=env=env ~~~ - Run the must-gather ~~~bash oc adm must-gather --image=quay.io/mtulio/must-gather:${MG_VER} -- gather_monitoring ~~~ - Run the script standalone (require `/must-gather` path) ~~~ export MG_BASE_PATH=./must-gather-metrics # Set env vars (see Usage section) bash collection-scripts/gather-monitoring-data ~~~ ### Samples All examples below could be used running in must-gather workflow or locally, the dependency is the environment var that must be properly set on each setup: - must-gather: uses a configMap - local: uses a manual environment #### Customizing start/end The start, end and resolution can be customized to adjust the range of queries. It will impact directly in the amount of data points and size that will be collected. - Gather last 15 days of metrics with metrics resolution of `5m` (it may broke dashboards that needs high resolutions) ~~~bash cat <<EOF> ./env GAHTER_MONIT_START_DATE="15 days ago" GAHTER_MONIT_QUERY_STEP="5m" EOF ~~~ #### Collect metrics from **instant queries** Goal: collect instant queries from a valid Query ~~~bash cat << EOF > ./env GATHER_PROM_QUERIES="prometheus_http_requests_total" EOF ~~~ #### Collect metrics from **query ranges** Goal: collect a query range from a valid PromQL query. ~~~bash cat << EOF > ./env GATHER_PROM_QUERIES_RANGE="etcd_disk_backend_commit_duration_seconds_bucket" EOF ~~~ #### Collect metrics from **query ranges by prefixes** Goal: collect query range from all group(s) of metric(s) from a specific component. Eg: `etcd_disk` - Collect custom metrics with prefixes `etcd_disk_`, `apiserver_flowcontrol_` ~~~bash cat << EOF > ./env GATHER_PROM_QUERIES_RANGE_PREFIX="etcd_disk_ apiserver_flowcontrol_" EOF ~~~ #### (WIP) Collect metrics from/and dashboards from Grafana - Enable/disable Grafana metrics discovery Disabling Grafana metrics discovery may save data collected, it will be usefull to collect specific metrics (Eg: using `GATHER_PROM_QUERIES_RANGE_PREFIX`) ~~~bash cat << EOF > ./env GATHER_MONIT_DISCOVERY_GRAFANA="no" GATHER_PROM_QUERIES_RANGE_PREFIX="apiserver_flowcontrol_" EOF ~~~ <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Deprecated script to use Grafana provisioning Script to setup custom Datasources on Grafana. Grafana provisioning was not working properly when using DS name 'default'. Issue tracked on https://github.com/grafana/grafana/issues/32460 {License_info} """ import os import json import logging import copy import requests from requests.auth import HTTPBasicAuth with open('./env.json', 'r') as f: defaults_env = json.loads(f.read()) with open('./base-ds.json', 'r') as f: defaults_ds = json.loads(f.read()) def build_ds_prometheus(name='default', url=os.getenv('PROMETHEUS_URL', defaults_env['PROMETHEUS_URL']), isDefault=False ): ds = copy.deepcopy(defaults_ds) ds['name'] = name ds['url'] = url ds['type'] = "prometheus" ds['isDefault'] = isDefault return ds def build_ds_influxdb(name='influxdb-prom', url=os.getenv('INFLUXDB_URL', defaults_env['INFLUXDB_URL'])): ds = copy.deepcopy(defaults_ds) ds['name'] = name ds['url'] = url ds['type'] = "influxdb" ds['database'] = os.getenv('INFLUXDB_DB', defaults_env['INFLUXDB_DB']) ds['isDefault'] = False ds['basicAuth'] = True ds['basicAuthUser'] = os.getenv('INFLUXDB_ADMIN_USER', defaults_env['INFLUXDB_ADMIN_USER']) ds['basicAuthPassword'] = os.getenv('INFLUXDB_ADMIN_PASSWORD', defaults_env['INFLUXDB_ADMIN_PASSWORD']) return ds if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') gf_url = os.getenv('GF_URL', defaults_env['GF_URL']) gf_usr = os.getenv('GF_SECURITY_ADMIN_USER', defaults_env['GF_SECURITY_ADMIN_USER']) gf_pass = os.getenv('GF_SECURITY_ADMIN_USER', defaults_env['GF_SECURITY_ADMIN_USER']) gf_url_ds = (f"{gf_url}/api/datasources") gf_auth = HTTPBasicAuth(gf_usr, gf_pass) logging.info(f"Using Grafana login user: {gf_usr}") logging.info(f"GF DS endpoint: {gf_url_ds}") # Create Prometheus DS resp = None try: logging.info("Creating Prometheus Datasource 02") ds_prom = build_ds_prometheus(name="must-gather-prometheus", isDefault=True) logging.info(f"-> Payload: {ds_prom}") resp = requests.post(gf_url_ds, data=ds_prom, auth=gf_auth) logging.info(f"-> DS Prometheus creation status code: {resp}") if resp.status_code/100 != 2: logging.info(resp.text) except Exception as e: logging.info(f"-> DS Prometheus creation error code: {resp}") logging.error(e) pass # Create InfluxDB DS resp = None try: logging.info("Creating InfluxDB Datasource") ds_influxdb = build_ds_influxdb(name="must-gather-influxdb") logging.info(f"-> Payload: {ds_influxdb}") resp = requests.post(gf_url_ds, data=ds_influxdb, auth=gf_auth) logging.info(f"-> DS creation status code: {resp}") if resp.status_code/100 != 2: logging.info(resp.text) except Exception as e: logging.info(f"-> DS creation error code: {resp}") logging.error(e) pass <file_sep>FROM python:3.9-alpine3.12 WORKDIR /data-keeper ADD ./grafana/grafana-dash-fixes.py ./ <file_sep>CMD_CNT ?= podman IMAGE_NAME ?= quay.io/rhn_support_mrbraga/mgm-data-keeper IMAGE_VERSION ?= $(shell git rev-parse --short HEAD) build: .PHONY: build build: @echo "\n>> Build image: $(IMAGE_NAME):$(IMAGE_VERSION)" $(CMD_CNT) build -t $(IMAGE_NAME):$(IMAGE_VERSION) . $(CMD_CNT) tag $(IMAGE_NAME):$(IMAGE_VERSION) $(IMAGE_NAME):latest .PHONY: push push: @echo "\n>> Pushing image to registry: $(IMAGE_NAME):$(IMAGE_VERSION)" $(CMD_CNT) push $(IMAGE_NAME):$(IMAGE_VERSION) $(CMD_CNT) push $(IMAGE_NAME):latest <file_sep>--- # experimental tools version: 3 networks: mgm: services: prometheus: container_name: prometheus image: prom/prometheus:v2.24.1 restart: always env_file: - "${PWD}/.env" ports: - 9090:9090 volumes: - ${WORKDIR}/prometheus:/prometheus:z - ./prometheus/etc:/etc/prometheus:z command: - '--web.enable-lifecycle' - '--config.file=/etc/prometheus/prometheus.yml' depends_on: - influxdb grafana: container_name: grafana image: grafana/grafana:7.5.1 restart: always user: ${UID} env_file: - "${PWD}/.env" ports: - 3000:3000 volumes: - ${WORKDIR}/grafana:/var/lib/grafana:z - ./grafana/provisioning:/etc/grafana/provisioning:z - ./grafana/dashboards:/etc/grafana/dashboards:z depends_on: - influxdb - prometheus # Prometheus' remote storage: InfluxDB influxdb: container_name: influxdb image: influxdb:1.8.0-alpine restart: always env_file: - "${PWD}/.env" ports: - 8086:8086 volumes: - ${WORKDIR}/influxdb:/var/lib/influxdb:z #> InfluxDB UI (optional) # chronograf: # container_name: chronograf # image: chronograf:1.8.8-alpine # restart: always # env_file: # - "${PWD}/.env" # ports: # - 8888:8888 # depends_on: # - influxdb # Experimental loki: container_name: loki image: grafana/loki:latest restart: always env_file: - "${PWD}/.env" ports: - 3100:3100 volumes: - ./loki:/config:z - ${WORKDIR}/loki:/var/lib/loki:z command: - '--config.file=/config/loki-config.yaml' depends_on: grafana lokitail: container_name: lokitail image: grafana/promtail:2.0.0 restart: always env_file: - "${PWD}/.env" volumes: - ./loki:/config:z - "${WORKDIR}:/logs:z" command: - '-config.file=/config/promtail-config.yaml' depends_on: loki <file_sep># Runner using podman-compose all: run start: run run: ./podman-manage up stop: ./podman-manage down clean: ./podman-manage clean # $(PODMAN) pod rm -f $(shell $(PODMAN) pod ps --format="{{ .Id }}" ) # misc prom-reload: curl -XPOST localhost:9090/-/reload influx-dbs: curl -G 'http://localhost:8086/query' --data-urlencode 'q=SHOW DATABASES' <file_sep> REPO ?= <EMAIL>:mtulio/must-gather REPO_VER ?= fix/gather-monitoring DEST_REPO ?= ./.build CMD_CNT ?= sudo podman IMAGE_NAME ?= quay.io/rhn_support_mrbraga/must-gather IMAGE_VERSION ?= $(shell git rev-parse --short HEAD) IMAGE_NAME_GH ?= docker.pkg.github.com/mtulio/must-gather-monitoring/must-gather-monitoring .PHONY: all all: clone build-image push-image .PHONY: update update: test -d $(DEST_REPO) && ( \ cd $(DEST_REPO); \ git pull; ) .PHONY: clone clone: test -d $(DEST_REPO) || \ git clone --recursive \ $(REPO) -b $(REPO_VER) $(DEST_REPO) .PHONY: build-image build-image: @echo "\n>> Build image: $(IMAGE_NAME):$(IMAGE_VERSION)" cd $(DEST_REPO); \ $(CMD_CNT) build -t $(IMAGE_NAME):$(IMAGE_VERSION) . $(CMD_CNT) tag $(IMAGE_NAME):$(IMAGE_VERSION) $(IMAGE_NAME):latest $(CMD_CNT) tag $(IMAGE_NAME):$(IMAGE_VERSION) $(IMAGE_NAME_GH):$(IMAGE_VERSION) $(CMD_CNT) tag $(IMAGE_NAME):latest $(IMAGE_NAME_GH):latest .PHONY: push-image push-image: @echo "\n>> Pushing image to registry: $(IMAGE_NAME):$(IMAGE_VERSION)" $(CMD_CNT) push $(IMAGE_NAME):$(IMAGE_VERSION) $(CMD_CNT) push $(IMAGE_NAME):latest $(CMD_CNT) push $(IMAGE_NAME_GH):$(IMAGE_VERSION) $(CMD_CNT) push $(IMAGE_NAME_GH):latest # make image IMAGE_VERSION=$(git rev-parse --short HEAD)-${RANDOM} .PHONY: image image: clone build-image push-image <file_sep>#!/bin/bash # Sync must-gather collected dashboards to Grafana provisioner dashboard directory MUST_GATHER_DASHBOARD=${1} GRAFANA_FOLDER=${2:-'must-gather'} GF_DASH_PATH=$(dirname $0)/../grafana/dashboards/ if [[ -z ${MUST_GATHER_DASHBOARD} ]]; then echo 'ARGV1 was not set to grafana dashboard source dir. Eg:' echo "${0} data/must-gather/monitoring/grafana/" exit 1 fi for DASH in $(ls ${MUST_GATHER_DASHBOARD}/dashboard_*.json); do echo "Converting $DASH to provisioner"; NAME=$(basename ${DASH} |sed 's/dashboard_//') cat ${DASH} |jq .dashboard > "${GF_DASH_PATH}/${GRAFANA_FOLDER}/${NAME}" done <file_sep>pyyaml # evaluating https://github.com/containers/podman-compose/archive/devel.tar.gz <file_sep># must-gather-monitoring stack > This is not a official OpenShift project. must-gather-monitoring will deploy locally a monitoring stack (Grafana and Prometheus/remote storage) backfilling the data collected by [OpenShift must-gather monitoring](https://github.com/mtulio/must-gather-monitoring/tree/master/must-gather) to be explored 'out of the box'. The following projects are used on this stack: - Prometheus - InfluxDB (as remote storage) - Grafana - [OpenShift must-gather](https://github.com/openshift/must-gather/pull/214) - [Prometheus-backfill](https://github.com/mtulio/prometheus-backfill) Use cases: - troubleshooting the OpenShift cluster when you haven't access to monitoring stack - investigate specific components/metrics using custom dashboards ## Dependencies - [podman](https://podman.io/) - [podman-compose](https://github.com/containers/podman-compose) : `pip3 install podman-compose` - git ## Usage ### Collect metrics > **IMPORTANT** note: please make sure to use persistent storage AND not query long periods, it can generate a hige amount of data points. > **IMPORTANT**: don't use it in production clusters if you are uncertain what data need to be collected. No warranty. The collector will make API calls to query metrics from Prometheus endpoint and save it locally. To automate the process to collect in OCP environment, you can use the script that is [WIP on PR #214](https://github.com/openshift/must-gather/pull/214). Extract the script from latest image created by above PR: ```bash podman create --name local-must-gather quay.io/mtulio/must-gather:latest-pr214 podman cp local-must-gather:/usr/bin/gather-monitoring-data /tmp/gather-monitoring-data ``` Check if script is present on local machine: ```bash /tmp/gather-monitoring-data -h ``` Remove temp container: ```bash podman rm -f local-must-gather ``` Now you can explore all possibilities to collect the data from Prometheus (see `-h`). Some examples: - To collect all `up` metric and save it on directory `./metrics-up`, run: ```bash /tmp/gather-monitoring-data --query "up" --dest-dir ./monitoring-metrics ``` - To collect all metrics with prefix `etcd_disk_`, from 1 hour ago and save it on directory `./metrics-etcd`, run: ```bash /tmp/gather-monitoring-data -s "1 hours ago" -e "now" -o "./metrics-etcd" --query-range-prefix "etcd_disk_" ``` ### Load metrics to a local Prometheus deployment 1. Clone this repository: `git clone <EMAIL>:mtulio/must-gather-monitoring.git` 2. Deploy stack (Prometheus, Grafana and InfluxDB[Prometheus remote storage]) on local environment using podman: ~~~ $ export WORKDIR=/mnt/data/tmp/123456789/ $ ./podman-manage up ~~~ 3. Load the metrics [collected](#collect-metrics) to stack using [prometheus-backfill tool](https://github.com/mtulio/prometheus-backfill): > Set the variable `METRICS_PATH` to the directory where metrics was saved. Ex: `METRICS_PATH="${PWD}/metrics-etcd"` > When using must-gather to collect metrics, the directory should be similar to: `METRICS_PATH=/path/to/must-gather.local/quay.io-image/monitoring/prometheus`. ~~~bash podman run --rm --pod must-gather-monitoring \ -v ${METRICS_PATH}:/data:Z \ -it quay.io/mtulio/prometheus-backfill \ /prometheus-backfill -e json.gz -i "/data/" \ -o "influxdb=http://127.0.0.1:8086=prometheus=admin=admin" ~~~ 4. Explore the data on the stack: - Grafana: http://localhost:3000 - Prometheus: http://localhost:9090 ## Keep in touch / How to contribute Use it! and give us a feedback opening issues or PR. <file_sep>server: http_listen_port: 9080 grpc_listen_port: 0 positions: filename: /tmp/positions.yaml clients: - url: http://127.0.0.1:3100/loki/api/v1/push scrape_configs: - job_name: must-gather static_configs: - targets: - localhost labels: job: must-gather agent: promtail workspace: "${WORKSPACE}" log_type: host_service_logs_masters __path__: /logs/host_service_logs/masters/*log - targets: - localhost labels: job: must-gather agent: promtail workspace: "${WORKSPACE}" log_type: namespace_pods __path__: /logs/namespaces/*/pods/*/*/*/logs/*.log # TODO: # Create extracted metrics (and setup Prometheus to scrap): # https://grafana.com/docs/loki/latest/clients/promtail/configuration/#scrape_configs <file_sep>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ grafana-dash-fixes will look to "desired" state of the dashboard to be successfull loaded on a local Grafana environment. Example of changes: - payload returned by API should be contain the value of .dashboard - refresh variables should be reloaded when time range has changed Usage: cat dashboard.json | python3 grafana-dash-fixes.py {License_info} """ import sys import os import json import logging def extract_dashboard_payload(data): """ Extract .dashboard from raw Grafana API response """ try: return data['dashboard'] except KeyError as e: return { "errorMessage": e, "error": "Error extracting .dashboard from current payload" } except Exception as e: raise e def fix_refresh_behavior(data): """ Fix Dashboard variables refresh method from "On Dashboard Load" to "On Time Range Change" to automatic discover new variables when exploring old data. PR opened to fix it: https://github.com/openshift/cluster-monitoring-operator/pull/1097 """ def_refresh = 2 for t in data['templating']['list']: if t['query'].startswith('label_values'): logging.debug(f"Updating refresh behavior for variable {t['name']} from value {t['refresh']} to {def_refresh}") t['refresh'] = 2 return data def fix_graph_tooltip(data): """ Change Tooltip behavior to "Shared crosshair". 0: Default 1: Shared crosshair 2: Shared tooltip """ def_tooltip = 1 old = 0 # if 'graphTooltip' not in data: # return data try: old = data['graphTooltip'] except KeyError: pass logging.debug(f"Updating Tooltip behavior from {old} to value {def_tooltip}") data['graphTooltip'] = def_tooltip return data if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') try: data = sys.stdin.readlines() payload = extract_dashboard_payload(json.loads(data[0])) payload = fix_refresh_behavior(payload) payload = fix_graph_tooltip(payload) print(json.dumps(payload)) except Exception as e: logging.error(f"ERROR: {e}") sys.exit(1) sys.exit(0) <file_sep>#!/bin/bash # # Script to manage dependencies before run podman-compose. # # COMPOSE_FILE='docker-compose-exp.yml' COMPOSE_FILE='docker-compose.yml' test -x $(command -v podman-compose) || { \ echo "podman-compose is not installed, please install it: pip3 install podman-compose" \ && exit 1; \ } test -z "${WORKDIR}" && { \ echo "WORKDIR env var not found. Please set the workdir" \ && exit 1; \ } test -f ./.env || { \ echo ".env file not found, creating from .env-default..." \ && cp ./.env-default ./.env } function deps_dirs() { echo "WORKDIR=${WORKDIR}" test -d "${WORKDIR}" || mkdir -p "${WORKDIR}" ; for SUB in grafana prometheus influxdb loki; do test -d "${WORKDIR}/${SUB}" || mkdir "${WORKDIR}/${SUB}"; done # Reinforce permissions (may changed by containes on runtime) sudo rm -rf ${WORKDIR}/grafana/png/ } function deps_perms() { chmod -R o+w "${WORKDIR}/" } function cmd_up() { deps_dirs; deps_perms; podman-compose -f ${COMPOSE_FILE} up -d } function cmd_down() { podman-compose -f ${COMPOSE_FILE} down; } function cmd_clean() { podman pod rm -f must-gather-monitoring } case $1 in "up") cmd_up ;; "down") cmd_down ;; "clean") cmd_clean ;; *) echo "Invalid option [$1]. Accept: up|down|clean" ;; esac <file_sep>import sys import time import logging from watchdog.observers import Observer from watchdog.events import RegexMatchingEventHandler import os import magic import shutil import pathlib from datetime import datetime import tarfile import re class StorageHandler(RegexMatchingEventHandler): def __init__(self, watch_dir): self.storage_dir = watch_dir self.watch_reg = (f"{self.storage_dir}/*") super().__init__([self.storage_dir]) def on_created(self, event): self.process(event) def process(self, event): # create uniq symlink based on must-gather name try: mg_root = r'.*(?P<mg_path>must-gather\.local\.\d+\/[a-z0-9\-]+)(\/|)$' mg_name = r'.*(?P<mg_name>must-gather\.local\.\d+)(\/|).*' re_mr = re.search(mg_root, event.src_path) if re_mr: re_nm = re.search(mg_name, event.src_path) if re_nm: self.link_mustgather(event.src_path, re_nm.group('mg_name')) except Exception as e: logging.error(e) pass # # lookup for 'version' file on a valid must-gather # if os.path.isfile(event.src_path + "/version"): # logging.info("Version found...") # #self.link_mustgather(event.src_path, re_nm.group('mg_name')) # return def link_mustgather(self, path, linkname): #symlink = f"00-{datetime.now().isoformat().replace(':','').split('.')[0]}" #dst_link = f"{self.storage_dir}/{symlink}" dst_link = f"{self.storage_dir}/00-{linkname}" logging.info(f"Creating symlink for must-gather {path} -> {dst_link}") try: os.symlink(path, dst_link) except FileExistsError: pass except: raise class UploadHandler(RegexMatchingEventHandler): def __init__(self, watch_dir, storage_dir='/tmp'): self.watch_dir = watch_dir self.watch_reg = (f"{self.watch_dir}/*") super().__init__([self.watch_reg]) self.storage_dir = storage_dir def on_created(self, event): self.process(event) def process(self, event): # print("UploadHandler() Processing") # print(event.src_path) # filename, ext = os.path.splitext(event.src_path) # print(filename, ext) # wait for file complete sleep_time = 10 time.sleep(sleep_time) if os.path.isdir(event.src_path): fname = os.path.basename(event.src_path) logging.info(f"Moving directory [{fname}] to storage...") shutil.move(event.src_path, f'{self.storage_dir}/{fname}') return #print(magic.from_file(event.src_path, mime=True)) if event.src_path.endswith('.tar.gz'): logging.info(f"Extracting tar.gz: {event.src_path}") with tarfile.open(event.src_path, "r:gz") as so: so.extractall(path=self.storage_dir) logging.info(f"Extract done to {self.storage_dir}") if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S') path_pref = '/tmp/data' path_storage = f'{path_pref}/storage' path_upload = f'{path_pref}/uploads' pathlib.Path(path_storage).mkdir(parents=True, exist_ok=True) pathlib.Path(path_upload).mkdir(parents=True, exist_ok=True) uploader_handler = UploadHandler(path_upload, storage_dir=path_storage) storage_handler = StorageHandler(path_storage) observer = Observer() observer.schedule(uploader_handler, path_upload, recursive=True) observer.schedule(storage_handler, path_storage, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
22221cd7f1f06f0f256703c11176d5d7d821c470
[ "Makefile", "Shell", "Markdown", "Dockerfile", "YAML", "Python", "Text" ]
15
Makefile
mtulio/omg-metrics
13b448e243558d86b6927a51b92dca51ba0ce93a
4240025d7f01d8e9f7ca94c4164b9d24bdd7ec4a
refs/heads/master
<repo_name>yangmacheng/hello-world<file_sep>/README.md # hello-world Just another repository Ok! Yes, I am making some changes. Ha, Ha, Ha......
58676e33a21dd665639d52cec7841ce7cc28cd13
[ "Markdown" ]
1
Markdown
yangmacheng/hello-world
490d8c333bd5e4d0ec2c2a6b09556820de69baf6
d095de23139ce3aa69a2f00a47857d6309cd3ae0
refs/heads/master
<file_sep>""" Differential Equations in Action Lesson 1 - Houston We have a problem """ # Import import math # import math.cos(), math.sin(), math.pi import numpy # import distance import matplotlib.pyplot as plt # import plot """ ----------------------------------------------------------------------- - 1 - Exercices ----------------------------------------------------------------------- """ # Exo 1 - Define x, sin(x) and cos(x) def sin_cos(num_steps): x = numpy.zeros(num_steps) sin_x = numpy.zeros(num_steps) cos_x = numpy.zeros(num_steps) for i in range(num_steps): x[i] =2 * math.pi * i / (num_steps-1) sin_x[i] = math.cos(x[i]) cos_x[i] = math.sin(x[i]) return x, sin_x, cos_x # Exo 2 - Forward Euler method def forward_euler(time_steps, num_steps, g): t = numpy.zeros(num_steps + 1) x = numpy.zeros(num_steps + 1) v = numpy.zeros(num_steps + 1) for step in range(num_steps): t[step + 1] = (step+1) * time_steps x[step + 1] = x[step] + time_steps*v[step] v[step + 1] = v[step] - time_steps*g return t, x, v # Exo 3 - Spaceship acceleration with Moon and Earth at a t-time def acceleration(moon_position, spaceship_position): X_ES = - spaceship_position X_MS = moon_position - spaceship_position F_ES = ( gravitational_constant * earth_mass / ( numpy.linalg.norm(X_ES)**3) ) * X_ES F_MS = ( gravitational_constant * earth_mass / ( numpy.linalg.norm(X_MS)**3) ) * X_MS return F_ES + F_MS """ ----------------------------------------------------------------------- - 2 - Problems ----------------------------------------------------------------------- """ # PROBLEM 1 # Modelise one revolution of the moon around the earth, assuming that # the orbit is circular. def orbit(num_steps): x = numpy.zeros([num_steps + 1, 2]) for i in range(num_steps + 1): x[i,0] = moon_distance * math.cos(2. * math.pi * i /num_steps) x[i,1] = moon_distance * math.sin(2. * math.pi * i /num_steps) return x # PROBLEM 2 # Free fall at initial speed with initial angles. def trajectory(time_steps, num_steps, g, initial_speed, inital_angles): acceleration = numpy.array([0., -g]) x = numpy.zeros([num_steps + 1, 2]) # m v = numpy.zeros([num_steps + 1, 2]) # m / s # init position and speed x[0,:] = [0,0] v[0,:] = [initial_speed * math.cos(inital_angles), initial_speed * math.sin(inital_angles) ] for step in range(num_steps): # Forward Euler Method v[step + 1,:] = v[step] + time_steps*acceleration x[step + 1,:] = x[step] + time_steps*v[step] return x, v # PROBLEM 3 # Spaceship Acceleration def acceleration(spaceship_position): a = numpy.zeros(2) # m a[0] = - gravitational_constant * (earth_mass * spaceship_position[0]) / numpy.linalg.norm(spaceship_position)**3 a[1] = - gravitational_constant * (earth_mass * spaceship_position[1]) / numpy.linalg.norm(spaceship_position)**3 return a # Trajectory of a spacecraft with the given initial position and velocity. def ship_trajectory(time_steps, num_steps, x_init, v_init): x = numpy.zeros([num_steps + 1, 2]) # m v = numpy.zeros([num_steps + 1, 2]) # m / s # init position and speed x[0, :] = x_init v[0, :] = v_init for step in range(num_steps): # Forward Euler Method v[step + 1,:] = v[step] + time_steps*acceleration(x[step,:]) x[step + 1,:] = x[step] + time_steps*v[step] return x, v """ ----------------------------------------------------------------------- - 3 - Plot ----------------------------------------------------------------------- """ # Exo 1 - plot sin(x) and cos(x) def plot_sin_cos(): plt.plot(x, sin_x) plt.plot(x, cos_x) plt.show() # Exo 2 - plot Forward Euler Method def plot_euler(): axes_height = plt.subplot(211) plt.plot(t, x) axes_velocity = plt.subplot(212) plt.plot(t, v) axes_height.set_ylabel('Height in m') axes_velocity.set_ylabel('Velocity in m/s') axes_velocity.set_xlabel('Time in s') plt.show() # Pb1 - plot moon orbit def plot_orbit(): plt.axis('equal') plt.plot(x[:, 0], x[:, 1]) axes = plt.gca() axes.set_xlabel('Longitudinal position in m') axes.set_ylabel('Lateral position in m') plt.show() # Pb2 - plot Earth free fall def plot_earth_free_fall(time_steps, num_steps, earth_gravitation, initial_speed, inital_angles): for angles in inital_angles: x,v = trajectory(time_steps, num_steps, earth_gravitation, initial_speed, angles) plt.plot(x[:, 0], x[:, 1]) axes = plt.gca() axes.set_xlabel('x position in m') axes.set_ylabel('y position in m') plt.show() # Pb3 - plot spaceship orbit def plot_ship_trajectory(): plt.plot(x[:, 0], x[:, 1]) plt.scatter(0, 0) plt.axis('equal') axes = plt.gca() axes.set_xlabel('Longitudinal position in m') axes.set_ylabel('Lateral position in m') plt.show() """ ----------------------------------------------------------------------- - Main ----------------------------------------------------------------------- """ # STEPS num_steps = 50 # Max iteration number time_steps = 0.1 # s # EARTH and MOON DATA # Mass earth_mass = 5.97e24 # kg moon_mass = 7.35e22 # kg # Distance moon_distance = 384e6 # m # Gravitation gravitational_constant = 6.67e-11 # N m2 / kg2 earth_gravitation = 9.81 # m / s2 """ -------------------- Exercices -------------------- """ # Exo 1 - Cosinus and sinus x, sin_x, cos_x = sin_cos(num_steps) #plot_sin_cos() # uncomment for ploting # Exo 2 - Forward Euler Method t, x, v = forward_euler(time_steps, num_steps, earth_gravitation) #plot_euler() # uncomment for ploting """ -------------------- Problems -------------------- """ # pb1 - Moon orbit x = orbit(num_steps) #plot_orbit() # uncomment for ploting # pb2 - Earth free fall # Initial value initial_speed = 20. # m / s initial_angles = math.pi /180 * numpy.linspace(20., 70., 6) #plot_earth_free_fall(time_steps, num_steps, earth_gravitation, initial_speed, initial_angles) # uncomment for ploting # pb3 - spaceship orbit time_steps = 0.1 # s num_steps = 130000 x_init = [15e6, 1e6] v_init = [2e3, 4e3] x, v = ship_trajectory(time_steps, num_steps, x_init, v_init) plot_ship_trajectory() # uncomment for ploting <file_sep># Dossiers CODE := $(shell pwd) PDFDIR = _pdf THEME = # Visualiser les pdf LOG=evince # Créer le dossier pdf s'il n'éxiste pas. target: test -d $(PDFDIR) || mkdir $(PDFDIR) all: img poly proper # Générations des images FIGSRC = $(wildcard sources/1/*.ipe sources/2/*.ipe ) FIGOBJ = $(FIGSRC:.ipe=.pdf) img: $(FIGOBJ) sources/1/%.pdf: sources/1/%.ipe ipetoipe -pdf $< # Cinquième # Quatrième # Troisième t1: pdflatex tex/1-second-degree.tex pdflatex tex/1-second-degree.tex mv 1-second-degree.pdf '$(PDFDIR)'/1-second-degree.pdf t2: pdflatex tex/2-statistiques.tex pdflatex tex/2-statistiques.tex mv 2-statistiques.pdf '$(PDFDIR)'/2-statistiques.pdf t3: pdflatex tex/3-suites.tex pdflatex tex/3-suites.tex mv 3-suites.pdf '$(PDFDIR)'/3-suites.pdf # nettoyage proper: rm -f *.log *.toc *.aux *.nav *.snm *.out *.bbl *.blg *.dvi rm -f tex/*.log tex/*.fls tex/*.synctex.gz tex/*.aux tex/*.fdb_latexmk rm -f *.backup *~ <file_sep>\input{doc-class-cours.tex} \begin{document} In this introductory course on Ordinary Differential Equations, we first provide basic terminologies on the theory of differential equations and then proceed to methods of solving various types of ordinary differential equations. We handle first order differential equations and then second order linear differential equations. We also discuss some related concrete mathematical modeling problems, which can be handled by the methods introduced in this course. The lecture is self contained. However, if necessary, you may consult any introductory level text on ordinary differential equations. \section*{Semaine 1} \begin{multicols}{2} \subsection*{Objectifs d'apprentissage} \begin{itemize}[label={$\bullet$}] \item Learn basic definitions and terminologies in ordinary differential equations. \item Understand initial value problem and Picard's theorem. \end{itemize} \subsection*{1. Basic Terminologies} \begin{itemize}[label={$\bullet$}] \item Vidéo 1-1 What is a Differentiable Equations? \item Vidéo 1-2 Order and Normal Form \item Vidéo 1-3 Linear and Nonlinear Equations \end{itemize} \subsection*{2. Solutions and Examples} \begin{itemize}[label={$\bullet$}] \item Vidéo 1-4 Solution \item Vidéo 1-5 Implicit Solution \end{itemize} \subsection*{3. Various Solutions, Initial Value Problem} \begin{itemize}[label={$\bullet$}] \item Vidéo 1-6 Types of Solutions \item Vidéo 1-7 Initial Value Problem \end{itemize} \subsection*{4. Picard Theorem and Examples } \begin{itemize}[label={$\bullet$}] \item Vidéo 1-8 Picard's Theorem I \item Vidéo 1-9 Picard's Theorem II \end{itemize} \end{multicols} \section*{Semaine 2} \begin{multicols}{2} \subsection*{Objectifs d'apprentissage} \begin{itemize}[label={$\bullet$}] \item Learn analytic methods to obtain general solutions of first order DE. \item Apply solution methods to examples. \end{itemize} \subsection*{1. Separable Equations} \begin{itemize}[label={$\bullet$}] \item Vidéo 2-1 Separable Equations \item Vidéo 2-2 Separable Equations - Ex's 1 \& 2 \end{itemize} \subsection*{2. Separable and Linear Equations} \begin{itemize}[label={$\bullet$}] \item Vidéo 2-3 Separable Equations - Ex's 3 \& 4 \item Vidéo 2-4 Integrating Factor \end{itemize} \subsection*{3. Exact Equations I} \begin{itemize}[label={$\bullet$}] \item Vidéo 2-5 Does IVP Have a Unique Solution? \item Vidéo 2-6 Exact Equations I \end{itemize} \subsection*{4. Exact Equations II} \begin{itemize}[label={$\bullet$}] \item Vidéo 2-7 Exact Equations II \end{itemize} \subsection*{5. Examples} \begin{itemize}[label={$\bullet$}] \item Vidéo 2-8 Exact Equations - Ex.1 \item Vidéo 2-9 Exact Equations - Ex.2 \end{itemize} \end{multicols} \end{document}<file_sep># Dossiers CODE := $(shell pwd) # Visualiser les pdf all: calc tests toolsca calc-l4: python3 src/rpn_list4_calc.py tools: python3 tools/rpn_tools.py tests: python3 tests/tests.py # nettoyage proper: rm -f *.log *.toc *.aux *.nav *.snm *.out *.bbl *.blg *.dvi rm -f *.backup *~ <file_sep>\input{doc-class-cours.tex} \begin{document} Welcome to Introduction to Applied Cryptography. Cryptography is an essential component of cybersecurity. The need to protect sensitive information and ensure the integrity of industrial control processes has placed a premium on cybersecurity skills in today’s information technology market. Demand for cybersecurity jobs is expected to rise 6 million globally by 2019, with a projected shortfall of 1.5 million, according to Symantec, the world’s largest security software vendor. According to Forbes, the cybersecurity market is expected to grow from \$75 billion in 2015 to \$170 billion by 2020. In this specialization, you will learn basic security issues in computer communications, classical cryptographic algorithms, symmetric-key cryptography, public-key cryptography, authentication, and digital signatures. These topics should prove especially useful to you if you are new to cybersecurity Course 1, Classical Cryptosystems, introduces you to basic concepts and terminology related to cryptography and cryptanalysis. It is recommended that you have a basic knowledge of computer science and basic math skills such as algebra and probability. \section*{Semaine 1 - Introduction} \subsection*{Introduction to the Course} This module covers an introduction of the specialization and instructors, covers what to expect from this educational experience and also, an introduction to the course Classical Cryptosystems and Core Concepts. \begin{itemize}[label={$\bullet$}] \item About the Instructors \item Course Introduction \item About the Course \item About the Instructor \item About the Instructor \end{itemize} \subsection*{Cryptographic Tidbits} In this module we present an introduction to cryptography, differentiate between codes and ciphers, describe cryptanalysis, and identify the guiding principles of modern cryptography. After completing this course you will be able to read material related to cryptographic systems, understanding the basic terminology and concepts. You will also have an appreciation for the historical framework of modern cryptography and the difficulty of achieving its aims. \begin{itemize}[label={$\bullet$}] \item What is Cryptography? \item Lecture Slide - What is Cryptography? \item Additional Reference Material \item Codes and Ciphers \item Lecture Slide - Codes and Ciphers \item L2: Additional Reference Material \item What is Cryptanalysis? \item Lecture Slide - What is Cryptanalysis \item L3: Additional Reference Material \item Modern Guiding Principles in Cryptography \item Lecture Slide - Modern Guiding Principles \item L4: Additional Reference Material \item Video - Cryptography for the masses: <NAME> \item Quiz pour s'exercer: Practice Assessment - Cryptographic Tidbits \item Discussion Prompt: What do you think? \item Noté: Graded Assessment - Cryptographic Tidbits \end{itemize} \newpage \section*{Semaine 2 - cryptanalysis} Delving deeper into cryptanalysis, in this module we will discuss different types of attacks, explain frequency analysis and different use cases, explain the significance of polyalphabetical ciphers, and discuss the Vigenere Cipher. When you have completed this module, you will have an appreciation of the different types of attacks and under what kinds of situations each might be applicable. \subsection*{Objectifs d'apprentissage} \begin{itemize}[label={$\bullet$}] \item Identify different types of cryptanalysis attacks. \item Describe the single-character frequency analysis method of cryptanalysis. \item Explain the multi-character frequency analysis method of cryptanalysis. \item Apply the different frequency analysis methods of cryptanalysis. \item Explain the significance of key length in polyalphabetic ciphers. \item Demonstrate how to determine the key length for a polyalphabetic cipher. \item Apply frequency analysis cryptanalysis methods to crack a Vigenere Cipher. \end{itemize} \subsection*{Lectures} \begin{itemize}[label={$\bullet$}] \item L5 - Type of attacks \item L6 - Frequency Analysis of Monoalphabetic Ciphers - Single-Character Frequencies \item L7 - Multi-Character Frequency Analysis \item L8 - Frequency Analysis for Monoalphabetic Ciphers - Example \item L9 - Key Length Determination in Polyalphabetic Ciphers \item L10 - Example of Cracking a Vigenere Cipher \end{itemize} \newpage \end{document}<file_sep>package main import "fmt" import "io/ioutil" import "strings" type Names struct { fname string lname string } func main() { var filename string fmt.Printf("Enter the file name : ") fmt.Scan(&filename) sli := make([]Names, 0) data, _ := ioutil.ReadFile(filename) lignes := strings.Split(string(data), "\n") for i := 0; i < len(lignes); i = i + 1 { res := strings.Split(lignes[i], " ") var idPersonne Names idPersonne.fname = res[0] idPersonne.lname = res[1] sli = append(sli, idPersonne) } for i := 0; i < len(sli); i = i + 1 { fmt.Printf("First Name : %s, Last Name : %s\n", sli[i].fname, sli[i].lname) } }<file_sep>/* Calcul du pgcd par une méthode géométrique. * CONTRIBUTEUR * <NAME> * * LICENCE * GPLv3 */ #include <iostream> #include <math.h> using namespace std; // on affiche notre rationnel de manière simple. void aff_r( int r[2]) { cout << "[ " << r[0] << ", " << r[1] << " ]" << endl; } void aff_p( int p[][2], int n) { for (int i =0; i < n+1; i++) { cout << "[ " << p[i][0] << ", " << p[i][1] << " ]" << endl; } } // algo simple void geogcd( int r[2], int p[][2], int &n) { // on passe n par référence pour affiner l'affichage // et connaitre le nombre d'itération // Valeur initiale p[0][0] = 1; p[0][1] = 0; p[1][0] = 0; p[1][1] = 1; // Compteur // i compte le nombre d'itérations int i = 2; // position correspond à si on doit être au dessus // ou en dessous de la ligne l:y = r*x // on change à chaque fois en la multipliant par -1 int position = 1; // booléen pour savoir si on a le pgcd bool gcd = false; // algo while ( i<(n+2) && gcd == false) { // on calcul p_i avec q_i = 1 // p_i = q_i * p_i-1 + p_i-2 p[i][0] = p[i-1][0] + p[i-2][0]; p[i][1] = p[i-1][1] + p[i-2][1]; // On teste notre position relative par rapport à l:y = r*x // et on teste le fait d'avoir trouvé le pgcd while( (p[i][1] - (((float)r[1])/r[0])*p[i][0]) * position <=0 && gcd == false) { // On se demande si on a le pgcd if ( (p[i][1] - (((float)r[1])/r[0])*p[i][0]) * position ==0 ) { // on est au pgcd // on en profite pour changer n n = i; gcd = true; } // Sinon, on poursuit l'algo en incrémentant q_i // Ce qui consiste à ajouter un p_i-1 p[i][0] = p[i][0] + p[i-1][0]; p[i][1] = p[i][1] + p[i-1][1]; } // On est allé trop loin en dépassant l. // On revient à l'itération d'avant. p[i][0] = p[i][0] - p[i-1][0]; p[i][1] = p[i][1] - p[i-1][1]; // On met à jour la position position = position * -1; // On passe au convergent suivant i++; } } // Programme principal int main() { int r[2]; int n = 20; // pas très élégant de fixer le nombre de convergent à 20... int p[n][2]; // cas 1 r[0]=5; r[1]=8; geogcd(r, p, n); cout << "resul pour r =: "; aff_r(r); aff_p(p,n); // cas 2 r[0]=3; r[1]=7; n = 20; geogcd(r, p, n); cout << "resul pour r =: "; aff_r(r); aff_p(p,n); // cas 3 r[0]=5; r[1]=15; n = 20; geogcd(r, p, n); cout << "resul pour r =: "; aff_r(r); aff_p(p,n); return(0); } <file_sep># Estimation de la longueur de la file pour la chantier routier ## Paramètres N=5000;# // nombre d'échantillons (npmbre de simulations) n=500;# // taille des échantillons (durée de chaque simulation) a=4/60; # // a= 4 sec. = 4/60 mn. lambda1= 4; lambda2= 3; L=.6; v=.5; d1=1.5; d2=1.1; K= floor(d1/a); mu1= lambda1 * d1; mu2= lambda1 * (d2+2*L/v); #// Simulation de la suite X(i) (1 <= i <= n) Y = matrix(0,N,n); Z = matrix(0,N,n); X = matrix(0,N,n); for (i in 1:n) { Y[,i]=rpois(N,mu1); Z[,i]=rpois(N,mu2); } #Nombre de voiture #Calcul de Xn i=1 while (i < n) { j = 1 while (j <= N) { X[j, i+1] = max(0 ,X[j, i]+Y[j, i] - K ) + Z[j, i]; j = j +1 } i = i +1 } #Longueur de file i = 1 XX = matrix(0,N,1) while (i <= N) { XX[i] = mean(max(X[i,])) *(0.6*5 + 0.3 *10 + 0.1*20) i = i + 1; } #Nombre de voitures moyen moy_long = mean(X[, n]) #Longeur de file moyenne moy_file = moy_long*(0.6*5 + 0.3 *10 + 0.1*20) #Affichage des boxplots par(mfrow=c(1,2)) boxplot(X[,n]) title("Boxplot du nombre voitures au bout de 500 cycles") boxplot(XX) title("Boxplot de la longueur de la file au bout de 500 cycles") #Affichage des histogrammes par(mfrow=c(1,2)) hist(X, freq=TRUE) hist(XX) length(XX[XX>235]) / N # frequences empiriques femp = table(X)/(n*N) hist(femp) title("Fréquences empiriques") <file_sep>import numpy as np from scipy import interpolate import matplotlib.pyplot as plt # DATA NX=4 NY=4 y,x = np.mgrid[0:NX,0:NY] x = x/NX y = y/NY dx=0.01 dy=0.01 NXNEW = int(NX/dx) NYNEW = int(NY/dy) ynew, xnew = np.mgrid[0:NXNEW,0:NYNEW] xnew = xnew/NXNEW ynew = ynew/NYNEW Data=np.loadtxt("tab.dat") z = np.reshape(Data[:,2],(NX,NY)) # INTERPOLATE tck = interpolate.bisplrep(x,y,z,s=0) znew = interpolate.bisplev(xnew[0,:],ynew[:,0],tck) # GRAPH xgp,ygp = np.mgrid[0:NX+1,0:NY+1] xgpnew,ygpnew = np.mgrid[0:NXNEW+1,0:NYNEW+1] plt.figure() plt.pcolor(xgp,ygp,z) plt.colorbar() plt.title("Sparsely sampled function.") plt.figure() plt.pcolor(xgpnew,ygpnew,znew) plt.colorbar() plt.title("Interpolated function.") plt.show() exit() <file_sep>\input{doc-class-cours.tex} \begin{document} Welcome to Introduction to Applied Cryptography. Cryptography is an essential component of cybersecurity. The need to protect sensitive information and ensure the integrity of industrial control processes has placed a premium on cybersecurity skills in today’s information technology market. Demand for cybersecurity jobs is expected to rise 6 million globally by 2019, with a projected shortfall of 1.5 million, according to Symantec, the world’s largest security software vendor. According to Forbes, the cybersecurity market is expected to grow from \$75 billion in 2015 to \$170 billion by 2020. In this specialization, you will learn basic security issues in computer communications, classical cryptographic algorithms, symmetric-key cryptography, public-key cryptography, authentication, and digital signatures. These topics should prove especially useful to you if you are new to cybersecurity Course 1, Classical Cryptosystems, introduces you to basic concepts and terminology related to cryptography and cryptanalysis. It is recommended that you have a basic knowledge of computer science and basic math skills such as algebra and probability. \section*{Semaine 1 - The insides of giant planets (week 1)} \begin{itemize}[label={$\bullet$}] \item Vidéo : 2.01: Introduction to Jupiter \item Vidéo : 2.02: Measuring density \item Demande de discussion : Transit of Venus! \item Vidéo : 2.03: Using density \item Vidéo : 2.04: Hydrostatic equilibrium \item Vidéo : 2.05: Hydrogen equation of state \item Vidéo : 2.06: Heat transport \item Vidéo : 2.07: Theoretical internal structure \item Vidéo : 2.08: A core from gravity ? \item Vidéo : 2.09: Magnetic fields \item Vidéo : 2.10: The upper atmosphere and the Galileo probe \item Vidéo :2.11: Picture models \end{itemize} \end{document}<file_sep>package main import ( "fmt" "strconv" "strings" ) func tronquer( nombre float64 ) (nbInt int64){ fmt.Println("Tronquer: ",nombre) var nbString string = fmt.Sprintf("%f", nombre) var i int for i = 0; i < len(nbString) && nbString[i] != '.' ; i++ {} var intString string = nbString[0:i] nbInt, _ = strconv.ParseInt(intString, 10, 0) return } func testString( mot string ){ if mot[0] == 'i' { fmt.Println("commence avec i") } if mot[len(mot)-1] == 'n' { fmt.Println("fini avec n") } if strings.Contains(mot,"a") { fmt.Println("avec a") } } func main() { fmt.Println("Pour la semaine 2") /* var nbScan float64 fmt.Scan(&nbScan) fmt.Println("Scan de nombre :", nbScan) */ var nbFloat float64 = 128.5 nbInt := tronquer(nbFloat) fmt.Println(nbInt) // on pouvait aussi faire : var resultat2 = int(nbFloat) fmt.Println(resultat2) var chScan string fmt.Scan(&chScan) fmt.Println("Scan un mot :", chScan) fmt.Println(chScan) testString(chScan) fmt.Println("median") testString("median") fmt.Println("irrmedian") testString("irrmedian") } <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 2 : - Les nombres de fibonacci pair. ----------------------------------------------------------------- L'algorithme 1 calcule la suite de nombre de Fibonacci et ne fait la somme que des nombres pairs. L'algorithme 2 s'appuie sur la 3-périodicité des nombres pairs dans la suite de Fibonacci. ----------------------------------------------------------------- """ def SommeFibonacciPair(aFin): # Les deux premiers termes aFib1 = 1 aFib2 = 2 somme = 2 while(aFib2 < aFin): # b2 -> a1 + b1 # a2 -> b1 -> b2 - a1 aFib2 += aFib1 aFib1 = aFib2-aFib1 # On vérifie si aFib2 est pair if aFib2 % 2 == 0: somme += aFib2 return somme # Utilisation de la parité def SommeFibonacciPair3(aFin): # Les deux premiers termes aFib1 = 1 aFib2 = 2 somme = 0 while(aFib2 < aFin): somme += aFib2 # b2 -> a1 + b1 # a2 -> b1 -> b2 - a1 # itérations 1 aFib2 += aFib1 aFib1 = aFib2-aFib1 # itération 2 aFib2 += aFib1 aFib1 = aFib2-aFib1 # itération 3 aFib2 += aFib1 aFib1 = aFib2-aFib1 return somme # Main fin = 4000000 # Affiche la somme print("1 - somme des nombres de Fibonacci pairs: ",SommeFibonacciPair(fin)) print("2 - somme des nombres de Fibonacci pairs: ",SommeFibonacciPair3(fin)) <file_sep>#include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { if(argc == 2 && argv) { int arg_i; int val_i; char values[16]; arg_i = 0; val_i = 0; while( argv[1][arg_i] != '\0') { if (argv[1][arg_i] != ' ') { values[val_i] = (int)argv[1][arg_i] - 48; printf("%d\n", values[val_i]); //debugging if (values[val_i] <= 0 || values[val_i] > 4 || val_i > 15) { write(2, "Invalide value or too much\n", 27); return 1; } val_i++; } arg_i++; } if (val_i < 15) { write(2, "too few values\n", 27); return 1; } } else { write(2, "no values given or too much argv\n", 33); return 1; } //debug : write(2, "\nEnd Well\n", 10); // ne doit pas etre afficher en cas de data non valide return 0; }<file_sep>""" Differential Equations in Action Lesson 1 - Houston We have a problem """ # Import import math # import math.cos(), math.sin(), math.pi import numpy # import distance import matplotlib.pyplot as plt # import plot """ ----------------------------------------------------------------------- - 1 - Exercices - Orbit Error ----------------------------------------------------------------------- """ # QUIZ # # Determine the step size h so that after num_points the time total_times has passed. # Compute the trajectory of the spacecraft starting from a point a distance r from the origin with a velocity of magnitude equal to the speed. # Use the Forward Euler Method. Return the distance between the final and the initial position in the variable error. # These are used to keep track of the data we want to plot h_array = [] error_array = [] total_time = 24. * 3600. # s g = 9.81 # m / s2 earth_mass = 5.97e24 # kg gravitational_constant = 6.67e-11 # N m2 / kg2 radius = (gravitational_constant * earth_mass * total_time**2. / 4. / math.pi ** 2.) ** (1. / 3.) speed = 2.0 * math.pi * radius / total_time def acceleration(spaceship_position): vector_to_earth = - spaceship_position # earth located at origin return gravitational_constant * earth_mass / numpy.linalg.norm(vector_to_earth)**3 * vector_to_earth def calculate_error(num_steps): # h_step h = total_time / num_steps x = numpy.zeros([num_steps + 1, 2]) v = numpy.zeros([num_steps + 1, 2]) # conditions initiales # Pour la position : pas de composante verticale : x[0,1] = 0 x[0,0] = radius # Pour la vitesse : pas de composante horizontale : v[0,0] = 0 v[0,1] = speed # Methode d'Euler for step in range(num_steps): x[step + 1] = x[step] + h*v[step] v[step + 1] = v[step] + h*acceleration(x[step]) #dernier - premier error = numpy.linalg.norm(x[-1] - x[0]) # This is used for plotting h_array.append(h) error_array.append(error) return error h_array=[] error_array=[] for num_steps in [200, 500, 1000, 2000, 5000, 10000]: error = calculate_error(num_steps) def plot_orbit(): axes = plt.gca() axes.set_xlabel('Step size in s') axes.set_ylabel('Error in m') plt.scatter(h_array, error_array) plt.xlim(xmin = 0.) plt.ylim(ymin = 0.) plt.show() plot_orbit() <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 4 : - Le plus grand produit de deux facteurs entre 100 et 999 qui soit un palindrome. ----------------------------------------------------------------- - boolean fonction to check if palindrome - unique and sorted list of 3-digits factors (thanks python do not let me code this myself) with a started a set in order to have unique entry and a lst = sorted(list(from_set)) - Found the biggest one by pop. ----------------------------------------------------------------- """ # True if aNombre is a palindrome def EstPalindrome(aNombre): strNombre = str(aNombre) digit = len(strNombre) idigit = 0 isPal = True while isPal and idigit < digit//2: if strNombre[idigit] != strNombre[digit - idigit -1]: isPal = False idigit += 1 return isPal # A list of unique and sorted integer as factor of aNombre-digits number def lstFactor(aNombre): aMax1 = aNombre aMax2 = aNombre setfact = set() while (aMax1 > 0): aMax2 = aNombre while (aMax2 > 0): setfact.add(aMax1 * aMax2) aMax2 -= 1 aMax1 -=1 lstfact= sorted(list(setfact)) return lstfact # Biggest palindrome def maxPalindrome(aNombre): lstfact = lstFactor(aNombre) pal = lstfact.pop() while not EstPalindrome(pal): pal = lstfact.pop() return pal # Main print("lst facteur",maxPalindrome(999)) <file_sep>all: pb1 pb2 pb3 pb4 pb5 pb6 pb7 pb8 pb9 pb10 pb1: python3 algo/pb1_entiers-multiple-3-5.py pb2: python3 algo/pb2_entiers-fibonacci-pair.py pb3: python3 algo/pb3_plus-grand-facteur-premier.py pb4: python3 algo/pb4_plus-grand-produit-facteurs.py pb5: python3 algo/pb5_plus-petit-facteur-1-20.py pb6: python3 algo/pb6_différence-carrés-100.py pb7: python3 algo/pb76_1001-premier.py pb8: python3 algo/pb8_produit-5-chiffres.py pb9: python3 algo/pb9_3-pythagore.py pb10: python3 algo/pb10_somme-premiers-10-millions.py <file_sep>\documentclass[11pt]{article} \usepackage{geometry,marginnote} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,french]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern,numprint} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx,float,grffile} \usepackage{pst-eucl, pst-plot,units} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} \DeclareUnicodeCharacter{20AC}{\euro} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height \newcommand{\Pointilles}[1][3]{% \multido{}{#1}{\makebox[\linewidth]{\dotfill}\\[\parskip] }} \newtheorem{Definition}{Définition} \usepackage{siunitx} \sisetup{ detect-all, output-decimal-marker={,}, group-minimum-digits = 3, group-separator={~}, number-unit-separator={~}, inter-unit-product={~} } \setlength{\columnseprule}{1pt} \begin{document} \begin{titlepage} \begin{sffamily} \begin{center} ~\\[1.5cm] \textsc{\Large Mon établissement}\\[2cm] \textsc{\large ma classe}\\[1.5cm] \hrule[0.4cm] \\ {\huge \bfseries Condensé de l'année et notions importantes\\[0.4cm]} \hrule[4cm] \\ \vfill \begin{minipage}{0.3\textwidth} \begin{flushleft}\large Mon prénom \textsc{<NAME>}\\ 2021-2022 \end{flushleft} \end{minipage} \begin{minipage}{0.5\textwidth} \begin{flushright}\large \begin{tabular}{Sl Sl} \emph{Professeur de Physique :} &xxx \textsc{XXX}\\ \emph{Professeur de S.I.I. :} &yyy \textsc{YYY}\\ \emph{Professeur de Mathématiques :}&zzz \textsc{ZZZ} <--- C'est ici que l'erreur est reportée \end{tabular} \end{flushright} \end{minipage} \vfill \large \today \end{center} \end{sffamily} \end{titlepage} \titlepage \end{document}<file_sep>########################################################################### # # # Traffic routier # # # ########################################################################### ## ## Flux continu ## ############################ #On récupère un échantillon: #Simulation des tau : le temps entre l'arrivé de deux voitures #n le nombre de voiture compté n_1 = 50 n_2 = 50 #lambda_theo_1 le paramètre lambda_theo_1 = 0.12 lambda_theo_2 = 0.13 #Tau_1 est le fichier récupérer de l'intervalle de temps entre le passage de deux voitures tau_1 = rexp(n_1, rate = lambda_theo_1) tau_2 = rexp(n_1, rate = lambda_theo_1) #plot(tau_1,type="b") #plot(tau_1,type="s") #En second #En moyenne, il passe une voiture en mean(tau) en seconde #tau_1 #mean(tau_1) On peut ainsi récupérer lambda_exp_1 = 1/mean(tau_1) lambda_exp_2 = 1/mean(tau_2) # flux_1 = tau_1 for(i in 2:n_1) { flux_1[i]=flux_1[i-1]+flux_1[i] } flux_2 = tau_2 for(i in 2:n_2) { flux_2[i]=flux_2[i-1]+flux_2[i] } #Graph par(mfrow=c(2,2)) plot(tau_1,type="s") title("Intervalle d'arrivée entre deux voitures sur la voie 1") plot(flux_1,seq(1,n_1),type="s") title("Temps de passage au point de départ sur la voie 1") plot(tau_2,type="s") title("Intervalle d'arrivée entre deux voitures sur la voie 2") plot(flux_2,seq(1,n_2),type="s") title("Temps de passage au point de départ sur la voie 2") tau_1 tau_2 #Deuxième méthode: #On compte le nombre de voiture dans un intervalle de 30s fluxx_1 = rpois(50, lambda=lambda_1*30) fluxx_1 for(i in 2:n_1) { fluxx_1[i]=fluxx_1[i-1]+fluxx_1[i] } plot( seq(1,n_1*30,30), fluxx_1,type="s") <file_sep># La trigonométrie. *L'idée de base est de chercher à comprendre un peu mieux comment son liées les longueurs et les angles dans un triangle.* ## A - Une grosse introduction ### 1 - Les triangles semblables Un premier bon réflexe est de faire un rappel sur les triangles semblables. **Rappel vieux mais important :** - **la somme des angles dans un triangle fait 180°.** **Nouveauté du chapitre triangles semblables.** - **Deux triangles sont semblables s'ils ont les trois mêmes angles.** - **Deux triangles semblables ont des côtés deux à deux proportionnels.** Ici, on découvre l'idée que dans un triangle la notion d'angle et de longueur sont en lien. Il y a une question de proportionnalité. On peut passer d'une longueur à une autre en multipliant toujours par un même nombre. ### 2 - Le triangle rectangle. On pourrait le faire pour tous les triangles (au programme de première ou term), mais pour que ça soit plus simple, on va juste se concentrer sur les triangles rectangles. On peut visualise cette idée assez simplement : ![triangles](https://raw.githubusercontent.com/homeostasie/petits-pedestres/master/2022.d/trigo.d/triangles.png) Ici le côté [BC] est plus petit que [BD] et de même [AC] est plus petit que [AD]... et ça, c'est à cause de l'angle en A, BÂD qui est plus grand que celui BÂC. En lien avec les rappels; Comme on a un angle droit (=90°) dès qu'on connaît un angle de plus, on peut calculer le troisième angle. **ex1 : Calculer les angles dans un triangle.** ### 3 - La proportionnalité L'idée de départ de la trigo (un peu dur à prouver simplement) : Si on a un triangle rectangle et qu'on connaît un angle et un côté, alors on va pouvoir calculer les autres côtés. On a besoin de trouver ce *"cœfficient"* qui me permet de *"jongler"* entre les côtés. La question est comment avoir ce cœfficient... Ben, on a un peu de chance parce que des gens se sont un peu cassés la tête à ça avant... Avant, on nous donnait des tables sur papier, voir pour les plus riches une règle à calculer. ![tables](https://raw.githubusercontent.com/homeostasie/petits-pedestres/master/2022.d/trigo.d/table.png) ![règles](https://raw.githubusercontent.com/homeostasie/petits-pedestres/master/2022.d/trigo.d/regle.jpg) ### 4 - Les cœfficients Il reste deux questions : 1. Comment avoir ce cœfficient ? 2. Comment l'appliquer ? #### Calculer le cœfficient Maintenant on a un peu de chance, on a la calculatrice. La calculatrice permet de calculer directement ces cœfficients. On s'assure que la calculatrice est en mode degré (mesure d'angle et un petit d affiché en haut de l'écran.) Par exemple, dans ce triangle rectangle avec un angle de 30° (et l'autre de 60°) et un grand côté qui fait 10cm. ![reciproque](https://raw.githubusercontent.com/homeostasie/petits-pedestres/master/2022.d/trigo.d/tria1.png) * Le côté du dessous fait **10 × cos(30) = 8,66cm**. * Le côté de gauche fait **10 × sin(30) = 5cm**. L'idée est que la calculatrice va nous donner ces cœfficients en fonction de l'angle qu'on précise. cos(30) pour un angle de 30°. Si l'angle avait été 48°, on calcule cos(48) Ici, c'est bien de manipuler un peu ces calculs de cœfficients avant de vraiment rentrer dans les exercices un peu plus dur. On reste dans cette configuration de triangle et on change un peu la longueur du grand côté et l'angle. **ex2 - calculer des cœfficients** * Si le grand côté mesure 12 et l'angle 45° * le côté du dessous mesure : **12 × cos(45)** * le côté de gauche mesure : **12 × sin(45)** Si pas trop allergique à la proportionnalité, on peut marquer cette phrase : **Dans un triangle rectangle, si on connaît le grand côté : l'hypoténuse, alors on peut calculer les deux autres avec un cœfficient de réduction qui dépend de l'angle.** #### Le vocabulaire On va devoir se sensibiliser au fait que les notations "grand côté, petit côté, côté du haut, du bas, de gauche, de droite" ne sont pas satisfaisante. On introduit le vocabulaire. Dans un triangle rectangle, si on marque un angle, on peut nommer les trois côtés : * **Hypoténuse** : le grand côté, en face de l'angle droit. * **Adjacent** : le côté entre l'angle droit et l'angle marqué. * **opposé** : le côté opposé à l'angle marqué. **ex3 : Repérer le nom mathématiques des côtés dans des triangles rectangles.** On peut reprendre l'exercice 2 avec plus de précision. **adj = hyp × cos(angle)** **opp = hyp × sin(angle)** Il faut essayer de bien insister sur le fait que * **$\cos(angle)$ est le cœfficient qui permet de calculer le côté adjacent à partir de l'hypoténuse.** * **$\sin(angle)$ est le cœfficient qui permet de calculer le côté opposé à partir de l'hypoténuse.** Et si déjà on arrive à ce point, alors la trigonométrie est comprise. Maintenant, il reste à réussir à l'appliquer tout le temps et rapidement. ## B - On rentre dans le chapitre Pour s'en sortir en trigonométrie, il faut des pré-requis : * **La somme des angles dans un triangle fait 180°.** * **Savoir repérer : l'hypoténuse, l'opposé et l'adjacent dans un triangle rectangle avec un angle marqué.** Ensuite il faut accepter l'objectif de base : **Dans un triangle rectangle, à partir d'un angle et d'un côté, je vais pouvoir calculer les deux autres côtés.** Pour faire tout ça, on a besoin de trois formules : les 3 coeff qui dépendent des angles : * **cosinus** * **sinus** * **tangente** * **adj = hyp × cos(angle)** * **opp = hyp × sin(angle)** * **opp = adj × tan(angle)** Un problème : il est assez dur d'apprendre ces trois formules dans ce sens. Il est souvent plus simple de retenir les formules avec les quotients. * **cos = adj / hyp** * **sin = opp / hyp** * **tan = opp / adj** Il y a deux phrases mnémotechniques pour les retenir : * **CAH SOH TOA** (une sorte de *casse-o-toi*) * **SOH CAH TOA** La difficulté est vraiment, vraiment maintenant. Parce qu'on doit adapté nos envies et nos connaissances. Il ne faut pas partir que "le côté que je cherche est égal à celui que je connais fois le coeff". Parce qu'à partir d'une définition, je vais pouvoir calculer de deux manières. **cos = adj / hyp** => **adj = hyp × cos(angle)** ET **hyp = adj / cos(angle)** **sin = opp / hyp** => **opp = hyp × sin(angle)** ET **hyp = opp / sin(angle)** **tan = opp / adj** => **opp = adj × tan(angle)** ET **adj = opp × tan(angle)** Là, la stratégie est de se poser les questions : **"Qu'est-ce que j'ai ?" et "Qu'est-ce que je veux ?" **ex4 : Modéliser : "je vais utiliser".** **ex5 : l'exo type ; on donne une longueur et un angle et on demande les autres longueurs** ## C - Dans l'autre sens. Souvent quand ça marche bien dans un sens, on se pose toujours la question de savoir si on ne pourrait pas s'en servir dans l'autre. (ex réciproque de Pythagore) L'idée de base ici est que si on nous donne un triangle rectangle avec deux longueurs (et pas seulement une), alors on va pouvoir calculer les angles de ce triangle. ### À partir des coeff * Dans l'idée si je peux connaître le coefficient à partir de l'angle : **sin(30) = 0.5** * J'ai envie de dire que si je connais le coefficient alors je dois aussi pouvoir connaître l'angle : **30 = arcsin(0.5)**. Les trois fonctions réciproques : **arccos**, **arcsin**, **arctan** sont accessibles via la calculatrice. On demande à la calculatrice : *Je te donne le cœfficient : **cos**, **sin** ou **tan** et toi, tu me donnes l'angle.*. Souvent l'accès est avec la touche seconde ou shift puis la touche cos, sin et tan. **ex6 : Calculer l'angle à partir du cœfficient.** ### À partir des côtés C'est un peu plus dur, à partir des longueurs car il faut repartir des définitions. En effet, comme : * **cos = adj / hyp** * **sin = opp / hyp** * **tan = opp / adj** On peut facilement connaître la valeur d'un de ces cœfficients. Époque moderne, on se passe de table, la calculatrice va aussi pouvoir nous donner la valeur exacte de l'angle en fonction de la valeur du cœfficient. ![reciproque](https://raw.githubusercontent.com/homeostasie/petits-pedestres/master/2022.d/trigo.d/reciproque.png) Ici, on connaît : * **Hyp = 10cm** * **Adj = 7cm** Donc on peut calculer la valeur du cosinus **cos = 6/10 = 0.6** Pour connaître la valeur de l'angle, on utilise ce qu'on appelle la fonction réciproque. Attention à bien mettre les parenthèses : arccos(6/10 ne marche pas comme il faut. **angle = arccos(6/10) = 53,13°** **ex7 : Calculer l'angle à partir des longueurs.** ## D - Le paradis des problèmes La trigonométrie est le paradis des problèmes parce qu'on peut mélanger des questions d'angles et des questions de longueurs. On a juste besoin d'un triangle rectangle... et c'est souvent le cas en math. Dès qu'on nous donne un triangle rectangle, une longueur et un angle, ça veut dire : *"probablement de la trigo."*<file_sep># Dossiers CODE := $(shell pwd) PDFDIR = _pdf THEME = # Visualiser les pdf LOG=evince # Créer le dossier pdf s'il n'éxiste pas. target: test -d $(PDFDIR) || mkdir $(PDFDIR) info_intro-go-1: pdflatex info_Go-1.tex pdflatex info_Go-1.tex mv info_Go-1.pdf '$(PDFDIR)'/info_Go-1.pdf info_mind-ai-1: pdflatex info_Mind-AI-1.tex pdflatex info_Mind-AI-1.tex mv info_Mind-AI-1.pdf '$(PDFDIR)'/info_Mind-AI-1.pdf info_crypto-1: pdflatex info_Applied-Crypto-1.tex pdflatex info_Applied-Crypto-1.tex mv info_Applied-Crypto-1.pdf '$(PDFDIR)'/info_Applied-Crypto-1.pdf astro_ss: pdflatex astro_Solar-System.tex pdflatex astro_Solar-System.tex mv astro_Solar-System.pdf '$(PDFDIR)'/astro_Solar-System.pdf # nettoyage proper: rm -f *.log *.toc *.aux *.nav *.snm *.out *.bbl *.blg *.dvi *.ps rm -f *.backup *~<file_sep>part1: pdflatex partie1.tex pdflatex partie1.tex # nettoyage proper: rm -f *.log *.toc *.aux *.nav *.snm *.out *.bbl *.blg *.dvi *.ps rm -f *.backup *~<file_sep>#include <stdio.h> #include <stdlib.h> char CH1 = 'X'; char CH2 = 'O'; int J1 = 1; int J2 = -1; // Affichage de la lettre choisie en fonction du joueur. char affiche_lettre(int *plateau, int indice) { if (plateau[indice] == 0 ){return(' ');} if (plateau[indice] == 1 ){return(CH1);} if (plateau[indice] == -1){return(CH2);} } // Affichage du plateau de jeu /* * ------- * |7|8|9| * ------- * |4|5|6| * ------- * |1|2|3| * ------- */ void affiche_plateau(int *plateau) { int i, j; printf("%s\n", "-------"); for (i = 2 ; i >= 0 ; i--) { for (j = 0 ; j <3 ; j++) { printf("%s", "|"); printf("%c", affiche_lettre( plateau, (3*i+j))); } printf("%s\n", "|"); printf("%s\n", "-------"); } } // Produit des cases pour savoir si le jeu est fini. int partie_nulle(int *plateau) { int i=0; int res=1; for (i = 0 ; i < 9 ; i++) { res = res*plateau[i]; } return(res); } // Initialisation du tableau pour rejouer une partie. void init_plateau(int *plateau) { int i=0; for (i = 0 ; i < 10 ; i++) { plateau[i] = 0; } } /* * Return 1 si la case est libre et que le coup est valide. * Return 0 si la case est déjà occupé et que le coup est invalide. */ int jeu_plateau(int *plateau, int joueur, int choix) { if (plateau[choix-1] == 0) { // tableau indexé à partir de 0 et non 1 : d'où choix -1. plateau[choix-1] = joueur; return(1); } else{return(0);} } /* * Return 0 si on peut encore jouer. * Return 10 si la grille est complète. * Return 1 si J1 gagne. * Return -1 si J1 gagne. */ int test_plateau(int *plateau) { int i; // Tests horizontaux if (plateau[0] + plateau[1] + plateau[2] == 3 || plateau[3] + plateau[4] + plateau[5] == 3 || plateau[6] + plateau[7] + plateau[8] == 3 ) { plateau[9] = J1; return J1; } if (plateau[0] + plateau[1] + plateau[2] == -3 || plateau[3] + plateau[4] + plateau[5] == -3 || plateau[6] + plateau[7] + plateau[8] == -3 ) { plateau[9] = J2; return J2; } // Tests verticaux if (plateau[0] + plateau[3] + plateau[6] == 3 || plateau[1] + plateau[4] + plateau[7] == 3 || plateau[2] + plateau[5] + plateau[8] == 3 ) { plateau[9] = J1; return J1; } if (plateau[0] + plateau[3] + plateau[6] == -3 || plateau[1] + plateau[4] + plateau[7] == -3 || plateau[2] + plateau[5] + plateau[8] == -3 ) { plateau[9] = J2; return J2; } // Tests diagonaux if (plateau[0] + plateau[4] + plateau[8] == 3 || plateau[2] + plateau[4] + plateau[6] == 3 ) { plateau[9] = J1; return J1; } if (plateau[0] + plateau[4] + plateau[8] == -3 || plateau[2] + plateau[4] + plateau[6] == -3 ) { plateau[9] = J2; return J2; } // La grille est complète sans gagnant. int nulle=1; for (i = 0 ; i < 9 ; i++) { nulle = nulle*plateau[i]; } if(nulle != 0) { printf("%s\n", "----------------------------"); printf("\n"); printf("%s\n", "------ PAS DE GAGNANT ------"); printf("\n"); printf("%s\n", "----------------------------"); return(10); } // La partie continue. return (0); } int tour_plateau(int *plateau) { if (plateau[9] == 0) { printf("%s\n", " ------- Prochain tour : "); return (0); } if (plateau[9] == J1) { printf("%s\n", "----------------------------"); printf("\n"); printf("%s\n", "------- Gagnant : J1 -------"); printf("\n"); printf("%s\n", "----------------------------"); return (J1); } if (plateau[9] == J2) { printf("%s\n", "----------------------------"); printf("\n"); printf("%s\n", "------- Gagnant : J2 -------"); printf("\n"); printf("%s\n", "----------------------------"); return (J2); } } int main() { int plateau[10]; int victoire = 0; int valide =0; printf("%s\n", "------- DEBUT INITIALISATION PLATEAU ------ I"); init_plateau(plateau); affiche_plateau(plateau); printf("%s\n", "------- FIN INITIALISATION PLATEAU ------ I"); printf("\n"); int choix; printf("%s\n", "------- DEBUT PARTIE ------ I"); printf("\n"); // tant que personne ne gagne ou que la partie n'est pas finie. while(victoire == 0 && victoire != 10) { // joueur 1 do { printf("%s", "J1 prend la case : "); scanf("%i", &choix); valide = jeu_plateau(plateau, J1, choix); affiche_plateau(plateau); } while(valide == 0); victoire = test_plateau(plateau); tour_plateau(plateau); // Le joueur 1 gagne ou complète la grille. if(victoire == 0 && victoire != 10) { // joueur 2 do { printf("%s", "J2 prend la case : "); scanf("%i", &choix); valide = jeu_plateau(plateau, J2, choix); affiche_plateau(plateau); } while(valide ==0); victoire = test_plateau(plateau); tour_plateau(plateau); } } // fin du main(). return 0; }<file_sep>\documentclass[11pt]{article} \usepackage{geometry} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,francais]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx, float} \usepackage{tikz,tkz-tab} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} % No page header \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height %---------------------------------------------------------------------------------------- % Début du document %---------------------------------------------------------------------------------------- \begin{document} %---------------------------------------------------------------------------------------- % RE-DEFINITION %---------------------------------------------------------------------------------------- % MATHS %----------- \newtheorem{Definition}{Définition} \newtheorem{Theorem}{Théorème} \newtheorem{Proposition}{Propriété} % MATHS %----------- \renewcommand{\labelitemi}{$\bullet$} \renewcommand{\labelitemii}{$\circ$} %---------------------------------------------------------------------------------------- % Titre %---------------------------------------------------------------------------------------- \setlength{\columnseprule}{1pt} \section{Second degrée} Globalement, on est sur des exercices où l'on fait des gammes, de l'entrainement. Il n'y a pas trop de finesse, ni de raisonnement. Cela veut dire qu'on va faire pas mal de calculs et donc qu'on va devoir faire attention aux erreurs de calculs et d'écritures.\\ Exercice 7, on est dans les fonctions du second degrée. C'est assez classique car la résolution est connue et que les variations sont simples. C'est toujours intéréssant d'avoir une idée de ce à quoi ressemble la courbe. Ici, c'est une parabole (\url{https://www.desmos.com/calculator}). \subsection{résoudre l'équation} $$ax^2 +bx +c =0$$ On calcule le discriminant : $\Delta = b^2 - 4ac$.\\ \begin{itemize} \item $\Delta < 0$ : Pas de solution réélles. \item $\Delta = 0$ : Une solution (double) en $x = \frac{-b}{2a}$. C'est de toute façon toujours un extremum pour la courbe. Sauf que là en plus, il touche l'axe horizontal. \item $\Delta > 0$ : Deux solutions : $x_1 = \frac{-b - \sqrt{\Delta}}{2a}$ et $x_2 = \frac{-b + \sqrt{\Delta}}{2a}$. \end{itemize} \subsection{variations} Ici, je suis toujours un peu mitigé. En vrai, pour les variations on passe toujours par le calcul de la dérivée et on étudie son signe... C'est vraiment le cas, le plus classique et même pour du second degrée, j'aurai tendance à faire ça... Mais, là, dans l'exercice 7, on te fait parler d'équation puis on te dit d'en déduire, les variations... Je pense qu'il souhaite que tu recraches un peu "le cours" sans trop te poser de question. $$f(x) = ax^2 +bx +c$$ \begin{itemize} \item Si $a>0$. La parabole est vers le haut. Elle est décroissante jusqu'en $\dfrac{-b}{2a}$ (le minimum global) puis croissante. \item Si $a<0$. La parabole est vers le bas. Elle est croissante jusqu'en $\dfrac{-b}{2a}$ (le maximum global) puis décroissante. \end{itemize} \section{Dérivée} \subsection{Sens} Les dérivées servent principalement à étudier les variations d'une fonction. En effet, la valeur de la dérivée correspond à la pente de la courbe. Donc négative quand décroissant et positive quand décroissant. \subsection{Calcul} Là, ça se bachote, on a deux catégories à connaitre : \begin{itemize} \item dérivées usuelles : $x$, $x^2$, $x^3$, $1/x$, $cos(x)$,... \item dérivées composées : $f(x) \times g(x)$, $1 / f(x)$, ... \end{itemize} \newpage \section{Cours en ligne} J'ai un peu essayé d'écumer les cours en lignes qu'on peut trouver pour ce niveau. Sans être exhaustif. \begin{itemize} \item \url{https://fr.khanacademy.org/} : Le plus complet et le mieux fait... \item \url{https://www.fun-mooc.fr/cours/#filter/university/Polytechnique?page=1&rpp=50} : Les cours de polytech couvrent un large spectre des maths du lycée. Pour autant, le rythme est assez speed et c'est vraiment du bachotage bête et méchant... Mais surtout, il se sert assez souvent de méthodes et astuces de matheux un peu finaud mais pas forcément simple à retenir... et le niveau est un cran au dessus de ce qui t'es demandé ici. \item \url{https://www.fun-mooc.fr/courses/course-v1:UCA+107001+session01/about} : Pour autant, si on te demande d'avoir des connaissances de base en informatiques, et le plus souvent c'est en python, ce mooc là fait plutôt bien l'affaire. \end{itemize} \newpage \section{exercice 7} \subsection{$1. - f(x) = 5x^2 +3x + 1$} \begin{enumerate} \item[1a.] Résoudre $5x^2 +3x + 1 = 0$\\ calcul du discriminant : \begin{eqnarray*} \Delta &=& 3^2 - 4*5*1\\ &=& 9 - 20\\ &=& -11 \end{eqnarray*} Comme $\Delta < 0$, l'équation $f(x) =0 $ n'a pas de solution. \item[1b.] La fonction $f$ ne s'annule pas et donc change pas de signe. Elle est du signe de $a=5$, donc $f$ est positive sur \degree. \item[1c.] Comme $a=5$, la fonction $f$ est décroissante jusqu'à $\dfrac{-b}{2a} = \dfrac{-3}{10}$ puis croissante.\\ \begin{multicols}{2} \begin{eqnarray*} f(-2) &=& 5 \times (-2)^2 + 3 \times (-2) + 1 \\ f(-2) &=& 5 \times 4 - 6 + 1 \\ f(-2) &=& 15 \end{eqnarray*} \begin{eqnarray*} f(4) &=& 5 \times (4)^2 + 3 \times (4) + 1 \\ f(4) &=& 5 \times 16 + 12 + 1 \\ f(4) &=& 93 \end{eqnarray*} \begin{eqnarray*} f(\dfrac{-3}{10}) &=& 5 \times (\dfrac{-3}{10})^2 + 3 \times (\dfrac{-3}{10}) + 1 \\ f(\dfrac{-3}{10}) &=& 5 \times \dfrac{9}{100} - \dfrac{9}{10} + 1 \\ f(\dfrac{-3}{10}) &=& \dfrac{45}{100} - \dfrac{9}{10} + 1 \\ f(\dfrac{-3}{10}) &=& \dfrac{45}{100} - \dfrac{90}{100} + \dfrac{100}{100} \\ f(\dfrac{-3}{10}) &=& \dfrac{55}{100} \end{eqnarray*} \end{multicols} Tableau\\ \begin{tikzpicture} \tkzTabInit{$x$ / 1 , $f(x)$ / 2}{$-2$, $\dfrac{-3}{10}$, $4$} \tkzTabVar{+/ $15$, -/ $\dfrac{55}{100}$, +/ $93$} \end{tikzpicture} \item[1d.] La valeur minimale de $f$ sur l'intervale $[-2, 4]$ est atteinte en $\dfrac{-3}{10}$ et vaut $\dfrac{55}{100}$. La valeur maximale de $f$ sur l'intervale $[-2, 4]$ est atteinte en 4 et vaut 93. \end{enumerate} \newpage \subsection{$2. - f(x) = -3x^2 + 4x + 4$} \begin{enumerate} \item[2a.] Résoudre $-3x^2 + 4x + 4 = 0$\\ calcul du discriminant : \begin{eqnarray*} \Delta &=& 4^2 - 4*(-3)*4\\ &=& 16 + 48\\ &=& 64 \\ &=& 8^2 \end{eqnarray*} Comme $\Delta > 0$, l'équation $f(x) =0 $ a deux solutions. \begin{multicols}{2} \begin{eqnarray*} x_1 &=& \dfrac{-4 - \sqrt{64}}{-6} \\ &=& \dfrac{-4 - 8}{-6} \\ &=& 2 \end{eqnarray*} \begin{eqnarray*} x_2 &=& \dfrac{-4 + \sqrt{64}}{-6} \\ &=& \dfrac{-4 + 8}{-6} \\ &=& \dfrac{-2}{3} \end{eqnarray*} \end{multicols} \item[2b.] Comme $a=-3$, $f$ est croissante puis décroissante. Elle commence en étant du signe de $a$. (parenthèse : Ici, c'est un peu une question de merde pour moi. La justification n'a pas vraiment de sens. C'est un peu du cours / mais du cours pas franchement démontré.) \begin{tikzpicture} \tkzTabInit{$x$ / 1 , $f(x)$ / 1}{$-\infty$, $\dfrac{-2}{3}$, 2, $+\infty$} \tkzTabLine{,-, z, +, z, -,} \end{tikzpicture} \item[2c.] À partir du tableau de signe, $f(x) \geq 0$ pour $x \in \left[ \dfrac{-2}{3} ; 2 \right]$. \item[2d.] On sait que $f(x) = 0$ pour $x_1 = 2$. Je choisis $(x-2)$ comme facteur, puis je développe $(x-2)(ax + b)$. \begin{eqnarray*} (x-2)(ax + b) &=& ax^2 + bx -2ax -2b \\ &=& ax^2 + x(b-2a) -2b \end{eqnarray*} J'identifie avec $f(x) = -3x^2 + 4x + 4$ \\ \begin{multicols}{2} \begin{eqnarray*} a &=& -3 \\ \end{eqnarray*} \begin{eqnarray*} -2b &=& 4 \\ b &=& -2 \end{eqnarray*} \end{multicols} La fonction s'écrit sous forme factorisée : $f(x) = (x-2)(-3x - 2)$ \item[2d'.] J'aurai pu aller plus vite. On sait que $f(x) = 0$ pour $x_1 = 2$ et $x_2 = \frac{-2}{3}$. De plus $a = -3$. La fonction s'écrit sous forme factorisée : $f(x) = -3(x-2)(x + \frac{2}{3})$ \newpage \item[2e.] Comme $a=-3$, la fonction $f$ est croissante jusqu'à $\dfrac{-b}{2a}$ puis décroissante.\\ \begin{multicols}{2} \begin{eqnarray*} \dfrac{-b}{2a} &=& \dfrac{-4}{2 \times (-3)} \\ &=& \dfrac{-4}{-6} \\ &=& \dfrac{2}{3} \end{eqnarray*} Comme $1 > \dfrac{2}{3}$, $f$ est décroissante sur $[1 ; 3]$. \begin{eqnarray*} f(1) &=& -3 \times 1^2 + 4 \times 1 + 4 \\ f(1) &=& -3 + 4 + 4 \\ f(1) &=& 5 \end{eqnarray*} \begin{eqnarray*} f(3) &=& -3 \times 3^2 + 4 \times 3 + 4 \\ f(3) &=& -27 + 12 + 4 \\ f(3) &=& -11 \end{eqnarray*} \end{multicols} \begin{tikzpicture} \tkzTabInit{$x$ / 1 , $f(x)$ / 2}{$1$, $3$} \tkzTabVar{+/ $5$, -/ $-11$} \end{tikzpicture} \item[1f.] La valeur minimale de $f$ sur l'intervale $[1 ; 3]$ est atteinte en $3$ et vaut $-11$. La valeur maximale de $f$ sur l'intervale $[1 ; 3]$ est atteinte en $1$ et vaut $5$. \end{enumerate} \newpage \subsection{$3. - f(x) = 4x^2 - 4x + 1$} \begin{enumerate} \item[3a.] Résoudre $4x^2 - 4x + 1$\\ calcul du discriminant : \begin{eqnarray*} \Delta &=& (-4)^2 - 4*4*1\\ &=& 16 - 16\\ &=& 0 \end{eqnarray*} Comme $\Delta = 0$, l'équation $f(x) =0 $ admet un solution double en $\dfrac{-b}{2a}$ \begin{eqnarray*} \dfrac{-b}{2a} &=& \dfrac{4}{2 \times 4} \\ &=& \dfrac{1}{2} \end{eqnarray*} L'équation $f(x) = 0$ admet une solution double en $x = \dfrac{1}{2}$. \item[3b.] Comme le disciminant est nul, $f$ est du signe de $a=4$ donc positif. $f$ est nulle en $\dfrac{1}{2}$ \begin{tikzpicture} \tkzTabInit{$x$ / 1 , $f(x)$ / 1}{$-\infty$, $\dfrac{1}{2}$, $+\infty$} \tkzTabLine{,+, z, +, } \end{tikzpicture} \item[3c.] $\dfrac{1}{2}$ est une racine double et $a=4$. La fonction s'écrit sous forme factorisée : $f(x) = 4 \left( x-\dfrac{1}{2} \right)^2$ \end{enumerate} \newpage \subsection{$4. - f(x) = x^2 - 7x + 3$} \begin{enumerate} \item[4a.] calcul du discriminant : \begin{eqnarray*} \Delta &=& (-7)^2 - 4*1*3\\ &=& 49 - 12\\ &=& 37 \end{eqnarray*} Comme $\Delta > 0$, l'équation $f(x) =0 $ admet deux solutions. \begin{eqnarray*} x_1 &=& \dfrac{7 - \sqrt{37}}{2} \\ x_2 &=& \dfrac{7 + \sqrt{37}}{2} \end{eqnarray*} (ici, on ne va surtout pas chercher à simplifier car $\sqrt{37}$ ne mène nulle part, après si on a une calculatrice, c'est intéressant de calculer les valeurs approchées. ici $x_1 \approx 0.45$ et $x_2 \approx 6.5$ ) \item[4b.] Comme $a = 1$, la fonction $f$ est décroissante jusqu'à $\dfrac{-b}{2a}$ puis croissante.\\ On calcule $f(0)$, $f(5)$ et $f(\frac{-b}{2a})$. \begin{multicols}{2} \begin{eqnarray*} \frac{-b}{2a} &=& \frac{7}{2} \\ f(\frac{7}{2}) &=& (\frac{7}{2})^2 -7 \times (\frac{7}{2}) + 3 \\ f(\frac{7}{2}) &=& \frac{49}{4} - \frac{49}{2} + 3 \\ f(\frac{7}{2}) &=& \frac{49}{4} - \frac{98}{4} + \frac{12}{4} \\ f(\frac{7}{2}) &=& \frac{-37}{4} \\ f(\frac{7}{2}) &\approx& -9.25 \end{eqnarray*} (On peut se rappeler que $\frac{-b}{2a}$, l'extremum de notre parabole est entre les deux racines.) \begin{eqnarray*} f(0) &=& 0^2 -7 \times 0 + 3 \\ f(0) &=& 3 \end{eqnarray*} \begin{eqnarray*} f(5) &=& 5^2 -7 \times 5 + 3 \\ f(5) &=& 25 - 35 + 3 \\ f(5) &=& -7 \end{eqnarray*} \end{multicols} \begin{tikzpicture} \tkzTabInit{$x$ / 1 , $f(x)$ / 2}{$0$, $\dfrac{7}{2}$, $5$} \tkzTabVar{+/ $3$, -/ $\dfrac{-37}{4}$, +/ $-7$} \end{tikzpicture} \item[4b.] À partir du tableau de variation. La valeur minimale de $f$ sur l'intervale $[0 ; 5]$ est atteinte en $\dfrac{7}{2}$ et vaut $\dfrac{-37}{4}$. La valeur maximale de $f$ sur l'intervale $[0 ; 5]$ est atteinte en $0$ et vaut $3$. \end{enumerate} \newpage \section{Exercice 8} \begin{enumerate} \item[1.] ($(x^n)' = n \times x^{n-1} $) \begin{eqnarray*} f(x) &=& 3x^2 - 5x + 2 \\ f'(x) &=& 3 \times 2 \times x - 5 \\ f'(x) &=& 6x - 5 \end{eqnarray*} \item[2.] \begin{eqnarray*} f(x) &=& x^3 - 3x + 1 \\ f'(x) &=& 3 x^2 - 3 \end{eqnarray*} \item[3.] (du type ( $\frac{1}{v})' = -\frac{v'}{v^2}$ ) \begin{eqnarray*} f(x) &=& \dfrac{1}{2x + 1} \\ f'(x) &=& -\dfrac{2}{(2x + 1)^2} \end{eqnarray*} \item[4.] (du type ( $\frac{u}{v})' = \frac{u'v-v'u}{v^2}$ ) \begin{eqnarray*} f(x) &=& \dfrac{3x - 1}{6x - 7} \\ \text{on a } u = 3x - 1 \text{ donc } u'= 3\\ \text{et on a } v = 6x - 7 \text{ donc } v'= 6\\ f'(x) &=& \dfrac{3 \times (6x - 7) - 6 \times (3x - 1)}{(6x-7)^2}\\ f'(x) &=& \dfrac{(18x - 21) - (18x - 6)}{(6x-7)^2}\\ f'(x) &=& \dfrac{18x - 21 - 18x + 6}{(6x-7)^2}\\ f'(x) &=& \dfrac{-15}{(6x-7)^2}\\ \end{eqnarray*} \end{enumerate} \newpage \section{Exercice 9} (Je ne peux pas faire les question 1, je n'ai pas l'énoncé) \begin{enumerate} \item[2b.] \begin{eqnarray*} g(x) &=& 20 + \dfrac{16000}{x} \\ g'(x) &=& -\dfrac{16000}{x^2} \end{eqnarray*} \item[2c.] Sur l'intervale $[1 ; 1500]$, $x^2 > 0$ donc $g'(x) < 0$ \item[2d.] \begin{eqnarray*} g(1) &=& 20 + 16000\\ g(1) &=& 16020 \end{eqnarray*} \begin{eqnarray*} g(1500) &=& 20 + \dfrac{16000}{1500}\\ g(1500) &=& 20 + \dfrac{160}{15}\\ g(1500) &=& 20 + \dfrac{32}{3}\\ g(1500) &=& \dfrac{60}{3} + \dfrac{32}{3}\\ g(1500) &=& \dfrac{92}{3}\\ g(1500) &\approx& 30.6 \end{eqnarray*} \begin{tikzpicture} \tkzTabInit{$x$ / 1 , $g'(x)$ / 1, $g$ / 2}{$1$, $1500$} \tkzTabLine{,-, } \tkzTabVar{+/ $16020$, -/ $\dfrac{92}{3}$} \end{tikzpicture} \end{enumerate} \end{document} <file_sep>def hello(repetition): for i in range( 0, repetition): print("-------- Hello World !!! ---------") return(1) hello(10)<file_sep>## Pile ou Face Une pièce avec deux côtés : Pile et Face est lancée en l'air par un lanceur et retombe sur une de ses deux faces. L'adversaire doit deviner la face sur laquelle va tomber une pièce. Pour pimenter un peu le jeu, on permet au lanceur d’allègrement tricher en choisissant de son plein grès la face sur laquelle la pièce va tomber. Ce résultat est intégrée dans un fichier composé de ligne avec soit 0 pour pile ou soit 1 pour face. L'adversaire découvre alors en jouant le résultat de chaque partie. Il lui revient alors la possibilité, que dis-je la nécessité de s'adapter à son adversaire pour tenter de gagner le plus de partie possible. <file_sep>// <NAME> function [fon_exo3] = F_fon_exo3(x) fon_exo3=abs(log(x)) endfunction fon_exo3= F_fon_exo3 function [U_n] = f_rec(U_0,n) i=0 U_n=U_0 while i<n U_n=F_fon_exo3(U_n) i=i+1 end endfunction [U_n] = f_rec k=1.5:0.005:2.5; plot2d(k,U_n(k,30)) <file_sep># Implémentation d'une pile de hauteur 4 à partir de la structure listes class list4: """Gestion de la *pile / liste* : - sa pile""" def __init__(self): """Constructeur de notre classe - Les 4 registres sont mis à 0 """ self.list4 = [0.0, 0.0, 0.0, 0.0] def affiche(self): print("T: ",self.list4[3]) print("Z: ",self.list4[2]) print("Y: ",self.list4[1]) print("X: ",self.list4[0]) def empile(self, valeur): self.list4.insert(0, valeur) self.list4.pop() def depile(self): self.list4.append(self.list4[len(self.list4)-1]) self.list4.pop(0) # avec un tempon def swap(self): self.list4[0] = self.list4[0] + self.list4[1] self.list4[1] = self.list4[0] - self.list4[1] self.list4[0] = self.list4[0] - self.list4[1] def fhaut(self): self.empile(self.list4[3]) def fbas(self): temp = self.list4[0] self.depile() self.list4[3] = temp def additioner(self): self.list4[1] += self.list4[0] self.depile() def soustraire(self): self.list4[1] -= self.list4[0] self.depile() def multiplier(self): self.list4[1] *= self.list4[0] self.depile() def diviser(self): self.list4[1] /= self.list4[0] self.depile() """ soustraire multiplier diviser diviser swap fhaut fbas """ <file_sep>\documentclass[11pt]{article} \usepackage{geometry} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,francais]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx, float} \usepackage{tikz,tkz-tab} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} % No page header \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height %---------------------------------------------------------------------------------------- % Début du document %---------------------------------------------------------------------------------------- \begin{document} %---------------------------------------------------------------------------------------- % RE-DEFINITION %---------------------------------------------------------------------------------------- % MATHS %----------- \newtheorem{Definition}{Définition} \newtheorem{Theorem}{Théorème} \newtheorem{Proposition}{Propriété} % MATHS %----------- \renewcommand{\labelitemi}{$\bullet$} \renewcommand{\labelitemii}{$\circ$} %---------------------------------------------------------------------------------------- % Titre %---------------------------------------------------------------------------------------- \setlength{\columnseprule}{1pt} \section{Suites} La suite est-elle monotone correspond à la question des variations d'une fonction. Sauf qu'étudier une suite est un poil plus complexe alors on se contente de demander : est-elle monotone ? on ne peut répondre que trois choses : \begin{itemize} \item oui ; croissante. ($u_{n+1} > u_n$) \item oui ; décroissante. ($u_{n+1} < u_n$) \item non. \end{itemize} Cela revient à essayer d'ordonner $u_{n+1}$ et $u_n$. Pour cela plusieurs techniques. \begin{itemize} \item calculer $u_{n+1} - u_n$. Si on tombe sur un nombre (sans n). On peut conclure. positif = croissant ; négatif ) décroissant. On fait toujours ça dans le cadre des suites arithmétiques. \item calculer $\dfrac{u_{n+1}}{u_n}$. Un peu plus complexe comme cas (car il faut faire gaffe au nombre négatif), mais en gros si > 1 alors croissant. On fait toujours ça dans le cadre des suites géométriques. \end{itemize} Ici sur les suites, géométriques et arithmétiques, il y a un peu de cours. Genre les variations sont immédiates dès qu'on connaît le premier terme et la raison. \newpage \begin{multicols}{2} \section{exercice 2} \begin{enumerate} \item[1a.] \begin{eqnarray*} u_{n+1} &=& u_n + r \\ u_n &=& u_0 + nr \\ u_n &=& 5 + n \times (-3)\\ u_n &=& 5 - 3n \end{eqnarray*} \item[1b.] \begin{eqnarray*} u_{30} &=& u_0 + 30 \times r \\ u_{30} &=& 5 - 30 \times 3\\ u_{30} &=& 5 - 90\\ u_{30} &=& -85 \end{eqnarray*} \item[1c.] \begin{eqnarray*} u_{n+1} - u_n &=& r \\ u_{n+1} - u_n &=& -3 \end{eqnarray*} Donc $u_{n+1} < u_n$. La suite est monotone et décroissante. \end{enumerate} \end{multicols} \horrule{1px} \begin{multicols}{2} \begin{enumerate} \item[2a.] \textit{ (ici, il faut faire attention car on part du rang 1 et non 0.)} \begin{eqnarray*} v_{n+1} &=& v_n + r \\ v_n &=& v_1 + (n-1) \times r \\ v_n &=& \dfrac{4}{5} + (n-1) \times \dfrac{2}{5} \end{eqnarray*} \item[2b.] \begin{eqnarray*} v_{30} &=& v_1 + (30-1) \times r \\ v_{30} &=& \dfrac{4}{5} + (30-1) \times \dfrac{2}{5}\\ v_{30} &=& \dfrac{4}{5} + 29 \times \dfrac{2}{5}\\ v_{30} &=& \dfrac{4}{5} + \dfrac{58}{5}\\ v_{30} &=& \dfrac{20}{15} + \dfrac{174}{15}\\ v_{30} &=& \dfrac{194}{15} \end{eqnarray*} \item[2c.] \begin{eqnarray*} v_{n+1} - v_n &=& r \\ v_{n+1} - v_n &=& \dfrac{2}{5} \end{eqnarray*} Donc $v_{n+1} > v_n$. La suite est monotone et croissante. \end{enumerate} \end{multicols} \horrule{1px} \begin{multicols}{2} \begin{enumerate} \item[3a.] \textit{ (ici, il faut faire attention car on part du rang 1 et non 0.)} \begin{eqnarray*} w_{n+1} &=& w_n \times q \\ w_n &=& w_1 \times q^{n-1} \\ w_n &=& -2 \times 3^{n-1} \end{eqnarray*} Étude du signe de $w_n$. \begin{eqnarray*} 3 &>& 0 \\ 3^{n-1} &>& 0 \\ -2 \times 3^{n-1} &<& 0 \\ w_n &<& 0 \end{eqnarray*} $w_n$ est négatif. \item[3b.] \begin{eqnarray*} w_{50} &=& w_1 \times q^{50-1} \\ w_{50} &=& -2 \times 3^{49} \end{eqnarray*} \item[3c.] \begin{eqnarray*} \dfrac{w_{n+1}}{w_n} &=& q \\ \dfrac{w_{n+1}}{w_n} &=& 3 \end{eqnarray*} La suite est monotone. Comme le premier terme est $w_1 = -2$ est négatif. La suite est décroissante. \end{enumerate} \end{multicols} \horrule{1px} \begin{multicols}{2} \begin{enumerate} \item[4a.] \begin{eqnarray*} t_{n+1} &=& t_n \times q \\ t_n &=& t_0 \times q^n \\ t_n &=& 1000 \times \left(-\dfrac{1}{2} \right)^n \end{eqnarray*} Étude du signe de $t_n$. \begin{eqnarray*} 1000 &>& 0 \\ \left(-\dfrac{1}{2} \right) &<& 0 \\ \left(-\dfrac{1}{2} \right)^n &>& 0 \text{ si n est pair.} \\ \left(-\dfrac{1}{2} \right)^n &<& 0 \text{ sinon.} \end{eqnarray*} Le signe de la suite change à chaque rang. La suite est positive quand le rang est pair, et négative quand le rang est impair. \item[4b.] \begin{eqnarray*} t_{50} &=& t_0 \times q^{50} \\ t_{50} &=& 1000 \times \left(-\dfrac{1}{2} \right)^{50} \\ t_{50} &=& 1000 \times \dfrac{1}{2^{50}} \end{eqnarray*} \item[4c.] La suite est géométrique de raison $q = -\dfrac{1}{2}$. Les termes de la suite change donc de signe au rang suivant. La suite n'est donc pas monotone. (Elle converge par contre vers 0.) \end{enumerate} \end{multicols} \newpage \begin{multicols}{2} \section{exercice 3} \begin{enumerate} \item[1.] \begin{eqnarray*} u_0 &=& \dfrac{3n - 7}{2n + 3} \\ u_0 &=& \dfrac{- 7}{3} \end{eqnarray*} \begin{eqnarray*} u_1 &=& \dfrac{3n - 7}{2n + 3} \\ u_1 &=& \dfrac{3 - 7}{2 + 3} \\ u_1 &=& \dfrac{- 4}{5} \\ \end{eqnarray*} \begin{eqnarray*} u_2 &=& \dfrac{3n - 7}{2n + 3} \\ u_2 &=& \dfrac{3\times 2 - 7}{2\times 2 + 3} \\ u_2 &=& \dfrac{6 - 7}{4 + 3} \\ u_2 &=& \dfrac{- 1}{7} \\ \end{eqnarray*} \begin{eqnarray*} u_5 &=& \dfrac{3n - 7}{2n + 3} \\ u_5 &=& \dfrac{3\times 5 - 7}{2\times 5 + 3} \\ u_5 &=& \dfrac{15 - 7}{10 + 3} \\ u_5 &=& \dfrac{8}{13} \end{eqnarray*} \end{enumerate} \end{multicols} \begin{enumerate} \item[2.] Ici, on est sur une suite un peu plus originale. Il faut un peu plus chercher à la main. \begin{eqnarray*} u_{n+1} - u_n &=& \dfrac{3(n+1) - 7}{2(n+1) + 3} - \dfrac{3n - 7}{2n + 3}\\ u_{n+1} - u_n &=& \dfrac{3n - 4}{2n + 5} - \dfrac{3n - 7}{2n + 3}\\ \textit{On met sur le même dénominateur.} \\ u_{n+1} - u_n &=& \dfrac{(3n - 4)(2n + 3)}{(2n + 5)(2n + 3)} - \dfrac{(3n - 7)(2n + 5)}{(2n + 3)(2n + 5)}\\ u_{n+1} - u_n &=& \dfrac{(3n - 4)(2n + 3) - (3n - 7)(2n + 5)}{(2n + 5)(2n + 3)} \end{eqnarray*} \textit{On simplifie le numérateur. Ici, c'est parfois une bonne astuce en terme de gain de temps et d'emmerdement de ne s'occuper que de la partie qui nous intéresse. On reviendra au reste après. Mais ça évite de se balader avec une fraction pour la simplification.} \begin{eqnarray*} (3n - 4)(2n + 3) - (3n - 7)(2n + 5) &=& (6n^2 + 9n - 8n - 12) - (6n^2 + 15n - 14n - 35) \\ &=& (6n^2 + n - 12) - (6n^2 + n - 35) \\ &=& -12 - (-35) \\ &=& -12 + 35 \\ &=& 23 \\ \end{eqnarray*} Donc $u_{n+1} - u_n = \dfrac{23}{(2n + 5)(2n + 3)}$. \begin{eqnarray*} 2n + 5 &>& 0 \\ 2n + 3 &>& 0 \\ 23 &>& 0 \\ \dfrac{23}{(2n + 5)(2n + 3)} &>& 0 \\ u_{n+1} - u_n &>& 0 \end{eqnarray*} La suite est croissante. \end{enumerate} \newpage \begin{multicols}{2} \section{exercice 4} \begin{enumerate} \item[1.] \begin{eqnarray*} u_1 &=& u_{0}^{2} - 2u_0 + 3 \\ u_1 &=& 1 - 2 + 3 \\ u_1 &=& 2 \end{eqnarray*} \begin{eqnarray*} u_2 &=& u_{1}^{2} - 2u_1 + 3 \\ u_2 &=& 2^2 - 2 \times 2 + 3 \\ u_2 &=& 4 - 4 + 3 \\ u_2 &=& 3 \end{eqnarray*} Ici, on est obligé de calculer les rang 3 et 4. \begin{eqnarray*} u_3 &=& u_{2}^{2} - 2u_2 + 3 \\ u_3 &=& 3^2 - 2 \times 3 + 3 \\ u_3 &=& 9 - 6 + 3 \\ u_3 &=& 6 \end{eqnarray*} \begin{eqnarray*} u_4 &=& u_{3}^{2} - 2u_3 + 3 \\ u_4 &=& 6^2 - 2 \times 6 + 3 \\ u_4 &=& 36 - 12 + 3 \\ u_4 &=& 27 \end{eqnarray*} pas très drôle à calculer sans calculatrice... $(27 \times 25 + 3)$ \begin{eqnarray*} u_5 &=& u_{4}^{2} - 2u_4 + 3 \\ u_5 &=& 27^2 - 2 \times 27 + 3 \\ u_5 &=& 678 \end{eqnarray*} \item[2.] Je n'aime pas trop ces questions : sans calcul mais en justifiant... On ne sait jamais trop ce qu'on veut.\\ En s'appuyant sur le trinôme du second degré : $x^2 -2x +3$. Le coefficient du carré est positif. De plus $u_0 = 1$.\\ La suite semble croissante et a termes positifs. \item[3a.] \begin{eqnarray*} u_{n+1} - u_n &=& u_{n}^{2} - 2u_n + 3 - u_n\\ u_{n+1} - u_n &=& u_{n}^{2} - 3u_n + 3 \end{eqnarray*} \item[3b.] Soit $f(x) = x^2 -3x + 3$. (Pour étudier le signe, nulle besoin de passer par la dérivée. Ici, on utilise plus la forme général et passe par le discriminant.) \begin{eqnarray*} \Delta &=& b^2 - 4ac \\ \Delta &=& (-3)^2 - 4 \times 1 \times 3 \\ \Delta &=& 9 - 12 \\ \Delta &=& -3 \end{eqnarray*} L'équation $f(x) = 0$ n'a pas de racine réèlle. $f(x)$ est donc du signe de $a$. Donc $f(x) > 0$ pour tout $x$ réel. \item[3c.] \begin{eqnarray*} f(x) &>& 0 \\ u_{n+1} - u_n &>& 0 \\ \text{donc } u_{n+1} > u_n \end{eqnarray*} La suite est croissante. \item[3d.] La suite est croissante et le premier terme est $u_0 = 1$ est positif. La suite est à termes tous positifs. \end{enumerate} \end{multicols} \newpage \begin{multicols}{2} \section{exercice 5} La lecture de l'énoncé est ici un peu plus complexe et prend un peu plus de temps. Il faut faire attention car la suite correspond à une proportion et non à un nombre de personne. De plus, on s'intéresse au nombre de non-fumeurs. Les calculs sont un peu cotons par contre, sans calculatrice, c'est pas une partie de plaisir... \begin{enumerate} \item[1.] On a au départ 2000 fumeurs. Au premier jour, 1600 fument encore. Donc 400 ne fument pas / plus. \begin{eqnarray*} p_1 &=& \dfrac{400}{2000} \\ p_1 &=& 0.2 \end{eqnarray*} \begin{eqnarray*} p_2 &=& -0.6 p_1 + 0.9 \\ p_2 &=& -0.6 \times 0.2 + 0.9 \\ p_2 &=& -0.12 + 0.9 \\ p_2 &=& 0.78 \end{eqnarray*} \item[2a.] La question est un poil plus dur que d'habitude. Je suis redevenue à la définition.\\ Montrons que $u_{n+1} = -0.6 u_n$. \begin{eqnarray*} u_n &=& p_n - 0.5625 \\ -0.6 u_n &=& -0.6(p_n - 0.5625) \\ -0.6 u_n &=& -0.6p_n + 0.3375 \\ u_{n+1} &=& p_{n+1} - 0.5625 \\ u_{n+1} &=& -0.6 p_n + 0.9 - 0.5625 \\ u_{n+1} &=& -0.6 p_n + 0.3375 \\ \end{eqnarray*} Donc $u_{n+1} = -0.6 u_n$. \begin{eqnarray*} u_1 &=& p_1 - 0.5625 \\ u_1 &=& 0.2 - 0.5625 \\ u_1 &=& - 0.3625 \\ \end{eqnarray*} La suite $(u_n)$ est géométrique de raison $-0.6$. \item[2b.] \begin{eqnarray*} u_n &=& u_1 \times q^{n-1} \\ u_n &=& -0.3625 \times (-0.6)^{n-1} \end{eqnarray*} \item[3.] \begin{eqnarray*} u_n &=& p_n - 0.5625 \\ p_n &=& u_n + 0.5625 \\ p_n &=& -0.3625 \times (-0.6)^{n-1} + 0.5625 \\ \end{eqnarray*} \end{enumerate} \end{multicols} \begin{enumerate} \item[4a.] \begin{eqnarray*} p_{n+1} - p_n &=& ( -0.3625 \times (-0.6)^{n} + 0.5625) - ( -0.3625 \times (-0.6)^{n-1} + 0.5625) \\ p_{n+1} - p_n &=& -0.3625 \times (-0.6)^{n} + 0.3625 \times (-0.6)^{n-1} \\ p_{n+1} - p_n &=& (-0.6)^{n-1} \times (-0.3625 \times (-0.6) + 0.3625 ) \\ p_{n+1} - p_n &=& (-0.6)^{n-1} \times (-0.3625 \times (-0.6 + 1) \\ p_{n+1} - p_n &=& (-0.6)^{n-1} \times 0.58 \\ \end{eqnarray*} \item[4b.] $(-0.6)^{n-1}$ change de signe à chaque rang. $(-0.6)^{n-1} < 0$ si n est pair et $(-0.6)^{n-1} > 0$ sinon. La suite n'est pas monotone. \item[4c.] \begin{eqnarray*} p_{25} &=& -0.3625 \times (-0.6)^{25-1} + 0.5625 \\ p_{25} &\approx& 0.5625 \end{eqnarray*} \item[5a.] Les questions sont ici assez ouvertes. Je ne suis pas certain de ce dont ils veulent. \\ Au fil des jours, la proportion de non-fumeurs augmente de façon non monotone jusqu'à se stabiliser vers 0.5625. \item[5b.] La proportion se stabilise vers 0.5625. Avec une population de départ de 2000. Il y a à la fin de l'enquête 1125 non fumeurs. \\ $2000 \times 0.5625 = 1125$ \\ Ce nombre est stable au jour le jour mais ne représente pas le nombre de personne ayant arrêté de fumer. Il représente le nombre de personne ne fumant pas à un jour précis. En effet dans ce nombre, certain reprendront le lendemain alors que d'autre fumant aujourd'hui s’arrêteront demain et peut-être reprendront juste après... Ces nombres se compensent. Du coup, cette enquête ne donne pas une réponse précise sur les personnes ayant arrêtées de fumer sur le long terme. \end{enumerate} \end{document} <file_sep>//Liste des fonctions utilisées pour le TP function [fon_sqrt]= F_fon_sqrt(x) fon_sqrt=sqrt(x) endfunction function [fon_abs]= F_fon_abs(x) fon_abs=abs(x) endfunction function [fon_xpuisn]= F_xpuisn(x,n) fon_xpuisn=x**n endfunction function [fon_car]= F_fon_car(x) fon_car=1-3*x+x^2 endfunction <file_sep>\documentclass[12pt]{article} \usepackage{geometry} \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,french]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx,float,grffile} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} \fancyfoot{} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0pt} \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height %---------------------------------------------------------------------------------------- % Début du document %---------------------------------------------------------------------------------------- \begin{document} %$$=101 325 - 920 \times 9,81 \times (-1) \times 7\times 10^{-2} = 101 389,4‬‬$$ % Ta ligne qui ne passe pas... $$101 325 - 920 \times 9,81 \times (-1) \times 7 \times 10^{-2} = 101 389,4$$ $$101\,325 - 920 \times 9{,}81 \times (-1) \times 7 \times 10^{-2} = 101\, 389{,}4$$ \end{document} <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 5 : - Le plus petit nombre qui est divisible par tous les entiers compris entre 1 et 20. ----------------------------------------------------------------- - Fonctions 1 et 2 issues du problème 3. - - EstPremier et ProchainPremier - Cacule de la puissance des nombres premiers inférieurs à 20 ----------------------------------------------------------------- """ # True si aNombre est premier def EstPremier(aNombre): if aNombre == 2: estPremier = True elif aNombre % 2 == 0: estPremier = False else: p = 3 estPremier = True miNombre = aNombre // 2 while (p < miNombre and estPremier): if aNombre % p == 0: estPremier = False else: p +=2 return estPremier # Le prochain nombre premier def ProchainPremier(aNombre): suivPremier = aNombre +1 while(not EstPremier(suivPremier)): suivPremier += 1 return(suivPremier) # Cacule de la puissance des nombres premiers inférieurs à aNombre def maxFactor(aNombre): lstfact = [] p = ProchainPremier(1) i = 0 maxfact = 1 # Parcours des nombres premiers while p < aNombre: lstfact.append(p) alpha = p # Maximise les facteurs while(lstfact[i] * alpha < aNombre): lstfact[i] = lstfact[i] * alpha p = ProchainPremier(p) # Effectue le produit maxfact *= lstfact[i] i += 1 return maxfact # Main print("min facteur",maxFactor(100)) <file_sep>#include "Cellule.cpp" #include "Plateau.cpp" void testCellule() { Cellule cell; std::cout << "Sortie standart pour une cellule : "<< cell << std::endl; Cellule cell1(0); std::cout << "Sortie standart pour une cellule morte : "<< cell1 << std::endl; Cellule cell2(1); std::cout << "Sortie standart pour une cellule en vie : "<< cell2 << std::endl; Cellule cell3 = cell2; std::cout << "Sortie standart pour une cellule en vie à partir de la copie : "<< cell2 << std::endl; } int main() { testCellule(); Plateau p1(3); Plateau p2(true); p2.show(); p2.showTotal(); std::cout << "p2" << std::endl; std::copy(p2.plateau.begin(), p2.plateau.end(), std::ostream_iterator<Cellule>(std::cout, ", ") ); std::cout << std::endl; Plateau p3 = p2.Evolution(); std::cout << "Expected" << std::endl; std::copy(p3.plateau.begin(), p3.plateau.end(), std::ostream_iterator<Cellule>(std::cout, ", ") ); std::cout << std::endl; p3.showTotal(); p3.show(); p3 = p2.Evolution(2); std::cout << "Expected" << std::endl; std::copy(p3.plateau.begin(), p3.plateau.end(), std::ostream_iterator<Cellule>(std::cout, ", ") ); std::cout << std::endl; p3.showTotal(); p3.show(); } <file_sep># Project Euler Ce dépot contiendra des solutions aux problèmes posés sur [Project Euler](http://projecteuler.net/about). J'utile un makefile : **make pb1** pour executer le programme correspondant au premier problème. Les remarques propres au problème sont à la fois dans le fichier et dans la pull-request (une par problème). ## Problèmes résolus - [Problème 1](https://github.com/homeostasie/Project-Euler/pull/2) - Sommme des entiers multiples de 3 ou 5. - [Problème 2](https://github.com/homeostasie/Project-Euler/pull/3) - Sommme des entiers pairs de Fibonacci. - [Problème 3](https://github.com/homeostasie/Project-Euler/pull/4) - Plus grand facteur premier. - [Problème 4](https://github.com/homeostasie/Project-Euler/pull/5) - Plus grand palindrome issue du produit de deux facteurs compris entre 100 et 999. - Problème 5 - Plus petit entier divisible par tous les nombres compris entre 1 et 20. - Problème 6 - Différence de sommme de carrés - Problème 7 - 10001-ième nombre premier - Problème 8 - Plus grand produit de 5 chiffres consécutifs dans un nombre. - Problème 9 - a + b + c = 1000 et a² + b² = c² - Problème 10 - Somme des nombres premiers inférieur à 10 millions. ## Langages utilisés ### Python 3 [8] - Problème 1 - 8 <file_sep>\input{doc-class-cours.tex} \begin{document} Learn the basics of Go, an open source programming language originally developed by a team at Google and enhanced by many contributors from the open source community. This course is designed for individuals with previous programming experience using such languages as C, Python, or Java, and covers the fundamental elements of Go. Topics include data types, protocols, formats, and writing code that incorporates RFCs and JSON. Most importantly, you’ll have a chance to practice writing Go programs and receive feedback from your peers. Upon completing this course, you'll be able to implement simple Go programs, which will prepare you for subsequent study at a more advanced level. \section*{Semaine 1} \subsection*{Introduction to the Specialization} \begin{itemize}[label={$\bullet$}] \item Reading: Specialization Overview \end{itemize} \subsection*{Introduction to the Course} \begin{itemize}[label={$\bullet$}] \item Vidéo: Welcome to the Course \item Reading: Go Documentation \end{itemize} \subsection*{Module 1: Getting Started with Go} This first module gets you started with Go. You'll learn about the advantages of using Go and begin exploring the language's features. Midway through the module, you’ll take a break from "theory" and install the Go programming environment on your computer. At the end of the module, you'll write a simple program that displays “Hello, World” on your screen. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Vidéo: Module 1 Overview \item Vidéo: M1.1.1 - Why Should I Learn Go ? (Advantages of Go) \item Vidéo: M1.1.2 - Objects \item Vidéo: M1.1.3 - Concurrency \item Vidéo: M1.2.1 - Installing Go \item Vidéo: M1.2.2 - Workspaces \& Packages \item Vidéo: M1.2.3 - Go Tool \item Vidéo: M1.3.1 - Variables \item Vidéo: M1.3.2 - Variable Initialization \item Noté: Module 1 Activity: "Hello, world!" \item Noté: Module 1 Quiz \end{itemize} \end{multicols} \section*{Semaine 2} \subsection*{Module 2: Basic Data Types} Now that you’ve set up your programming environment and written a test program, you’re ready to dive into data types. This module introduces data types in Go and gives you practice writing routines that manipulate different kinds of data objects, including floating-point numbers and strings. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Reading: STOP -Read This First! \item Vidéo: Module 2 Overview \item Vidéo: M2.1.1 - Pointers \item Vidéo: M2.1.2 - Variable Scope \item Vidéo: M2.1.3 - Deallocating Memory \item Vidéo: M2.1.4 - Garbage Collection \item Vidéo: M2.2.1 - Comments, Printing, Integers \item Vidéo: M2.2.2 - Ints, Floats, Strings \item Vidéo: M2.2.3 - String Packages \item Vidéo: M2.3.1 - Constants \item Vidéo: M2.3.2 - Control Flow \item Vidéo: M2.3.3 - Control Flow, Scan \item Noté: Module 2 Activity: trunc.go \item Noté: Module 2 Activity: findian.go \item Noté: Module 2 Quiz \end{itemize} \end{multicols} \section*{Semaine 3} \subsection*{Module 3: Composite Data Types} At this point, we’re ready to move into more complex data types, including arrays, slices, maps, and structs. As in the previous module, you’ll have a chance to practice writing code that makes use of these data types. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Vidéo: Module 3 Overview \item Vidéo: M3.1.1 - Arrays \item Vidéo: M3.1.2 - Slices \item Vidéo: M3.1.3 - Variable Slices \item Vidéo: M3.2.1 - Hash Tables \item Vidéo: M3.2.2 - Maps \item Vidéo: M3.3.1 - Structs \item Noté: Module 3 Activity: slice.go \item Noté: Module 3 Quiz \end{itemize} \end{multicols} \section*{Semaine 4} \subsection*{Module 4: Protocols and Formats} This final module of the course introduces the use of remote function calls (RFCs) and JavaScript Object Notation (JSON) in Go. You’ll learn how to access and manipulate data from external files, and have an opportunity to write several routines using Go that exercise this functionality. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Vidéo: Module 4 Overview \item Vidéo: M4.1.1 - RFCs \item Vidéo: M4.1.2 - JSON \item Vidéo: M4.2.1 - File Access, ioutil \item Vidéo: M4.2.2 - File Access, os \item Noté: Module 4 Activity: makejson.go \item Noté: Final Course Activity: read.go \end{itemize} \end{multicols} \end{document}<file_sep>#include <iostream> #include <vector> #include <iterator> /** * Classe de base du programme. * Elle définit une cellule qui évolue au cours du temps. */ class Cellule { private: int vie; public: /** * Constructeur par défaut */ Cellule():vie(0) {} /* * Constructeur standart * @param i valeur booléenne à appliquer */ Cellule(const int tonInt):vie(tonInt) {} /** * Constructeur par copie * @param c autre cellule à copier */ Cellule(const Cellule& cell): vie(cell.statut()) {} /* * Destructeur par défaut */ ~Cellule() {} private: /** * Accéder au statut. * @return le statut de la cellule. */ bool statut() const { return vie == 1?true:false; } int presence() const{ return vie;} public: /** * Accéder au statut */ bool Estenvie() const { return vie == 1?true:false; } int EstPresent() const{ return vie;} /** * Sortie standart pour une cellule */ Cellule operator+(const Cellule cell) { return (Cellule(vie + cell.presence())); } Cellule operator+=(const Cellule cell) { vie += cell.presence(); return( *this ); } /** * Sortie standart pour une cellule */ friend std::ostream& operator<<(std::ostream& out, const Cellule& cell ) { if (cell.statut() == false) { out << "o"; } else { out << "+"; } return(out); } }; <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 6 : - La différence entre le carré de la somme des cents premiers entiers et la somme des cents premiers entiers au carré. ----------------------------------------------------------------- - Fonction 1 : Carré de la somme - Fonction 2 : Somme des carrés ----------------------------------------------------------------- """ # def carreSomme(aLast): return (aLast*(aLast+1)//2)*(aLast*(aLast+1)//2) # Le prochain nombre premier def sommeCarre(aLast): return (2*aLast + 1)*(aLast + 1)*aLast//6 def diffopti(aLast): return aLast*(aLast + 1)*(3*aLast*aLast - aLast -2)//12 # Main #print(carreSomme(100) - sommeCarre(100)) print(diffopti(100)) <file_sep>\input{doc-class-cours.tex} \begin{document} Partez à la découverte de l'infiniment grand et de l'infiniment petit dans leurs aspects les plus proches de notre quotidien, en compagnie de physiciens et de physiciennes qui vont vous faire découvrir leur présence insoupçonnée dans notre vie de tous les jours. Vous vous initierez à la vie et aux métiers d'une grande collaboration en physique de l'infiniment petit et de l'infiniment grand, vous découvrirez comment les outils développés dans ces domaines ont trouvé des applications inattendues, comment la physique nucléaire a profondément modifié les domaines de l'énergie et de la santé, et comment les propriétés de certaines particules aident à présent d'autres disciplines à sonder la matière d'une manière totalement différente. \section*{Semaine 1 - Des Infinis et des Hommes} \textit{Ce module s'intéresse à la nature de la recherche fondamentale et à ses liens avec notre quotidien. Il aborde aussi la manière dont travaillent les hommes et les femmes qui participent aux progrès de la connaissance.} \begin{itemize}[label={$\bullet$}] \item Vidéo : Deux infinis proches de nous \item Vidéo : Les grandes collaborations \item Vidéo : Les métiers de la recherche \end{itemize} \section*{Semaine 2 - Des technologies dans notre quotidien} \textit{Ce module décrit des technologies qui sont présentes dans notre quotidien et qui présentent des liens forts avec la physique de l'infiniment grand et de l'infiniment petit, tantôt par le biais des concepts, tantôt par celui des outils.} \begin{itemize}[label={$\bullet$}] \item Vidéo : Le GPS \item Vidéo : Les semi-conducteurs, du transistor aux détecteurs \item Vidéo : Du web au big data \end{itemize} \section*{Semaine 3 - De nouveaux regards sur le monde} \textit{Ce module montre comment les propriétés de certaines particules ont pu être exploitées pour mieux sonder la structure de la matière, en utilisant le rayonnement synchrotron, les neutrinos ou les muons.} \begin{itemize}[label={$\bullet$}] \item Vidéo : Neutrinos et muons, des particules pleines de ressources \item Vidéo : Le rayonnement synchrotron \end{itemize} \section*{Semaine 4 - Les noyaux au service de l'énergie et de la santé} \textit{Ce module décrit des applications importantes de la physique nucléaire afin de produire de l'énergie ou bien d'aider la recherche médicale par de nouvelles techniques d'imagerie et de soin.} \begin{itemize}[label={$\bullet$}] \item Vidéo : L'énergie nucléaire \item Vidéo : La médecine et les deux infinis \end{itemize} \end{document}<file_sep>\input{doc-class-cours.tex} \begin{document} Learn the basics of Go, an open source programming language originally developed by a team at Google and enhanced by many contributors from the open source community. This course is designed for individuals with previous programming experience using such languages as C, Python, or Java, and covers the fundamental elements of Go. Topics include data types, protocols, formats, and writing code that incorporates RFCs and JSON. Most importantly, you’ll have a chance to practice writing Go programs and receive feedback from your peers. Upon completing this course, you'll be able to implement simple Go programs, which will prepare you for subsequent study at a more advanced level. \section*{Semaine 1 - Introduction} \subsection*{Introduction to the Course} Learn the basics of Go, an open source programming language originally developed by a team at Google and enhanced by many contributors from the open source community. This is the first in a series of three courses comprising the Programming with Google Go specialization. It is designed for individuals with previous programming experience using such languages as C, Python, or Java, and covers the fundamental elements of Go. Topics include data types, protocols, formats, and writing code that incorporates RFCs and JSON. Most importantly, you’ll have a chance to practice writing Go programs and receive feedback from your peers. Upon completing this course, you’ll be able to implement simple Go programs, which will prepare you for the remaining two courses in this specialization: Functions, Methods, and Interfaces in Go and Concurrency in Go. \begin{itemize}[label={$\bullet$}] \item Welcome to the Course \item Reading: Go Documentation \end{itemize} \subsection*{Module 1: Getting Started with Go} This first module gets you started with Go. You'll learn about the advantages of using Go and begin exploring the language's features. Midway through the module, you’ll take a break from "theory" and install the Go programming environment on your computer. At the end of the module, you'll write a simple program that displays “Hello, World” on your screen. \begin{itemize}[label={$\bullet$}] \item Module 1 Overview \item M1.1.1 - Why Should I Learn Go? (Advantages of Go) \item M1.1.2 - Objects \item M1.1.3 - Concurrency \item M1.2.1 - Installing Go \item M1.2.2 - Workspaces \& Packages \item M1.2.3 - Go Tool \item M1.3.1 - Variables \item M1.3.2 - Variable Initialization \item Noté : Module 1 Activity: "Hello, world!" \item Noté : Module 1 Quiz \end{itemize} \newpage \section*{Semaine 2 - Basic Data Types} Now that you’ve set up your programming environment and written a test program, you’re ready to dive into data types. This module introduces data types in Go and gives you practice writing routines that manipulate different kinds of data objects, including floating-point numbers and strings. \begin{itemize}[label={$\bullet$}] \item Module 2 Overview \item M2.1.1 - Pointers \item M2.1.2 - Variable Scope \item M2.1.3 - Deallocating Memory \item M2.1.4 - Garbage Collection \item M2.2.1 - Comments, Printing, Integers \item M2.2.2 - Ints, Floats, Strings \item M2.2.3 - String Packages \item M2.3.1 - Constants \item M2.3.2 - Control Flow \item M2.3.3 - Control Flow, Scan \item Noté : Module 2 Activity: trunc.go \item Noté : Module 2 Activity: findian.go \item Noté : Module 2 Quiz \end{itemize} \end{document}<file_sep>\input{doc-class-cours.tex} \begin{document} \section*{Semaine 4 - The insides of giant planets (week 1)} \begin{itemize}[label={$\bullet$}] \item Vidéo : 2.01: Introduction to Jupiter \item Vidéo : 2.02: Measuring density \item Demande de discussion : Transit of Venus! \item Vidéo : 2.03: Using density \item Vidéo : 2.04: Hydrostatic equilibrium \item Vidéo : 2.05: Hydrogen equation of state \item Vidéo : 2.06: Heat transport \item Vidéo : 2.07: Theoretical internal structure \item Vidéo : 2.08: A core from gravity ? \item Vidéo : 2.09: Magnetic fields \item Vidéo : 2.10: The upper atmosphere and the Galileo probe \item Vidéo :2.11: Picture models \end{itemize} \subsection*{Quiz 4} \begin{enumerate} \item[1.] Kepler's planetary laws, coupled with Newton's equation of gravitation, lets us determine the mass of a planet by measuring the orbital semimajor axis and orbital period. Which one of the following moons will have almost exactly the same period as a moon with the mass of Europa $1 M_e$ with a semimajor axis of 1 million km $10^6 km$ around a planet with the mass of Jupiter $1 M_J$ A moon with a mass of $(in M_e)$, a semimajor axis of (in km), and orbital a planet with the mass of in $(M_J)$: \begin{itemize}[label={$\bullet$}] \item moon mass = $2 M_e$ ; semi axis = $2 \times 10^6 km$ ; planet mass = $8 M_j$ \item moon mass = $1/2 M_e$ ; semi axis = $1/2 \times 10^6 km$ ; planet mass = $8 M_j$ \item moon mass = $1/2 M_e$ ; semi axis = $2 \times 10^6 km$ ; planet mass = $2 M_j$ \item moon mass = $1 M_e$ ; semi axis = $1/2 \times 10^6 km$ ; planet mass = $2 M_j$ \item moon mass = $1/2 M_e$ ; semi axis = $8 \times 10^6 km$ ; planet mass = $2 M_j$ \item moon mass = $1 M_e$ ; semi axis = $1/8 \times 10^6 km$ ; planet mass = $1/2 M_j$ \end{itemize} \item[2.] Of the planets in the solar system Earth is the most dense and Saturn is the least dense, but the densities of the planets are greatly affected by compression. Planetary scientist often talk of "uncompressed densities" meaning the density that the planet would have if all of its materials were at 1 bar of pressure. Using what you know of the densities of materials and the compositions of the planets, which planet has the highest uncompressed density? \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item Mercury \item Venus \item Earth \item Mars \item Jupiter \item Saturn \item Uranus \item Neptune \end{itemize} \end{multicols} \item[3.] The equation of hydrostatic equilibrium allows you to determine the pressure inside of a planet as a function of depth. What piece of information is required in all cases to use the equation of hydrostatic equilibrium? \begin{itemize}[label={$\bullet$}] \item A knowledge of whether or not there is a core inside of the planet. \item An equation of state telling you the density of the material as a function of pressure. \item The temperature profile inside of the planet. \item A phase diagram of the substance at the temperatures and pressures of the interior. \item The mean molecular mass of the substance \item An understanding of the interior heat flow. \end{itemize} \item[4.] In a Fermi gas -- which is not a bad approximation to the equation of state in the center of Jupiter -- what is the main reason for the resistance of the gas to compression? \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item Electrons which are unable to occupy the same quantum state. \item Electrostatic repulsion \item High temperatures \item A high effective mean molecular mass \item A phase transition to a solid \item Convective instability \end{itemize} \end{multicols} \item[5.] Which of the following is the farthest from being in hydrostatic equilibrium? (notice that I say farthest here, because new things are perfectly in hydrostatic equilibrium, but many things are pretty close). \begin{itemize}[label={$\bullet$}] \item The water inside of a glass \item The interior of the Earth \item The interior of Jupiter \item The Earth's atmosphere \item A rock \end{itemize} \item[6.] Which of the following is NOT true about the process of convection? \begin{itemize}[label={$\bullet$}] \item Convection can occur due to cooling at the top as well as heating at the bottom. \item Convection of a conducting medium is required for the generation of a magnetic field inside of a planet \item Convection is the fastest way for a planet to remove heat from its interior \item Convection can only be sustained if energy is both input at the bottom and removed at the top. \item These are all true \item Any time warm air is below cooler air, convection will occur \end{itemize} \item[7.] We think Jupiter most likely has a core, though it is one of the major goals of the Juno spacecraft to find out for sure. Which of the following is NOT a reason that we think Jupiter most likely has a core? \begin{itemize}[label={$\bullet$}] \item To fit the density of Jupiter you need to add a significant amount of extra heavier material compared to the atmosphere. \item Saturn clearly has a core and it would seem odd to have two planets right next to each other and that look so similar to actually be so different on the inside. \item The best fit interior models, though still uncertain, work better with a core than without. \item The presence of a magnetic field strong suggests the presence of a core \item All of these are reasons to think that Jupiter has a core \end{itemize} \item[8.] Which of the following is a TRUE statement about what was found by sending the Galileo probe into Jupiter? \end{enumerate} \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item None of these is true \item The chemicals in the atmosphere of Jupiter are spatially homogeneous \item The upper atmosphere has elevated abundances of many elements \item The abundances of helium and neon are elevated because they are retained in clouds in the upper atmosphere \item Water vapor is abundant just below the cloud tops \end{itemize} \end{multicols} \newpage \section*{Semaine 5 - The insides of giant planets (week 2)} \begin{itemize}[label={$\bullet$}] \item Vidéo : 2.12: Planetesimal formation \item Vidéo : 2.13: Core formation \item Vidéo : 2.14: Core-collapse vs. Disk instability \item Demande de discussion : Core collapse vs. disk instability? \item Vidéo : 2.15: Saturn and the ice giants \item Vidéo : 2.16: Discovering hot Jupiters \item Vidéo : 2.17: Densities of hot Jupiters \item Vidéo : 2.18: Inflating hot Jupiters \item Vidéo : 2.19: Kepler and the sub-Neptunes \item Vidéo : 2.20: Exoplanet spectroscopy \item Vidéo : 2.21: Juno and future exploration \item Demande de discussion : Juno results? \end{itemize} \newpage \subsection*{Quiz 5} \begin{enumerate} \item[1.] Which planet would have the lowest uncompressed density? \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item Mercury \item Venus \item Earth \item Mars \item Jupiter \item Saturn \item Uranus \item Neptune \end{itemize} \end{multicols} \item[2.] Which of the following is not a reason that we expect metallic hydrogen inside of Jupiter? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The phase diagram predicts metallic hydrogen. \item All of these statements are true. \item Helium rains out of the upper layers into the lower layers. \item The presence of a strong magnetic field suggests a conductive interior. \item The dipole nature of the magnetic field suggests a deep conductive layer \item The interior pressures are higher than the gas-to-metal transition. \end{itemize} \end{multicols} \begin{multicols}{2} \item[3.] Which of the following orbits (some of which would require extra propulsion to follow) would be best for using gravitational measurements to determine the interior structure of a planet? (the inner and outer dashed lines are circles of 10 planet radius and 100 planet radius, for consistent scale) \begin{figure}[H] \centering \includegraphics[width=0.8\linewidth]{orbits.png} \end{figure} \end{multicols} \item[4.] Which of the following is not required for the creation of a dynamo-driven magnetic field? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Interior motions deflected by the Coriolis effect \item A core of ice and/or rock \item A rotating planet \item All of these are required \item A conducting liquid in the interior \item An interior which gets hotter with depth \item Convection in the interior \end{itemize} \end{multicols} \item[5.] Which of the following is the best description of the formation of a giant planet with a massive core? (at least as described in the lectures!) \begin{itemize}[label={$\bullet$}] \item In a massive disk the force of gravity in a patch of the disk overcomes the pressure and rotational forces and the patch quickly collapses into a giant planet. The heavy materials sink to the bottom and form the core. \item Planetesimals grow through gravitational focusing. Dynamical friction slows the motions of the largest objects leading to runaway growth of oligarchs, which are isolated from other nearby oligarchs. The gravitational pull of the oligarch quickly overcomes the rotational and pressure forces from the disk, causing rapid growth of the gaseous atmosphere. \item Planetesimals grow through gravitational focusing. Dynamical friction slows the motions of the largest objects leading to runaway growth of oligarchs, which are isolated from other nearby oligarchs. Gas slowly accretes onto the oligarch through an envelope until the pressures are too high to support the envelope and massive amounts of gas collapse making the gas giant. \item Planetesimals grow through gravitational focusing. Dynamical friction speeds the motions of the largest objects leading to more frequent collisions and runaway growth of oligarchs, which are isolated from other nearby oligarchs. Gas slowly accretes onto the oligarch through an envelope until the pressures are too high to support the envelope and massive amounts of gas collapse making the gas giant. \item Planetesimals grow through gravitational focusing. Dynamical friction slows the motions of the largest objects leading to runaway growth of oligarchs, which are isolated from other nearby oligarchs. Large numbers of oligarchs merge over hundreds of millions of years, leading to a giant core.Gas slowly accretes onto the oligarch through an envelope until the pressures are too high to support the envelope and massive amounts of gas collapse making the gas giant. \end{itemize} \item[6.] Based on our current understanding of the results from the Kepler mission, what is the most common type of planet with orbital periods less than 90 days? \begin{multicols}{3} \begin{itemize}[label={$\bullet$}] \item Planets with masses between that of the Earth and Neptune \item Hot Jupiters \item Water worlds \item Super earths with solid surfaces \item Planets less massive than the Earth \item Sub-Neptunes with ice/rock cores and gas envelopes \end{itemize} \end{multicols} \item[7.] The processes of gravitational focusing and dynamical friction are critical to our understanding of how planetesimals form. Which of the following is NOT true about gravitational focusing and dynamical friction? \begin{itemize}[label={$\bullet$}] \item As dynamical friction slows down large bodies with respect to each other, gravitational focusing increases dramatically \item Dynamical friction makes small bodies go fast and large bodies go slow \item Dynamical friction works most efficiently when all of the bodies are approximately the same size \item All of these statements are true \item Gravitational focusing gets much stronger for bodies that are nearly motionless with respect to each other \item Gravitational focusing gets stronger for larger bodies \end{itemize} \item[8.] Isolation mass is another key concept in understanding the formation of planetesimals and eventually planets. We sometimes use the term "oligarch" to describe a body which has become isolated. Which of the following statements about isolation mass is false? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Oligarchs are space further and further apart further out in the dis \item Isolation masses are much higher outside of the ice line \item Dynamical friction causes the oligarchs to slow each other down \item When an object reaches isolation mass it stops growing rapidly by gravitational focusing \item Oligarchs get more massive futher out in the disk \item All of these statements are true \end{itemize} \end{multicols} \item[9.] While we think that our planets formed through the process of core collapse, planets around other stars might or might not have formed from the process of disk instability. Which of the following would make disk instability MORE LIKELY to have occurred around a star? \begin{multicols}{3} \begin{itemize}[label={$\bullet$}] \item A hotter disk of material \item A more massive disk \item A more massive star \item A larger fraction of solid material in the disk \item A previously formed planet \item None of these would make disk instability more likely \end{itemize} \end{multicols} \item[10.] Uranus and Neptune are very different from Jupiter and Saturn. Which of the following is NOT true of the differences between these sets of planets? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Uranus and Neptune are more dense than Jupiter and Saturn, even though Jupiter and Saturn are much more compressed. \item While Jupiter and Saturn have mostly regular magnetic fields, the complex non-dipolar magnetic fields of Uranus and Neptune suggest that the magnetic field is generating closer to the top of the atmosphere on these planets. \item Uranus and Neptune have only a fraction of the mass of Jupiter or Saturn \item All of these statements are true \item Neither Uranus nor Neptune is massive to have metallic hydrogen on the inside \end{itemize} \end{multicols} \end{enumerate} \newpage \section*{Semaine 6 - Big questions from small bodies} \begin{itemize}[label={$\bullet$}] \item 3.01: Introduction to the small bodies of the solar system \item 3.02: The formation of small bodies \item 3.03: The formation of terrestrial planets \item 3.04: The surface density of the solar system \item 3.05: An ode to comets \item 3.06:The composition of comets \item 3.07: Where do comets come from? \item 3.08: The formation of the Oort cloud \item 3.09: Meteorites and the beginning of the solar system \item 3.10 Types of meteorites: Chondrites \item 3.11: Types of meteorites: Achondrites \item 3.12: Asteroids and meteorite delivery \end{itemize} \newpage \subsection*{Quiz 6} \begin{enumerate} \item[1.] Which of the following is the best explanation of why we have small bodies in the solar system? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The oligarchs that formed in the region of the terrestrial planets and the asteroid belt slowly merged over ~100 Myr and the oligarchs at the outer range of this region were excited by Jupiter enough to cause impacts to shatter the objects. A similar process took place in the Kuiper belt. \item Planetesimal formation in the region of the asteroid and Kuiper belts was delayed until after the gas in the nebular disk had dissipated, preventing these objects from acquiring gassy envelopes. \item Insufficient mass existed in the region of the asteroid belt and Kuiper belt to allow full sized planets to form. \item Nearby planets caused excitation of the orbits of planets in the region of the asteroid belt and Kuiper belt and these planets collided and their fragments are now the small bodies. \item Nearby planets caused the orbits of forming planetesimals to acquire high velocities and eccentricities, preventing run away growth and leading to shattering impacts. \end{itemize}\end{multicols} \item[2.] Which of the following statements about comets is NOT true? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Water is the most abundant ice on comets and the most abundant gas in the coma of a comet \item All of these statements about comets are true \item Much of the light we see in the coma of a comet is sunlight reflected off of an extended dust coma lifted off the surface \item Comets typically become bright at distances of about 3 AU from the sun where water ice begins to sublime \item Comets have slight deviations in their orbits when they get close to the sun due to the jetting effect of evaporation \item The ices present in comets show that these bodies were formed in the regions beyond Jupiter \end{itemize}\end{multicols} \item[3.] Which of the following is NOT required for the formation of a large nearly isotropic Oort cloud full of many small bodies, assuming the scenario that we discussed is the dominant mechanism? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item A planet like Jupiter which is massive enough to scatter bodies out of the solar system \item Passing stars which perturb the orbits of low perihelion, high semimajor axis objects \item A smaller planet like Neptune to scatter icy bodies inward so they can be ejected by a more massive planet like Jupiter \item A population of small bodies which is close enough to a planet to get scattered outward \item Multiple stellar encounters to randomize the cometary orbits into an isotropic cloud \item All of these are required \end{itemize}\end{multicols} \item[4.] The terrestrial planets appear to have taken much longer to finally assemble than the gas giants did. Which of the following statements about these timescale is NOT true? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item We can learn about the timescale of terrestrial planet differentiation by looking at isotopic ratios of hafnium and tungsten. \item Mars differentiated quickly, so tungsten-182, the radioactive decay product of hafnium, is abundant in Martian meteorites. \item One reason that the gas giant formation timescale is thought to be so fast is that we do not observe stars to have gas around them after they are ~3 Myr old \item Growth of the terrestrial planets was slowed by the rapid growth of the gas giants, which caused oligarchs to have have velocities and break apart. \item All of these statements are true \item Oligarchs form very quickly through runaway growth but because they are gravitationally isolated it takes a long time for them to assemble into larger bodies. \end{itemize}\end{multicols} \item[5.] The "minimum mass solar nebula" shows how much initial mass was needed in the disk around the sun to form the planets that we know of today. Which statement about the minimum mass solar nebula below is FALSE? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item WAll of these are true \item The minimum mass solar nebula approximately accounts for all of the hydrogen and helium that were present in the initial disk but which were not incorporated into the terrestrial planets. \item Mars appears to have less mass than would be predicted by a smooth minimum mass solar nebula \item The initial distribution of mass in the solar system could have been very different from that reconstructed in the "minimum mass solar nebula" \item The disk of material around the sun could have had more material than the minimum mass solar nebula \end{itemize}\end{multicols} \item[6.] Which of the following is NOT part of the explanation for why we continue to have near earth asteroids hit the earth even though the dynamical lifetime of a typical NEA is very short compared to the age of the solar system? (by dynamical lifetime we mean the time before it is likely to hit a planet or get ejected from the solar system) \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The existence of families of asteroids formed by asteroid impact and shattering \item The high current eccentricities and inclinations of asteroids population leading to shattering impacts \item All of these are true \item The Yarkovsky effect \item Heating of small asteroids on one side coupled with rotation causing orbital drift \item Our improved technology which allows us to find ever-smaller near earth asteroids \item Resonances with Jupiter and Saturn in the asteroid belt leading to removal of objects in the asteroid belt \end{itemize}\end{multicols} \item[7.]Lead-lead dating is a great way to figure out the age of something that is close to the age of the solar system. It based on the radioactive decay of uranium.Uranium-238 decays (with intermediate steps) to lead-206 with a half life of 4.5 billion years. Uranium-235 decays to lead-207 with a half life of 0.7 billion years. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item A higher ratio of lead-204 to lead-206 implies a younger rock \item Measuring the abundance of uranium-235 shows you how many half-lives have passed since the formation of the rock \item The technique requires finding parts of the meteorite with different abundances of lead and trying to determine how much extra lead exists because of uranium decay \item Objects which are younger will have more lead-207 than objects which are older. \end{itemize}\end{multicols} \item[8.] We find chondrules in meteorites that fall from the sky, but we have never found them on the Earth, the Moon, or Mars. Why not? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item They are in the interior of the Earth where we cannot reach. \item None of these is correct \item Meteorites probably formed from different materials than the planets \item They most likely form as the meteorite is falling through the atmosphere \item Materials inside large bodies like the Earth, Moon, and Mar undergo so much transformation due to heat and pressure that their original structure is not preserved. \end{itemize}\end{multicols} \item[9.] Pallasites are not only once of the most beautiful types of meteorites that you can find, they are also one of the most special. Many things must happen before a pallasite can form and be delivered to your hand. Which of the following is NOT one of them? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Someone has to find the pallasite on the Earth (and, eventually, it gets handed to you) \item A body must form which is large enough to retain enough heat to differentiate \item Pieces of a shattered body must hit a resonance which puts them onto an Earth crossing orbit \item All of these must happen \item A differentiated body must have an impact which shatters it into pieces \item A piece of the core-mantle boundary from a shattered mini-planet must land on the Earth \end{itemize}\end{multicols} \end{enumerate} \newpage \section*{Semaine 7 - Big questions from small bodies} \begin{itemize}[label={$\bullet$}] \item 3.13: Asteroid compositions \item 3.14: Pictures of asteroids \item 3.15: Asteroid hazards \item 3.16: The Kuiper belt \item 3.17: Properties of dwarf planets \item 3.18: Dynamical instabilities \item 3. : Lucy! \item 3.19: The Grand Tack \item 3.20: Planet Nine \item 3.21: A trip to the Subaru telescope \end{itemize} \newpage \begin{enumerate} \item[1.] Put the following in order from earliest to latest. In doing so, assume that the Nice model occurred as described and that the Grand Tack model also occurred as described. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The formation of Jupiter \item The inward migration of Jupiter due to gas forces \item The instability "explosion" which scattered small bodies throughout the solar system \item The inward migration of Saturn due to gas forces \item The formation of the Earth \item The outward migration of Jupiter due to gas forces Be very careful typing in your answer! If you think the order is 1,2,3,4,5,6 please type, exactly "123456" with no spaces, no commas, and no quotation marks. \end{itemize}\end{multicols} \item[2.] What problem does the Grand Tack model of the early solar system evolution attempt to explain? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The continued delivery of near earth asteroids into the inner solar system. \item The early inward migration of Jupiter and Saturn \item The mixing of the asteroid belt \item The timing of the Late Heavy Bombardment \item The apparently low mass of Mars \item The number of terrestrial planets \end{itemize}\end{multicols} \item[3.] For lead-lead dating, we measure the ratio of 207Pb to 206Pb and the ratio of 204Pb to 206Pb in a series of different regions of a meteorite. We then construct a plot of all of our measurements which looks something like this. The individual measurements are the points labeled things like "L1" and "W8"; a line is drawn through the points. The line is defined by a slope and the location where it hits the y-axis (the "intercept"), which is about 0.62 in this case. If we made similar plots for each of a series of calcium aluminum inclusions (CAIs) and a collection of chondrites, what are we most likely to find? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would range from that of the CAIs to larger (steeper) values \item The slope of each measured line would be nearly identical. The intercepts for the CAIs would all be equal, and the intercepts for the chondrites would range from that of the CAI to larger values. \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would all be smaller (shallower) \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would range from that of the CAIs to smaller (shallower) values \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would all be larger (steeper). \item The slope of each measured line would be nearly identical, but the intercepts for the CAIs would all be smaller than the intercepts for the chondrites. \item The slope of each measured line would be nearly identical. The intercepts for the CAIs would all be equal, and the intercepts for the chondrites would range from that of the CAI to smaller values. \end{itemize}\end{multicols} \item[4.] What can not we infer from this plot of the eccentricity vs. semimajor axis of known Kuiper belt objects? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Neptune may have migrated outward, pushing parts of the Kuiper belt outward \item No objects with circular orbits are known beyond the 2:1 resonance with Neptune \item Many Kuiper belt objects share identical orbital periods as Pluto \item Kuiper belt objects have had giant impacts which have made families \item Kuiper belt objects exist out to at least ~180 AU \item Neptune is currently scattering Kuiper belt objects \end{itemize}\end{multicols} \item[5.] What is the explanation for the apparent lack of abundant solid nitrogen on the surface of Makemake even though it dominates the surface of Pluto and is inferred to be present on Eris? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item MThe saturated spectrum of the slabs of methane make nitrogen too difficult to detect. \item MMakemake is warmer than Eris but colder than Pluto, allowing methane to be stable but not nitrogen \item MMakemake is colder than Pluto, so nitrogen is frozen on the surface and not detected in the atmosphere \item MMakemake is smaller than Pluto and Eris, so nitrogen escapes while the less volatile methane remains behind. \item MMethane is so abundant on Makemake that chemical reactions between methane and nitrogen make ammonia \item MMakemake is smaller than Pluto and Eris, so molecular nitrogen undergoes hydrodynamic escape while leaving the lighter methane molecule behind \end{itemize}\end{multicols} \item[6.] Is Pluto a planet? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item yes \item no \end{itemize}\end{multicols} \item[7.] Which of the following is not a possible consequence of the Nice model for the dynamical instability of the early solar system? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The small mass of the Kuiper belt \item The presence of icy bodies among the Jupiter trojan \item The abundance of Kuiper belt objects in resonaces \item The low mass of Mars \item The higher than expected eccentricities of the giant planets \item The lateness of the Late Heavy Bomdardment \end{itemize}\end{multicols} \item[8.] Is it possible that a civilization destroying asteroid is going to hit us within the next century? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item yes \item no \end{itemize}\end{multicols} \item[9.] Which of the following statements about the hypothetical Planet Nine is NOT true? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item In the Planet Nine model, Planet Nine clears out the majority of the high eccentricity high semimajor axis objects in the outer solar system \item All of these are true \item Planet Nine can raise the perihelion of objects like Sedna and 2012 VP113 \item Planet Nine finally explains the discrepancies in the orbital position of Neptune \item Pluto was originally though to be possibly as large as Jupiter \item In the Planet Nine model, Planet Nine tilts the orbits of distant eccentric Kuiper belt objects into a plane different from the plane of the planets. \end{itemize}\end{multicols} \item[10.] NASA is planning to send the Lucy spacecraft to study Trojan asteroids in the next decade. What of the following statements about Trojan asteroids is TRUE? Check all that apply. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item In the Nice dynamical instability model, Trojan asteroids and Kuiper belt objects come from the same source \item It is possible that Trojan asteroids formed in the asteroid belt \item Trojan asteroids are dynamically unstable on ~1 million year lifetimes so must be replenished by asteroid collisions. \item Trojan asteroids look different spectroscopically from the majority of the asteroids in the main asteroid belt \end{itemize}\end{multicols} \end{enumerate} \newpage \section*{Semaine 8 - Life in the solar system (week 1)} \begin{itemize}[label={$\bullet$}] \item 4.01: Introduction to life \item Discussion Prompt: Life as we do (or don't) know it \item 4.02: Photosynthesis \item 4.03: Water \item 4.04: Alternative energy sources \item 4.05: History of life on Earth \item 4.06: Mars -- The Viking experiement \item 4.07: Mars -- Microbial hitchhikers \item 4.08: Mars -- Methane? \item 4.09: Mars -- Methane!! \item 4.10: Mars -- a habitable environment \end{itemize} \newpage \begin{enumerate} \item[1.] Which of the following is not an advantage of photosynthesis and the organic chemistry it allows? \begin{itemize}[label={$\bullet$}] \item The ability to extract previously stored energy through respiration \item The ability to extract energy from chemicals that are available in the environment \item The ability to store energy in insoluble compact forms. \item The ability to form carbohydrates which can be transported to use energy elsewhere. \item The ability to use the most abundant source of energy easily available on the planet \item The ability to make complex hydrocarbons which are capable of building structures. \end{itemize} \item[2.] Which of the following statements about methane on Mars is not true? \begin{itemize}[label={$\bullet$}] \item The abundance of methane initially reported could be caused by well understood geochemistry without the need for biological agents \item The abundance of methane initially reported could be caused by a few isolated areas containing methanogenic microbes. \item The amount of methane measured by Curiosity in the "enhanced" measurements is equivalent to that emitted in the burps of about 100 cows. \item The expected methane lifetime on Mars is decades, so it is difficult to explain the variability observed. \item Detection of methane on Mars from the Earth is made more difficult by the presence of methane in Earth's atmosphere. \item The Mars Curiosity detections of methane show that the previous reports of methane on Mars were correct. \end{itemize} \item[3.] The Curiosity Rover found abundant evidence that Yellowknife Bay would have been a habitable environment. Which of the following did Curiosity not find? \begin{itemize}[label={$\bullet$}] \item Evidence for chemicals that could have been used for energy extraction \item Evidence for the presence of a lake \item Evidence for chemicals that make up nutrients for life on Earth \item Evidence for the extended presence of water \item Abundant calcium carbonate created out of the former CO$_2$ atmosphere \item Evidence for flowing water \end{itemize} \item[4.] Which of the following statements is not true? \begin{itemize}[label={$\bullet$}] \item If microbes are to hitchhike from Earth to Mars, the rock in which they are embedded needs to not have been molten by the initial impact. \item If microbes hitchhiked to Mars from Earth and found a habitable environment, the terrestrial microbes would most likely have had to have been archea. \item Microbes would have been more likely to have survived the trip from Earth to Mars if they were in space for only a few years. \item Microbes capable of surviving years in space have been found. \item To survive unmelted, the rocks with embedded microbes would need to fall on a planet with a very small atmosphere \item Meteorites have been found on the Earth that have come from Mars and that have stayed at temperatures low enough for microbe survival \item Microbes could have traveled from Mars to Earth and started life on Earth \end{itemize} \item[5.] Which one of the following statements is correct? \begin{itemize}[label={$\bullet$}] \item The Archean on the Earth and the Noachian on Mars cover approximately the same time periods. \item If photosynthesis had never developed on Earth we would have a climate much like that of Mars today \item Archea dominated the Earth and its atmosphere for the vast majority of the history of the Earth. \item During the Great Oxygenation Event photosynthetic microbes poisoned the atmosphere for much of the previous life on Earth \item After the rise of oxygen the archea all went extinct and we only find them in the fossil record today \item The banded iron formations occurred when methanogens reduced the iron ore leading to enhanced rusting. \item None of these statements is correct \end{itemize} \item[6.] What do you think is a good definition of "life" and why? \item[7.] Which of the following are reasons why liquid water environments might be the most common place for life throughout the universe? (check all that apply) \begin{itemize}[label={$\bullet$}] \item Water is a good solvent \item Water is an abundant molecule in the universe \item Many of the chemical reactions for life take place in liquids \item Water is positively charged and easily attaches to electrons \end{itemize} \item[8.] Archaea are a fascinating and only recently understood domain of life. Which of the following statements about archaea is NOT true? \begin{itemize}[label={$\bullet$}] \item Many (most?) species of archaea died out when oxygen began to become abundant in the Earth's atmosphere methanogens can live completely independently of solar energy \item Archaea appear to have more primitive cellular structures than bacteria \item Archaea have been found in hot springs, in deep underground caverns, at the bottom of the ocean, and in the guts of cows and humans \item These are all true \end{itemize} \end{enumerate} \newpage \section*{Semaine 9 - Life in the solar system and beyond (week 2)} \begin{itemize}[label={$\bullet$}] \item 4.11: Oceans on Europa \item 4.12: Energy on Europa \item 4.13: Exploring Europa \item Prompt: Europa Clipper! \item 4.14: Enceladus \item 4.15: Introduction to Titan \item 4.16: Weird life on Titan \item 4.17: Habitable zones \item 4.18: Detecting exo-life \item 4.19: Looking around M-dwarfs \item Prompt: Planets! \item 4.20: A mission to find life in the solar system \item 4.21: All good things must come to an end \end{itemize} \newpage \begin{enumerate} \item[1.] The existence of an ocean on Europa has been established from several different lines of evidence. First, spectroscopy of the surface shows that water ice is present. Second, gravitational measurements show that the upper layer of Europa is low density. The third line of evidence is the most convincing. What is this most convincing line of evidence? \begin{itemize}[label={$\bullet$}] \item When the surface ice shell of Europa flexes due to tidal forces, the magnitude of the effect is much larger than it would be for a thick solid shell. \item Electric currents within the ocean induce magnetic fields which have been measured. \item Europa has an oxygen atmosphere \item Europa has definitive evidence of plumes of water coming from the interior. \item Many geological features suggest the presence of liquid underneath the ice. \item The faint hum of whale songs can be heard coming from underneath the ice \end{itemize} \item[2.] Why do we think that Enceladus seems less likely to have developed life than Europa (although, admittedly, we don't really know)? \begin{itemize}[label={$\bullet$}] \item Unlike Europa, the ocean of Enceladus is not in contact with a rock core. \item Enceladus does not have the complex organic materials known to be present on Europa \item It is difficult to imagine life evolving in an active plume. \item The low density of Enceladus suggests a rocky core which is too small to provide the heat required to have a liquid water layer. \item Liquid water on Enceladus might be a recent phenomenon, giving insufficient time for life to evolve \item At the distance of Enceladus, the liquid water would be too cold for life \end{itemize} \item[3.] Which of the following is not a viable argument against the possibility that there is some sort of life on Titan? \begin{itemize}[label={$\bullet$}] \item Temperatures on Titan are so cold that chemical reactions would be too slow for organisms to evolve and thrive. \item Pools of liquid water that might transiently exist after impacts don't survive long enough for water-based life to develop. \item If life existed on Titan, it should leave a detectable signal in the atmosphere. \item Liquid water probably exists under the icy surface of Titan, but it is unlikely to be in contact with rock, and thus unlikely to have sustainable sources of energy and nutrients. \item Liquid methane is non-polar and thus would be non-ideal for life. \item Titan has such a thick haze layer that the amount of sunlight reaching the surface provides little energy. \end{itemize} \item[4.] Ignoring the greenhouse effect, and assuming a simplistic definition that the habitable zone around a star is the region where the surface temperature is between O C and 100 C (and rememberiing that 0 C = 273 K), how big is a habitable zone around a star? Calculate the answer in terms of Router, $R_{inner} / R_{outer}$ such that if the inner edge of the habitable zone is, say, 1 AU and the outer edge if 1.5 AU, your answer would be 1.5. Round to the nearest tenth. \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item 3.0 \item 1.9 \item 2.5 \item 1.6 \item 1.4 \item 3.5 \item 1.2 \end{itemize} \end{multicols} \item[5.] In the mid-infrared region of the spectrum (~5 to ~20 microns), what is the best signature of abundant oxygen in an atmosphere? \begin{itemize}[label={$\bullet$}] \item The presence of $CH_4$ in the atmosphere \item The presence of a strong $O_3$ absorption feature \item The presence of strong $N_2$ absorption \item The presence of a strong $O_2$ absorption \item The presence of a strong $CO_2$ absorption \item The presence of detectable water in the atmosphere \end{itemize} \end{enumerate} \section*{Semaine 10 - Final Exam} \begin{itemize}[label={$\bullet$}] \item Reading: Bonus material \item Bonus: The formation of the moon \item Bonus: What we used to think about Sedna (before we knew about Planet Nine!) \item Bonus: Seasons on Titan \item Bonus: Why Pluto had to die \item Noté: Final exam \end{itemize} \newpage \begin{enumerate} \item[1.] It is possible, though still not certain, that Mars was once globally warmer and wetter, with liquid water globally stable at the surface during the Noachian. If liquid water was once stable on Mars, most of the following statements are true. One is false. Find the false statement. \begin{itemize}[label={$\bullet$}] \item The surface temperature was at least 0 degrees Celsius. \item Rain was likely common, at least in some places. \item Liquid water would also have been stable in the subsurface. \item The giant outflow channels would have brought copious water into a northern ocean at this time. \item Substantially more water was present in the atmosphere than is present today. \item It is likely that a substantial $CO_2$ atmosphere caused a large greenhouse effect. \end{itemize} \item[2.] While it is not surprising the Mars has ice at the poles, there is evidence that subsurface ice on Mars extends even down to the tropics. Which one of the following is the likely explanation for this ice? \begin{itemize}[label={$\bullet$}] \item A colder equatorial climate during periods of high Martian obliquity. \item Globally cold temperatures during the late Hesperian/early Amazonian as the atmospheric greenhouse diminished. \item A colder equatorial climate during periods of high eccentricity. \item Melting and migration of ground water due to magmatic interaction. \item Remnant water from outflow channels which has slowly frozen over time. \item Globally colder temperatures during the Noachian when the sun was fainter. \end{itemize} \item[3.] What is generally thought to be the most likely explanation for most giant outflow channels on Mars? \begin{itemize}[label={$\bullet$}] \item Catastrophic flooding from locally intense rainfall. \item The transition from high obliquity to low obliquity causing substantial melting and runoff. \item Pre-Noachian impacts causing local regions of liquid water stability and ice melting. \item Sapping of ground water. \item Massive melting of ground ice by magmatic intrusion. \item Melting of glacial dams leading to masive outflow of previously confined water. \end{itemize} \item[4.] If Mars once had a massive $CO_2$ atmosphere that led to a warmer and wetter Noachian period, all of that $CO_2$ must have gone somewhere. Most of the statements below about atmospheric removal on Mars are true. Which one of the following statements about atmospheric removal is not true? \begin{itemize}[label={$\bullet$}] \item If the Martian atmosphere was removed by hydrodynamic escape, all isotopes of atmospheric molecules would be removed equally well, contrary to what is observed. \item If Mars still possessed a substantial magnetic field, its atmosphere would probably have been protected against loss. \item Giant impacts during the late heavy bombardment could have been responsible for the drying out of the Hesperian, but all isotopes of atmospheric molecules would have been removed equally well, contrary to observations. \item If the Martian atmosphere was removed by solar wind scavenging, lighter isotopes of atmospheric molecules would be preferentially removed -- an effect which is seen. \item Mars continues to lose its atmosphere today. \item If $CO_2$ was removed chemically, large deposits of carbonates should exist somewhere, yet no such large deposits have been found. \end{itemize} \item[5.] Place the following events in the likely order of their occurrence. \begin{itemize}[label={$\bullet$}] \item 1. The presence of the acidic playa environment at Meridiani Planum. \item 2. The formation of the Hellas basin. \item 3. The formation of dendritic channels. \item 4. The formation of the layers visible on the polar caps. \end{itemize} \item[6.] We have learned about the interiors of giant planets through many different methods. Once again, most of the statements below are true, but one is not. Which statement below is not true? \begin{itemize}[label={$\bullet$}] \item The primary measurement that the Juno spacecraft will make which will indicate whether or not Jupiter has a core will be of the gravitational field as close to Jupiter as possible. \item Jupiter, Saturn, Uranus, and Neptune likely have metallic hydrogen in them, as evidenced by both the phase diagram and their magnetic fields. \item With the exception of a few condensible species like water and helium, the composition of the atmosphere of Jupiter is likely almost identical to that measured in the upper layer by the Galileo probe. \item If Jupiter were suddenly tripled in mass, it would get smaller. \item Jupiter is more dense than Saturn only because it is more massive and thus more compressed. \item Saturns interior is currently being heated by helium rain. \end{itemize} \item[7.] We think that Jupiter most likely has a rock/ice core, but it is still possible that it doesn’t. The Juno spacecraft should give definitive measurements that will tell us. What is one of the conclusions that could be drawn if Jupiter is found to not have a core? \begin{itemize}[label={$\bullet$}] \item Helium rainout has not yet begun on Jupiter. \item Jupiter most likely formed in a manner substantially different from that of the other giant planets. \item Jupiter is larger than it should be for a body without a core and thus must have undergone some form of inflation like hot Jupiters. \item Jupiter could not have undergone the migration envisioned in the Grand Tack model. \item The planets – at least in our solar system – most likely formed from direct collapse of the initial nebula. \item Jupiter formed substantially later than the other giant planets. \end{itemize} \item[8.] Which of the following statements about hot Jupiters is not true? \begin{itemize}[label={$\bullet$}] \item Hot Jupiters have been discovered by both radial velocity surveys and transit surveys. \item Hot Jupiters likely formed much further out from their parent star and migrated in to their current position. \item Hot Jupiters likely have their rotation period locked to their orbital period such that one side always faces the sun, one side always faces away. \item The presence of Saturn might have saved Jupiter from becoming a hot Jupiter. \item Planets smaller than Jupiter can also be found as close to their parent star as hot Jupiters. \item Hot Jupiters can be substantially larger than Jupiter because the intense heat of the very nearby star inflates their upper atmospheres greatly. \end{itemize} \item[9.] Why did objects in the asteroid belt region and the Kuiper belt region not grow into planets? \begin{itemize}[label={$\bullet$}] \item The giant planets perturbed these regions, raising mutual velocities, preventing strong gravitational focusing and inhibiting run away growth. \item Giant planet perturbations prevented dynamical friction from slowing the small bodies enough to be captured by larger, growing bodies. \item Timescale for formation in these regions is longer. Accretion is still occurring. Given time, large bodies will grow. \item The giant planets perturbed these regions such that planet-sized bodies forming had high enough eccentricities that they either impact the giant planet or the sun or were ejected from the solar system. \item Not enough material was initially present to allow the formation of the initial oligarchs. \item They did! Pluto is a planet! I insist! \end{itemize} \item[10.] Most of the statements below about near Earth asteroid are true. Except for one. Find the false statement. \begin{itemize}[label={$\bullet$}] \item Asteroids are delivered to the near Earth region through resonances in the main asteroid belt. \item Near Earth asteroids are removed from the near Earth region on a timescale short compared to the age of the solar system. \item The total number of near Earth asteroids is rapidly decreasing with time as they impact terrestrial planets or get ejected from the solar system. \item Near Earth asteroids that land on the Earth provide evidence that small bodies differentiated, grew iron cores, and were shattered. \item Small asteroids have their orbits changed by a combination of heating, rotation, and uneven reemission of heat. \item Near Earth asteroids are replenished by collisions in the main asteroid belt. \item The impact of a near Earth asteroid is likely to cause continental scale destruction on the Earth within the next few 100,000 years. \end{itemize} \item[11.] The Nice model is nice. What is the key aspect of this model \begin{itemize}[label={$\bullet$}] \item The Late Heavy Bombardment occurred 3.9 billion years ago. \item The giant planets have migrated substantial distances. \item The giant planets can achieve very low eccentricities and inclinations through migration. \item Jupiter migrated inward in the gas disk. \item Jupiter and Saturn entered a resonance which excited their orbits and led to a solar system wide planetary rearrangement. \item Mars is less massive than expected. \end{itemize} compared to previous ideas about the evolution of the solar system? \item[12.] Place the following events in order: \begin{itemize}[label={$\bullet$}] \item 1. The rise of archean microbes . \item 2. The first photosynthetic microbes. \item 3. The end of the Late Heavy Bombardment. \item 4. The emergence of an oxygen rich atmosphere. \end{itemize} \item[13.] "Habitable zone" is a nice concept, even if one should not try to not take calculations of such things too literally. Below are mostly true statements about habitable zones. But one statement is not true. Which one is not true? \begin{itemize}[label={$\bullet$}] \item The "continuously habitable zone" is smaller than the "habitable zone." \item For stars just a little fainter than the sun, the habitable zone is inside the region where planets will be tidally locked with one side always facing the star. \item Because planets with atmospheres will have some amount of greenhouse warming, a habitable planet with liquid water stable on the surface could exist inside the simple boundary of our calculated habitable zone. \item The transit of an earth-sized planet in the habitable zone of an M-dwarf would be easier to detect than that of an earth-sized planet in the habitable zone of a sun-like star (assume the two stars are equally bright in the sky). \item Geological or biological feedback on planets can work to keep temperatures within a certain range even in the face of varying heat from the sun. \end{itemize} \end{enumerate} \end{document}<file_sep>/* Algorithme qui décompose un réel x en en fraction continue. * On récupère en sortie une suite d'entier qui sont les coefficients * de la fration continue. * On précise n le nombre d'occurence de la fration. * Par la suite une précision epsilon peut être envisagé * * CONTRIBUTEUR * <NAME> * * LICENCE * GPLv3 */ #include <iostream> #include <math.h> using namespace std; // décomposition simple void f1continue(double x, int n, int suite_a[]) { // suite_x représente la suite des nombres réels dont on cherche à // approximer l'inverse double suite_x[n]; // suite_a représente la suite des nombres entiers qui forme la // fraction continue // compteur i int i; // on affecte les premières valeurs // On se sert de la librairie math.h // pour trouver la partie entière avec // la fonction floor suite_a[0] = floor(x); suite_x[0] = 1/(x - suite_a[0]); // on boucle jusqu'au n_e coefficents for (i=1; i<n; i++) { // On vérifie le bon nombre de tour // cout << i << endl; // On extrait la partie entière dans suite_a suite_a[i] = floor(suite_x[i - 1]); // on inverse le reste compris entre 0 et 1 pour y mettre sous forme // de fraction suite_x[i] = 1/(suite_x[i - 1] - suite_a[i]); } } // On test si le coefficient suite-x n'est pas entier // auquelc cas, il faut terminer l'algo. bool estentier(double x) { return x == floor(x); } void f2continue(double x, int n, int suite_a[]) { // suite_x représente la suite des nombres réels dont on cherche à // approximer l'inverse double suite_x[n]; // suite_a représente la suite des nombres entiers qui forme la // fraction continue // compteur i int i; // on affecte les premières valeurs // On se sert de la librairie math.h // pour trouver la partie entière avec // la fonction floor suite_a[0] = floor(x); suite_x[0] = 1/(x - suite_a[0]); // on boucle jusqu'au n_e coefficents for (i=1; i<n; i++) { // On vérifie le bon nombre de tour // cout << i << endl; // On extrait la partie entière dans suite_a suite_a[i] = floor(suite_x[i - 1]); // on inverse le reste compris entre 0 et 1 pour y mettre sous forme // de fraction suite_x[i] = 1/(suite_x[i - 1] - suite_a[i]); if (estentier(suite_x[i]) == 1) { for (i; i<n; i++) { suite_a[i] = -1; } } } } // calcul l'approximation double fc_approx(int suite_a[], int n) { // n nombre de coefficient // i compteur int i = n - 2; // approx = approximation double approx = suite_a[n-1]; while (i>=0 && suite_a[i != -1]) { // on calcul la dernière fraction et on remonte approx = 1/approx + suite_a[i]; i--; } return(approx); } // affichage de la suite de coefficient void fc_affiche(int suite_a[], int n) { // n le nombre de coefficient // i compteur int i; cout << "a = [ "; for (i=0; i<n; i++) { cout << suite_a[i] << ", "; } cout << " ]" << endl; // on affiche l'approximation cout << "Approximation : " << fc_approx(suite_a, n) << endl; } // Programme principal int main() { // nombre d'occurence : n int n = 20; // nombre réel à décomposer double reel = 1.4142135; // resultat int suite_a[n]; // appel de la première fonction f2continue(reel, n, suite_a); // affichage de la fonction cout << "Fraction contine de "<< reel << " : " << endl; fc_affiche( suite_a, n); return(0); } <file_sep>################################################################################## # # # Combien faut-il d'achat de carte pour finir une collection. # # # ################################################################################## #################### # # 1 - Paramètres de la simulation # La taille de la collection # abrégé en TC dans les commentaires tailleCollection = 220 # Le nombre de carte par lot lors de l'achat. # abrégé en TL dans les commentaires tailleLot = 44 # Le nombre de simulation total et les itérations succéssives nbrSimulation = 500 iteSimulation = 100 #################### # 2 - Structure du tableau de donnée # A - dataCollection # Tableau de données de notre simulation pour faire nos stats sur # le nombre d'achat nécéssaire pour compléter une collection. # # dataCollection : 4 x nbrSimulation # -- numSimulation : Le numéro de la simulation - entier # -- nbrAchat : Le nombre d'achat nécéssaire - entier # -- maxDouble : Le plus grand nombre de double - entier # -- moyCarte : Le nombre moyen de carte - réel dataCollection = data.frame(numSimulation=1:nbrSimulation, nbrAchat=0, maxDouble=0, moyCarte = 0) # B - aCollection # Tableau de donnée par simulation recueillant l'ensemble des # cartes achetées. # # aCollection : tableau de TCx2. # -- numCarte : Numéro de carte - entier (1 à TC). # -- nbrCarte : Nombre de carte aquise - entier. #################### # 3 - Départ de la simulation while(iteSimulation <= nbrSimulation) { # initialisation de notre collection aCollection = data.frame(numCarte=1:tailleCollection, nbrCarte=0) # La collection est fini quand la somme du nombre de cartes # possédant au moins un exemplaire est égale à la taille de # la collection while(sum(aCollection$nbrCarte!=0) != tailleCollection) { # Il y a TL cartes par paquet acheté ech=0 while( ech < tailleLot ) { # tirage : achat d'une carte au hasard parmi TC # sortie équiprobable d'un nombre entier de 1 à TC compris tirage = floor(tailleCollection*runif(1)+1) # On rajoute 1 au numéro de carte nouvellement aquis. aCollection$nbrCarte[tirage] = aCollection$nbrCarte[tirage] + 1 ech = ech +1 } }# La collection est complète # On récupère les données, on n'oublie pas la virgule pour # intégrer les données sur la ligne et non dans la colonne dataCollection[iteSimulation,] = c(iteSimulation, sum(aCollection$nbrCarte), max(aCollection$nbrCarte), mean(aCollection$nbrCarte)) # On passe à la simulation suivante iteSimulation = iteSimulation + 1 }# Le nombre de simulation est suffisant # la simulation est terminé, on passe au traitement... #################### # 4 - Traitement des données # Trois histogrammes et leur boxplot associé sont tracés # - 1 - Le nombre d'achat de paquet à la fin d'une collection # - 2 - Le plus grand nombre de double moyen à la fin d'une collection # - 3 - Le nombre moyen de carte à la fin d'une collection pdf(file="1-nombre-achats.pdf") par(fig=c(0,1,0.3,.9), new=TRUE) hist(dataCollection$nbrAchat, freq=FALSE, col="grey", main="Nombre d'achats", xlab=NULL, ylab="Fréquence") lines(density(dataCollection$nbrAchat), col="red") par(fig=c(0,1,0,0.5), new=TRUE) boxplot(dataCollection$nbrAchat, horizontal = TRUE, col="grey") pdf(file="2-maximum-doubles.pdf") par(fig=c(0,1,0.3,.9), new=TRUE) hist(dataCollection$maxDouble, freq=FALSE, col="grey", main="Maximum de doubles", xlab=NULL, ylab="Fréquence") lines(density(dataCollection$maxDouble), col="red") par(fig=c(0,1,0,0.5), new=TRUE) boxplot(dataCollection$maxDouble, horizontal = TRUE, col="grey") pdf(file="3-moyenne-cartes.pdf") par(fig=c(0,1,0.3,.9), new=TRUE) hist(dataCollection$moyCarte, freq=FALSE, col="grey", main="Nombre moyen de cartes", xlab=NULL, ylab="Fréquence") lines(density(dataCollection$moyCarte), col="red") par(fig=c(0,1,0,0.5), new=TRUE) boxplot(dataCollection$moyCarte, horizontal = TRUE, col="grey") # Quelques informations importantes concernant le nombre de paquets achetés sont # affichées dans la sortie standart : Min, Q1, Mediane, Moyenne, Q3, Max print(summary(dataCollection$nbrAchat)) print(summary(dataCollection$maxDouble)) print(summary(dataCollection$moyCarte)) <file_sep>function [X_n,X_fin]=F_interval(inter,fin) //On peut utiliser la fonction linspace(a,n,b) X_n(1)=inter(1) X_fin(1)=inter(1) for i=1:1:n X_n(i+1)=inter(1)+i*(inter(2)-inter(1))/(n), end for i=1:1:fin X_fin(i+1)=inter(1)+i*(inter(2)-inter(1))/(fin), end endfunction function [X_n]=F_permut(X_n,val,place) // si place = 1 alors on incrémente a partir du premier et si place = -1 on incremente à partir du dernier Xtemp=X_n if place ==1 then X_n(1)=val for i1=1:1:length(X_n)-1 X_n(i1+1)=Xtemp(i1) end else X_n(length(X_n))=val for i1=1:1:length(X_n)-1 X_n(i1)=Xtemp(i1+1) end end endfunction<file_sep>\documentclass[12pt]{article} \usepackage{geometry} \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,french]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx,float,grffile} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} \fancyfoot{} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0pt} \usepackage{hyperref} \begin{document} \newtheorem{Theorem}{Théorème} \subsection*{1 - Vocabulaire} \begin{Theorem}{Expérience aléatoire} \label{thm1-ea}\\ Une expérience est aléatoire si elle vérifie deux conditions. \begin{itemize} \item On connait toutes les \textbf{issues} possibles. \textit{On sait ce qui peut se passer.} \item Le résultat n'est pas \textbf{prévisible}. \textit{On ne sait pas ce qui va se passer.} \end{itemize} \end{Theorem} \newpage blabla \newpage J'ai envie de me rappeler de ça : \hyperref[thm1-ea]{Théorème blabla} \end{document} <file_sep>/** * <NAME>, <NAME>. * This file must be used under the term of the GPLv3 * Decomposition LU séquentielle */ #include <stdio.h> #include <math.h> #define NRA 15 /* number of rows in matrix A */ // ligne pour compiler // gcc LU-seq.c -o LU-seq //Matrice de départ double a_mat[NRA][NRA]; double b_mat[NRA]; //Décomposition de A double l_mat[NRA][NRA]; double u_mat[NRA][NRA]; //Vecteur colonne résultat double y_mat[NRA]; double x_mat[NRA]; /***************************************** * * * Création des matrices de tests * * * ******************************************/ void creactionmatrice(void) { int i = 0; while (i < NRA -1) { b_mat[i] = i+2; a_mat[i][0] = 1; a_mat[i][i+1] = i+1; u_mat[i][0] = 1; u_mat[i][i+1] = i+1; l_mat[i][i]=1; i = i + 1; } b_mat[NRA - 1] = 1; a_mat[NRA - 1][0] = 1; u_mat[NRA - 1][0] = 1; l_mat[NRA - 1][NRA - 1] = 1; } /******************************************* * * * affichage des matrices * * * ********************************************/ void mat_display(void) { int i,j=0; printf("**************matrice A************:\n"); printf("\n"); for(j=0; j < NRA; j++) { for (i=0; i < NRA; i++) { printf("%lf ",a_mat[j][i]); } printf("\n"); } printf("\n"); printf("\n************matrice B************:\n"); printf("\n"); for (j=0;j<NRA;j++) { printf("%lf ",b_mat[j]); printf("\n"); } printf("\n"); printf("**************matrice L************:\n"); printf("\n"); for(j=0; j < NRA; j++) { for (i=0; i < NRA; i++) { printf("%lf ",l_mat[j][i]); } printf("\n"); } printf("\n"); printf("**************matrice U************:\n"); printf("\n"); for(j=0; j < NRA; j++) { for (i=0; i < NRA; i++) { printf("%lf ",u_mat[j][i]); } printf("\n"); } printf("\n"); printf("\n************matrice X************:\n"); printf("\n"); for (j=0;j<NRA;j++) { printf("%lf ",x_mat[j]); printf("\n"); } } /******************************************* * * * décomposition de A * * * ********************************************/ void decompmatriceA(void) { int i = 0; int j = 0; int k; while(j < NRA - 1) { k = j + 1; //Calcul de la j-eme colonne de L while(k < NRA) { l_mat[k][j] = u_mat[k][j] / u_mat[j][j]; //printf("Calcul de L : j = %d, i = %d, k = %d",j,i,k);printf("\n"); k++; } i = j + 1; //Calul pour la i-eme ligne de U while(i < NRA) { k=j; //Calcul pour les différents coeff de cette i-eme ligne while(k < NRA) { u_mat[i][k] = u_mat[i][k] - l_mat[i][j] * u_mat[j][k]; //printf("Calcul de U : j = %d, i = %d, k = %d",j,i,k);printf("\n"); k++; } i++; } j++; } } /******************************************* * * * Résolution du problème * * * ********************************************/ void resolution(void) { //Ly = b int i; int j = 1; //On calcul Le premier terme de la remonté, comme 1 sur la diagonale y_mat[0] = b_mat[0]; double tmp; // on fait une descente while( j < NRA) { tmp = 0.0; i = 0; while( i < j) { tmp = tmp + y_mat[i]*l_mat[j][i]; i++; } y_mat[j] = b_mat[j] - tmp; j++; } j = NRA -2; //Ux = b //On calcul Le premier terme de la remonté, x_mat[NRA - 1] = y_mat[NRA-1]/u_mat[NRA-1][NRA-1]; tmp = 0.0; // on fait une remonté while( j >= 0) { tmp = 0.0; i = j+1; while( i <= NRA -1) { tmp = tmp + x_mat[i]*u_mat[j][i]; i++; } x_mat[j] = (y_mat[j] - tmp)/u_mat[j][j]; j--; } } int main() { //Création des matrices creactionmatrice(); //Décomposition de A en LU decompmatriceA(); //On résoud le système linéaire resolution(); //On affiche le résultat mat_display(); return(0); } <file_sep>funcprot(0) function [Coef_poly,Erreur]=F_Coef_Tcheby(fon_uti) //Soit Coef_poly la matrice des coéfficients du polynôme //Soit Vender la matrice de Vandermonde for i=1:1:n+1 for j=0:1:n Vander(i,j+1)=X_n(i)**j, end Vander(i,n+1)=(-1)**(i+1) end //Soit ColFunc1 le vecteur colonne de la fonction fon_uti aux points de X_n for i=1:1:n+1 ColFunc1(i)=fon_uti(X_n(i)) end Coef_poly=lsq(Vander,ColFunc1) Erreur=abs(Coef_poly(n+1)) endfunction funcprot(0) function [Poly_tcheby]=F_Poly_Tcheby(x) //On construit le polynome à partir des coefficients obtenu par Tcheby //On appelle la fonction qui calcul les coeffs A=0 for i=1:1:n A=A+Coef_poly(i)*(x)^(i-1) end Poly_tcheby=A endfunction [Coef_poly,Erreur]=F_Coef_Tcheby(fon_uti); [Poly_tcheby]=F_Poly_Tcheby; funcprot(0) function [fmoinsp]=F_fmoinsp(x) fmoinsp=fon_uti(x)-Poly_tcheby(x) endfunction funcprot(0) [fmoinsp]=F_fmoinsp;<file_sep># Le jeu de la vie. > [ - Wikipédia -](http://fr.wikipedia.org/wiki/Jeu_de_la_vie) Le jeu de la vie imaginé par <NAME> en 1970 est un automate cellulaire. Le jeu se déroule sur un plateau dont les cases appelés cellules sont *vivantes* ou *mortes*. L’évolution des cellules est déterminée par l’état de ses huit voisines. > * Une cellule morte possédant exactement trois voisines vivantes devient vivante (elle naît). * Une cellule vivante possédant deux ou trois voisines vivantes le reste, sinon elle meurt. ## Organisation * *Cellule* : Classe pour la cellule. * *Plateau* : Classe pour le plateau et les règles de jeu. ## Utilisation ### Cellules ```c++ // Créer une cellule morte Cellule cell_morte(0); // Créer une cellule vivante Cellule cell_vivante(1); ``` ### Plateau ```c++ // Plateau carré de taille 3x3. Plateau plateau_de_3(3); // Évoluer une fois. plateau_de_3.Evolution(); // Évoluer *n* fois. plateau_de_3.Evolution(n); ``` ### Affichage ```c++ // Afficher le plateau dans la sortie standart. plateau_de_3.show(); // Afficher le plateau ainsi que les bords utiles pour le calcul. plateau_de_3.showTotal(); ``` <file_sep> d <- data.frame(pre = data.fgsm3$pre, post = data.fgsm3$post) ggpaired(d, cond1 = "pre", cond2 = "post", fill = "condition", palette = "jco") wdata = data.frame( test = groupes.FGSM3.PP, notes = c(data.fgsm3$pre, post = data.fgsm3$post)) head(wdata, 4) gghistogram(wdata, x = "notes", add = "mean", rug = TRUE, color = "test", fill = "test", palette = c("#00AFBB", "#E7B800")) ggboxplot(wdata, x = "test", y = "notes", color = "test", palette =c("#00AFBB", "#E7B800", "#FC4E07"), add = "jitter", shape = "test") ggviolin(wdata, x = "test", y = "notes", fill = "test", palette = c("#00AFBB", "#E7B800", "#FC4E07"), add = "boxplot", add.params = list(fill = "white")) ggbarplot(wdata, x = c(1:(nb.fgsm3*2)), y = "notes", fill = "test", # change fill color by cyl color = "white", # Set bar border colors to white palette = "jco", # jco journal color palett. see ?ggpar sort.val = "desc", # Sort the value in dscending order sort.by.groups = FALSE, # Don't sort inside each group x.text.angle = 90 # Rotate vertically x axis texts ) <file_sep>// n+1 est le nombre de points dans [a,b]. n correspond également au degré du polynôme. // X_n ces points //fin+1 un nombre de point bien plus précis pour X_fin sur le même intervalle //inter est l'intervalle d'étude //fon_tp crée les fonctions utilisées pour le tester le TP exec('fon_tp.sci'); //main avec boite de lancement choix=x_choose(['Racine de X sur [0 1]';'Valeur absolue de X sur [-1 1]';'x**n'],['Choisissez l exercice']) if choix==1 inter=[0 1]; n=4; fon_uti=F_fon_sqrt; ite=6 elseif choix==2 inter=[-1 1]; n=6; fon_uti=F_fon_abs; ite=6 elseif choix==3 sig=x_mdialog('choisir n',['n'],['5']) n=evstr(sig(1)) inter=[-1 1] fon_uti=F_xpuisn ite=10 end fin=100; Erreur=0.1; //intervalle.sci crée deux vecteurs d'abscisses exec('intervalle.sci'); [X_n,X_fin]=F_interval(inter,fin); //fon_tp crée les fonctions utilisées pour le tester le TP //Ici on choisit la fonction qu'on va utilisé //On execute l'algorythme de Tchebytchev qui nous sort une matrice avec les coefficients alterné du polynome dans la matrice Coef_poly et l'Erreur. On construit également le polynôme. //Dans l'exec se situe aussi le graph de la fonction demandé sur les X_fin plot2d(X_fin,fon_uti(X_fin),style=5) j=1 while j<ite exec('tcheby.sci'); exec('remez.sci'); //disp('Erreur =',Erreur) [Cprime]=F_remez(Poly_tcheby); //disp('Cprime =',Cprime) //On trace les fonction plot2d(X_fin,F_Poly_Tcheby(X_fin)) plot2d(X_n,F_Poly_Tcheby(X_n),style=-2) xpause(10**6) //on appelle l'algo de remez exec('algofin_remez.sci'); [X_n]=F_alog_remez(Cprime,X_n); //disp(X_n); j=j+1; end <file_sep># On est sur la première case. # On a un grain de blé sur la première case. # On a un grain de blé sur l'échéquier. # Nombre de grain de blé par case. # case est un nombre entier. case = 1 # Nombre de grain blé au total sur l'échiquier. # blé est un nombre entier. ble = 1 # Coefficient d'augmentation du nombre de grain de blé par case. # coef est un nombre entier coef = 2 # Il y a 8*8=64 cases sur un échiquier. # Il nous reste 63 cases à remplir de grain de blé. # Si on veut connaitre pour toutes les cases. print("Sur la première case, il y a : ", case, "grains de blé, pour un total de : ", ble , "grains sur l'échiquier.") # On parcours les 63 cases restantes for i in range(2,65): # Les cases suivantes contienent deux fois plus de grain de blé. case = case * coef # À chaque fois on rajoute les grains de la case dans le sac de blé. ble = ble + case # Si on veut connaitre pour toutes les cases. print("Sur la case : ", i , " , il y a : ", case, "grains de blé, pour un total de : ", ble , "grains sur l'échiquier.") print("Nombre de grain de blé sur l'échéquier", ble) print("Écriture scientifique : ", ble*1.) # Poids en g. On multiplie le nombre de grain par 0.05g poids = ble * 0.05 # Poids en tonnes. On divise par 10^6 ou on multiplie par 10^-6 poids = ble * 0.05 * 10**(-6) print("Poids du blé total en tonnes : ", poids, " tonnes") # Le nombre d'année nécéssaire. # Par an, la production mondiale de blé est : 600 millions. prod_an = 600 * 10 **6 print("La production annuelle de blé est de ", prod_an, "tonnes de blé") # Le nombre d'année nécéssaire = # notre poids de blé sur l'échiquier diviser par la production annuelle. nombre_an = poids / prod_an print("Il faudra : ", nombre_an, "années à l'empereur afin de combler ça promesse.") <file_sep># importation des donnees # création des tableaux # lignes les notes d'une même personne # deux colonnes de notes : pre et post data.fgsm3 = read.csv("data.fgsm3.csv", header=TRUE, sep=",") data.eleves = read.csv("data.eleves.csv", header=TRUE, sep=",") # packages à charger # install.packages("ggpubr") library(ggpubr) # les effectifs des groupes nb.fgsm3 = length(data.fgsm3$pre) nb.eleves = length(data.eleves$pre) nb.total = nb.eleves + nb.fgsm3 # Le groupes FGSM3, Eleves, Pré et Post groupes.FGSM3.ELEVES = c(rep("fgsm3",nb.fgsm3),rep("eleves",nb.eleves)) groupes.FGSM3.PP = c(rep("fgsm3.pre",nb.fgsm3),rep("fgsm3.post",nb.fgsm3)) groupes.ELEVES.PP = c(rep("eleves.pre",nb.eleves),rep("eleves.post",nb.eleves)) # I. test de normalité ; Test Shapiro # H0 l'échantillon suit une loi normale. # 1. FGSM 3 : PréTest et PostTest test.norm.fgsm3.pre = shapiro.test(data.fgsm3$pre) test.norm.fgsm3.post = shapiro.test(data.fgsm3$post) # 2. ELEVES : PréTestPostTest test.norm.eleves.pre = shapiro.test(data.eleves$pre) test.norm.eleves.post = shapiro.test(data.eleves$post) # II. test de distribution ; Test Wilcoxon <NAME> # H0 la distribution des données est la même pour les deux groupes. # B. FGSM3 vs Eleves # 1. Pré notes.pre.fgsm3vseleves = c(data.fgsm3$pre,data.eleves$pre) test.notes.pre.fgsm3vseleves = wilcox.test(notes.pre.fgsm3vseleves~groupes.FGSM3.ELEVES) boxplot(notes.pre.fgsm3vseleves~groupes.FGSM3.ELEVES, col=c("pink","lightsteelblue3"), main="Notes : PréTest Élèves et PréTest FGSM3") # 2. Post notes.post.fgsm3vseleves = c(data.fgsm3$post,data.eleves$post) test.notes.post.fgsm3vseleves = wilcox.test(notes.post.fgsm3vseleves~groupes.FGSM3.ELEVES) boxplot(notes.post.fgsm3vseleves~groupes.FGSM3.ELEVES, col=c("pink","lightsteelblue3"), main="Notes : PostTest Élèves et PostTest FGSM3") # 3. Pré FGSM3 vs Post Élèves notes.pre.fgsm3vspost.eleves = c(data.fgsm3$pre,data.eleves$post) test.notes.pre.fgsm3vspost.seleves = wilcox.test(notes.pre.fgsm3vspost.eleves~groupes.FGSM3.ELEVES) boxplot(notes.pre.fgsm3vspost.eleves~groupes.FGSM3.ELEVES, col=c("pink","lightsteelblue3"), main="Notes : PostTest Élèves et PréTest FGSM3") # Explication du W rangs=rank(notes.pre.fgsm3vspost.eleves) data=data.frame(groupes.FGSM3.ELEVES,notes.pre.fgsm3vspost.eleves,rangs) boxplot(rangs~groupes.FGSM3.ELEVES, col=c("pink","lightsteelblue3"), main="Rang des notes : PostTest Élèves et PréTest FGSM3") # C. Pré vs Post # 1. FGSM3 notes.fgsm3prevspost = c(data.fgsm3$pre,data.fgsm3$post) test.fgsm3.prevspost = wilcox.test(data.fgsm3$pre, data.fgsm3$post, paired = TRUE) boxplot(notes.fgsm3prevspost~groupes.FGSM3.PP, col=c("pink","lightsteelblue3"), main="Notes : PréTest FGSM3 et PostTest FGSM3") test.eleves.prevspost = wilcox.test(data.eleves$pre, data.eleves$post, paired = TRUE) # 2. Élèves notes.elevesprevspost = c(data.eleves$pre,data.eleves$post) test.eleves.prevspost = wilcox.test(data.eleves$pre, data.eleves$post, paired = TRUE) boxplot(notes.elevesprevspost~groupes.ELEVES.PP, col=c("pink","lightsteelblue3"), main="Notes : PréTest Élèves et PostTest Élèves") # Ecriture dans le fichier sink("sortie.R-these-med.txt") print("A. Test de normalité") print("1. Normalité : PréTest FGSM3") print(test.norm.fgsm3.pre ) print("2. Normalité : PostTest FGSM3") print(test.norm.fgsm3.post ) print("3. Normalité : PréTest Élèves") print(test.norm.eleves.pre ) print("4. Normalité : PréTest Élèves") print(test.norm.eleves.post ) print("B. FGSM3 vs Eleves") print("1. Notes : PréTest FGSM3 vs PréTest Élèves") print(test.notes.pre.fgsm3vseleves) print("2. Notes : PostTest FGSM3 vs PostTest Élèves") print(test.notes.post.fgsm3vseleves) print("3. Notes : PréTest FGSM3 vs PostTest Élèves") print(test.notes.post.fgsm3vseleves) print("C. pré vs Post") print("1. Notes : PréTest FGSM3 vs PostTest FGSM3") print(test.fgsm3.prevspost) print("2. Notes : PréTest Élèves vs PostTest Élèves") print(test.eleves.prevspost) sink() <file_sep># Dossiers CODE := $(shell pwd) BUILD = build/ src: gcc -wall src/morpions.c –o $(BUILD)/morp gcc -c -Wall main.c gcc -o prog main.o structure.o operation.o $(BUILD)/morp: src/morpion.c gcc src/morpions.c –o $@<file_sep># Échiquier ## Contexte En tant qu'intendant du roi, vous compter le nombre de grain de blé que Sissa a gagner lors de sa requête auprès de l'empereur pour avoir un échiquier rempli de grain de blé de la manière suivante : - 1 grain de blé sur la première case. - 2 grains de blé sur la deuxième case. - 4 grains de blé sur la troisième case. Et on multiplie le nombre de grain de blé par deux en avançant de case en case. ## Énoncé L'énoncé a été gracieusement récupérer chez mathonautes. http://mathonautes.free.fr/Quatrieme/Puissances/ActiviteEchecs.pdf ## Correction ### Programme python3 grain-de-ble.py ### Fichiers - **src/grain-de-ble.py** : script écrit en python qui permet de compter. - **log/log_17-01-19.txt** : fichier réponse archivé. <file_sep>from __future__ import division # -*- coding: utf-8 -*- import math import random random.seed() ######################################################### # # # Lièvre # # VS # # Tortue # # # ######################################################### # On fait tourner un grand nombre de partie et on compte # les manches gagnées par le lapin et par la tortue. # --- Entrées # - nombremanche : le nombre de manche joué. # - case : Nombre de case que doit parcourir la tortue afin # de gagner. # --- Sorties # - partieLapin # - partieTortue def manche(nombreManche, case): # Le nombre de partie gagné par le lapin partieLapin = 0 # Le nombre de partie gagné par la tortue partieTortue = 0 # On part à la partie 1 for i in range( 0, nombreManche): if lot(case) == 0: partieLapin += 1 #print("Lapin") else: partieTortue += 1 #print("tortue") return( [partieLapin, partieTortue]) # Fonction lot() : # --- Entrée : # # --- Sorties # - 1 : si le lapin gagne. # - 0 : si la tortue gagne. def lot(case): # caseLapin : Fait avancer le lapin caseLapin = 0 # caseTortue : Fait avancer la tortue caseTortue = 0 # Soit le lapin avance et gagne. # Soit la tortue arrive à avancer suffisament loin # jusqu'à un certain nombre de case. while (caseLapin != 1 and caseTortue != case): de = random.randint(1,6) # Si on fait un 6, le lapin avance if(de == 6): caseLapin = 1 # et gagne (on écrit retourne un 0) return(0) # Sinon, la tortue avance caseTortue += 1 # La tortue a gagné return(1) # Execution du programme. print("-------- Lièvre ---------") print("-------- VS ---------") print("-------- Lapin ---------") # Nombre de partie N = 1000 # La tortue doit avancer de quatre cases. print("Si la tortue doit avancer de 4 cases") res = manche(N,4) print("Resultat = [lapin , tortue]",res) # La tortue doit avancer de trois cases. print("Si la tortue doit avancer de 3 cases") res = manche(N,3) print("Resultat = [lapin , tortue]",res) <file_sep>// Main // <NAME> //Exo 1 exec('tp0-ex1.sci'); halt //Exo 2 n_in=evstr(x_dialog('Grandeur de la récurrence ?','30')) xset("window",1); exec('tp0-ex2.sci'); tab_comp(n_in) halt x_dialog (['Exo 2';'En rouge la récurrence classique et en vert l-inversé';'On trouve que la récurrence simple est passablement fausse dès le rang 13']); zoom_rect([12.8,0.005,14.2,0.0075]) halt //Exo 3 xset("window",2); exec('tp0-ex3.sci'); <file_sep># Fonction pour définir si oui ou non l'année est bissextile def bissextile(annee) : if (annee % 4 ==0 and annee % 100 != 0) or annee % 400 == 0 : return True return False def jour_mois(mois, annee) : if (bissextile(annee)) : jour = [31, 29, 31, 30 , 31, 30, 31, 31, 30, 31, 30, 31] return (jour[mois - 1]) else : jour = [31, 28, 31, 30 , 31, 30, 31, 31, 30, 31, 30, 31] return (jour[mois - 1]) def affiche_jour(mois, annee) : if (bissextile(annee)) : est_bissextile = " est bissextile" else : est_bissextile = " n'est pas bissextile" jour = str(jour_mois(mois, annee)) print("Le mois numéro: " + str(mois) + " possède " + jour + " jours et l année" + est_bissextile) annee = int(input("Choissisez une année : ")) mois = int(input("Choissisez un mois : ")) affiche_jour(mois, annee)<file_sep>//Le TP0 Erreur d'arrondi // <NAME> //Exo 1 - Le but est d'approximer la fonction cosinus d'une manière stable //a - Volontairement on va faire selon la série entière classique... function [a1_cos]=F_a1_cos(x) // A1_cos est la fonction de sortie // x est l'entrée de la fonction // N est le nombre d'itération qu'on va faire pour la série entière. N=50 // On part avec une série entière avec un premier terme a1 = 1 a1_cos=1 //on part à k = 1!!! car on a déjà pris un a1 for k=1:1:N // On calcul la factoriel à chaque rang tout rang facto=prod([1:2*k]) a1_cos=a1_cos+(((-1)^k)*(x**(2*k)/facto)), end endfunction function [a2_cos]=F_a2_cos(x) // a2_cos est la fonction de sortie // x est l'entrée de la fonction // N est le nombre d'itération qu'on va faire pour la série entière. N=50 // Pour faire un calcul plus juste on utilise la périodicité de cos. en effet cos(a)=cos(2*pi*a) x_mod=pmodulo(x,2*%pi) // On part avec une série entière avec un premier terme a1 = 1 a2_cos=1 //on part à k = 1!!! car on a déjà pris un a1 for k=1:1:N // On calcul la factoriel à chaque rang tout rang facto=prod([1:2*k]) a2_cos=a2_cos+(((-1)^k)*(x_mod**(2*k)/facto)), end endfunction function [a3_cos]=F_a3_cos(x) // a3_cos est la fonction de sortie // x est l'entrée de la fonction // N est le nombre d'itération qu'on va faire pour la série entière. N=50 //un sert a faire l'alternance des termes de la série entière un=1 //a3_cos est initialisé à un som1(1)=1 prod1(1)=1 for i=1:1:N-1 prod1(i+1)=prod1(i)*(x/(2*i))*(x/(2*i-1)), un=(-1)*un, som1(i+1)=som1(i)+(un*prod1(i+1)), end a3_cos=som1(N) endfunction function [a4_cos]=F_a4_cos(x) // a3_cos est la fonction de sortie // x est l'entrée de la fonction // N est le nombre d'itération qu'on va faire pour la série entière. N=50 // Pour faire un calcul plus juste on utilise la périodicité de cos. en effet cos(a)=cos(2*pi*a) x_mod=pmodulo(x,2*%pi) //un sert a faire l'alternance des termes de la série entière un=1 //a3_cos est initialisé à un som1(1)=1 prod1(1)=1 for i=1:1:N-1 prod1(i+1)=prod1(i)*(x_mod/(2*i))*(x_mod/(2*i-1)), un=(-1)*un, som1(i+1)=som1(i)+(un*prod1(i+1)), end a4_cos=som1(N) endfunction a1_cos=F_a1_cos; a2_cos=F_a2_cos; a3_cos=F_a3_cos; a4_cos=F_a4_cos; inter=30:0.1:39.5; plot2d(inter,a1_cos(inter),style=5) plot2d(inter,a2_cos(inter)) <file_sep># Importation des modules import sys sys.path.insert(0,'src') import rpn_list4_calc as calc # Essai interface pessai = calc.list4() registre = "0" while (registre != "q" and registre != "x"): regt = registre.split(" ") if regt[0] == "s": pessai.swap() elif regt[0] == "h": pessai.fhaut() elif regt[0] == "b": pessai.fbas() elif regt[0] == "+": pessai.additioner() elif regt[0] == "-": pessai.soustraire() elif regt[0] == "*": pessai.multiplier() elif regt[0] == "/": pessai.diviser() else : nb = float(regt[0]) pessai.empile(nb) pessai.affiche() registre = input('Registre : ') <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { double nombre = 24589 ; double compteur = nombre ; int i = 1 ; while(compteur >= 10) { compteur = compteur / 10 ; i = i + 1; } printf("%d \n",i); } <file_sep># Dossiers CODE := $(shell pwd) PDFDIR = _pdf THEME = # Visualiser les pdf LOG=evince # Créer le dossier pdf s'il n'éxiste pas. target: test -d $(PDFDIR) || mkdir $(PDFDIR) math_intro-edo-1: pdflatex math_intro-edo-1.d/math_intro-edo-1.tex pdflatex math_intro-edo-1.d/math_intro-edo-1.tex mv math_intro-edo-1.pdf '$(PDFDIR)'/math_intro-edo-1.pdf info_intro-go-1: pdflatex info_intro-go.d/info_intro-go-1.tex pdflatex info_intro-go.d/info_intro-go-1.tex mv info_intro-go-1.pdf '$(PDFDIR)'/info_intro-go-1.pdf astro_deux-infinis-4: pdflatex astro-deux-infinis.d/astro_2-infinis-4.tex pdflatex astro-deux-infinis.d/astro_2-infinis-4.tex mv astro_2-infinis-4.pdf '$(PDFDIR)'/astro_2-infinis-4.pdf astro_ss: pdflatex astro_system.d/astro_ss.tex pdflatex astro_system.d/astro_ss.tex mv astro_ss.pdf '$(PDFDIR)'/astro_system-solar-ss.pdf # nettoyage proper: rm -f *.log *.toc *.aux *.nav *.snm *.out *.bbl *.blg *.dvi *.ps rm -f *.backup *~<file_sep>\input{doc-class-cours.tex} \begin{document} \section*{Semaine 4 - The insides of giant planets (week 1)} \begin{itemize}[label={$\bullet$}] \item Vidéo : 2.01: Introduction to Jupiter \item Vidéo : 2.02: Measuring density \item Demande de discussion : Transit of Venus! \item Vidéo : 2.03: Using density \item Vidéo : 2.04: Hydrostatic equilibrium \item Vidéo : 2.05: Hydrogen equation of state \item Vidéo : 2.06: Heat transport \item Vidéo : 2.07: Theoretical internal structure \item Vidéo : 2.08: A core from gravity ? \item Vidéo : 2.09: Magnetic fields \item Vidéo : 2.10: The upper atmosphere and the Galileo probe \item Vidéo :2.11: Picture models \end{itemize} \subsection*{Quiz 4} \begin{enumerate} \item[1.] Kepler's planetary laws, coupled with Newton's equation of gravitation, lets us determine the mass of a planet by measuring the orbital semimajor axis and orbital period. Which one of the following moons will have almost exactly the same period as a moon with the mass of Europa $1 M_e$ with a semimajor axis of 1 million km $10^6 km$ around a planet with the mass of Jupiter $1 M_J$ A moon with a mass of $(in M_e)$, a semimajor axis of (in km), and orbital a planet with the mass of in $(M_J)$: \begin{itemize}[label={$\bullet$}] \item moon mass = $2 M_e$ ; semi axis = $2 \times 10^6 km$ ; planet mass = $8 M_j$ \item moon mass = $1/2 M_e$ ; semi axis = $1/2 \times 10^6 km$ ; planet mass = $8 M_j$ \item moon mass = $1/2 M_e$ ; semi axis = $2 \times 10^6 km$ ; planet mass = $2 M_j$ \item moon mass = $1 M_e$ ; semi axis = $1/2 \times 10^6 km$ ; planet mass = $2 M_j$ \item moon mass = $1/2 M_e$ ; semi axis = $8 \times 10^6 km$ ; planet mass = $2 M_j$ \item moon mass = $1 M_e$ ; semi axis = $1/8 \times 10^6 km$ ; planet mass = $1/2 M_j$ \end{itemize} \item[2.] Of the planets in the solar system Earth is the most dense and Saturn is the least dense, but the densities of the planets are greatly affected by compression. Planetary scientist often talk of "uncompressed densities" meaning the density that the planet would have if all of its materials were at 1 bar of pressure. Using what you know of the densities of materials and the compositions of the planets, which planet has the highest uncompressed density? \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item Mercury \item Venus \item Earth \item Mars \item Jupiter \item Saturn \item Uranus \item Neptune \end{itemize} \end{multicols} \item[3.] The equation of hydrostatic equilibrium allows you to determine the pressure inside of a planet as a function of depth. What piece of information is required in all cases to use the equation of hydrostatic equilibrium? \begin{itemize}[label={$\bullet$}] \item A knowledge of whether or not there is a core inside of the planet. \item An equation of state telling you the density of the material as a function of pressure. \item The temperature profile inside of the planet. \item A phase diagram of the substance at the temperatures and pressures of the interior. \item The mean molecular mass of the substance \item An understanding of the interior heat flow. \end{itemize} \item[4.] In a Fermi gas -- which is not a bad approximation to the equation of state in the center of Jupiter -- what is the main reason for the resistance of the gas to compression? \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item Electrons which are unable to occupy the same quantum state. \item Electrostatic repulsion \item High temperatures \item A high effective mean molecular mass \item A phase transition to a solid \item Convective instability \end{itemize} \end{multicols} \item[5.] Which of the following is the farthest from being in hydrostatic equilibrium? (notice that I say farthest here, because new things are perfectly in hydrostatic equilibrium, but many things are pretty close). \begin{itemize}[label={$\bullet$}] \item The water inside of a glass \item The interior of the Earth \item The interior of Jupiter \item The Earth's atmosphere \item A rock \end{itemize} \item[6.] Which of the following is NOT true about the process of convection? \begin{itemize}[label={$\bullet$}] \item Convection can occur due to cooling at the top as well as heating at the bottom. \item Convection of a conducting medium is required for the generation of a magnetic field inside of a planet \item Convection is the fastest way for a planet to remove heat from its interior \item Convection can only be sustained if energy is both input at the bottom and removed at the top. \item These are all true \item Any time warm air is below cooler air, convection will occur \end{itemize} \item[7.] We think Jupiter most likely has a core, though it is one of the major goals of the Juno spacecraft to find out for sure. Which of the following is NOT a reason that we think Jupiter most likely has a core? \begin{itemize}[label={$\bullet$}] \item To fit the density of Jupiter you need to add a significant amount of extra heavier material compared to the atmosphere. \item Saturn clearly has a core and it would seem odd to have two planets right next to each other and that look so similar to actually be so different on the inside. \item The best fit interior models, though still uncertain, work better with a core than without. \item The presence of a magnetic field strong suggests the presence of a core \item All of these are reasons to think that Jupiter has a core \end{itemize} \item[8.] Which of the following is a TRUE statement about what was found by sending the Galileo probe into Jupiter? \end{enumerate} \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item None of these is true \item The chemicals in the atmosphere of Jupiter are spatially homogeneous \item The upper atmosphere has elevated abundances of many elements \item The abundances of helium and neon are elevated because they are retained in clouds in the upper atmosphere \item Water vapor is abundant just below the cloud tops \end{itemize} \end{multicols} \newpage \section*{Semaine 5 - The insides of giant planets (week 2)} \begin{itemize}[label={$\bullet$}] \item Vidéo : 2.12: Planetesimal formation \item Vidéo : 2.13: Core formation \item Vidéo : 2.14: Core-collapse vs. Disk instability \item Demande de discussion : Core collapse vs. disk instability? \item Vidéo : 2.15: Saturn and the ice giants \item Vidéo : 2.16: Discovering hot Jupiters \item Vidéo : 2.17: Densities of hot Jupiters \item Vidéo : 2.18: Inflating hot Jupiters \item Vidéo : 2.19: Kepler and the sub-Neptunes \item Vidéo : 2.20: Exoplanet spectroscopy \item Vidéo : 2.21: Juno and future exploration \item Demande de discussion : Juno results? \end{itemize} \newpage \subsection*{Quiz 5} \begin{enumerate} \item[1.] Which planet would have the lowest uncompressed density? \begin{multicols}{4} \begin{itemize}[label={$\bullet$}] \item Mercury \item Venus \item Earth \item Mars \item Jupiter \item Saturn \item Uranus \item Neptune \end{itemize} \end{multicols} \item[2.] Which of the following is not a reason that we expect metallic hydrogen inside of Jupiter? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The phase diagram predicts metallic hydrogen. \item All of these statements are true. \item Helium rains out of the upper layers into the lower layers. \item The presence of a strong magnetic field suggests a conductive interior. \item The dipole nature of the magnetic field suggests a deep conductive layer \item The interior pressures are higher than the gas-to-metal transition. \end{itemize} \end{multicols} \begin{multicols}{2} \item[3.] Which of the following orbits (some of which would require extra propulsion to follow) would be best for using gravitational measurements to determine the interior structure of a planet? (the inner and outer dashed lines are circles of 10 planet radius and 100 planet radius, for consistent scale) \begin{figure}[H] \centering \includegraphics[width=0.8\linewidth]{astro_system.d/orbits.png} \end{figure} \end{multicols} \item[4.] Which of the following is not required for the creation of a dynamo-driven magnetic field? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Interior motions deflected by the Coriolis effect \item A core of ice and/or rock \item A rotating planet \item All of these are required \item A conducting liquid in the interior \item An interior which gets hotter with depth \item Convection in the interior \end{itemize} \end{multicols} \item[5.] Which of the following is the best description of the formation of a giant planet with a massive core? (at least as described in the lectures!) \begin{itemize}[label={$\bullet$}] \item In a massive disk the force of gravity in a patch of the disk overcomes the pressure and rotational forces and the patch quickly collapses into a giant planet. The heavy materials sink to the bottom and form the core. \item Planetesimals grow through gravitational focusing. Dynamical friction slows the motions of the largest objects leading to runaway growth of oligarchs, which are isolated from other nearby oligarchs. The gravitational pull of the oligarch quickly overcomes the rotational and pressure forces from the disk, causing rapid growth of the gaseous atmosphere. \item Planetesimals grow through gravitational focusing. Dynamical friction slows the motions of the largest objects leading to runaway growth of oligarchs, which are isolated from other nearby oligarchs. Gas slowly accretes onto the oligarch through an envelope until the pressures are too high to support the envelope and massive amounts of gas collapse making the gas giant. \item Planetesimals grow through gravitational focusing. Dynamical friction speeds the motions of the largest objects leading to more frequent collisions and runaway growth of oligarchs, which are isolated from other nearby oligarchs. Gas slowly accretes onto the oligarch through an envelope until the pressures are too high to support the envelope and massive amounts of gas collapse making the gas giant. \item Planetesimals grow through gravitational focusing. Dynamical friction slows the motions of the largest objects leading to runaway growth of oligarchs, which are isolated from other nearby oligarchs. Large numbers of oligarchs merge over hundreds of millions of years, leading to a giant core.Gas slowly accretes onto the oligarch through an envelope until the pressures are too high to support the envelope and massive amounts of gas collapse making the gas giant. \end{itemize} \item[6.] Based on our current understanding of the results from the Kepler mission, what is the most common type of planet with orbital periods less than 90 days? \begin{multicols}{3} \begin{itemize}[label={$\bullet$}] \item Planets with masses between that of the Earth and Neptune \item Hot Jupiters \item Water worlds \item Super earths with solid surfaces \item Planets less massive than the Earth \item Sub-Neptunes with ice/rock cores and gas envelopes \end{itemize} \end{multicols} \item[7.] The processes of gravitational focusing and dynamical friction are critical to our understanding of how planetesimals form. Which of the following is NOT true about gravitational focusing and dynamical friction? \begin{itemize}[label={$\bullet$}] \item As dynamical friction slows down large bodies with respect to each other, gravitational focusing increases dramatically \item Dynamical friction makes small bodies go fast and large bodies go slow \item Dynamical friction works most efficiently when all of the bodies are approximately the same size \item All of these statements are true \item Gravitational focusing gets much stronger for bodies that are nearly motionless with respect to each other \item Gravitational focusing gets stronger for larger bodies \end{itemize} \item[8.] Isolation mass is another key concept in understanding the formation of planetesimals and eventually planets. We sometimes use the term "oligarch" to describe a body which has become isolated. Which of the following statements about isolation mass is false? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Oligarchs are space further and further apart further out in the dis \item Isolation masses are much higher outside of the ice line \item Dynamical friction causes the oligarchs to slow each other down \item When an object reaches isolation mass it stops growing rapidly by gravitational focusing \item Oligarchs get more massive futher out in the disk \item All of these statements are true \end{itemize} \end{multicols} \item[9.] While we think that our planets formed through the process of core collapse, planets around other stars might or might not have formed from the process of disk instability. Which of the following would make disk instability MORE LIKELY to have occurred around a star? \begin{multicols}{3} \begin{itemize}[label={$\bullet$}] \item A hotter disk of material \item A more massive disk \item A more massive star \item A larger fraction of solid material in the disk \item A previously formed planet \item None of these would make disk instability more likely \end{itemize} \end{multicols} \item[10.] Uranus and Neptune are very different from Jupiter and Saturn. Which of the following is NOT true of the differences between these sets of planets? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Uranus and Neptune are more dense than Jupiter and Saturn, even though Jupiter and Saturn are much more compressed. \item While Jupiter and Saturn have mostly regular magnetic fields, the complex non-dipolar magnetic fields of Uranus and Neptune suggest that the magnetic field is generating closer to the top of the atmosphere on these planets. \item Uranus and Neptune have only a fraction of the mass of Jupiter or Saturn \item All of these statements are true \item Neither Uranus nor Neptune is massive to have metallic hydrogen on the inside \end{itemize} \end{multicols} \end{enumerate} \newpage \section*{Semaine 6 - Big questions from small bodies} \begin{itemize}[label={$\bullet$}] \item 3.01: Introduction to the small bodies of the solar system \item 3.02: The formation of small bodies \item 3.03: The formation of terrestrial planets \item 3.04: The surface density of the solar system \item 3.05: An ode to comets \item 3.06:The composition of comets \item 3.07: Where do comets come from? \item 3.08: The formation of the Oort cloud \item 3.09: Meteorites and the beginning of the solar system \item 3.10 Types of meteorites: Chondrites \item 3.11: Types of meteorites: Achondrites \item 3.12: Asteroids and meteorite delivery \end{itemize} \newpage \subsection*{Quiz 6} \begin{enumerate} \item[1.] Which of the following is the best explanation of why we have small bodies in the solar system? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The oligarchs that formed in the region of the terrestrial planets and the asteroid belt slowly merged over ~100 Myr and the oligarchs at the outer range of this region were excited by Jupiter enough to cause impacts to shatter the objects. A similar process took place in the Kuiper belt. \item Planetesimal formation in the region of the asteroid and Kuiper belts was delayed until after the gas in the nebular disk had dissipated, preventing these objects from acquiring gassy envelopes. \item Insufficient mass existed in the region of the asteroid belt and Kuiper belt to allow full sized planets to form. \item Nearby planets caused excitation of the orbits of planets in the region of the asteroid belt and Kuiper belt and these planets collided and their fragments are now the small bodies. \item Nearby planets caused the orbits of forming planetesimals to acquire high velocities and eccentricities, preventing run away growth and leading to shattering impacts. \end{itemize}\end{multicols} \item[2.] Which of the following statements about comets is NOT true? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Water is the most abundant ice on comets and the most abundant gas in the coma of a comet \item All of these statements about comets are true \item Much of the light we see in the coma of a comet is sunlight reflected off of an extended dust coma lifted off the surface \item Comets typically become bright at distances of about 3 AU from the sun where water ice begins to sublime \item Comets have slight deviations in their orbits when they get close to the sun due to the jetting effect of evaporation \item The ices present in comets show that these bodies were formed in the regions beyond Jupiter \end{itemize}\end{multicols} \item[3.] Which of the following is NOT required for the formation of a large nearly isotropic Oort cloud full of many small bodies, assuming the scenario that we discussed is the dominant mechanism? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item A planet like Jupiter which is massive enough to scatter bodies out of the solar system \item Passing stars which perturb the orbits of low perihelion, high semimajor axis objects \item A smaller planet like Neptune to scatter icy bodies inward so they can be ejected by a more massive planet like Jupiter \item A population of small bodies which is close enough to a planet to get scattered outward \item Multiple stellar encounters to randomize the cometary orbits into an isotropic cloud \item All of these are required \end{itemize}\end{multicols} \item[4.] The terrestrial planets appear to have taken much longer to finally assemble than the gas giants did. Which of the following statements about these timescale is NOT true? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item We can learn about the timescale of terrestrial planet differentiation by looking at isotopic ratios of hafnium and tungsten. \item Mars differentiated quickly, so tungsten-182, the radioactive decay product of hafnium, is abundant in Martian meteorites. \item One reason that the gas giant formation timescale is thought to be so fast is that we do not observe stars to have gas around them after they are ~3 Myr old \item Growth of the terrestrial planets was slowed by the rapid growth of the gas giants, which caused oligarchs to have have velocities and break apart. \item All of these statements are true \item Oligarchs form very quickly through runaway growth but because they are gravitationally isolated it takes a long time for them to assemble into larger bodies. \end{itemize}\end{multicols} \item[5.] The "minimum mass solar nebula" shows how much initial mass was needed in the disk around the sun to form the planets that we know of today. Which statement about the minimum mass solar nebula below is FALSE? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item WAll of these are true \item The minimum mass solar nebula approximately accounts for all of the hydrogen and helium that were present in the initial disk but which were not incorporated into the terrestrial planets. \item Mars appears to have less mass than would be predicted by a smooth minimum mass solar nebula \item The initial distribution of mass in the solar system could have been very different from that reconstructed in the "minimum mass solar nebula" \item The disk of material around the sun could have had more material than the minimum mass solar nebula \end{itemize}\end{multicols} \item[6.] Which of the following is NOT part of the explanation for why we continue to have near earth asteroids hit the earth even though the dynamical lifetime of a typical NEA is very short compared to the age of the solar system? (by dynamical lifetime we mean the time before it is likely to hit a planet or get ejected from the solar system) \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The existence of families of asteroids formed by asteroid impact and shattering \item The high current eccentricities and inclinations of asteroids population leading to shattering impacts \item All of these are true \item The Yarkovsky effect \item Heating of small asteroids on one side coupled with rotation causing orbital drift \item Our improved technology which allows us to find ever-smaller near earth asteroids \item Resonances with Jupiter and Saturn in the asteroid belt leading to removal of objects in the asteroid belt \end{itemize}\end{multicols} \item[7.]Lead-lead dating is a great way to figure out the age of something that is close to the age of the solar system. It based on the radioactive decay of uranium.Uranium-238 decays (with intermediate steps) to lead-206 with a half life of 4.5 billion years. Uranium-235 decays to lead-207 with a half life of 0.7 billion years. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item A higher ratio of lead-204 to lead-206 implies a younger rock \item Measuring the abundance of uranium-235 shows you how many half-lives have passed since the formation of the rock \item The technique requires finding parts of the meteorite with different abundances of lead and trying to determine how much extra lead exists because of uranium decay \item Objects which are younger will have more lead-207 than objects which are older. \end{itemize}\end{multicols} \item[8.] We find chondrules in meteorites that fall from the sky, but we have never found them on the Earth, the Moon, or Mars. Why not? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item They are in the interior of the Earth where we cannot reach. \item None of these is correct \item Meteorites probably formed from different materials than the planets \item They most likely form as the meteorite is falling through the atmosphere \item Materials inside large bodies like the Earth, Moon, and Mar undergo so much transformation due to heat and pressure that their original structure is not preserved. \end{itemize}\end{multicols} \item[9.] Pallasites are not only once of the most beautiful types of meteorites that you can find, they are also one of the most special. Many things must happen before a pallasite can form and be delivered to your hand. Which of the following is NOT one of them? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Someone has to find the pallasite on the Earth (and, eventually, it gets handed to you) \item A body must form which is large enough to retain enough heat to differentiate \item Pieces of a shattered body must hit a resonance which puts them onto an Earth crossing orbit \item All of these must happen \item A differentiated body must have an impact which shatters it into pieces \item A piece of the core-mantle boundary from a shattered mini-planet must land on the Earth \end{itemize}\end{multicols} \end{enumerate} \newpage \section*{Semaine 7 - Big questions from small bodies} \begin{itemize}[label={$\bullet$}] \item 3.13: Asteroid compositions \item 3.14: Pictures of asteroids \item 3.15: Asteroid hazards \item 3.16: The Kuiper belt \item 3.17: Properties of dwarf planets \item 3.18: Dynamical instabilities \item 3. : Lucy! \item 3.19: The Grand Tack \item 3.20: Planet Nine \item 3.21: A trip to the Subaru telescope \end{itemize} \newpage \begin{enumerate} \item[1.] Put the following in order from earliest to latest. In doing so, assume that the Nice model occurred as described and that the Grand Tack model also occurred as described. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The formation of Jupiter \item The inward migration of Jupiter due to gas forces \item The instability "explosion" which scattered small bodies throughout the solar system \item The inward migration of Saturn due to gas forces \item The formation of the Earth \item The outward migration of Jupiter due to gas forces Be very careful typing in your answer! If you think the order is 1,2,3,4,5,6 please type, exactly "123456" with no spaces, no commas, and no quotation marks. \end{itemize}\end{multicols} \item[2.] What problem does the Grand Tack model of the early solar system evolution attempt to explain? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The continued delivery of near earth asteroids into the inner solar system. \item The early inward migration of Jupiter and Saturn \item The mixing of the asteroid belt \item The timing of the Late Heavy Bombardment \item The apparently low mass of Mars \item The number of terrestrial planets \end{itemize}\end{multicols} \item[3.] For lead-lead dating, we measure the ratio of 207Pb to 206Pb and the ratio of 204Pb to 206Pb in a series of different regions of a meteorite. We then construct a plot of all of our measurements which looks something like this. The individual measurements are the points labeled things like "L1" and "W8"; a line is drawn through the points. The line is defined by a slope and the location where it hits the y-axis (the "intercept"), which is about 0.62 in this case. If we made similar plots for each of a series of calcium aluminum inclusions (CAIs) and a collection of chondrites, what are we most likely to find? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would range from that of the CAIs to larger (steeper) values \item The slope of each measured line would be nearly identical. The intercepts for the CAIs would all be equal, and the intercepts for the chondrites would range from that of the CAI to larger values. \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would all be smaller (shallower) \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would range from that of the CAIs to smaller (shallower) values \item The slopes measured for the CAIs would all be nearly identical, while the slopes measured for the chondrites would all be larger (steeper). \item The slope of each measured line would be nearly identical, but the intercepts for the CAIs would all be smaller than the intercepts for the chondrites. \item The slope of each measured line would be nearly identical. The intercepts for the CAIs would all be equal, and the intercepts for the chondrites would range from that of the CAI to smaller values. \end{itemize}\end{multicols} \item[4.] What can not we infer from this plot of the eccentricity vs. semimajor axis of known Kuiper belt objects? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item Neptune may have migrated outward, pushing parts of the Kuiper belt outward \item No objects with circular orbits are known beyond the 2:1 resonance with Neptune \item Many Kuiper belt objects share identical orbital periods as Pluto \item Kuiper belt objects have had giant impacts which have made families \item Kuiper belt objects exist out to at least ~180 AU \item Neptune is currently scattering Kuiper belt objects \end{itemize}\end{multicols} \item[5.] What is the explanation for the apparent lack of abundant solid nitrogen on the surface of Makemake even though it dominates the surface of Pluto and is inferred to be present on Eris? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item MThe saturated spectrum of the slabs of methane make nitrogen too difficult to detect. \item MMakemake is warmer than Eris but colder than Pluto, allowing methane to be stable but not nitrogen \item MMakemake is colder than Pluto, so nitrogen is frozen on the surface and not detected in the atmosphere \item MMakemake is smaller than Pluto and Eris, so nitrogen escapes while the less volatile methane remains behind. \item MMethane is so abundant on Makemake that chemical reactions between methane and nitrogen make ammonia \item MMakemake is smaller than Pluto and Eris, so molecular nitrogen undergoes hydrodynamic escape while leaving the lighter methane molecule behind \end{itemize}\end{multicols} \item[6.] Is Pluto a planet? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item yes \item no \end{itemize}\end{multicols} \item[7.] Which of the following is not a possible consequence of the Nice model for the dynamical instability of the early solar system? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item The small mass of the Kuiper belt \item The presence of icy bodies among the Jupiter trojan \item The abundance of Kuiper belt objects in resonaces \item The low mass of Mars \item The higher than expected eccentricities of the giant planets \item The lateness of the Late Heavy Bomdardment \end{itemize}\end{multicols} \item[8.] Is it possible that a civilization destroying asteroid is going to hit us within the next century? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item yes \item no \end{itemize}\end{multicols} \item[9.] Which of the following statements about the hypothetical Planet Nine is NOT true? \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item In the Planet Nine model, Planet Nine clears out the majority of the high eccentricity high semimajor axis objects in the outer solar system \item All of these are true \item Planet Nine can raise the perihelion of objects like Sedna and 2012 VP113 \item Planet Nine finally explains the discrepancies in the orbital position of Neptune \item Pluto was originally though to be possibly as large as Jupiter \item In the Planet Nine model, Planet Nine tilts the orbits of distant eccentric Kuiper belt objects into a plane different from the plane of the planets. \end{itemize}\end{multicols} \item[10.] NASA is planning to send the Lucy spacecraft to study Trojan asteroids in the next decade. What of the following statements about Trojan asteroids is TRUE? Check all that apply. \begin{multicols}{2} \begin{itemize}[label={$\bullet$}] \item In the Nice dynamical instability model, Trojan asteroids and Kuiper belt objects come from the same source \item It is possible that Trojan asteroids formed in the asteroid belt \item Trojan asteroids are dynamically unstable on ~1 million year lifetimes so must be replenished by asteroid collisions. \item Trojan asteroids look different spectroscopically from the majority of the asteroids in the main asteroid belt \end{itemize}\end{multicols} \end{enumerate} \newpage \section*{Semaine 8 - Life in the solar system (week 1)} \begin{itemize}[label={$\bullet$}] \item 4.01: Introduction to life \item Discussion Prompt: Life as we do (or don't) know it \item 4.02: Photosynthesis \item 4.03: Water \item 4.04: Alternative energy sources \item 4.05: History of life on Earth \item 4.06: Mars -- The Viking experiement \item 4.07: Mars -- Microbial hitchhikers \item 4.08: Mars -- Methane? \item 4.09: Mars -- Methane!! \item 4.10: Mars -- a habitable environment \end{itemize} \end{document}<file_sep>#include <stdio.h> #include <unistd.h> int nb_argc(int argc) { if(argc != 2 ) { write(2, "no values given or too much argv\n", 33); return 1; } return argc; } int lg_argv(char *argv[]) { int arg_i =0; int val_i = 0; while( argv[1][arg_i] != '\0') { if (argv[1][arg_i] != ' ') { val_i++; } arg_i++; } return val_i ; } int cond_lg_argv(int arg_n) { if (arg_n < 16) { write(2, "too few values\n", 14); return 1; } else if (arg_n > 16) { write(2, "too much values\n", 15); return 1; } return arg_n; } int cond_int_argv(char arg_i) { int value = (int)arg_i; if (value <= 0 || value > 4) { write(2, "Invalide value\n", 15); return -1; } return value; } int cond_char_argv(char *argv[]) { int arg_i = 0; int val_i = 0; char values[16]; while( argv[1][arg_i] != '\0') { if (argv[1][arg_i] != ' ') { values[val_i] = (int)argv[1][arg_i] - 48; //printf("%d\n", values[val_i]); //debugging if (cond_int_argv(values[val_i]) != -1) { val_i++; } else { return -1; } } arg_i++; } return 0; } int main(int argc, char *argv[]) { // compile with ./a "1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4" if (nb_argc(argc) == 2 && cond_lg_argv(lg_argv(argv)) == 16 && cond_char_argv(argv) == 0) { write(2, "\n End Well \n", 10); } }<file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 7 : - Le 10001 nombre premier. ----------------------------------------------------------------- ----------------------------------------------------------------- """ # Return True if aNombre is prime def EstPremier(aNombre): if aNombre == 2: estPremier = True elif aNombre % 2 == 0: estPremier = False else: p = 3 estPremier = True miNombre = aNombre // 2 while (p < miNombre and estPremier): if aNombre % p == 0: estPremier = False else: p +=2 return estPremier # Return the next prime after aNombre def ProchainPremier(aNombre): suivPremier = aNombre +1 while(not EstPremier(suivPremier)): suivPremier += 1 return(suivPremier) # Return the aNombre prime def niemePremier(aNombre): i = 1 prem = 1 while i <= aNombre: prem = ProchainPremier(prem) i += 1 return prem # Main nombre = 10001 print (niemePremier(nombre)) <file_sep>/* * Enveloppe convexe discrète * Fonctionis, algo et programme principale * CONTRIBUTEUR * <NAME> * * LICENCE * GPLv3 */ /* * Taille max de notre quadrillage */ #include <iostream> #include <math.h> #include <ctime> using namespace std; const int N = 20; const int M = 16; void set_point(int p[2], int x, int y) { p[0] = x; p[1] = y; } void set_point(int p[2], int q[2]) { p[0] = q[0]; p[1] = q[1]; } void set_point(double p[2], int q[2]) { p[0] = (double)q[0]; p[1] = (double)q[1]; } void translation(int p[2], int q[2], int r[2]) { p[0] = q[0] + r[0]; p[1] = q[1] + r[1]; } void anti_translation(int p[2], int q[2], int r[2]) { p[0] = q[0] - r[0]; p[1] = q[1] - r[1]; } void oppose(int p[2], int q[2]) { p[0] = -q[0]; p[1] = -q[1]; } double f_produit_scalaire( double p[2], int q[2]) { return p[0]*(double)(q[0]) + p[1]*(double)(q[1]); } // On définit un quadrillage void quadrillage(int quad[N*M][2]) { int i; int j; for (i=0; i<=M-1; i++) { for (j=0; j<=N-1; j++) { set_point(quad[j + N*i], j, i); } } } double f_carre(double x) { return(x*x); } // On définit un disque discret void cercle( double rayon, double centre[2], int disque[][2], int quad[N*M][2]) { int i; int j; int k = 0; for (i=0; i<=M-1; i++) { for (j=0; j<=N-1; j++) { if ( (f_carre(quad[j + N*i][0] - centre[0]) + f_carre(quad[j +N*i][1] - centre[1])) <= rayon*rayon) { set_point(disque[k], j, i); k++; } } } while (k<N*M) { set_point(disque[k], -1, -1); k++; } } // Affichage du quadrillage void sortie_quad( int quad[N*M][2]) { int i; int j; cout << "-------Quad----------" << endl; for (i=0; i<=M-1; i++) { for (j=0; j<=N-1; j++) { cout << "*"; } cout << endl; } } // Affichage du disque void sortie_disk( int quad[N*M][2], int disk[N*M][2]) { int i; int j; int k = 0; cout << "-------Disk---------- (inversé) dans le sens des y" << endl; for (i=0; i<=M-1; i++) { for (j=0; j<=N-1; j++) { if ( disk[k][0] !=-1 && quad[j + N*i][0] == disk[k][0] && quad[j + N*i][1] == disk[k][1]) { cout << "+"; k++; } else { cout << "*"; } } cout << endl; } } // affichage d'un point void sortie_point( int p[2] ) { cout << "[ " << p[0] << ", " << p[1] << " ]" << endl; } // affichage des points du disque void sortie_points_disk( int disk[][2]) { int k = 0; cout << " { "; while (disk[k][0]!=-1 && disk[k][1] != -1 ) { if( (disk[k][0]!=0 && disk[k][1]!=0) || k==0) { cout << "[ " << disk[k][0] << ", " << disk[k][1] << " ]" ; } k++; } cout << " }" << endl << endl; } // init enveloppe convexe void init_convexe( int convexe[2*(N+M)][2]) { int k; for (k = 0; k < 2*(N+M); k++) { set_point(convexe[k], -1, -1); } } /* * mauvaise manière : brutal * On se demande si le point est contenu dans le domaine * On parcours tous le domaine * */ bool estcontenu( int p[2], int domaine[N*M][2]) { bool predicat = false; int k = 0; while (domaine[k][0] != -1) { if (p[0] == domaine[k][0] && p[1] == domaine[k][1]) { return(true); } k++; } return (false); } /* * On regarde si le vecteur allant du point p au point q * intersecte le domaine D * */ bool intersecte( int p[2], int q[2], int domaine[N*M][2]) { if( estcontenu(p, domaine) == estcontenu(q, domaine)) {return false;} else {return true;} } /* * On regarde si les points sont confondus. * */ bool estconfondu(int p[2], int q[2]) { return (p[0] == q[0] && p[1] == q[1]); } void convexhull_v1( int p_domaine[N*M][2], int p_convexe[2*(N+M)][2]) { /* * # Les ensembles * * On va se servir principalement de quatre ensembles. * * * Le domaine discret : p_domaine. * On munit cet ensemble d'un itérateur : k_domaine. * * * L'enveloppe discrète en construction : p_convexe. * On munit cet ensemble d'un itérateur : k_convexe. * * * L'ensemble des points qui candidatent pour le * rôle de prochain sommet de l'ensemble convexe : * p_candidat. * On munit cet ensemble d'un itérateur : k_candidat. * On utilise également un vecteur de taille 1x2 pour * savoir si l'on doit continuer l'algorithme. * * * L'ensemble des points convergents calculés pour * chaque sommet de l'enveloppe convexe : p_convergent. * On se servira également des deux vecteurs v_-2 et v_-1 * et d'un troisième vecteur permettant de les inversés : * v_convergent. * On muni ces ensembles d'un itérateur : k_convergent. * On se munit également également d'un compteur qk pour * calculer l'intersection du rayon avec le domaine. * * * L'indice des premiers éléments des tableaux est 0. * Même pour les "p_convergent[-2] -> p_convergent[0]. * */ // Le domaine discret p_domaine; int k_domaine; // L'enveloppe convexe p_convexe; init_convexe(p_convexe); int k_convexe; // Les candidats int p_candidat[N*M][2]; // taille ??? init_convexe(p_candidat); int k_candidat; int p_ray[N*M][2]; init_convexe(p_ray); double produit_scalaire; double p_scalaire[2]; // Les convergents int p_convergent[N*M][2]; init_convexe(p_convergent); int v_convergent[N*M][2]; init_convexe(v_convergent); int k_convergent; int qk; int test_p0[2]; /* * # Les variables de tests * * * * L'algorithme est terminer, l'ensemble des points de * l'enveloppe convexe discrète a été trouvé. On est * revenu à notre point de départ p_convexe[0] : bool_convexe_fini. * Par défaut bool_convexe_fini = false. * * * L'ensemble des candidats au poste de sommet * suivant de notre enveloppe convexe a été trouvé. * Il faut maintenant faire le choix parmi eux en sélectionnant * celui de plus grand angle : bool_candidat_fini. * */ // L'enveloppe convexe bool bool_convexe_fini = false; // On a tous les candidats bool bool_candidat_fini = false; /* * #1 - Initialisation de notre algorithme * par la recherche de notre premier point * de l'enveloppe convexe. * * On part du point le plus bas. * */ /* * Il serait sans doute sage d'en faire une procédure. * Mais ce n'est pas le point de ce programme. * */ k_domaine = 1; set_point(p_convexe[0], p_domaine[0]); while ( p_domaine[k_domaine][0] != -1 ) { if ( p_domaine[k_domaine][1] < p_convexe[0][1]) { set_point(p_convexe[0], p_domaine[k_domaine]); } k_domaine++; } /* * On a trouvé le premier point de notre enveloppe * convexe. * * On crée également les deux premiers vecteurs * v_-2 et v_-1 * */ k_convexe = 1; set_point(v_convergent[0], 1, 0); set_point(v_convergent[1], 0, 1); /* * On part maintenant du premier point de notre * enveloppe convexe et on lance l'algo. * * #2 - On fait tourner l'algorithme jusqu'à qu'il * se termine * */ while ( !bool_convexe_fini ) { /* * On test maintenant si nos vecteurs v_-1 et v_-2 * sont correctement orientés. On crée nos points * p_-1 et p_-2. * * Pour cela on test l'appartenance de p_-1 à notre ensemble. * * Une procédure est utilisée. * * #2.1 - On crée nos premiers convergents */ translation(p_convergent[0], p_convexe[k_convexe -1], v_convergent[0]); translation(p_convergent[1], p_convexe[k_convexe -1], v_convergent[1]); k_convergent = 2; if (!estcontenu(p_convergent[1], p_domaine) ) { /* * #2.1.1 - On vérifie nos vecteurs * * Si pm1 n'appartient pas au domaine, on effectue * On effectue une rotation de nos deux vecteurs et * une réactualisation de nos points p_-2 et p_-1. * * v_-2 devient v_-1. * v_-1 devient -v_-2 (l'ancien) */ set_point(v_convergent[2], v_convergent[0]); set_point(v_convergent[0], v_convergent[1]); oppose(v_convergent[1], v_convergent[2]); } /* * Sinon, les vecteurs sont bien orientés pour chercher * p_convexe+1. * * On teste maintenant l'éventualité d'avoir tous les * candidats au poste de p_convexe+1. * * #2.2 - On lance l'algo de la recherche du prochain * point de l'enveloppe * */ else { // On test si p_-2 est candidat. // Alors on est sûr de translater vers lui. if (estcontenu(p_convergent[0], p_domaine)) { set_point(p_candidat[k_candidat], p_convergent[0]); k_candidat++; bool_candidat_fini = true; } else // sinon on recherche le candidat { // p_-1 est candidat set_point(p_candidat[k_candidat], p_convergent[1]); k_candidat++; /* * On crée p_0. * */ set_point(p_convergent[2], p_convergent[0]); set_point(v_convergent[2], v_convergent[0]); set_point(test_p0, p_convergent[1]); while (!estcontenu(p_convergent[2], p_domaine) && estcontenu(test_p0, p_domaine)) { translation(p_convergent[2], p_convergent[2], v_convergent[1]); translation(test_p0, test_p0, v_convergent[1]); translation(v_convergent[2], v_convergent[2], v_convergent[1]); } // On revient au dernier point. anti_translation(p_convergent[2], p_convergent[2], v_convergent[1]); anti_translation(v_convergent[2], v_convergent[2], v_convergent[1]); // On test si p_1 existe qk = 0; set_point(p_ray[0], p_convergent[2]); translation(p_ray[1], p_convergent[2], v_convergent[1]); // On calcul qk tq l'intersection soit non nulle while (intersecte(p_ray[qk+1], p_ray[qk], p_domaine)) { qk++; translation(p_ray[qk+1], p_ray[qk], v_convergent[qk-2]); } if (qk != 0 || estcontenu(p_ray[qk+1], p_domaine)) { // on continue de calculer les convergents bool_candidat_fini = false; k_convergent++; if (estcontenu(p_ray[qk], p_domaine)) { set_point(p_candidat[k_candidat], p_ray[qk]); k_candidat++; } } else // on a trouvé tous les candidats { bool_candidat_fini = true; } // On assure k_convergent = 3; while (!bool_candidat_fini) { /* * On se pose maintenant la question de savoir si tous * les candidats sont présents * * On continue donc l'algo. On distingue le cas pair * du cas impair. * * On test ça en binaire : un nombre pair en binaire se termine * par 0. On aurait également pu faire %2 ==0 pour avoir le reste * de la division euclidienne. */ if (k_convergent & 1) // pair { // On cherche k minimal tq l'intersection entre // le rayon et le domaine soit non nulle. translation(p_convergent[k_convergent], p_convergent[k_convergent-1], v_convergent[k_convergent-2]); // On calcul le point p_k translation(v_convergent[k_convergent], v_convergent[k_convergent - 2], v_convergent[k_convergent - 1]); while (estcontenu(p_convergent[k_convergent], p_domaine)) { translation(p_convergent[k_convergent], p_convergent[k_convergent], v_convergent[k_convergent-1]); translation(v_convergent[k_convergent], v_convergent[k_convergent], v_convergent[k_convergent-1]); } // on revient au point précédent anti_translation(p_convergent[k_convergent], p_convergent[k_convergent], v_convergent[k_convergent-1]); anti_translation(v_convergent[k_convergent], v_convergent[k_convergent], v_convergent[k_convergent - 1]); // On test maintenant pour savoir si on continue la procédure. qk = 0; set_point(p_ray[qk], p_convergent[k_convergent-2]); translation(p_ray[qk+1], p_convergent[k_convergent-2], v_convergent[k_convergent-1]); // On calcul qk tq l'intersection soit non nulle while (intersecte(p_ray[qk+1], p_ray[qk], p_domaine)) { qk++; translation(p_ray[qk + 1], p_ray[qk], p_convergent[k_convergent-1]); } if (qk != 0) { // on continue de calculer les convergents bool_candidat_fini = false; k_convergent++; if (estcontenu(p_ray[qk], p_domaine)) { set_point(p_candidat[k_candidat], p_ray[qk]); k_candidat++; } } else // on a trouvé tous les candidats { bool_candidat_fini = true; } } // fin pair else // impair { // On cherche k maximal tq l'intersection entre // le rayon et le domaine soit non nulle. translation(p_convergent[k_convergent], p_convergent[k_convergent-1], p_convergent[k_convergent-2]); translation(v_convergent[k_convergent], v_convergent[k_convergent-1], v_convergent[k_convergent-2]); // On calcul le point p_k while (estcontenu(p_convergent[k_convergent], p_domaine)) {// ! - on sort du domaine translation(p_convergent[k_convergent], p_convergent[k_convergent], p_convergent[k_convergent-1]); translation(v_convergent[k_convergent], v_convergent[k_convergent], v_convergent[k_convergent-2]); } // on revient au point précédent anti_translation(p_convergent[k_convergent], p_convergent[k_convergent], p_convergent[k_convergent-1]); anti_translation(v_convergent[k_convergent], v_convergent[k_convergent], v_convergent[k_convergent-2]); // On test maintenant pour savoir si on continue la procédure. qk = 0; set_point(p_ray[qk], p_convergent[k_convergent-2]); translation(p_ray[qk+1], p_convergent[k_convergent-2], p_convergent[k_convergent-1]); // On calcul qk tq l'intersection devienne nulle while (!intersecte(p_ray[qk+1], p_ray[qk], p_domaine)) {// ! - on test la plus grande qk++; translation(p_ray[qk + 1], p_ray[qk], p_convergent[k_convergent]-1); } if (qk != 0) { bool_candidat_fini = false; k_convergent++; if (estcontenu(p_ray[qk-1], p_domaine)) { set_point(p_candidat[k_candidat], p_ray[qk-1]); k_candidat++; } } else { bool_candidat_fini = true; } } // fin impair } // fin du while candidat } // fin candidat /* * On a obtenu tous les candidats dans p_candidat. * Il est temps savoir lequel est le bon. * * On utilise la tangente : Plus la tangente est * */ //cout << "candidat : "<< k_candidat << " - "; //sortie_points_disk(p_candidat); if (k_candidat > 1) { set_point(p_convexe[k_convexe], p_candidat[k_candidat-1]); set_point(p_scalaire, p_candidat[k_candidat-1]); produit_scalaire = 0.0; while (k_candidat > 1) { // on crée le vecteur [p_-2; p_candidat] set_point(p_scalaire, p_candidat[k_candidat-1]); p_scalaire[0] = p_scalaire[0] - (double)p_convergent[0][0]; p_scalaire[1] = p_scalaire[1] - (double)p_convergent[0][1]; // On test si son ordonnée est nulle if (p_scalaire[1] != 0) { // On normalise p_scalaire[0] = p_scalaire[1]/p_scalaire[0]; p_scalaire[1] = 1.0; if (produit_scalaire < f_produit_scalaire( p_scalaire, p_convergent[0])) { produit_scalaire = f_produit_scalaire( p_scalaire, p_convergent[0]); set_point(p_convexe[k_convexe], p_candidat[k_candidat-1]); } } k_candidat--; } k_convexe++; } else { set_point(p_convexe[k_convexe], p_candidat[k_candidat - 1]); k_convexe++; k_candidat--; } /* * On test si l'algo est terminé. * Le test consiste à savoir si le dernier point de l'enveloppe * est le même que le premier. */ if (!estconfondu(p_convexe[0], p_convexe[k_convexe-1])) { // on continue l'algo en cherchant le prochain point de l'enveloppe bool_candidat_fini = false; bool_convexe_fini = false; k_candidat = 0; k_convergent = 0; } else { // on a terminé bool_convexe_fini = true; } } // fin d'une extrémité de notre convexe, on tourne nos v_-2, v_-1 } // on a fini de computer sur notre convexe. } // fin de proc int main() { // temps clock_t exec; exec = clock(); int quad[N*M][2]; int disk[N*M][2]; double rayon = 4.21; double centre[2]; centre[0] = 8.1; centre[1] = 5.7; quadrillage(quad); cercle(rayon, centre, disk, quad); sortie_disk(quad, disk); sortie_points_disk(disk); int disk_convexe[2*(N+M)][2]; convexhull_v1(disk, disk_convexe); cout << "Convexe : "; sortie_points_disk(disk_convexe); cout << "ÉXEC : " << exec - clock() << " ms" <<endl; return(0); } <file_sep>class Plateau { private: int dim; public: std::vector<Cellule> plateau; public: /* * Constructeur par défaut */ Plateau(){ dim = 3; } /* * Constructeur standart * @param taDim est la dimension du plateau. */ Plateau(const int taDim) { dim = taDim; } /** * Constructeur Pour des tests rapides. */ Plateau(const bool tonBool) { dim = 3; int it; for(it = 1 ;it<=11;it++) { plateau.push_back(0); } for(it = 12;it<=14;it++) { plateau.push_back(1); } for(it = 15;it<=25;it++) { plateau.push_back(0); } } /** * Constructeur par copie * @param pla un autre plateau à copier */ Plateau(const Plateau& pla) { dim = pla.dim; int it; for(it = 1 ;it<=(dim+2)*(dim+2);it++) { plateau.push_back(pla.plateau[it-1]); } } /* * Destructeur par défaut */ ~Plateau() {} /** * Montre le tableau ainsi que les bords vides * utiles aux calculs. */ void showTotal() { // iterateur sur le vector du plateau. std::vector<Cellule>::iterator itP = plateau.begin(); int ligne = 1; int colonne = 1; // On rajoute une ligne en haut et // en bas et une colonne à gauche et à droite. while( ligne <= dim + 2) { std::cout<<"|---------|"<<std::endl<<"|"; while( colonne <= dim + 2) { std::cout<<*itP<<"|"; itP++; colonne += 1; } std::cout<<std::endl; colonne = 1; ligne += 1; } std::cout<<"|---------|"<<std::endl; } /** * Affiche le plus sobrement possible de plateau, * donc sans les lignes en haut et en bas et les colonnes à gauche et à droite. */ void show() { // iterateur du plateau std::vector<Cellule>::iterator itP = plateau.begin(); int ligne = 1; int colonne = 1; // première ligne int i = 1; while( i <= dim + 2) { itP++; i++; } ligne +=1; while( ligne <= dim +1) { // on se déplace de 1 sur la colonne itP++; colonne ++; while(colonne <= dim +1) { std::cout<<*itP; itP++; colonne += 1; } std::cout<<std::endl; itP++; colonne = 1; ligne += 1; } } Plateau Evolution() { // Évolution du plateau au temps t + 1. Plateau pEvol(dim); const int dim2 = dim + 2; int it = dim2 + 1 + 1; int vois; int ligne = 1; int colonne = 1; while( colonne <= dim2 + 2) { pEvol.plateau.push_back(0); colonne++; } // Deuxième ligne, première colonne; ligne +=1; colonne = 2; while( ligne <= dim +1) { while(colonne <= dim +1) { // On calcul la somme des voisins présents au 8 directions. vois = plateau[it-dim2-1].EstPresent() + plateau[it-dim2].EstPresent() + plateau[it-dim2+1].EstPresent() + plateau[it-1].EstPresent() + plateau[it+1].EstPresent() + plateau[it+dim2-1].EstPresent() + plateau[it+dim2].EstPresent() + plateau[it+dim2+1].EstPresent(); // Si la cellule était morte if(!plateau[it].Estenvie()) { // Si le nombre de voisin est 3 => apparition de la vie. if(vois == 3) { pEvol.plateau.push_back(1); } else { pEvol.plateau.push_back(0); } } else { // Si le nombre de voisin est 2 ou 3 => conservation de la vie. if(vois == 2 || vois == 3) { pEvol.plateau.push_back(1); } else { pEvol.plateau.push_back(0); } } it++; colonne++; } ligne ++; colonne = 1; } while( colonne <= dim2+2) { pEvol.plateau.push_back(0); colonne++; } return pEvol; } Plateau Evolution(int temps) { if (temps > 0) { Evolution(temps - 1); } return (*this); } }; <file_sep># Differential Equations in Actions * Udacity : [Link](https://www.udacity.com/course/cs222) > * Course Code: CS222 > * Instructor: <NAME> > * TA: <NAME> ## Progress #### Lesson 1 - Houston We Have a Problem **Earth - Moon - Spaceship**. > * Introduction to physics with position, speed, acceleration and Newton laws. > * Introduction to computer science with the Forward Euler Method. > * Programming in Python3 and ploting with matplotlib. <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 1 : - La somme des entiers multiples de 3 ou 5. ----------------------------------------------------------------- L'algorithme parcourt les entiers les uns à la suite des autres en testant dans la boucle s'ils sont multiples ou non de 3 ou 5. Si oui, on les ajoute à la somme de retour. ----------------------------------------------------------------- """ # aNombre est-il multiple de aCoeff ? # Entrée : # - aNombre # - aCoeff # Sortie : # - True si aNombre est un multiple de aCoeff # - False sinon def EstMultiple(aNombre, aCoeff): if aNombre%aCoeff == 0: return True else: return False # La somme des entiers entre aDepart et aFin divisible par 3 ou 5 # Entrée : # - aDepart = Le nombre de départ non compris # - aFin = Le nombre de fin non compris # Sortie : # - La somme des mutliples def SommeMultiple(aDepart,aFin): # On commence avec le premier entier et # On initialise la somme à 0 nombreEntier = aDepart somme=0 # On boucle jusqu'au dernier entier (non compris) while(nombreEntier < aFin-1): nombreEntier += 1 # Multiple de 3 OU multiple de 5 if EstMultiple(nombreEntier,3) or EstMultiple(nombreEntier,5): somme += nombreEntier return somme # Main dep = 0 fin = 1000 # Affiche la somme print("somme : ",SommeMultiple(dep,fin)) <file_sep>########################################################################### # # # Traffic routier # # # ########################################################################### ## ## Réprésentation de la voie ## ############################ ## 1 flux continu rep_flux = matrix(1,nrow = 2, ncol= n_1 + n_2) rep_flux[2,] = c(rep(-1,n_1), rep(1,n_2)) rep_flux[1,]= c(-flux_1, flux_2) #rep_flux par(mfrow=c(2,2)) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = 0") abline(v=0, col = 2) abline(h=0, col = 4) rep_flux[1,] = c(-flux_1+60, flux_2-60) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = t + 60s") abline(v=0, col = 2) abline(h=0, col = 4) rep_flux[1,] = c(-flux_1+120, flux_2-120) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = t + 120s") abline(v=0, col = 2) abline(h=0, col = 4) rep_flux[1,] = c(-flux_1+180, flux_2-180) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = t + 180s") abline(v=0, col = 2) abline(h=0, col = 4) <file_sep>function [Cprime]=F_remez(Poly_tcheby) //Soit Col_diff la matrice de f(x) - p(x) sur cet petit intervalle for i=1:1:fin+1 Col_diff(i)=abs(fmoinsp(X_fin(i))) end //On crée un couple ordonnée, abscisse; Cmax pour rentrer les données utiles ultérieurement [Cmax(2),Cmax(1)]=max(Col_diff) Cprime=X_fin(Cmax(1)) endfunction <file_sep>\documentclass[11pt]{article} \usepackage{geometry} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,french]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} % No page header \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height %---------------------------------------------------------------------------------------- %   Début du document %---------------------------------------------------------------------------------------- \begin{document} \section{Le parcours professionnel} \subsection{Postes occupés avant l’accès au corps} \textit{Dans chacun des items ci-­dessus, il précise les éléments de contexte jugés significatifs sur les postes occupés.} \\ \begin{itemize} \item Du 15/06/2012 au 15/08/2012 - Stage recherche\\ \textbf{MmodD - Calcul Numérique} - \textit{Lyon} \\ Stage de deux mois portant sur des méthodes de décomposition de domaine pour les équations aux dérivées partielles et l'implémentation sous scilab d'une méthode de Dirichlet - Neumann dans le cadre du projet MmodD. \item Du 01/02/2012 au 01/07/2012 - Stage appliqué\\ \textbf{Irstea - Modélisation Hydrologique} - \textit{Lyon} \\ Stage de cinq mois portant sur "l’étude de l’influence de la variabilité spatiale sur le fonctionnement d’une zone tampon enherbée", par l’investigation d’un modèle hydrologique 3D à base physique et à paramètres distribués : CATHY-3D. \item Du 01/01/2013 au 01/07/2013 - Stage recherche\\ \textbf{LIRIS - Géométrie Discrète} - \textit{Lyon} \\ Stage de recherche de six mois portant sur la conception sous Linux et l’implémentation en C++ d’un algorithme de calcul d’alpha-shape en géométrie discrète. \item Du 01/09/2013 au 31/08/2014 - 6 h - Collège\\ \textbf{<NAME>} - \textit{Francheville}\\ admissible - contractuel 2nd degré session exceptionnelle 2014. \\ En responsabilité d'une classe de $5^{ème}$, découverte de l'AP $6^{ème}$ et utilisation de Labomep. \end{itemize} \subsection{Postes occupés pendant le stage - Affectation des stagiaires } \begin{itemize} \item Du 01/09/2014 au 31/08/2015 - 18 h - Lycée\\ \textbf{Lycée polyvalent Edouard Branly} - \textit{Lyon 5e Arrondissement} \\ \end{itemize} En responsabilité de 3 classes : $2^{nd}$ GT, $1^{ère}$ STI2D et BTS1 électrotechnique. \subsection{Postes occupés depuis l’accès au corps} \begin{itemize} \item Du 01/09/2015 au 31/08/2016 - 18 h - Collège \begin{itemize} \item \textbf{<NAME>} - \textit{Feyzin - (Zone prévention violence)} - 9h (Principale) \item \textbf{<NAME>} - \textit{Villeurbanne - (rep+)} - 9h (Complément de service) \end{itemize} \item Du 01/09/2016 au 31/08/2019 - 18 h - Collège\\ \textbf{<NAME>} - \textit{Feyzin - (Zone prévention violence)} - 18h \item Depuis 01/09/2019 - 18 h - Collège\\ \textbf{<NAME>} - \textit{Villefranche-sur-Saône - (Réseau d'éducation prioritaire)} - 18h \\ \end{itemize} En responsabilité de classe de tous niveaux avec une préférence pour les "grands" : $3^{ème}$ et $4^{ème}$. Professeur principal de 2015 à 2020. Référent numérique et réseau de 2015 à 2019 et membre projet DFIE Compétences au collège <NAME> à Feyzin. \newpage \section{Compétences mises en œuvre dans le cadre de son parcours professionnel} \subsection{L’agent dans son environnement professionnel propre} \textsc{la classe, le CDI, la vie scolaire, le CIO : compétences liées à la maîtrise des enseignements, compétences scientifiques, didactiques, pédagogiques, éducatives et techniques.}\\ \textit{L’agent expose les réalisations et les démarches qui lui paraissent déterminantes pour caractériser la mise en œuvre de ses compétences et leur contribution aux progrès et au développement de tous les élèves (20 lignes maximum)}\\ J'ai pour attachement d'essayer deux choses : Laisser les élèves en autonomie et sur des temps long en exercice. Et avoir un temps d'écoute, de correction, de cours plus court mais avec beaucoup d'attention. \subsubsection{Pour les troisièmes} Une problématique : Des chapitres qui s'enchaînent et ont tendance à s'oublier. Un fait : le DNB. J'ai choisi cette année de faire de petits chapitres, des évaluations régulières de connaissances. En parallèle, je fais chercher beaucoup de problèmes de type brevet, pas nécessairement en lien direct avec le cours lors des séances en demi-groupe. Utilisation intensive de la calculatrice, des fonctions avancées, des limites. Insister sur la rédaction. On n'écrit pas un nombre sans écrire le calcul. \subsubsection{Pour les cinquièmes} Je commence le cours par une phrase du jour. Un concept importé des collègues de français. Une phrase : definition, rappel, anecdote, citation sur le thème des maths à chaque début de cours en 5è. Utilisation régulière de la calculatrice et faire la distinction entre le résultat, les méthodes de calcul et la rédaction. Faire prendre conscience de l'importance de revenir régulièrement sur son cahier et pas seulement pour les évals ni même que pendant le cours avec l'utilisation d'un quadrillage à griser lors de la relecture. Beaucoup de travaux graphiques de représentation. \newpage \subsection{L’agent inscrit dans une dimension collective} \textit{L’agent s’appuie sur quelques exemples concrets et contextualisés pour analyser sa participation au suivi des élèves, à la vie de l’école/l’établissement et son implication dans les relations avec les partenaires et l’environnement (20 lignes maximum).}\\ Depuis ma première affectation à Feyzin en 2015, j’ai été \textbf{professeur principal} selon les besoins. J'ai particulièrement apprécié travailler sur le projet d’orientation des élèves de $3^{ème}$. Le rapport à la famille, s'entretenir auprès des collègues pour savoir comme ça se passe dans leur cours.\\ La découverte, la participation puis la labélisation en 2019 par la DFIE du \textbf{projet compétence} a rythmé mon travail au collège <NAME> à Feyzin. La première année, j'ai principalement assisté aux réunions la première année pour comprendre la notation, la technique avec pronote. Je me suis intéressé à la notion de compétences. Je me suis alors impliqué dans le projet DFIE, son évaluation et sa labélisation la dernière année qui nous demandé un travail conséquent.\\ Je me suis investissement dès septembre la première année comme \textbf{référent numérique et réseau} sur le collège de Feyzin sur à la mutation de ce dernier. J'ai suivi la formation DANE la première année. J'ai été un interlocuteur du gestionnaire, des collègues sur les questions techniques et j'ai participer à la mise en place de différents tests : pisa, éval 6è,...\\ \subsubsection{Le rôle de professeur principal} \begin{itemize} \item 2015 - 2016 : 4è - Frédéric Mistral à Feyzin \item 2016 - 2017 : 5è - Frédéric Mistral à Feyzin \item 2017 - 2018 : 3è - Frédéric Mistral à Feyzin \item 2018 - 2019 : 3è - Frédéric Mistral à Feyzin \item 2019 - 2020 : 4è - Faubert à Villefranche-sur-Saône \end{itemize} \subsubsection{Référent numérique et réseau} \begin{itemize} \item 2015 - 2019 : <NAME>. \end{itemize} \subsubsection{Cardie / DFIE} \begin{itemize} \item 2015 - 2019 : Projet DFIE Compétences Participation à la labélisation du projet en 2019 \item 2017 - 2019 : Chef de projet DFIE : Périscolaire. \end{itemize} \subsubsection{Autres} \begin{itemize} \item 2015 - 2019 : Membre élu au CA dans diverses commissions : commission permanente, le conseil de discipline, le conseil pédagogique, appel d'offre,... \item 2016 - 2019 : <NAME> de société : Périscolaire. \item 2016 - 2019 : Acteur dans le projet médiation par les pairs sur le niveau 5è. \item 2016 - 2019 : Participation à la liaison école/collège. \item 2020 - 2021 : Coordinateur de matière - Faubert à Villefranche-sur-Saône \end{itemize} \newpage \subsection{L’agent et son engagement dans une démarche individuelle et collective de développement professionnel} \textit{L’agent décrit les démarches accomplies pour développer cette compétence telle qu’explicitée dans le référentiel et formule ses besoins d’accompagnement (10 lignes maximum).}\\ Chaque année, je profite du PAF pour suivre des formations. Cette année avec une certaine appréhension du covid, je ne me suis pas inscrit. \subsubsection{Astronomie} J'ai grandement apprécié les formations sur le thème de l'astronomie proposées par le CRAL. Je continue à me former sur le sujet via la plateforme coursera. J'aimerai sensibiliser les élèves à ce domaine. \begin{itemize} \item Faire de l'astronomie en AP, dans les EPI, MPS ou TPE - CRAL - 2016 \item Ce que nous apprend la recherche des exoplanets - CRAL - 2015 \item Astronomie : explorer le temps et l'espace et Archaeoastronomy - Coursera (mooc) - 2019 \end{itemize} \subsubsection{Un besoin dans l'établissement} J'ai suivi des formations en lien direct avec mon travail au sein de l'établissement. \begin{itemize} \item Formation professeurs principaux de troisième et seconde pro - DAFOP - 2019 \item Colloque Académique sur le numérique éducatif - DANE - 2016 \item Gestion du réseau scribe - DANE - 2015 \item Regroupement des équipe en expérimentation - DFIE - 2017 \item Évènements de l'innovation - DFIE - 2019 \end{itemize} \subsubsection{En mathématiques} J'ai la première année suivi une très bonne formation proposée par l'IREM sur le calcul mental. Depuis, je continue chaque année à m'entretenir en maths. Je participe activement à un discord centré sur les mathématiques où je continue à être en contact avec des élèves de lycée, du supérieur et aussi un professeur de lycée qui l'administre. \begin{itemize} \item Du calcul mental à la mise - IREM - 2014 \item Mathématiques : préparation à l'entrée dans l'enseignement supérieur - FUN (mooc) - 2017 \end{itemize} \subsubsection{En transversal} J'ai suivi une très bonne formation sur la gestion de la voix l'année dernière. Je pense peut-être continuez sur une formation sur le théâtre. \begin{itemize} \item Connaître, entretenir et améliorer sa voix - 2020 \end{itemize} \newpage \section{Souhait(s) d’évolution professionnelle, de diversification des fonctions} \textit{L’agent qui le souhaite formule ses souhaits d’évolution professionnelle et de diversification des fonctions : tuteur, coordonnateur, formateur, formateur académique, mobilité vers d’autres types d’établissement scolaires, vers d’autres publics (établissement en EP, élèves à besoins éducatifs particuliers, collège, lycée, post bac, enseignement à l’étranger,...), vers d’autres métiers de l’enseignement, vers les corps d’encadrement, vers d’autres corps de la fonction publique, etc. (20 lignes maximum).}\\ Je suis assez partagé sur la question.\\ Je me sens à ma place là où je suis. Je ressens mon utilité. J'apprécie le challenge que propose l'enseignement des mathématiques au collège notamment dans un établissement d'un réseau prioritaire. J'ai une légère préférence pour les "grands" avec l'enseignement des grands théorèmes, la notation scientifique, les statistiques ainsi que la préparation du brevet ainsi que de la seconde. L'enjeu de l'orientation est présent et est vraiment intéressant.\\ D'un autre côté, j'ai encore cette expérience du lycée qui a été un plaisir pour moi. Suite à la réforme, l'ajout de SNT, de Python sont des parties qui m'attirent également. Je me tiens très à jour des sorties et des nouveautés liés aux calculatrices graphiques. Je suis en contact régulier avec des élèves de lycées pour proposer un peu d'aide en ligne sur un discord de maths. Un enseignant de maths de lycée est également présent. \end{document}<file_sep>NombreMax = 10000000 nombreTest = c(0:NombreMax) racineCarre = sqrt(nombreTest) partieEntiere = floor(racineCarre) partieEntiereCarre = partieEntiere^2 resteCarre = nombreTest - partieEntiereCarre Zettaleaf = function(n,a){n + a*(2*n+1)/(4*n^2+2*n+a)} testRacineCarre = Zettaleaf(partieEntiere, resteCarre) ecart = racineCarre - testRacineCarre plot(nombreTest, ecart, type="l", ylim=c(-1*10^(-7),1*10^(-7))) plot(nombreTest, racineCarre, col="blue",type="l") lines(nombreTest,testRacineCarre, col="red",type="l") legend("topleft", c("sqrt(x)","Zettaleaf(x)"), fill=c("blue","red"))<file_sep># Collection *Combien faut-il acheter de paquet de cartes afin de former une collection complète ?* ## mini-présentation En voilà une question hautement pertinent pour les fans de carte panini, magic et même pour ceux qui se pose la question de l'intérêt d'acheter des boosters pour leur badge steam. On va tenter d'apporter quelques éléments de réponses par le biais de la statistique en simulant un grand nombre d'achat et voir en combien de temps on peut espérer avoir enfin une collection complète. On souhaite regarder le nombre d'achat nécéssaire de paquet de taille variable : **tailleLot** afin de compléter une collection de taille variable : **tailleCollection**. ## objectif Le but est dans un premier temps d'attacher à regarder quelques nombres pour des valeurs remarquables puis de comparer un peu les résultats. ## langage : R - [(Lien)](http://www.r-project.org/) ### Éxecution * Windows à l'aide rgui * Linux ou Mac à l'aide de la commannde dans le dossier racine du dépôt. ``` $ R -q --vanilla < collection-de-carte.R ``` ### Méthodologie #### Recueil Le recueil de donnée reste aisé avec la plupart des langages de programmations capables de tirer des nombres uniformes entre 0 et 1. Nous avons fait ce tirage *(ligne 70)* à l'aide de la commande **runif(1)** sous R. Pour récupérer des entiers uniformément distribué entre 1 et 70 , on multiplie notre uniforme par 70 et on lui rajoute 1 (pour éviter d'être entre 0 et 69) puis on passe ce décimal à la moulinette à l'aide de la fonction partie entière : **floor** pour en retirer en nombre entier. Par exemple pour un tirage aléatoire d'un dé à six faces, on aurait fait **floor(6*runif(1)+1)** #### Traitement On se propose de regarder trois critères. 1. Le nombre d'achat nécéssaire pour compléter une collection. 2. Le nombre maximum d'une même carte par collection complète. 3. Le nombre moyen de carte par collection complète. Les principales caractéristiques de position et de dispersion de notre première série : **Min**, **Q1**, **Médiane**, **Moyenne**, **Q3**, **Max** sont obtenues à l'aide de la fonction **summary()**. La redirection dans la sortie standard se fait à l'aide de **print()** sinon, la sortie est celle du prompt de R. *(ligne 131)* ``` > print(summary(dataCollection$nbrAchat)) Min. 1st Qu. Median Mean 3rd Qu. Max. 12.00 21.00 24.00 26.92 33.00 69.00 ``` La représentation choisie des différentes valeurs à été un histogramme des critères couplés à un boxplot en dessous afin de mieux visualiser les critères. L'export en pdf est réalisé à l'aide de la fonction **pdf(file="ton-nom-de-fichier.pdf")**. On organise le fichier à l'aide de la fonction **par(fig=c(x_0, x_1, y_0, y_1))** qui place une image dans le rectangle suivant. ![position rectangle]'https://github.com/homeostasie/Collection/raw/master/doc/traitement/position-image.pdf) Afn d'agrandir un peu le boxplot, on le superpose un peu en hauteur vers l'histogramme. 0.5 > 0.3 et on finit l'histogramme en 0.9 afin d'avoir un graphique plus agréable. *(ligne 100)* ``` pdf(file="nombre-achats.pdf") par(fig=c(0,1,0.3,.9), new=TRUE) hist(dataCollection$nbrAchat, freq=FALSE, col="grey", main="Nombre d'achats", xlab=NULL, ylab="Fréquence") lines(density(dataCollection$nbrAchat), col="red") par(fig=c(0,1,0,0.5), new=TRUE) boxplot(dataCollection$nbrAchat, horizontal = TRUE, col="grey") ``` ![Nombre d'achat](https://github.com/homeostasie/Collection/raw/master/doc/exemple/1-nombre-achats.pdf) <file_sep>\documentclass[11pt]{article} \usepackage{geometry,marginnote} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,french]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern,numprint} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx,float,grffile} \usepackage{pst-eucl, pst-plot,units} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} \DeclareUnicodeCharacter{20AC}{\euro} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height \begin{document} \section{ex16} \textbf{Initialisation :} \\ \subsection*{a)} Pour $n = 0$, (la famille est vide). $\prod_{i=1}^{0}(1-a_i) = 1$ (produit vide) et $\sum_{i=1}^{0}(a_i) = 0 $ (somme vide). \\ Or $1 \geq 1$ donc la propriété est vérifiée. \textbf{Hérédité :} \\ Soit $n \in \mathbb{N}$. Supposons vrai : $\forall (a_i)_{i \in [1,n]} \in [0,1]^{[1,n]}$, on a $\prod_{i=1}^{n}(1-a_i) \geq 1 - \sum_{i=1}^{n}(a_i)$ Soit $(a_i)_{i \in [1,n+1]}$ une famille d'éléments de [0,1]. \\ On sait que $\prod_{i=1}^{n}(1-a_i) \geq 1 - \sum_{i=1}^{n}(a_i)$ Donc \begin{align} (1 - a_{n+1}) \prod_{i=1}^{n}(1-a_i) &= \prod_{i=1}^{n+1}(1-a_i) \geq (1 - a_{n+1}) (1 - \sum_{i=1}^{n}(a_i)) \\ &= 1 - \sum_{i=1}^{n+1}(a_i) + a_{n+1} \sum_{i=1}^{n}(a_i) \\ &\geq 1 - \sum_{i=1}^{n+1}(a_i) \\ \end{align} car $a_{n+1} \sum_{i=1}^{n}(a_i) \geq 0$ Donc la propriété est héréditaire et donc vraie $\forall n \in \mathbb{N}$. \subsection*{b)} $\sum_{i=1}^{n}(\dfrac{a_i}{m} - 1 ) = \dfrac{1}{m} \sum_{i=1}^{n}(a_i) - \sum_{i=1}^{n}(1) = \dfrac{\sum_{i=1}^{n}(a_i)}{\dfrac{1}{n}\sum_{i=1}^{n}(a_i)} - n = n - n = 0$. \subsection*{c)} $\forall i \in [1,n] ln \dfrac{a_i}{n} \leq \dfrac{a_i}{m} - 1$ car $\dfrac{a_i}{m} > 0$. donc en sommant $\sum_{i=1}^{n}(ln \dfrac{a_i}{m}) \leq \sum_{i=1}^{n}(\dfrac{a_i}{m}- 1) = 0$. Or, $\sum_{i=1}^{n}(ln \dfrac{a_i}{m}) = ln (\prod_{i=1}^{n}(\dfrac{a_i}{m})) = ln (\dfrac{1}{m^n} \prod_{i=1}^{n}(a_i)) \leq 0 $. Donc $\dfrac{1}{m^n} \prod_{i=1}^{n}(a_i)) \leq 1 $ donc $\prod_{i=1}^{n}(a_i) \leq m^n$ i;e, $ (\prod_{i=1}^{n}(a_i))^{\frac{1}{n}} \leq m$ , CQFD. \subsection*{d)} $A(\dfrac{1}{a_1},...,\dfrac{1}{a_n}) = \dfrac{1}{n} \sum_{i=1}^{n}(\dfrac{1}{a_i} = \dfrac{1}{1 / \sum_{i=1}^{n}(\dfrac{1}{a_i})} = \dfrac{1}{H(a_1,..., a_n)}$ Par conséquent, comme $G(\dfrac{1}{a_1},...,\dfrac{1}{a_n}) \leq \dfrac{1}{H(a_1,..., a_n)}$ On a : $H(a_{1},..., a_{n}) \leq \dfrac{1}{ G( \frac{1}{a_1},...,\frac{1}{a_n} ) } = (\prod_{i=1}^{n} \dfrac{1}{a_i})^{-1/n}$ \newline $= (\prod_{i=1}^{n} (\dfrac{1}{a_i})^{-1})^{1/n}$ \newline $= (\prod_{i=1}^{n} (a_i))^{1/n}$ \newline $= G(a_1,...,a_n)$ CQFD \end{document}<file_sep>#!/usr/bin/env python # LABORATOIRE <NAME> # CONTRIBUTEURS # - THOMAS # LICENCE # GPL v3 # Petite introduction à l'ia avec de l'adaptation et de la triche. # pile-face-didactique se propose de suivre l'évolution du code sans pour autant la supprimer. # C'est une bonne chose pour comprendre la démarche # Importation des modules import random # Structure du test de pile ou face simple et unique avec affichage #if 0.25 <= 0.5: # print("pile") #else: # print("face") # Tirage aléatoire uniforme entre 0 et 1 # random.random() #if random.random() < 0.5: # print("pile") #else: # print("face") # On structure en fonction def pilefacesimple(): if random.random() < 0.5: print("pile") else: print("face") # On tente un appel # pilefacesimple() # It's works ! # On essaye alors plusieurs = maxtirage def pilefacemax(maxtirage): # Notre compteur de tirage qu'on initialise tirage = 0 while ( tirage < maxtirage): if random.random() < 0.5: print("pile") else: print("face") tirage = tirage + 1 # On tente un appel pour vérifier le nombre de tirage # pilefacemax(5) # It's works # On essage maintenant de biaiser le jeu def pilefacebiais(biais, maxtirage): # Notre compteur de tirage qu'on initialise tirage = 0 while ( tirage < maxtirage): # On rajoute le biais ici. # Si on est inférieux à se nombre alors pile # sinon face if random.random() < biais: print("pile") else: print("face") tirage = tirage + 1 # On tente un appel pour vérifier le nombre de tirage # pilefacebiais(0.001, 5) # It's works # On améliore maintenant notre système en compartimentant # la sortie et l'affichage. # On écrit la sortie dans un fichier texte def fpileface(biais, maxtirage): # Notre compteur de tirage qu'on initialise tirage = 0 # Notre valeur de pile et face pile = 0 face = 1 # notre sortie=joute sous forme d'un fichier # avec une ligne par colonne # On ouvre en écriture un fichier (que l'on crée) joute = open("joute.csv","w") while ( tirage < maxtirage): if random.random() < biais: # on écrit dans le fichier et on saute une ligne joute.write("0\n") else: joute.write("1\n") tirage = tirage + 1 # On ferme le fichier joute.close() # Fonction qui affiche le résultat du lancer def resulpileface(files): # On ouvre en lecture notre fichier passer en paramètre # On crée une liste de chaine de caractère avec nos réponses resulstring= open(files,"r").read().splitlines() # Notre pile de réponses resul = [] tirage = 0 maxtirage= len(resulstring) while tirage < maxtirage: # On rajoute notre valeur nouvelle entière en haut de la pile resul.append(int(resulstring[tirage])) tirage = tirage + 1 #On imprime une première ligne informative print("-- RESULTAT --") print("0 = PILE -- 1 = FACE\n") print(resul) fpileface(0.8,100000) #resulpileface("joute.csv") # On commence la notion de joueur. # Ici le joueur va essayer de trouver la face sur laquelle la pièce va tomber. # Pour se faire, il va devoir choisir entre pile ou face au départ, # puis regarder le résultat et en fonction de ce dernier adapter sa stratégie # Pour les joueurs suivants, il n'y a pas vraiment d'adaptation ni d'intéligence. # Pour autant, c'est un bon point de départ. # Soit le joueur 1 = j1_opt l'optimiste qui répond toujours pile = 1. # Soit le joueur 2 = j2_pes le péssimiste qui répond toujours face =0. # Soit le joueur 3 = j3_haz qui répond au hasard avec une probabilité 0.5 # Les joueurs suivants tentent de réfléchier un poil et utilisent leur mémoire, # enfin la notre... ^^ # Soit le joueur 10 = j10-tout qui calcule à chaque pas la fréquence de pile et de face. # ... il a un gros cerveau et va donc recopier la liste entier au fil du temps. def j1_opt(files): #On importe les résultats (sans pour autant les lire) # On ouvre en lecture notre fichier passer en paramètre resulstring= open(files,"r").read().splitlines() resul = [] # le choix éffectué par j1 j1_choix = [] #j1_choix.append(0) # Le gain j1_gain = [] tirage = 0 maxtirage= len(resulstring) # Pourcentage de réussite j1_pour = 0 while tirage < maxtirage: resul.append(int(resulstring[tirage])) j1_choix.append(0) if resul[tirage] - j1_choix[tirage] == 0: j1_gain.append(1) j1_pour = j1_pour + 1 else: j1_gain.append(0) tirage = tirage + 1 # print("\n") # print("-- J1 - l'optimiste --") # print(j1_choix) print("\n") print("j1 -- 1 = GAGNER -- 0 = PERDU \t % = ",j1_pour/maxtirage) # print(j1_gain) j1_opt("joute.csv") def j2_pes(files): #On importe les résultats (sans pour autant les lire) # On ouvre en lecture notre fichier passer en paramètre resulstring= open(files,"r").read().splitlines() resul = [] # le choix éffectué par j1 j2_choix = [] #j1_choix.append(0) # Le gain j2_gain = [] tirage = 0 maxtirage= len(resulstring) j2_pour = 0 while tirage < maxtirage: resul.append(int(resulstring[tirage])) j2_choix.append(1) if resul[tirage] - j2_choix[tirage] == 0: j2_gain.append(1) j2_pour = j2_pour + 1 else: j2_gain.append(0) tirage = tirage + 1 # print("\n") # print("-- J2 - le pessimiste --") # print(j2_choix) print("\n") print("j2 -- 1 = GAGNER -- 0 = PERDU \t % = ",j2_pour/maxtirage) # print(j2_gain) j2_pes("joute.csv") def j3_cop(files): #On importe les résultats (sans pour autant les lire) # On ouvre en lecture notre fichier passer en paramètre resulstring= open(files,"r").read().splitlines() resul = [] # le choix éffectué par j3 j3_choix = [] # Premier choix au hasard if random.random() < 0.5: j3_choix.append(0) else: j3_choix.append(1) # Le gain j3_gain = [] tirage = 0 maxtirage= len(resulstring) # Pourcentage de réussite j3_pour = 0 while tirage < maxtirage: resul.append(int(resulstring[tirage])) # On pense que le résultat suivant sera le même que le précédent :petit_con: j3_choix.append(resul[tirage]) if resul[tirage] - j3_choix[tirage] == 0: j3_gain.append(1) j3_pour = j3_pour + 1 else: j3_gain.append(0) tirage = tirage + 1 # On régularise la liste en supprimant le dernier élément qui est en trop. j3_choix.pop() # print("\n") # print("-- J3 - copie le coup d'avant --") # print(j3_choix) print("\n") print("j3 -- 1 = GAGNER -- 0 = PERDU \t % = ",j3_pour/maxtirage) # print(j3_gain) j3_cop("joute.csv") def j4_invcop(files): #On importe les résultats (sans pour autant les lire) # On ouvre en lecture notre fichier passer en paramètre resulstring= open(files,"r").read().splitlines() resul = [] # le choix éffectué par j4 j4_choix = [] # Premier choix au hasard if random.random() < 0.5: j4_choix.append(0) else: j4_choix.append(1) # Le gain j4_gain = [] tirage = 0 maxtirage= len(resulstring) # Pourcentage de réussite j4_pour = 0 while tirage < maxtirage: resul.append(int(resulstring[tirage])) # On joue l'inverse du coup d'avant. if resul[tirage] == 1: j4_choix.append(0) else: j4_choix.append(1) if resul[tirage] - j4_choix[tirage] == 0: j4_gain.append(1) j4_pour = j4_pour + 1 else: j4_gain.append(0) tirage = tirage + 1 # On régularise la liste en supprimant le dernier élément qui est en trop. j4_choix.pop() # print("\n") # print("-- J4 - joue l'inverse du coup d'avant --") # print(j4_choix) print("\n") print("j4 -- 1 = GAGNER -- 0 = PERDU \t % = ",j4_pour/maxtirage) # print(j4_gain) j4_invcop("joute.csv") def j5_proba(files): #On importe les résultats (sans pour autant les lire) # On ouvre en lecture notre fichier passer en paramètre resulstring= open(files,"r").read().splitlines() resul = [] # le choix éffectué par j5 j5_choix = [] # Premier choix au hasard if random.random() < 0.5: j5_choix.append(0) else: j5_choix.append(1) # Le gain j5_gain = [] tirage = 0 maxtirage= len(resulstring) # Pourcentage de réussite j5_pour = 0 # Pourcentage de pile compter par j5 pile_pour = 0 while tirage < maxtirage: resul.append(int(resulstring[tirage])) # On compte le nombre de pile qui tombe. if resul[tirage] == 0: pile_pour = pile_pour + 1 # et on joue selon cette probabilité if random.random() < (pile_pour / (tirage+1)): j5_choix.append(0) else: j5_choix.append(1) if resul[tirage] - j5_choix[tirage] == 0: j5_gain.append(1) j5_pour = j5_pour + 1 else: j5_gain.append(0) tirage = tirage + 1 # On régularise la liste en supprimant le dernier élément qui est en trop. j5_choix.pop() # print("\n") # print(P"-- J5 - joue selon la meme proba--") # print(j5_choix) print("\n") print("j5 -- 1 = GAGNER -- 0 = PERDU \t % = ",j5_pour/maxtirage) # print(j5_gain) j5_proba("joute.csv") def j6_proba5(files,groupe): #On importe les résultats (sans pour autant les lire) # On ouvre en lecture notre fichier passer en paramètre resulstring= open(files,"r").read().splitlines() resul = [] # le choix éffectué par j6 j6_choix = [] # Les 5 premiers choix au hasard tirage = 0 # Le gain j6_gain = [] maxtirage= len(resulstring) # Pourcentage de réussite j6_pour = 0 # Première proba pa = 0.5 while tirage < maxtirage: tirage5 = 0 pile5 = 0 while tirage5 < groupe: # On choisit selon la proba des "groupes" derniers if random.random() < pa: j6_choix.append(0) else: j6_choix.append(1) resul.append(int(resulstring[tirage + tirage5])) # On compte le nombre de pile par groupe pile5 = pile5 + (1 - resul[tirage + tirage5]) if resul[tirage + tirage5] - j6_choix[tirage + tirage5] == 0: j6_gain.append(1) j6_pour = j6_pour + 1 else: j6_gain.append(0) tirage5 = tirage5 + 1 tirage = tirage + groupe # On calcul la probabilité pa = pile5 / groupe # On régularise la liste en supprimant le dernier élément qui est en trop. # print("\n") # print("-- J6 - joue selon la meme proba pendant 5 coups--") # PRINT(J6_choix) print("\n") print("J6 -- 1 = GAGNER -- 0 = PERDU \t % = ",j6_pour/maxtirage) # print(j6_gain) j6_proba5("joute.csv",10) <file_sep>\documentclass[11pt]{article} \usepackage{geometry} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,francais]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx, float} \usepackage{tikz,tkz-tab} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} % No page header \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height %---------------------------------------------------------------------------------------- % Début du document %---------------------------------------------------------------------------------------- \begin{document} $$\sqrt{1 - x } + \sqrt{1 + x } + 2\sqrt{1 - x^2 } = 4$$ \setlength{\columnseprule}{1pt} \begin{multicols}{2} \subsection*{domaine de définition} \textit{des racines donc des problèmes pour les valeurs négatives.} \begin{eqnarray*} 1 - x &\geq& 0 \\ 1 + x &\geq& 0 \\ 1 - x^2 &\geq& 0 \end{eqnarray*} On cherche $x \in [-1 ; 1]$ \subsection*{Factorisation} On sait que $a^2 + b^2 + 2ab = (a+b)^2$ \\ On prend $a = \sqrt{1 - x }$ et $b = \sqrt{1 + x }$.\\ De plus : \begin{eqnarray*} ab &=& \sqrt{1 + x } \times \sqrt{1 - x } \\ ab &=& \sqrt{(1+x)(1-x)} \\ ab &=& \sqrt{1 - x^2} \end{eqnarray*} On factorise notre équation. \begin{eqnarray*} \sqrt{1 - x } + \sqrt{1 + x } + 2\sqrt{1 - x^2 } &=& 4 \\ (\sqrt{1-x} + \sqrt{1+x})^2 &=& 4 \\ \left\{ \begin{aligned} \sqrt{1-x} + \sqrt{1+x} &=& 2 \\ \sqrt{1-x} + \sqrt{1+x} &=& -2 \\ \end{aligned} \right. \end{eqnarray*} \textit{ // impossible, une somme de racine de ne peut être négative dans R.} \subsection*{Changement de variable} $$\sqrt{1-x} + \sqrt{1+x} = 2$$ On pose $y = \sqrt{1-x}$ On a alors : \begin{eqnarray*} y &=& \sqrt{1-x} \\ y^2 &=& 1-x \\ x &=& 1-y^2 \\ \end{eqnarray*} On obtient aussi : \begin{eqnarray*} \sqrt{1+x} &=& \sqrt{1+1-y^2} \\ \sqrt{1+x} &=& \sqrt{2-y^2} \end{eqnarray*} d'où notre équation : \begin{eqnarray*} \sqrt{1-x} + \sqrt{1+x}) &=& 2 \\ y + \sqrt{2-y^2} &=& 2 \\ y - 2 &=& - \sqrt{2-y^2}\\ (y - 2)^2 &=& 2 - y^2\\ y^2 -4y + 4 &=& 2 - y^2\\ 2y^2 - 4y + 2 &=& 0 \end{eqnarray*} \subsection*{Polynôme du second degré} Calcul du discriminant \begin{eqnarray*} \Delta &=& 4^4 - 4\times 2\times 2 \\ \Delta &=& 0 \end{eqnarray*} Une seule racine double. \begin{eqnarray*} y &=& -\dfrac{-4}{2\times2} \\ y &=& 1 \end{eqnarray*} \subsection*{Solution} \begin{eqnarray*} y &=& 1 \\\ \sqrt{1-x} &=& 1 \\ 1-x &=& 1\\ x &=& 0 \end{eqnarray*} x=0 est bien l'unique putain de solution qu'on avait déjà trouver visuellement... mais au moins, on sait qu'il y en a pas d'autre... Même si le tracer graphique de la fonction nous donnait bien le résultat aussi... \end{multicols} \end{document} <file_sep>\documentclass{beamer} \usetheme{Warsaw}% le thème choisi pour ma présentation. Essayer aussi Warsaw Singapore Pittsburgh Montpellier Malmoe Luebeck Goettingen... \usepackage[frenchb]{babel} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} \usepackage{amsmath} \usepackage{epsfig,pslatex,colortbl} \usepackage{graphics} \usepackage{graphicx}%pour les includegraphics \usepackage{array}% pour des tableaux particuliers. Nécessaire pour les révéler colonne par colonne %\setbeamercovered{transparent}%l'autre option : invisible, cache totalement le texte pas encore découvert (ie, n'utilise pas le ``grisé''). \setbeamercovered{invisible} \colorlet{orange}{red!70!yellow}% mes petites couleurs que j'aime bien \colorlet{mauve}{blue!70!red} \colorlet{brouge}{red!70!blue} \addtobeamertemplate{footline}{\insertframenumber/\inserttotalframenumber} %pour ajouter un numéro de page en bas. \title[Étude d'un chantier routier]{Étude d'un chantier routier} %l'argument entre [] est une version courte du titre, qu'on met en bas des transparents. \author{<NAME>} \date{\today} \institute{Master SITN - UCBL} \AtBeginSection[] % pour mettre la table des matières % % au début de chaque section { \begin{frame}<beamer> \frametitle{Outline} \tableofcontents[currentsection] \end{frame} } \begin{document} \begin{frame}\titlepage \end{frame} \begin{frame} \frametitle{Plan de l'exposé} \tableofcontents% comme en latex normal, met la table des matières \end{frame} \section{Introduction} \begin{frame} \frametitle{Schéma~} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route0.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route1.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route2.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route3.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route4.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \frametitle{Modèle~} \begin{definition} Processus de comptage\newline \begin{itemize}\itemsep2pt \item Pour t $\geq$ 0 le nombre N(t) est à valeur entières positives. \item La fonction t $\longrightarrow$ N(t) est croissante. \item Pour tout couple (a,b) (0 < a < b), la différence N(b) - N(a) représente le nombre de << tops >> se produisant dans l'intervalle de temps ]a, b]. Dans notre cas un top est le passage d'une voiture. \end{itemize} \end{definition} \end{frame} \begin{frame} \begin{definition} Processus de Poisson\newline \begin{itemize}\itemsep2pt \item N(0) = 0 \item Le processus est à accroissement indépendant. Les nombres de << tops >> se produisant dans des intervalles de temps disjoints est sont indépendants. \item Le nombre de << tops >> se produisant dans un intervalle de temps de longueur t $\geq$ 0 suit la loi de Poisson de paramètre $\lambda t$, c'est-à-dire, pour tout s $\geq$ 0 et pour tout t $\geq$ 0, on a pour n $\geq$ 0: $$P[N(s+t) - N(s) = n] = e^{- \lambda t}\frac{\lambda t^{n}}{n!}$$ \end{itemize} \end{definition} \end{frame} \section{Estimation du trafic} \begin{frame} \frametitle{Deux caractérisations possibles} \begin{itemize}\itemsep4pt \item Soit à partir des instants $(Ti) _{i \in N*}$ de sauts, en disant que la suite des $\tau_{i} = T_{i} - T_{i-1}$ est une suite de variables aléatoires indépendantes de même loi exponentielle de paramètre $\lambda s$. \item relever les intervalles de temps séparant les passages de deux véhicules consécutifs. Ces données nous permettent d'utiliser la première caractérisation. \end{itemize} \end{frame} \begin{frame} \frametitle{Deux statistiques à relever} \begin{itemize}\itemsep4pt \item Soit à partir de sa fonction de comptage $N(t) = \sum 1_{0<T_{i}\leq t}$ en disant que N(t) est à accroissements indépendants et que pour tout couple (t,s) de réels $N(t \geq 0, s>0 )$ l'accroissement N(t + s) - N(t) suit une loi de Poisson de paramètre $\lambda s$. \item compter à intervalles réguliers (une minute par exemple) le nombre de véhicules qui passent dans l'intervalle. Ces données nous permettent d'utiliser la deuxième caractérisation. \end{itemize} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{estim0.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{estim1.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{estim2.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{estim3.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{estim4.jpg} \end{center} \end{figure} \end{frame} \section{Condition de non-engorgement} \begin{frame} \begin{itemize}\itemsep3pt \item a : Temps qu'a besoin un véhicule pour démarrer \item v : Vitesse constante de déplacement des véhicules \item L : Longueur du chantier \item $d_{1}$ : Durée du feu vert pour la voie 1 \item $d_{2}$ : Durée du feu vert pour la voie 2 \item K : Nombre de véhicule qu'on souhaite faire passer dans un sens à chaque cycle. \item $\lambda_{1}$ = Moyenne des véhicules sur la voie 1. \item $\lambda_{2}$ = Moyenne des véhicules sur la voie 2. \end{itemize} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{feu1.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{feu2.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{feu3.jpg} \end{center} \end{figure} \end{frame} \begin{frame} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{feu4.jpg} \end{center} \end{figure} \end{frame} \begin{frame} Il faut que d $\geq$ aK pour faire passer au moins K véhicule. $$d_{1} \geq a \lambda_{1} ( d_{1} + d_{2} + 2L/v)$$ $$d_{2} \geq a \lambda_{2} ( d_{1} + d_{2} + 2L/v)$$ \end{frame} \begin{frame} \begin{itemize}\itemsep3pt \item a = 4 secondes = 4/60 minutes: Temps qu'a besoin un véhicule pour démarrer \item v = 30 km / h = 0.5 m / min: Vitesse constante de déplacement des véhicules \item $\lambda_{1}$ = 4 = 4 : Moyenne des véhicules sur la voie 1. \item $\lambda_{2}$ = 3 = 3 : Moyenne des véhicules sur la voie 2. \item L = 600 mètres. \item $d_{1}$ = 4/3 $d_{2}$ = 1.5 min \item $d_{2}$ = 1.1 min \end{itemize} \end{frame} \section{Longueur de la longueur de la file de véhicule} \begin{frame} $$X_{n+1} = (X_{n} + Y_{n} - K)^{+} + Z_{}n$$ \begin{itemize}\itemsep3pt \item $(Y_{n})$ est une suite de variable aléatoire de même loi de Poisson de paramètre $\lambda_{1} d_{1}$ \item $(Z_{n})$ est une suite de variable aléatoire de même loi de Poisson de paramètre $\lambda_{1} (d_{2} + 2L/v)$ \end{itemize} \end{frame} \begin{frame} \begin{definition} Chaîne de Markov\newline Une chaîne de Markov est un processus sans mémoire, non héréditaire.\newline Dans l'évolution au cours du temps, l'état du processus à l'instant (n+1) ne dépend que de celui à l'instant n précédent, mais non de ses états antérieurs. \end{definition} \end{frame} \begin{frame} \begin{definition} On fait tourner une grosse simulation avec N=100 le nombre d'échantillons et n=2000 la taille des échantillons. \newline On obtient une moyenne de 16 / 17 véhicules. \begin{itemize}\itemsep2pt \item 0.60 de voiture = 5m \item 0.30 de bus = 10 \item 0.10 de camion = 20m \end{itemize} Soit une file d'attente de 16.8 * (0.6*5 + 0.3*10 + 0.1*20) = 134.50 m \newline On regarde le nombre de fois où la file dépasse les 235 mètres : \newline p = 37 / 1000 = 0.037 \end{definition} \end{frame} \section{Conclusion} Un modèle stochastique assez simple qui donne des résultats sur la quantité de véhicule. \newline Bien d'autre modèle existe... \end{document} <file_sep>//Le TP0 Erreur d'arrondi // <NAME> //Exo 2 - Un peu de récurrence - Voir document pdf pour les questions théoriques. function [I_x5] = F_intpos(n_in) //I_x5 est la variable de sortie sous forme d'un tableau qui sort les valeurs trouver par récurrence positif. //n_in est la variable d'entrée qui demande jusqu'a quel rang nous appliquerons la récurrence. //soit I_x5(1,3) le calcul au rang 0 I_x5(1)=log(11/10) // i est la variable utilisé pour la boucle while on la commence à 1 pour ne pas avoird de souci avec les tableaux i=1 while i<n_in //On réalise la récurrence I_x5(i+1)=1/i-10*I_x5(i) //On encadre le tabeau dans les 2ieme et 3ieme colonnes par les vérifications d'encadrement i=i+1, end endfunction function [I_xinv5] = F_intinv(n_in) //I_xinv5 est la variable de sortie sous forme d'un tableau qui sort les valeurs trouver par récurrence inverse. //n_in est la variable d'entrée qui demande à quel rang on affecte le premier terme par son approximation. I_xinv5(n_in)=1/(10*(n_in+1)) // n_in est une variable d entree qui indique le nombre d'itération à faire // Le I_xinv5 1 range les In trouvé par récurrence en partant de In entre 1/(11*(n_in+1)) et 1/(10*(n_in+1)) // Le I_xinv5 2 teste la première inégalités et renvoie le résultat i=n_in-1 while i>0 I_xinv5(i) = (1/10)*(1/(i)-I_xinv5(i+1)), i=i-1 end endfunction function [tab_comp] = F_tab_comp(n_in) [I_x5] = F_intpos(n_in); [I_xinv5] = F_intinv(n_in); for j=0:1:n_in-1 tab_comp(j+1,1)=j; tab_comp(j+1,2)=1/(11*(j+1)); tab_comp(j+1,3)=1/(10*(j+1)); tab_comp(j+1,4)=I_x5(j+1); tab_comp(j+1,5)=I_xinv5(j+1); end endfunction [tab_comp] = F_tab_comp(30) j=1:1:15 plot2d(j,tab_comp(j,2)) plot2d(j,tab_comp(j,3)) plot2d(j,tab_comp(j,4),style=5) plot2d(j,tab_comp(j,5),style=[color("green")]) <file_sep>\documentclass[11pt]{article} \usepackage{geometry,marginnote} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,french]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern,numprint} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx,float,grffile} \usepackage{pst-eucl, pst-plot,units} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} \DeclareUnicodeCharacter{20AC}{\euro} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height \newcommand{\Pointilles}[1][3]{% \multido{}{#1}{\makebox[\linewidth]{\dotfill}\\[\parskip] }} \newtheorem{Definition}{Définition} \usepackage{siunitx} \sisetup{ detect-all, output-decimal-marker={,}, group-minimum-digits = 3, group-separator={~}, number-unit-separator={~}, inter-unit-product={~} } \setlength{\columnseprule}{1pt}<file_sep># petits-pedestres *Petits projets plus ou moins finis dans différents langages.* ## 2012 * **1 - Pile ou Face** : **Python**. * **2 - Décomposition LU** : **C++ / Open MP**. * **3 - Algorithme de Remez** : **scilab**. * **4 - Chantier de voitures** : **R**. ## 2013 * **1 - décomposition en fraction continue** : **C++**. * **2 - Enveloppe convexe** : **C++**. * **3 - Arrondis de fonctions** : **scilab**. ## 2014 * **1 - Calcul de PI par répétitions** : **Python / C**. Calcul de PI par chaine de Markov. * **2 - Jeu de la vie** : **C++**. Le jeu de la vie imaginé par <NAME> en 1970 est un automate cellulaire. * **3 - Mooc : Differential equations in action** : **Python**. Les deux premières parties : Houston we have a problem & Houston we have a solution. * **4 - Project Euler** : **Python**. Les 10 premiers problèmes du project Euler. ## 2015 * **1 - Collection de cartes** : **R**. Combien faut-il acheter de paquet de cartes afin de former une collection complète ? * **2 - Lièvre VS Tortue** : **Python**. Un petit jeu de probabilité d'une course du lièvre et de la tortue. ## 2017 * **1 - <NAME>** : **Python**. En tant qu'intendant du roi, vous compter le nombre de grain de blé que Sissa a gagner lors de sa requête auprès de l'empereur. * **2 - RPN** : **Python**. Petite implémentation d'une calculette rpn en Python. ## 2018 * **1 - Interpolation** : **Python**. Petite interpolation graphique d'un tableau de donnée. * **2 - Morpions** : **C**. Un petit morpion CLI en C. ## Discussions Questions de maths suite à des discussions ### 1 - Pour le frangin **Latex** * Second degrée - *2018* * Statistiques - *2018* * Suites - *2018* ### 2 - Max * **c++** : Vector - *2017* ### 3 - Discord Mathmématiques * **Latex** : Équation avec racine carré - *2018* ## Contributeur * - **<NAME> - <EMAIL> / <EMAIL>** ## Licence - MIT Licence <file_sep>package main import ( "fmt" "encoding/json" ) func main() { var Personne = make(map[string]string) var monNom string var monAdresse string fmt.Println("Votre nom ?") fmt.Scanln(&monNom) fmt.Println("Votre addresse ?") fmt.Scanln(&monAdresse) Personne["Nom"] = monNom Personne["Addresse"] = monAdresse json, err := json.MarshalIndent(Personne, "", "\t") if err != nil { fmt.Println(err) } fmt.Println(string(json)) }<file_sep>Dans mon établissement, nous constatons depuis plusieurs années un écart croissant entre les attendus des référentiels et programmes des STS et le niveau effectif de nos étudiants (en particulier en MSP, CIRA et MMV). Et ce constat n'est pas propre à notre discipline. Il est très compliqué (voir impossible dans certaines sections) de "boucler le programme" tant les lacunes des étudiants sont importantes (par exemple, résoudre une équation de degré 1, tracer la courbe représentative d'une fonction affine). Nous essayons de comprendre d'où vient le problème, en particulier en terme de recrutement. - Est-ce un constat partagé ? - Qu'en est-il dans vos établissements ? ------------------------- Même constant en BTS MS chez nous avec 90% de bac pro pour qui repérer un coefficient directeur pour une fonction affine relève de l'exploit. Alors parler de dérivation... Et ce constat se généralise à toutes les matières. Les élèves se démotivent et quittent la section. Et ceux qui restent n'arrivent même plus à se mettre au travail. J'ai l'impression de participer à une course de formule 1 avec un 103 SP... J'ai une question concernant le recrutement et vos effectifs : Vous en êtes ou ? Sur 15 places, il me reste 10 étudiants dont 8 pour qui l'obtention du diplôme relève de l'utopie. ------------------------- Je fais le même constat pour le BTS MGTMN (ancien Géomètre Topographe). Plus particulièrement depuis deux ans, le niveau a grandement baissé. Concernant la motivation des élèves, nous pensons qu'une partie du problème vient du fonctionnement de Parcoursup : depuis que nous avons des quotas pour les STI (50% de STI2D, 25% de bac Pro et 25% de bac généraux), nous avons même du mal à remplir la section (il manque entre 2 et 4 étudiants à la fin de la première phase). De ce fait des étudiants de STI2D arrivent en procédures complémentaires alors que d'autres seraient intéressés en bac général ou bac pro.. Malheureusement ces étudiants sont peu souvent intéressés par la filière et nous avons des abandons avant la fin de la première année (ce qui n'arrivait pas avant). ------------------------- Je fais aussi ce constat en bts SIO, même si les maths n'y sont pas trop relevées. Le domaine aidant, on est souvent sur les machines pour apprendre l'algorithmique en python, et du coup les maths qui vont avec passent peut-être un peu mieux. Les activités de type jupyter notebook sont une aide précieuse pour s'adapter au rythme des élèves; notamment capytale est vraiment bien. Autrement, j'en profite pour signaler un autre outils numérique méconnu: dans le moodle intégré à l'ENT région, les questions de type stack sont vraiment puissantes: elles autorisent du calcul littéral et une analyse fine des réponses (voir la petite vidéo en teasing). ------------------------- Nous faisons le même constat en mathématiques avec nos BTS CRSA. Nous déplorons l'écart abyssal entre le niveau de nos étudiants et les attendus du programme. ------------------------- Même constat en BTS MTE et CIM. Le recrutement des BTS est fait en priorité aux élèves venant de la voie pro qui parfois avaient 18 en maths et qui n'arrivent pas à suivre en BTS. En parallèle nous avons des élèves qui ont fait une première année de Fac ou d'iut et l'écart est énorme pour exemple les limites font peur aux élèves venant de la voie pro et l'étudiant réorienté me parle de petit o!! ------------------------- Même chose en CRSA où on doit traiter les équations différentielles avec des élèves qui n'ont pas compris ce qu'est une fonction ! Il y a un gros écart entre ceux qui viennent de bac pro et ceux qui viennent de STI2D, la difficulté étant de ne pas perdre les premiers tout en alimentant les seconds qui peuvent prétendre à une poursuite d'études. Même en utilisant très largement les outils informatiques, on est face à des élèves qui ont une très faible capacité d'abstraction et qui n'arrivent pas à les utiliser. ------------------------- Nouvellement prof en STS CIRA après une dizaine d'années en retrait de la série, je suis confronté au même problème de niveau, globalement très faible, hétérogène avec un manque de motivation pour près d'un quart des élèves qui plombent l'ambiance de travail. Avec ce constat encourageant, j'avance à petits pas pour ne pas décourager les uns, faire fuir les autres... Mais ce qui me préoccupe le plus est effectivement l'écart (abyssal est le mot) entre ce niveau et les attendus de l'épreuve (oups, on me demande de mettre au pot à la banque des sujets interacadémiques, donc j'ai regardé plus attentivement les sujets et je ne sais pas comment composé). ------------------------- Le constat est-il partagé seulement pour les BTS, ou pour l'ensemble des formations post-bac ? Est-ce qu'on ne paye pas surtout les pots cassés du covid, en particulier pour les élèves issus de bac pro, puisque les élèves qui sont en bac +1 actuellement étaient en seconde lors du premier confinement (si je ne me trompe pas), et ont donc eu une scolarité hachée durant tout le lycée (et équivalent en bac pro, avec je suppose moins d'assiduité des ces élèves-là qui n'ont pas dû passer beaucoup de temps sur leurs cours de maths pendant les confinements et restrictions successifs). Je suis PRAG à l'INSA de Lyon, et cette année particulièrement, je trouve que le niveau est très hétérogène, avec des élèves qui restent bons pour la plupart (ils sont sélectionnés pour), mais beaucoup parmi eux avec des bases de lycée très fragiles (encore plus que d'habitude !) De plus, il est assez frustrant de voir tant de belles choses dans le programme de Spé maths, pour qu'au final quand on fait un petit sondage, systématiquement un tiers minimum n'a pas vu cette notion. Mais jamais le même tiers ! Par exemple sur l'IPP, ou les equa diff, les différents types de raisonnement mathématiques, cela ne disait rien ou pas grand-chose à la moitié des élèves que j'ai. Je ne jette pas du tout la pierre aux collègues de lycée qui font bien comme ils peuvent avec les contraintes actuelles, mais on a l'impression vu de l'extérieur d'un programme à la carte avec des pans entiers laissés de côté (mais pas les meme) où dans le supérieur on ne peut s'appuyer sur rien et où il faut systématiquement tout refaire de 0, puisque certains ne l'auront pas fait. Et que dire du fait que même ce qui a été fait, est bien loin avec des épreuves en Mars... En tout cas tout cela est bien déprimant, et vos messages aussi :( Pauvres élèves qui pâtissent de tout cela... Bon courage à tous,<file_sep># Dossiers CODE := $(shell pwd) all: exo1 exo1: pdflatex tex/exo1-racine.tex pdflatex tex/exo1-racine.tex liens: pdflatex tex/liens.tex pdflatex tex/liens.tex # nettoyage proper: rm -f *.log *.toc *.aux *.nav *.snm *.out *.bbl *.blg *.dvi rm -f tex/*.log tex/*.fls tex/*.synctex.gz tex/*.aux tex/*.fdb_latexmk rm -f *.backup *~ <file_sep># RPN Tentative pour implémenter une petite calculatrice RPN en python avec une petite CLI. ### Projet ##### V1 1. Implementation d'une liste de 4 éléments : **x**, **y**, **z**, **t**. 2. Quelques opérations sur la liste : **x<->y**, **↑**, **↓**. 3. Ajout des quatre opérations : **+**, **-**, **\***, **/** ### Dépôts - **src** : gestion de la liste et des entrées - **tests** : vérification des calculs - **tools** : affichage de la pile et interface CLI - *license* - *makefile* - *readme* ## Contributeur * - **<NAME> - <EMAIL> / <EMAIL>** ## Licence - MIT License <file_sep>#include <iostream> #include <vector> class coordonnate { public: int x; int y; int z; }; int main() { coordonnate myCoor; std::vector<coordonnate> myvec; myvec.push_back (myCoor); std::cout<<"OK"<<std::endl; return(0); } <file_sep>% <NAME> - <NAME> % Décomposition LU - Small Project \documentclass[10pt,a4paper]{article} \usepackage{amsmath} % multline \usepackage{amsfonts} \usepackage{amssymb} \usepackage{lmodern} \usepackage[french]{babel} \usepackage[utf8]{inputenc} %french accents \usepackage[T1]{fontenc} %french accents \usepackage{fixltx2e} \usepackage{fullpage} % change margins \usepackage{ucs} \usepackage{graphicx} \usepackage{latexsym} %distribution tilde \usepackage{pstricks} \DeclareMathOperator*{\argmin}{arg\,min} %\usepackage[french]{babel} %\newcommand{\nocomma}{} %\newcommand{\tmop}[1]{\ensuremath{\operatorname{#1}}} \usepackage[final]{pdfpages} \usepackage{pdfpages} \usepackage{epsfig} \DeclareGraphicsExtensions{.ep s,.ps,.eps.gz,.ps.gz, .txt} \usepackage{hyperref} \usepackage{fancyhdr} \pagestyle{fancy} \headsep=25pt \begin{document} \thispagestyle{empty} \begin{flushleft} \textbf{<NAME>}\\ \end{flushleft} \begin{LARGE} \begin{center} \vfill \textbf{PROJET : CALCUL PARALLELE}\\ \textbf{Décomposition LU} \vfill \end{center} \end{LARGE} \newpage \section*{SOMMAIRE} \hypertarget{SOMMAIRE}{} \begin{itemize} \item[] ~~\hyperlink{Introduction}{Introduction} \hfill 3\\ \item[1] ~~\hyperlink{un peu de théorie}{un peu de théorie} \hfill 4\\ \item[2] ~~\hyperlink{Programme}{Programme} \hfill 5\\ \item[2.1] \hyperlink{Programme Séquentiel}{Programme Séquentiel} \hfill 5\\ \item[2.1] \hyperlink{Programme Parallèle}{Programme Parallèle} \hfill 5\\ \item[] ~~\hyperlink{Conclusion}{Conclusion} \hfill 5\\ \end{itemize} \newpage \section*{Introduction} \hypertarget{Introduction}{} La décomposition \textbf{LU} est une méthode importante pour la résolution d'équation du type $Ax=b$, où $A$ et $b$ sont des matrices et vecteurs respectivement. Losque la matrice $A$ est de taille très grande, le calcul de la solution $x$ est parfois très fastidieux. Dans une première partie, nous verrons la théorie du concept, puis une brève application de cette méthode sur une matrice donnée. Pour finir, nous détaillerons le programme \textbf{MPI} effectuant la factorisation \textbf{LU} d'une matrice pleine distribuée par colonnes, ainsi que le calcul du vecteur solution par descente-remontée. \newpage \section{un peu de théorie} \hypertarget{un peu de théorie}{} La décomposition \textbf{LU} consiste à transformer la matrice $A$ en un produit de matrices $L$ et $U$. Où $L$ est une matrice triangulaire inférieure avec les éléments diagonaux égaux à $1$ et $U$ une matrice triangulaire supérieure. $A$ peut s'écrire de la manière suivante : $A=LU$ selon certaines conditions. En effet, cette décomposition ne peut se faire que si $A$ est inversible et ses mineures sont inversibles. Voici ce que l'on veut résoudre : $$Ax=b \Longleftrightarrow \begin{pmatrix} 1 & 1 & 0 & 0 & 0 & ... & 0\\ 1 & 0 & 2 & 0 & ... & ... & 0\\ 1 & 0 & 0 & 3 & 0 & ... & 0\\ ... & ... & ... & ... & ... & ... & \vdots \\ 1 & 0 & 0 & 0 & 0 & ... & n-1\\ 1 & 0 & 0 & 0 & 0 & ... & 0 \end{pmatrix} \left( \begin{array}{c} x_{1} \\ x_{2} \\ x_{3} \\ \vdots \\ \vdots \\ x_{n} \\ \end{array} \right) = \left( \begin{array}{c} 2 \\ 3 \\ 4 \\ \vdots \\ \vdots \\ n \\ \end{array} \right) $$ Ici, $A=\begin{pmatrix} 1 & 1 & 0 & 0 & 0 & ... & 0\\ 1 & 0 & 2 & 0 & ... & ... & 0\\ 1 & 0 & 0 & 3 & 0 & ... & 0\\ ... & ... & ... & ... & ... & ... & \vdots \\ 1 & 0 & 0 & 0 & 0 & ... & n-1\\ 1 & 0 & 0 & 0 & 0 & ... & 0 \end{pmatrix}$, $b = \left( \begin{array}{c} 2 \\ 3 \\ 4 \\ \vdots \\ \vdots \\ n \\ \end{array} \right)$, $x = \left( \begin{array}{c} x_{1} \\ x_{2} \\ x_{3} \\ \vdots \\ \vdots \\ x_{n} \\ \end{array} \right) $\linebreak\linebreak Ces mineures principales doivent être de déterminant non-nulle. En effet, les mineurs prinicpaux sont les matrices pour lesquelles on lui retranche la i-ème ligne et la j-ème colonne. \\ D'après un calcul fastidieux, nous obtenons pour la matrice $A$ la factorisation \textbf{LU} suivante : $$\begin{pmatrix} 1 & 1 & 0 & 0 & 0 & .. & 0\\ 1 & 0 & 2 & 0 & .. & .. & 0\\ 1 & 0 & 0 & 3 & 0 & .. & 0\\ .. & .. & .. & .. & .. & .. & \vdots \\ 1 & 0 & 0 & 0 & 0 & .. & n-1\\ 1 & 0 & 0 & 0 & 0 & .. & 0 \end{pmatrix} =\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & .. & .. & 0\\ 1 & 1 & 0 & 0 & .. & .. & .. & 0\\ 1 & 1 & 1 & 0 & 0 & .. & .. & 0\\ 1 & 1 & 1 & 1 & .. & .. & \vdots & \vdots \\ 1 & 1 & 1 & 1 & 1 & .. & .. & 0\\ 1 & 1 & 1 & 1 & 1 & 1 & .. & 1 \end{pmatrix} \begin{pmatrix} 1 & 1 & 0 & 0 & 0 & .. & .. & 0\\ 0 & -1 & 2 & 0 & .. & .. & .. & 0\\ 0 & 0 & -2 & 3 & 0 & .. & .. & 0\\ 0 & 0 & 0 & -3 & 4 & 0 & \vdots & \vdots \\ 0 & 0 & 0 & 0 & -4 & 5 & .. & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & .. & -(n-1) \end{pmatrix}$$ Où $L=\begin{pmatrix} 1 & 0 & 0 & 0 & 0 & .. & .. & 0\\ 1 & 1 & 0 & 0 & .. & .. & .. & 0\\ 1 & 1 & 1 & 0 & 0 & .. & .. & 0\\ 1 & 1 & 1 & 1 & .. & .. & \vdots & \vdots \\ 1 & 1 & 1 & 1 & 1 & .. & .. & 0\\ 1 & 1 & 1 & 1 & 1 & 1 & .. & 1 \end{pmatrix}$, et $U=\begin{pmatrix} 1 & 1 & 0 & 0 & 0 & .. & .. & 0\\ 0 & -1 & 2 & 0 & .. & .. & .. & 0\\ 0 & 0 & -2 & 3 & 0 & .. & .. & 0\\ 0 & 0 & 0 & -3 & 4 & 0 & \vdots & \vdots \\ 0 & 0 & 0 & 0 & -4 & 5 & .. & 0\\ 0 & 0 & 0 & 0 & 0 & 0 & .. & -(n-1) \end{pmatrix}$ \linebreak Nous remarquons ces deux matrices $L$ et $U$ sont calculées en fonction de $n$ pour cette matrice particulière $A$.\\ Ajoutons tout de même que le déterminant de $A$ vaut : $$ det(A)=det(L)det(U)=1 \times det(U)=det(U)=(-1)^{n-1}(n-1)!$$ Grace à cette décomposition, nous pouvons calculer la valeur de cette solution $x$ de l'équation $Ax=b$.\\ Pour cela, nous étudions le système suivant :\\ $$ \left\{ \begin{array}{ll} Ly=b \\ Ux=y \\ \end{array} \right. $$ La résolution du système linéaire $Ly=b$ est une méthode de descente. Une fois $y$ connue, la résolution du système linéaire $Ux=y$ est une méthode de remontée. Ainsi, la valeur de $x$ sera connue. \section{Programme} \hypertarget{Programme}{} \subsection{Programme Séquentiel} \hypertarget{Programme Séquentiel}{} Ici, nous présentons le programme de la \textbf{factorisation LU} séquentiel. En pièces jointes, nous avons appliqué cet algorithme sur la matrice particulière \textbf{A}. \\ Pour compiler ce programme, il faut tapper sur un terminal \textit{gcc LU-seq.c -o LU-seq}. \\ Ce programme résoud aussi le système linéaire $Ax=b$ par la méthode de descente-remontée comme on l'a déjà montré dans la première section.\\ Les lignes de l'algorithme sont commentées sur le fichier en pièces jointes. \subsection{Programme Parallèle} \hypertarget{Programme Parallèle}{} Ici, nous présentons le programme de la \textbf{factorisation LU} parallel. En pièces jointes, nous avons appliqué cet algorithme sur la matrice particulière \textbf{A}. \\ Pour compiler ce programme, il faut tapper sur un terminal \textit{gcc -fopenmp LU-parallele-openmp.c}. \\ Ce programme résoud aussi le système linéaire $Ax=b$ par la méthode de descente-remontée comme on l'a déjà montré dans la première section. \\ Nous utilisons un thread par ligne. En ce qui concerne les matrices $L$ et $U$, on calcule en même temps les coefficients des lignes du dessous. \\ \section*{Conclusion} \hypertarget{Conclusion}{} Ce que l'on peut retenir, c'est la facilité de \textit{openmp}. En effet, son utilisation est relativement simple. Tous les calculs sont liés entre-eux. Chacune des condition \textit{while} est remplacée par \textit{openmp for}. Tout au long du projet, nous avons été dans une optique de découverte de calcul parallélisable. Cependant, une décomposition LU ne mérite pas forcément une parallélisation. \end{document} <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 10 : - La somme des premiers en dessous de 2 millions. ----------------------------------------------------------------- ----------------------------------------------------------------- """ # Return True if aNombre is prime def EstPremier(aNombre): if aNombre == 2: estPremier = True elif aNombre % 2 == 0: estPremier = False else: p = 3 estPremier = True miNombre = aNombre // 2 while (p < miNombre and estPremier): if aNombre % p == 0: estPremier = False else: p +=2 return estPremier # Return the next prime after aNombre def ProchainPremier(aNombre): suivPremier = aNombre +1 while(not EstPremier(suivPremier)): suivPremier += 1 return(suivPremier) # Return the sum of prime under aNombre def sommeNPremier(aNombre): sumPrem = 1 prem = 1 while prem < aNombre: prem = ProchainPremier(prem) sumPrem += prem print(prem, ", ",sumPrem) return sumPrem # Main nombre = 2000000 print (sommeNPremier(nombre)) <file_sep># Tortue-VS-Li-vre Un petit jeu de probabilité d'une course du lièvre et de la tortue <file_sep>package main import ( "fmt" "sort" "strconv" ) func main() { fmt.Println("Pour la semaine 3") var inScan string var nbScan int fmt.Println("Scan d'un entier :", nbScan) fmt.Scan(&inScan) var sli = make([]int, 0) for inScan != "x" { nbScan,_ = strconv.Atoi(inScan) fmt.Println("Scan d'un entier :", nbScan) sli = append(sli, nbScan) fmt.Println("Affiche slice d'entier :", sli) sort.Ints(sli) fmt.Println("Affiche slice ordonnée des entiers :", sli) fmt.Scan(&inScan) } } <file_sep>function [X_n]=F_alog_remez(Cprime,X_n) l=0 if X_n(1)<=Cprime & Cprime<X_n(2) if sign(fmoinsp(X_n(2))) == sign(fmoinsp(Cprime)) X_n(2)=Cprime disp('display',10) else [X_n]=F_permut(X_n,Cprime,1) disp('display',20) end l=1 end if l==0 if X_n(n)< Cprime & Cprime <=X_n(n+1) if sign(fmoinsp(X_n(n))) == sign(fmoinsp(Cprime)) X_n(n)=Cprime disp('display',30) else [X_n]=F_permut(X_n,Cprime,-1) disp('display',40) end l=1 end end if l==0 k=3 while (X_n(k)<Cprime) k=k+1 end if sign(fmoinsp(X_n(k)))== -sign(fmoinsp(Cprime)) X_n(k-1)=Cprime disp('display',50) l=1 else X_n(k)=Cprime disp('display',60) l=1 end end endfunction<file_sep>########################################################################### # # # Traffic routier # # # ########################################################################### ## ## Flux continu ## ############################ #On connait maintenant les les paramètres #On prends les deux voies et on cherche le nombre de voitures qui s'accumulent #le temps du feu #Nombre de voiture arrété au feu si aucune au départ pendant le temps length(flux_1[flux_1<30]) length(flux_2[flux_2<30]) ################## ## lambda_1 = 4 lambda_2 = 3 # v = 30 km / heure, on veut en mètre par min v = 0.5 #Calcul de L v/2 * (5 - 4/60 * 5* (lambda_1 + lambda_2)) L = 0.6 #d1 + d2 = 5minutes - 2L/v 5 - 2*L / v #d1 >= 4/60 * 4 *5 #d2 >= 4/60 * 3 * 5 2L/v<file_sep>package main import "fmt" func main() { fmt.Println("Début du mooc sur Go") var x float64 = 135.2 var y float64 = 1.352e2 fmt.Println("Résultat de x-y : ") fmt.Println(x-y) var i int for i=0 ; i<10 ; i++ { fmt.Println("Boucle avant break : i=5 : ",i) if i == 5 { fmt.Println("break : i=5 : ",i) break } fmt.Println("Boucle après break : i=5 : ", i) } var j int for j=0 ; j<10 ; j++ { fmt.Println("Boucle avant continue : j=5 : ",j) if j == 5 { fmt.Println("continue : j=5 : ",j) continue } fmt.Println("Boucle après continue : j=5 : ", j) } } <file_sep>#!/usr/bin/env python3 """ ----------------------------------------------------------------- Contributeur : - <NAME> ----------------------------------------------------------------- PROJECT EULER ----------------------------------------------------------------- Problème 3 : - Le plus grand facteur premier (de 600851475143). ----------------------------------------------------------------- ----------------------------------------------------------------- """ # Return True if aNombre is prime def EstPremier(aNombre): if aNombre == 2: estPremier = True elif aNombre % 2 == 0: estPremier = False else: p = 3 estPremier = True miNombre = aNombre // 2 while (p < miNombre and estPremier): if aNombre % p == 0: estPremier = False else: p +=2 return estPremier # Return the next prime after aNombre def ProchainPremier(aNombre): suivPremier = aNombre +1 while(not EstPremier(suivPremier)): suivPremier += 1 return(suivPremier) # Return the last prime factor def DernierPremier(aNombre): suiNombre = aNombre p = 2 while suiNombre > p: while suiNombre % p == 0: suiNombre = suiNombre / p p = ProchainPremier(p) return p # Main nombre = 600851475143 print(" Plus grand facteur premier de",nombre, " = ",DernierPremier(nombre)) <file_sep>\documentclass{report} \usepackage[latin1]{inputenc} \usepackage[francais]{babel} \usepackage[T1]{fontenc} \usepackage{fancyhdr} \pagestyle{fancy} \fancyfoot[LE,RO]{\textit{Étude d'un chantier routier}} \fancyfoot[RE,LO]{\textit{M2-SITN T.LAFOND}} \usepackage{graphicx} \usepackage{verbatim} \usepackage[top=1cm, bottom=2cm, left=2.5cm, right=2.5cm]{geometry} \newenvironment{definition}[1][Definition]{\begin{trivlist} \item[\hskip \labelsep {\bfseries #1}]}{\end{trivlist}} \begin{document} \nocite{*} \title{Étude d'un chantier routier} \author{<NAME>} \date{06/02/2012} \maketitle \begin{abstract} Dans ce rapport nous allons étudier la faisabilité d'un chantier routier. Cette étude se fera en trois parties avec en premier lieu une estimation du trafic actuel, en second lieu une recherche d'optimisation des feux de travaux et de la longueur du chantier et enfin dans un dernier temps une étude de la file d'attente. Pour cela, processus de Poissons, chaîne de Markov et autre "stochasticité" seront de la partie. \end{abstract} % Les commandes de sectionnement (\chapter, \section, \subsection, \etc.) % sont automatiquement numérotés, et permettent de produire facilement % une table des matières au moyen de : \tableofcontents \newpage \chapter{Introduction} \section{Licence} Cette étude a été proposée à l'Université des Sciences et Technologies de Lille - UFR de Mathématiques Pures et Appliquées en Agrégation - modélisation en 2005 - 2006 par <NAME>. Elle est disponible sous licence CC BY-NC-SA 2.0.. \section{Problématique} Une entreprise de travaux publics a pour charge de réparer une route. Cette dernière en double sens, possède une seule et unique voie de circulation sur chaque côté. L'entreprise souhaite réparer au plus vite le tronçon de cette route tout en minimisant la gêne occasionnée pour les automobilistes et les autres utilisateurs. La technique préconisée et qui sera utilisée revient à couper alternativement une partie de la voie pour y réaliser les travaux tout en permettant aux automobilistes de circuler sur l'autre voie par l'intermédiaire d'un feu alterné. Le but est de réussir à maximiser cette distance de travaux pour espérer réparer de plus grands tronçons possibles à chaque fois et donc passer le moins de temps possible sur l'ensemble chantier en limitant l'installation et la désinstallation de toute la logistique à chaque changement de tronçon. Dans cette optique on cherche à optimiser la durée des feux verts et des deux rouges de chaque côté pour minimiser le désagrément infligé aux conducteurs en essayant de réduire au minimum leur temps d'attente au feu rouge. \section{Modèle} On modélise la présence de véhicule, son passage en une borne repère par un processus de comptage et plus particulièrement un processus de Poisson. Les véhicules roulent à une vitesse constante du début à la fin du tronçon. En l'absence d'obstacle ou de feu rouge, leurs vitesses reste ainsi la même sur l'intégralité du trajet. Ni elles ne s'éloignent, ni elles ne s'approchent les unes des autres. Lorsque un véhicule est arrêté à un feu, il met un certain temps "a" pour démarrer, sa vitesse initiale étant sa vitesse de croisière. La moyenne des véhicules par minutes est spécifiques à chaque voie mais reste constant durant la journée. Si la modélisation d'un flot de véhicules dans de tel condition peut paraître absurde, il ne faut pas perdre de vue que cette étude est plus portée sur le comptage des voitures que sur la modélisation du flux de voitures. \newpage \chapter{Estimation du trafic} Dans un premier temps, l'entrepreneur a besoin de se faire une idée de la circulation sur les deux voies avant même de pouvoir espérer commencer les travaux. Il cherche alors à estimer l'intensité du trafic dans les deux sens. On souhaite compter au mieux les véhicules qui passent sur cette route tout en prenant en compte différents paramètres comme l'intervalle de temps entre deux véhicules consécutifs. On modélise l'arrivée d'une voiture sur le tronçon qu'on souhaite réparer par un processus de Poisson. On prend l'évènement : la voiture passe devant la borne du début du futur chantier comme une file d'attente avec résolution immédiate. Les deux voies possèdent chacune un paramètre $\lambda$ qui leur est propre. $\lambda$ caractérise la loi de Poisson modélisant l'arrivée des voitures. \section{Théorie} Beaucoup de notion de probabilité ont été abordé dans cette introduction. Pour espérer continuer sereinement, il est nécessaire de les définir. \begin{definition} Processus de comptage\newline Un processus de comptage noté N(t) vérifie trois propriétés : \begin{itemize}\itemsep4pt \item Pour t $\geq$ 0 le nombre N(t) est à valeur entières positives. \item La fonction t $\longrightarrow$ N(t) est croissante. \item Pour tout couple (a,b) (0 < a < b), la différence N(b) - N(a) représente le nombre de << tops >> se produisant dans l'intervalle de temps ]a, b]. Dans notre cas un top est le passage d'une voiture. \end{itemize} \end{definition} \begin{definition} Processus de Poisson\newline Un processus de comptage noté N(t) est un processus de Poisson de densité $\lambda$ si et seulement si il vérifie les trois propriétés suivantes : \begin{itemize}\itemsep4pt \item N(0) = 0 \item Le processus est à accroissement indépendant. Les nombres de << tops >> se produisant dans des intervalles de temps disjoints est sont indépendants. \item Le nombre de << tops >> se produisant dans un intervalle de temps de longueur t $\geq$ 0 suit la loi de Poisson de paramètre $\lambda t$, c'est-à-dire, pour tout s $\geq$ 0 et pour tout t $\geq$ 0, on a pour n $\geq$ 0: $$P[N(s+t) - N(s) = n] = e^{- \lambda t}\frac{\lambda t^{n}}{n!}$$ \end{itemize} \end{definition} \newpage \section{Pratique} \begin{center} Comment estimer au mieux l'intensité du trafic à partir de donnée expérimentales? \end{center} Par hypothèse, le flot de véhicules est modélisé par un processus de Poisson. On connait deux caractérisations d'un processus de Poisson de paramètre $\lambda$ : \newline \begin{itemize}\itemsep4pt \item Soit à partir des instants $(Ti) _{i \in N*}$ de sauts ici les arrivées de voitures, en disant que la suite des $\tau_{i} = T_{i} - T_{i-1}$ des intervalles entre deux sauts consécutifs est une suite de variables aléatoires indépendantes de même loi exponentielle de paramètre $\lambda s$. \item Soit à partir de sa fonction de comptage $N(t) = \sum 1_{0<T_{i}\leq t}$ ici le nombre de véhicules arrivés entre les instants 0 exclu et t inclus en disant que N(t) est à accroissements indépendants et que pour tout couple (t,s) de réels $N(t \geq 0, s>0 )$ l'accroissement N(t + s) - N(t) suit une loi de Poisson de paramètre $\lambda s$. \end{itemize} On peut recueillir deux sortes de statistique sur le terrain :\newline \begin{itemize}\itemsep4pt \item relever les intervalles de temps séparant les passages de deux véhicules consécutifs. Ces données nous permettent d'utiliser la première caractérisation. \item compter à intervalles réguliers (une minute par exemple) le nombre de véhicules qui passent dans l'intervalle. Ces données nous permettent d'utiliser la deuxième caractérisation. \end{itemize} Les deux démarches sont relativement différentes, dans la première on prend une mesure de temps : la différence de temps entre deux véhicules consécutifs alors que dans le second on réalise un comptage de voiture en fonction d'un laps de temps arbitraire. \newline \begin{itemize}\itemsep4pt \item On peut assez facilement créer un échantillon de temps $T_{i}$ à l'aide de la fonction R qui simule un échantillon de loi exponentielle. Cette échantillon simule le temps séparant l'arrivée de deux voitures consécutives. On a juste alors à récupérer la somme cumulative deux à deux pour fabriquer notre échantillon $\tau _{i}$. On peut également estimer le paramètre $\lambda$ en cherchant l'inverse de la moyenne de l'échantillon $T{i}$. \item Dans le deuxième cas, on simule un échantillon suivant une loi de Poisson $\lambda s $. En comptant le nombre de voiture dans un << petit >> intervalle de temps, on peut dès lors reconstituer l'échantillon initial en faisant néanmoins une approximation sur le comptage alors réaliser non pas par voiture mais par unité de temps. \end{itemize} On remarque assez simplement que la première méthode est bien plus commode. D'un point de vue humain, elle est moins assujetti aux erreurs et d'un point de vu pratique, elle nécessite moins de voiture et donc moins de temps pour être mise en place et espérer avoir un estimateur correct. Néanmoins d'un point de vu statistique, son biais est légèrement plus élevé. \ \newpage \section{Graphe} En utilisant les deux méthodes précédentes, on peut recueillir des échantillons significatifs modélisant notre problème. On peut alors modéliser les véhicules sur notre tronçon à différents instants successifs. Les deux graphiques du haut représente les temps d'inter-arrivées. Les quatre autres représentent le nombre de véhicules passant par la borne (le point de comptage) pendant un certain laps de temps. \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{1-1tempspassage.jpg} \caption{Flux de véhicule} \end{center} \end{figure} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{1-2trafic.jpg} \caption{Tronçon} \end{center} \end{figure} \newpage \chapter{Condition de non-engorgement} Une fois les paramètres $\lambda_{1}$ et $\lambda_{2}$ estimés et donc fixés pour le reste de notre problème, l'entreprise commence à réfléchir à l'impact d'un feu tricolore. En effet, pendant qu'une partie d'une voie est en travaux et donc interdit à la circulation, les véhicules sont obligés de ce partager alternativement une seule et même voie. Alors qu'elle souhaite optimiser la taille des travaux et donc la longueur de la portion bloqué, une contrainte de temps s'impose naturellement. Il s'agit alors de bien régler la temporisation des feux en fonction de la vitesse : v (constante dans notre modèle), la taille du tronçon coupé L, la fréquence des voitures, le temps nécessaire pour une voiture pour démarrer : a , la durée des feux rouge et vert pour qu'il n'y ait pas d'engorgement. \section{Théorie} Beaucoup de paramètre parsèment cette étude. \begin{itemize}\itemsep3pt \item a : Temps qu'a besoin un véhicule pour démarrer \item v : Vitesse constante de déplacement des véhicules \item L : Longueur du chantier \item $d_{1}$ : Durée du feu vert pour la voie 1 \item $d_{2}$ : Durée du feu vert pour la voie 2 \item K : Nombre de véhicules qu'on souhaite faire passer dans un sens à chaque cycle. \item $\lambda_{1}$ = Moyenne des véhicules sur la voie 1. \item $\lambda_{2}$ = Moyenne des véhicules sur la voie 2. \end{itemize} On cherche à démontrer une condition de non-engorgement : $$d_{1} \geq a \lambda_{1} ( d_{1} + d_{2} + 2L/v)$$ $$d_{2} \geq a \lambda_{2} ( d_{1} + d_{2} + 2L/v)$$ \newpage Pour comprendre cette condition, il faut partir avec une vision globale du problème en réalisant un cycle entier. \newline \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route-feu1.jpg} \caption{Feu vert voie 1} \end{center} \end{figure} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{route-feu2.jpg} \caption{Feu vert voie 2} \end{center} \end{figure} On cherche à caractériser le temps totale d'un cycle. La première chose que l'on note est que lorsque les deux feux sont rouges, il faut laisser un certain temps pour que les véhiculess engagés sur la voie puissent la traverser en entier. Le chantier étant de longueur L et la vitesse des véhicules étant v. On obtient un temps pour sortir de la voie de L/v et ce une fois de chaque côté. On obtient alors la durée totale du temps d'un cycle. $$\Delta t = d_{1} + d_{2} + 2L/v$$ Le nombre de voitures arrivant au feu que ce soit pour passer ou bien pour s'arrêter est connu en moyenne. En effet, on sait qu'il arrive $\lambda_{1}$ et $\lambda_{2}$ véhicules par unité de temps. Le nombre de véhicules par cycle s'accumulant au feu est donc donnée par le produit. $$\lambda_{1} ( d_{1} + d_{2} + 2L/v)$$ $$\lambda_{2} ( d_{1} + d_{2} + 2L/v)$$ Mais on sait que les véhicules ne peuvent passer que pendant que le feu est vert de leur côté et ce nombre est bridé par la vitesse de démarrage des voitures : a. Donc, si on veut que tous les véhicules présents puissent passer au vert, il faut remettre à zéro le compteur, soit le nombre de voitures présentes aux feux. $$d_{1}/a \geq \lambda_{1} ( d_{1} + d_{2} + 2L/v)$$ $$d_{2}/a \geq \lambda_{2} ( d_{1} + d_{2} + 2L/v)$$ On obtient bien les deux inégalités. $$d_{1} \geq a \lambda_{1} ( d_{1} + d_{2} + 2L/v)$$ $$d_{2} \geq a \lambda_{2} ( d_{1} + d_{2} + 2L/v)$$ \newpage \section{Pratique} \begin{center} Comment optimiser les différents paramètres donnés? \end{center} Dans cette partie, on estime connu les paramètres suivants. On les transpose tous à la même échelle. \begin{itemize}\itemsep3pt \item a = 4 secondes = 4/60 minutes: Temps qu'a besoin un véhicule pour démarrer \item v = 30 km / h = 0.5 m / min: Vitesse constante de déplacement des véhicules \item $\lambda_{1}$ = 4 : Moyenne des véhicules sur la voie 1. \item $\lambda_{2}$ = 3 : Moyenne des véhicules sur la voie 2. \end{itemize} On cherche à estimer une bonne longueur de L. $$\Delta t \leq 5$$ $$d_{1} + d_{2} + 2L/v \leq 5$$ $$a \lambda_{1} ( d_{1} + d_{2} + 2L/v) + a \lambda_{2} ( d_{1} + d_{2} + 2L/v) + 2L/v \leq 5$$ $$a ( \lambda_{1} + \lambda_{2} ) ( d_{1} + d_{2} + 2L/v) + 2L/v \leq 5$$ $$2L/v \leq 5 - a ( \lambda_{1} + \lambda_{2} ) ( d_{1} + d_{2} + 2L/v)$$ $$L \leq \frac{v}{2}(5 - a ( \lambda_{1} + \lambda_{2} ) ( d_{1} + d_{2} + 2L/v))$$ $$L \leq 667 m$$ Le but de l'entreprise étant de maximiser L sans pour autant perturber le trafic, on pourrait prendre L = 667 mètres, néanmoins pour une question de commodité, L = 600m dans le reste du projet. \newline On cherche maintenant à connaître $d_{1}$ et $d_{2}$. $$d_{1} + d_{2} + 2L/v = 5min$$ $$d_{1} \geq a \lambda_{1} ( d_{1} + d_{2} + 2L/v)$$ $$d_{2} \geq a \lambda_{2} ( d_{1} + d_{2} + 2L/v)$$ On passe au numérique : $$d_{1} \geq 4/60 * 4 * 5 = 1.3333$$ $$d_{2} \geq 4/60 * 3 * 5 = 1$$ $$d_{1} + d_{2} = 5 - 2*0.6/0.5 = 2.6$$ Une infinité de choix s'offre à nous pour paramétrer $d_{1}$ et $d_{2}$. Il est néanmoins commode de choisir des nombres avec des décimales simples comme par exemple : $d_{1}$ = 1.4 minute et $d_{2}$ = 1.2 minute où bien $d_{1}$ = 1.5 minute et $d_{2}$ = 1.1 minute. \newpage \chapter{Étude de la longueur de la file de véhicules} Pour ce chapitre, nous allons nous concentrer sur la longueur de la file de véhicules arrêtés à un feu. La file arrêtée de l'autre feu jouant un rôle symétrique mais avec seulement un paramètre différent peut être vu de la même manière. On note $X_{n}$ le nombre de véhicules en attente quand le feu passe au vert pour eux. On établit une relation entre $X_{n}$ et $X_{n+1}$ avec n un cycle comme suit : $$X_{n+1} = (X_{n} + Y_{n} - K)^{+} + Z_{n}$$ \begin{itemize}\itemsep4pt \item $(Y_{n})$ est une suite de variable aléatoire de même loi de Poisson de paramètre $\lambda_{1} d_{1}$. \item $(Z_{n})$ est une suite de variable aléatoire de même loi de Poisson de paramètre $\lambda_{1} (d_{2} + 2L/v)$. \item K le nombre maximum de voitures qui peuvent passer durant la durée du feu vert. \end{itemize} \section{Modèle} Ce modèle est assez intuitif. Pour la voie une, la durée du feu rouge est de $d_{2}$ + 2 L/v. Il arrive donc en moyenne $\lambda1$ ($d_{2}$ + 2 L/v) nouvelles voitures qui vont venir s'agglutiner dans la file d'attente. \newline Ensuite, il intervient le max entre 0 et $X_{n}$ + $Y_{n}$ - K. Cela signifie que soit toutes les voitures ont pu passer lors du feu vert précédent et donc $X_{n+1} = Z_{n}$ : Seuls les véhicules qui arriveront lors du feu rouge seront arrêtés. Soit $X_{n+1} = X_{n} + Y_{n} - K + Z_{n}$ et alors on sait que K véhicules sont passés au feu vert mais qu'il y avait déjà $X_{n}$ véhicules déjà présents lors du dernier cycle et qu'en plus $Y_{n}$ véhicules sont arrivés à se rajouter dans la file alors que le feu était vert. \newline On a là un modèle assez réaliste et crédible. On note bien la présence d'une arrivée continue de véhicules, de la notion de mémoire du cycle précédent et d'un dés-engorgement possible avec la soustraction de K. \newline $X_{n}$ est une chaîne de Markov avec une infinité dénombrable d'état. La chaîne est irréductible et les états sont tous récurrents positifs. Il existe donc une loi stationnaire. Pour autant son calcul explicite n'est pas envisageable. \section{Théorie} \begin{definition} Chaîne de Markov\newline Une chaîne de Markov est un processus sans mémoire, non héréditaire. Dans l'évolution au cours du temps, l'état du processus à l'instant (n+1) ne dépend que de celui à l'instant n précédent et non de ses états antérieurs. \end{definition} \begin{definition} Probabilité stationnaire\newline Supposons que la chaîne est irréductible, récurrent positif et possède un nombre d'état dénombrable (dans notre cas N). Alors il existe une et une seule loi stationnaire $\Pi$ $$\Pi_{i, j} = \frac{1}{M_{i, j}} = \frac{1}{E^{j}[T_{j}]}$$ \end{definition} \section{Pratique} \begin{center} Quelle sera la longueur de la file d'attente après un grand temps de travaux. \end{center} On se propose d'étudier un problème particulier et de modéliser la file d'attente au feu. Pour réaliser cette simulation et obtenir des résultats intéressants sans pour autant dépasser la capacité de notre machine, on va utiliser une méthode connue qui consiste à faire tourner plusieurs simulations plus petites. \newline On fait une hypothèse sur la composition de la file de véhicules : \begin{itemize}\itemsep4pt \item 60/100 de voitures d'une longueur de 5m \item 30/100 de bus d'une longueur de 10m \item 10/100 de camions d'une longueur de 20m \end{itemize} On réalise N = 5000 Simulations d'une longueur n = 500. On s'intéresse en premier lieu au nombre moyen de véhicules arrêtés et à la longueur moyenne de la file d'attente qu'on calcule avec l'aide des pourcentages précédemment cités. \begin{center} Nombre moyen de véhicules arrêtés = 17 véhicules\newline Taille moyenne de la file d'attente = 136.5 m \newline \end{center} Pour autant la moyenne n'étant pas toujours un très bon estimateur, voici une visualisation de ces valeurs par un box plot et par l'affichage en histogramme de ces fréquences classiques et empiriques .\begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{longueur-file.jpg} \caption{Boxplot} \end{center} \end{figure} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{freq.jpg} \caption{Histogrammes} \end{center} \end{figure} \begin{figure}[!htbp] \begin{center} \includegraphics[width=0.8\textwidth]{freq_empirique.jpg} \caption{Fréquences empiriques} \end{center} \end{figure} Dans ce cas pratique, on apprend que l'entrepreneur a signé un cahier des charges fixant à 5/100 la probabilité que la file d'attente dépasse les 235 mètres. Pour vérifier ce point là, on utilise les données expérimentales recueillies et on calcul le nombre de fois où la file d'attente dépasse cette valeur de 235 mètres, en la divisant par le nombre de simulations, on obtient la probabilité de dépasser les 235 mètres. \begin{center} Probabilité de dépasser 235 mètre de file d'attente = 0.432 \end{center} Nous sommes en dessous du seuil fixé et donc l'entrepreneur peut signer cette engagement. \newpage \chapter{Conclusion} Bien nous a pris de lancer cette simulation, le chantier routier semble réalisable. \newline Durant toute l'étude de notre chantier routier, nous avons fait bon nombre d'hypothèse. Souvent elle était présente à raison pour simplifier le calcul. Néanmoins, il est bon de savoir que ces dernières ne sont pas toujours réaliste : \begin{itemize}\itemsep4pt \item D'un point de physique tout d'abord, il est impossible de tenir un tel modèle que cela soit au niveau de la vitesse constante, du temps de démarrage... \item D'un point de vue humain, il est bien rare qu'une route garde un même encombrement tout au file de la journée. Il est bien plus courant que cet encombrement augmente dans les périodes dites de pointes 8h-9h et 16h-18h et baisse dans les périodes creuses 10h-11h et 14h-16h. Cela se reflète dans le paramètre des lois de poissons qui alors dépend du temps. \end{itemize} D'autre modèles existent mais font également d'autres hypothèses. On en trouve notamment un grand nombre d'entre eux au rayon des équations aux dérivées partielles en cherchant à prendre en compte la notion de dilatation et de compression du flot de voiture. S'il semble plus précis sur le papier, il est tout de même une question de pertinence qui ne doit pas être négligé quand le but de la simulation porte en premier lieu sur le comptage des véhicules plus que sur la dynamique de ceux-ci. \newpage \chapter{Annexe} \section{Estimation du trafic} \subsection{Estimation des processus de Poisson} \begin{verbatim} #Simulation des tau : le temps entre l'arrivée de deux voitures #n le nombre de voiture compté n_1 = 50 n_2 = 50 #lambda_theo_1 le paramètre lambda_theo_1 = 0.12 lambda_theo_2 = 0.13 #tau_1 est le fichier récupérer de l'intervalle de temps entre le passage de deux voitures tau_1 = rexp(n_1, rate = lambda_theo_1) tau_2 = rexp(n_1, rate = lambda_theo_1) #plot(tau_1,type="b") #plot(tau_1,type="s") #En second #En moyenne, il passe une voiture en mean(tau) en seconde #tau_1 #mean(tau_1) On peut ainsi récupérer lambda_exp_1 = 1/mean(tau_1) lambda_exp_2 = 1/mean(tau_2) # flux_1 = tau_1 for(i in 2:n_1) { flux_1[i]=flux_1[i-1]+flux_1[i] } flux_2 = tau_2 for(i in 2:n_2) { flux_2[i]=flux_2[i-1]+flux_2[i] } #Graph par(mfrow=c(2,2)) plot(tau_1,type="s") title("Intervalle d'arrivée entre deux voitures sur la voie 1") plot(flux_1,seq(1,n_1),type="s") title("Temps de passage au point de départ sur la voie 1") plot(tau_2,type="s") title("Intervalle d'arrivée entre deux voitures sur la voie 2") plot(flux_2,seq(1,n_2),type="s") title("Temps de passage au point de départ sur la voie 2") #deuxième méthode: #On compte le nombre de voiture dans un intervalle de 30s fluxx_1 = rpois(50, lambda=lambda_exp_1*30) for(i in 2:n_1) { fluxx_1[i]=fluxx_1[i-1]+fluxx_1[i] } fluxx_2 = rpois(50, lambda=lambda_exp_2*30) for(i in 2:n_1) { fluxx_2[i]=fluxx_2[i-1]+fluxx_2[i] } par(mfrow=c(1,2)) plot( seq(1,n_2*30,30), fluxx_2,type="s") plot( seq(1,n_2*30,30), fluxx_2,type="s") abs(mean(1/flux_1) - lambda_theo_1) abs(mean(1/fluxx_1) - lambda_theo_1) abs(mean(1/flux_2) - lambda_theo_2) abs(mean(1/fluxx_2) - lambda_theo_2) \end{verbatim} \newpage \subsection{Modélisation du tronçon} \begin{verbatim} rep_flux = matrix(1,nrow = 2, ncol= n_1 + n_2) rep_flux[2,] = c(rep(-1,n_1), rep(1,n_2)) rep_flux[1,]= c(-flux_1, flux_2) #rep_flux par(mfrow=c(2,2)) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = 0") abline(v=0, col = 2) abline(h=0, col = 4) rep_flux[1,] = c(-flux_1+60, flux_2-60) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = t + 60s") abline(v=0, col = 2) abline(h=0, col = 4) rep_flux[1,] = c(-flux_1+120, flux_2-120) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = t + 120s") abline(v=0, col = 2) abline(h=0, col = 4) rep_flux[1,] = c(-flux_1+180, flux_2-180) plot(rep_flux[1,], rep_flux[2,],type="p") title("au temps t = t + 180s") abline(v=0, col = 2) abline(h=0, col = 4) \end{verbatim} \newpage \subsection{Condition de non-engorgement} \begin{verbatim} lambda_1 = 4 lambda_2 = 3 # v = 30 km / heure ~ en m / min v = 0.5 #Calcul de L v/2 * (5 - 4/60 * 5* (lambda_1 + lambda_2)) L = 0.6 #d1 + d2 = 5minutes - 2L/v 5 - 2*L / v #d1 >= 4/60 * 4 *5 #d2 >= 4/60 * 3 * 5 \end{verbatim} \newpage \subsection{Étude de la longueur de la file d'attente} \begin{verbatim} ## Paramètres # nombre de simulations N=5000; #Nombre de cycles n=500;# a=4/60; lambda1= 4; lambda2= 3; L=.6; v=.5; d1=1.5; d2=1.1; #Nombre de voitures qui passe au max par feu vert K= floor(d1/a); mu1= lambda1 * d1; mu2= lambda1 * (d2+2*L/v); Y = matrix(0,N,n); Z = matrix(0,N,n); X = matrix(0,N,n); #Simulation des lois de Poissons for (i in 1:n) { Y[,i]=rpois(N,mu1); Z[,i]=rpois(N,mu2); } # Nombre de voiture : calcul de Xn i=1 while (i < n) { j = 1 while (j <= N) { X[j, i+1] = max(0 ,X[j, i]+Y[j, i] - K ) + Z[j, i]; j = j +1 } i = i +1 } # Longueur de file : calcul de XX i = 1 XX = matrix(0,N,1) while (i <= N) { XX[i] = mean(X[i, n]) *(0.6*5 + 0.3 *10 + 0.1*20) i = i + 1; } # Nombre de voitures moyen moy_long = mean(X[, n]) # Longeur de file moyenne moy_file = moy_long*(0.6*5 + 0.3 *10 + 0.1*20) \end{verbatim} \subsection{Graphiques et résultats} \begin{verbatim} # Affichage des boxplots par(mfrow=c(1,2)) boxplot(X[,n]) title("Boxplot du nombre voitures au bout de 500 cycles") boxplot(XX) title("Boxplot de la longueur de la file au bout de 500 cycles") # Affichage des histogrammes par(mfrow=c(1,2)) hist(X, freq=TRUE) hist(XX) # file < 235 m pval = length(XX[XX>235]) / N # frequences empiriques femp = table(X)/(n*N) hist(femp) title("Fréquences empiriques") \end{verbatim} \end{document}<file_sep>Bonjour à toutes et tous, Je veux bien donner quelques éléments mais j'ai besoin de compléments et précision voire rectifications des collègues qui ont assisté (une bonne vingtaine) . Ma numérotation a pour seul but de me laisser corriger par les collègues en citant le point "n" n'est pas exact... * La réforme du bac ne permet plus de travailler avec la notion de groupe-classe qui change en fonction de chaque spécialité (souvent mélange d'élèves de différentes classes au sein d'une même spécialité) parcoursup ne peut pas faire le distingo entre l'un et l'autre. Que représente alors le classement d'un groupe de 6 élèves d'une même classe au sein d'une spécialité? * Les résultats de l'épreuve de spécialités seront pris en compte de façon importante car élément de comparaison entre tous les candidats. * La différence entre les lycées se fait uniquement sur le ratio de mentions au bac des années antérieures et actuellement des résultats pré-covid. * La différence de niveau entre classes de terminales que chaque lycée indique (les trois niveaux TB B et passable) n'est pas pris en compte car non quantitatif : on peut en déduire qu'un bon élève dans une classe de niveau moyen a plus de chance d'être sélectionné que s'il était dans une bonne classe. * Le fait de prendre en compte la moyenne de la spécialité, la meilleure moyenne (et désormais pas le rang dans le groupe cf point1) permet d'en déduire la position de l'élève. une moyenne de classe homogène haute ne permet donc pas de discriminer les élèves entre eux. * Il n'y a désormais qu'un seul classement pour toutes les INSA. les 5000 meilleurs dossiers regroupe des élèves qui sont tous 2 ou 3 ème dans chaque matière scientifique. Avant la crise sanitaire les 5000 dossiers provoquaient un entretien systématique qui rebrassait le classement parmi ces 5000(l'objet de l'entretien n'étant pas d'évaluer le niveau scientifique du candidat) . Depuis "seulement" 3000 entretiens ont eu lieu mais qui peuvent modifier le classement même avec des candidats n'ayant pas eu d'entretien. * Les maths expertes bien que recommandées pour la formation ne sont pas prises en compte car certains lycées ne peuvent pas l'offrir à leurs élèves. Sont pris en compte : 1. les résultats des matières scientifiques (les 5 : M-P-SVT-SI-NSI) et des élèves faisant par exemple P-SI et maths complémentaires sont aussi étudiés, * * je pense avoir compris que sans spé maths ni maths complémentaire le dossier n'est pas étudié. 2. les notes de contrôle continu LV de 1ere et Term 3. les notes de contrôle continu Français. Attention les notes de bac de l'EAF ne sont pas prises en compte (interdiction formelle). Ne sont pas pris en compte : 1. les notes de philo, d'HG * La lettre de motivation (22 000 lettres) n'est pas étudiée de façon générale. * la fiche avenir n'est pas un élément déterminant car l'avis n'est pas quantitatif et les avis "réservé" déclenche une étude à part et non pas un rejet du dossier pour comprendre la raison de cet avis réservé. * Une difficulté pour le recrutement est que chaque école doit déterminer un nombre de propositions pour lequel l'école s'engage à prendre les élèves (tant pis s'il y a plus de candidats que de places) mais inversement doit intégrer le nombre de dossiers qu'il veut étudier. D'où le double classement dans parcoursup du rang d'appel du dossier et du rang de la liste d'attente. J'ai conscience d'être incomplet, j'espère ne pas avoir fait d'erreur. à lire les collègues également auditeurs.<file_sep># Importation des modules import sys sys.path.insert(0,'src') import rpn_list4_calc as calc # Initialisation print("----- init et affichage -----") pessai = calc.list4() print(pessai.list4) pessai.affiche() # Empiler print("----- empiler -----") pessai.affiche() pessai.empile(12) pessai.affiche() pessai.empile(13) pessai.affiche() pessai.empile(14) pessai.affiche() pessai.empile(15) pessai.affiche() pessai.empile(17) pessai.affiche() #depiler print("----- depiler -----") pessai.affiche() pessai.depile() pessai.affiche() pessai.depile() pessai.affiche() pessai.depile() pessai.affiche() <file_sep>\documentclass[11pt]{article} \usepackage{geometry} % Pour passer au format A4 \geometry{hmargin=1cm, vmargin=1cm} % % Page et encodage \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs \usepackage[english,francais]{babel} % Français et anglais \usepackage[utf8]{inputenc} \usepackage{lmodern} \setlength\parindent{0pt} % Graphiques \usepackage{graphicx, float} \usepackage{tikz,tkz-tab} % Maths et divers \usepackage{amsmath,amsfonts,amssymb,amsthm,verbatim} \usepackage{multicol,enumitem,url,eurosym,gensymb} % Sections \usepackage{sectsty} % Allows customizing section commands \allsectionsfont{\centering \normalfont\scshape} % Tête et pied de page \usepackage{fancyhdr} \pagestyle{fancyplain} \fancyhead{} % No page header \fancyfoot{} \renewcommand{\headrulewidth}{0pt} % Remove header underlines \renewcommand{\footrulewidth}{0pt} % Remove footer underlines \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height %---------------------------------------------------------------------------------------- % Début du document %---------------------------------------------------------------------------------------- \begin{document} %---------------------------------------------------------------------------------------- % RE-DEFINITION %---------------------------------------------------------------------------------------- % MATHS %----------- \newtheorem{Definition}{Définition} \newtheorem{Theorem}{Théorème} \newtheorem{Proposition}{Propriété} % MATHS %----------- \renewcommand{\labelitemi}{$\bullet$} \renewcommand{\labelitemii}{$\circ$} %---------------------------------------------------------------------------------------- % Titre %---------------------------------------------------------------------------------------- \setlength{\columnseprule}{1pt} \section{Statistique} Dans le doute, je pars du début. \subsection{Exercice 6} \begin{enumerate} \item[1.] On étudie une population de 50 souris. (Je pense que le nombre est important. On étudie pas seulement la / des souris.) La taille de l'échantillon est 35. La variable statistique étudié est le nombre de souris noires parmi 50 desecendants. \item[2a.] \begin{center} \begin{tabular}{|c||c|c|c|c|c|c|c|c|c|c|c|c|c||c|} \hline $x_i$ & 18 & 19 & 20 & 21 & 22 & 23 & 24 & 25 & 26 & 27 & 28 & 29 & 32 & Total  \\ \hline $n_i$ & 1 & 1 & 1 & 2 & 4 & 4 & 5 & 9 & 2 & 2 & 1 & 2 & 1 & 35 \\ \hline $n_c$ & 1 & 2 & 3 & 5 & 9 & 13 & 18 & 27 & 29 & 31 & 32 & 34 & 35 & 35 \\ \hline \end{tabular} \end{center} \item[2b.] Le mode de la série est 25. \\ $\max - \min = 32 - 18 = 14$.\\ L'étendue de la série est 14. \item[2c.] La médiane sépare la série ordonnée en 2 parties de même effectifs. L'effectif total de la série est 35. La médiane est done la 18ième valeur car $35 = 17 + 1 + 17$.\\ Dans le tableau la 18ième valeur est 24 descendants de couleur noire.\\ Les quartiles séparent la série ordonnée à au moins $\frac{1}{4}$ de la série est plus petite puis à $\frac{3}{4}$. Q1 : $35 \times \dfrac{1}{4} = 8.75$ (de tête , ce calcul est loin d'être drôle par contre, c'est assez simple de voir que c'est plus petit que 9 car $4\times9 = 36$.) \\ On prend la 9ième valeur : 22.\\ Q1 est 22 descendants de couleur noire.\\ Q3 : $35 \times \dfrac{3}{4} = 26.25$ (de tête , ce calcul est loin d'être drôle par contre, Mais on peut savoir que 3 c'est pas très loin (toujours en plus petit) que 3 fois le précédent)\\ On prend la 27ième valeur : 25.\\ Q3 est 25 descendants de couleur noire.\\ \item[3a.] (Je suis assez sceptique sur ce genre de calcul à faire sans calculatrice...) \begin{center} \begin{tabular}{|c||c|c|c|c|c|c|c||c|} \hline $x_i$ & [18, 20[ & [20, 22[ & [22, 24[ & [24, 26[ & [26, 28[& [28, 30[& [30, 32[ & Total \\ \hline $n_i$ & 2 & 3 & 8 & 14 & 4 & 3 & 1 & 35 \\ \hline $n_c$ & 2 & 5 & 13 & 27 & 31 & 34 & 35 & 35 \\ \hline $c_i$ & 19 & 21 & 23 & 25 & 27 & 29 & 31 & \\ \hline $n_i c_i$ & 38 & 63 & 184 & 350 & 108 & 87 & 31 & 861 \\ \hline $n_i c_i^2$ & 722& 1323 & 4232 & 8750 & 2916 & 2523 & 961 & 21429 \\ \hline \end{tabular} \end{center} \item[3b.] Je fais les graphiques en scan, ça ira plus vite pour moi. Attention avec les histogrammes ; il y a un notion de proportionnalité d'aire du rectangle... En gros, il faut faire gaffe quand les classes n'ont pas la même largeur... Sinon, on s'en fout plutôt. Pour les gens tatillons, il faut que l'aire du rectangle soit égale à ton $n_i$... En vrai, on n'en fait rarement et on préfère les diagrammes en batons (même pour des classes...) La classe modale est $[24, 26[$. \item[3c.] Moyenne \begin{eqnarray*} m &=& \sum_i \dfrac{n_i c_i}{total} \text{ // Pas certain qu'ils attendent cette notation.} \\ m &=& \dfrac{n_1 c_1 + ... + n_7 c_7 }{total} \\ m &=& \dfrac{38 + ... + 31}{35} \\ m &=& \dfrac{861}{35} \\ m &=& 24.6 \end{eqnarray*} Avec des classes de largeurs deux, en moyenne il y a 24.6 descendants noirs. ecart-type \begin{eqnarray*} s &=& \sqrt { \frac {1}{total} \sum _i (c_i - m)^2} \\ s &=& \sqrt { \frac {1}{total} ( \sum _i (n_i c_i^2)) - m^2} \\ s & \approx & \sqrt { \frac {1}{35} \times (722 + ... + 961) - 24.6^2 } \\ s & \approx & \sqrt { \frac {1}{35} \times (21427) - 24.6^2 } \\ s & \approx & \sqrt { 612.2 - 24.6^2 } \\ s & \approx & \sqrt {7.04} \\ s & \approx & 2.65 \\ \end{eqnarray*} L'écart-type est de 2.65 %data = c(19, 19, 21, 21, 21, rep(23,8), rep(25,14), 27,27,27,27,29,29,29,31) \end{enumerate} \end{document}
04236ab1161ec860ab3b1d0c3225fcbdc54923a3
[ "Makefile", "C", "Markdown", "R", "Scilab", "TeX", "Python", "C++", "Go" ]
95
Makefile
homeostasie/petits-pedestres
557c810e26412bc34ebe063dcd904affe5a27855
957695cdb8a7823ed2e3fe79f7b441410928cba9
refs/heads/master
<file_sep>package top.spring.ioc.test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import top.spring.ioc.bean.Zoo; import top.spring.ioc.bean.Master; public class Demo { public static void main(String[] args) { visitHouse(); visitZoo(); } public static void visitHouse(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-ioc.xml"); Master master = context.getBean("master",Master.class); master.play(); } public static void visitZoo(){ ApplicationContext context = new AnnotationConfigApplicationContext(Zoo.class); Master master = context.getBean("master",Master.class); master.play(); } }<file_sep>package anson.zhong; public class LazyManNotThreadSafeBetter { private static LazyManNotThreadSafeBetter singleton; private LazyManNotThreadSafeBetter(){} public static LazyManNotThreadSafeBetter getSingleton(){ if (singleton == null){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (LazyManNotThreadSafeBetter.class){ singleton = new LazyManNotThreadSafeBetter(); } } return singleton; } } <file_sep>package top.spring.ioc.bean; public class Tiger implements Annimal { public void saySomething() { System.out.println("我是一只老虎:哇哇哇"); } } <file_sep>package anson.zhong; public enum Singleton { INSTANCE; public Void print(){ return null; } } <file_sep>package top.anson.zhong.xml.dao; import top.anson.zhong.xml.model.Area; import java.util.List; public interface AreaMapper { List<Area> getAllArea(); } <file_sep>package top.spring.ioc.bean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Zoo { @Bean public Master master(){ return new Master(new Annimal[]{new Tiger()}); } } <file_sep>package top.spring.ioc.bean; public class Master { private Annimal[] pets; public Master(Annimal[] pets) { this.pets = pets; } public void play(){ System.out.println("我有"+ this.pets.length +"个宠物"); for (Annimal pet:this.pets){ pet.saySomething(); } } } <file_sep>package anson.zhong; public class HungryManNoStatic { private static HungryManNoStatic singleton = new HungryManNoStatic(); private HungryManNoStatic(){} public static HungryManNoStatic getSingleton(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return singleton; } } <file_sep>package anson.zhong; public class LazyManThreadSafe { private static LazyManThreadSafe singleton; private LazyManThreadSafe(){} public static synchronized LazyManThreadSafe getSingleton(){ if (singleton == null){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } singleton = new LazyManThreadSafe(); } return singleton; } } <file_sep>package top.spring.ioc.bean; public interface Annimal { public void saySomething(); } <file_sep>package anson.zhong; public class HungryManStatic { private static HungryManStatic singleton ; static { singleton = new HungryManStatic(); } private HungryManStatic(){} public static HungryManStatic getSingleton(){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return singleton; } } <file_sep>package anson.zhong; public class LazyManNotThreadSafe { private static LazyManNotThreadSafe singleton; private LazyManNotThreadSafe(){} public static LazyManNotThreadSafe getSingleton(){ if (singleton == null){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } singleton = new LazyManNotThreadSafe(); } return singleton; } }
c236abd126b2e9757431d88eedd2110b176265bc
[ "Java" ]
12
Java
AnsonZhong/my-codes
676701e83bf8a3e135d0ac6ee145acb9b18f3545
917fc086e883398d3cd0216cd84f7d35a87093d9
refs/heads/master
<repo_name>Zombie8/hackerrank-30daysofcode<file_sep>/README.md # hackerrank-30daysofcode A repository that keeps track of my work on the hackerrank.com 30 days of code challenges
55055865cb8edd14ad8f60bdc1d8a8257b1f228e
[ "Markdown" ]
1
Markdown
Zombie8/hackerrank-30daysofcode
e47b7a38bd660c396fad0c94c506afbfdc2c3234
1e94be214aec80a604c392c0d9f1432244e7d34c
refs/heads/master
<file_sep># TaskanaTestDataGenerator Generator for test data structure. Can for example be used to create test data for performance tests.
6d122d20d9d69724fe55ce6c706a041ea23e2b89
[ "Markdown" ]
1
Markdown
BerndBreier/TaskanaTestDataGenerator
20b8185c020b4e3fbfb54083d215e5fc916e4e4d
9e7fddea3f9d1a9deef19ce5ba494330a70daeec
refs/heads/master
<file_sep>package br.com.company.explorer.domain; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * Created by <NAME> on 12/22/15. */ @Entity public class Land implements Serializable { private static final long serialVersionUID = 1L; public static final Integer ZERO = 0; @Id @GeneratedValue private Long id; @Column(nullable = false) private Integer topLimit; @Column(nullable = false) private Integer rightLimit; @OneToMany(mappedBy = "land", cascade={CascadeType.ALL}, orphanRemoval=true) private Set<Probe> probes = new HashSet<>(); public Land() { } public Land(Integer topLimit, Integer rightLimit) { this.topLimit = topLimit; this.rightLimit = rightLimit; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getTopLimit() { return topLimit; } public void setTopLimit(Integer topLimit) { this.topLimit = topLimit; } public Integer getRightLimit() { return rightLimit; } public void setRightLimit(Integer rightLimit) { this.rightLimit = rightLimit; } public Set<Probe> getProbes() { return probes; } public void setProbes(Set<Probe> probes) { this.probes = probes; } public Probe getProbeById(Long probeId) { for (Probe probe : probes) { if (probe.getId() == probeId) { return probe; } } return null; } } <file_sep>package br.com.company.explorer.service; import br.com.company.explorer.domain.Probe; import br.com.company.explorer.exception.InvalidParametersException; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; /** * Created by <NAME> on 12/17/15. */ @Service public class NavigationService { public static final List<String> ACCEPTED_COMMANDS = Arrays.asList("R", "L", "M"); public String move(Probe probe, List<String> commands) { for(String command : commands) { if (!ACCEPTED_COMMANDS.contains(command)) { throw new InvalidParametersException("Parameter '" + commands + "' is not allowed."); } switch (command) { case "R": probe.turnRight(); break; case "L": probe.turnLeft(); break; case "M": probe.goAhead(); } } return probe.toString(); } } <file_sep>package br.com.company.explorer.domain; /** * Created by <NAME> on 12/17/15. */ public enum CardinalDirection { NORTH("N"), EAST("E"), SOUTH("S"), WEST("W"); private String id; private CardinalDirection(String id) { this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String toString() { return this.id; } public static CardinalDirection getById(String id) { for(CardinalDirection e : values()) { if(e.getId().equals(id)) { return e; } } return null; } } <file_sep>package br.com.company.explorer.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * Created by <NAME> on 12/28/15. */ @ResponseStatus(HttpStatus.NOT_FOUND) public class ProbeNotFoundException extends RuntimeException { public ProbeNotFoundException(Long id) { super("could not find probe '" + id + "'."); } } <file_sep># Project to explore Mars<file_sep>package br.com.company.explorer.web; import br.com.company.explorer.domain.Land; import br.com.company.explorer.domain.LandRepository; import br.com.company.explorer.domain.Probe; import br.com.company.explorer.domain.ProbeRepository; import br.com.company.explorer.exception.LandNotFoundException; import br.com.company.explorer.exception.ProbeNotFoundException; import br.com.company.explorer.service.NavigationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.Serializable; import java.util.List; import java.util.Set; import static org.springframework.web.bind.annotation.RequestMethod.*; /** * Created by <NAME> on 12/18/15. */ @RestController @RequestMapping(value = "lands/{landId}/probes", produces="application/json;charset=UTF-8") public class ProbeController { @Autowired NavigationService navigationService; @Autowired ProbeRepository probeRepository; @Autowired LandRepository landRepository; @RequestMapping(method=GET) public Set<Probe> index(@PathVariable Long landId) { Land land = landRepository.findOne(landId); if (land == null) { throw new LandNotFoundException(landId); } return landRepository.findOne(landId).getProbes(); } @RequestMapping(method=POST, consumes="application/json;charset=UTF-8") public ResponseEntity<?> save(@PathVariable Long landId, @RequestBody Probe input) { Land land = landRepository.findOne(landId); input.setLand(land); Probe probe = probeRepository.save(input); return new ResponseEntity(probe, HttpStatus.CREATED); } @RequestMapping(path = "/{id}", method=GET) public Probe show(@PathVariable Long landId, @PathVariable Long id) { Land land = landRepository.findOne(landId); if (land == null) { throw new LandNotFoundException(landId); } Probe probe = land.getProbeById(id); if (probe == null) { throw new ProbeNotFoundException(id); } return land.getProbeById(id); } @RequestMapping(path = "/{id}", method=PUT, consumes="application/json;charset=UTF-8") public ResponseEntity<?> update(@PathVariable Long landId, @PathVariable Long id, @RequestBody Probe update) { Land land = landRepository.findOne(landId); if (land == null) { throw new LandNotFoundException(landId); } Probe probe = land.getProbeById(id); if (probe == null) { throw new ProbeNotFoundException(id); } probe.setLatitude(update.getLatitude()); probe.setLongitude(update.getLongitude()); probe.setDirection(update.getDirection()); probeRepository.save(probe); return new ResponseEntity(probe, HttpStatus.OK); } @RequestMapping(path = "/{id}", method=DELETE) public ResponseEntity<?> delete(@PathVariable Long landId, @PathVariable Long id) { Land land = landRepository.findOne(landId); if (land == null) { throw new LandNotFoundException(landId); } Probe probe = land.getProbeById(id); if (probe == null) { throw new ProbeNotFoundException(id); } probeRepository.delete(probe.getId()); return new ResponseEntity<Void>(HttpStatus.NO_CONTENT); } @RequestMapping(path = "/{id}/move", method=POST, consumes="application/json;charset=UTF-8") public ResponseEntity<?> move(@PathVariable Long landId, @PathVariable Long id, @RequestBody RequestWrapper wrapper) { Land land = landRepository.findOne(landId); if (land == null) { throw new LandNotFoundException(landId); } Probe probe = land.getProbeById(id); if (probe == null) { throw new ProbeNotFoundException(id); } navigationService.move(probe, wrapper.getCommands()); probeRepository.save(probe); return new ResponseEntity(probe, HttpStatus.OK); } } class RequestWrapper implements Serializable { private List<String> commands; public RequestWrapper() { super(); } public RequestWrapper(List<String> commands) { this.commands = commands; } public List<String> getCommands() { return commands; } public void setCommands(List<String> commands) { this.commands = commands; } }
2f9812b15623df567549191a257051c8f479ea4a
[ "Java", "Markdown" ]
6
Java
fabio-siqueira/explorer
74e6e85c371da6cee91c25afa1d7fa640a14a4e2
41357eb1c800a3c007859b77e055831ba5216308
refs/heads/master
<file_sep>Slider ====== Like the world needs another slider ----------------------------------- This is a slider being built for [Sugarloaf Mountainside](http://www.sugarloafmountainside.com). I decided to build it as a plugin mostly for practice building plugins. There are probably a dozen better sliders out there. And by *better* I mean more feature rich, more customizable, more built-in easings. This is built to be lightweight. To do nothing more than what I need it to do. Check it out, maybe it does what you need it to do, too. <file_sep>/*! * * Avalanche * Like the world needs another slider * Author: <NAME> * Requires: jQuery 1.6+ * * Copyright (c) 2012, <NAME> (derek[dot]wheelden[at]gmail[dot]com) * */ ;(function ( $, window, document, undefined ) { $.fn.avalanche = function( options ) { var settings = { $element : this, slideDuration : 3000, animationDuration : 1000, stopOnClick : false }; options && $.extend(settings, options); var properties = { sliderWidth : settings.$element.width(), sliderHeight : settings.$element.height(), slideCount : $(settings.$element).find(".slide").length, position : 0, makeSlide : null }; var methods = { positionSlides : function () { $(settings.$element).find(".slide").each(function(index) { $(this).css({ position : 'absolute', left : properties.sliderWidth * index }); }); }, buildUI : function () { $('<div/>', { 'class' : 'bulletContainer' }).appendTo('.slider'); for (var i = 0; i < properties.slideCount; i++) { var slideOffset = i * properties.sliderWidth * -1, firstBullet = (!i) ? ' active' : ''; $('<span/>', { 'class' : 'bullet' + firstBullet, 'data-offset' : slideOffset, 'html' : '&bull;', click : function() { methods.manualSlide(this); } }).appendTo('.bulletContainer'); } }, createInterval : function() { clearInterval(properties.makeSlide); properties.makeSlide = setInterval(function() { methods.autoSlide(); }, settings.slideDuration); }, manualSlide : function (that) { var offset = $(that).attr('data-offset'); $('.active').removeClass('active'); $(that).addClass('active'); $('.slideContainer').animate({ left : offset }, settings.animationDuration); if (settings.stopOnClick) { clearInterval(properties.makeSlide); } else { methods.createInterval(); } }, autoSlide : function () { var currentPosition = parseInt($('.slideContainer').css("left")) || 0, offset = properties.sliderWidth, maxOffset = properties.sliderWidth * (properties.slideCount - 1) * -1; if (currentPosition !== maxOffset) { $('.slideContainer').animate({ left : currentPosition - offset }, settings.animationDuration); $('.bulletContainer .active') .removeClass('active') .next() .addClass('active'); } else { $('.slideContainer').animate({ left : 0 }, settings.animationDuration); $('.bulletContainer > span') .removeClass('active') .first() .addClass('active'); } } }; return this.each(function() { if (properties.slideCount > 1) { methods.positionSlides(); methods.createInterval(); } methods.buildUI(); }); }; })( jQuery, window, document );
739d9aeae51b72127e7535f560f3fd044a5a14ba
[ "Markdown", "JavaScript" ]
2
Markdown
derekwheee/Slider
af4ef44e3cf860678dc250cd082f7d0e51fda867
73f094e5b5f9294a3bdfd93a53d16a8c34bd6f2e
refs/heads/master
<repo_name>keyurpatel7758/angular5sqlcrud<file_sep>/AngularDemo_WebAPI/AngularDemo_WebAPI/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml @using AngularDemo_WebAPI.Areas.HelpPage.ModelDescriptions @model SimpleTypeModelDescription @Model.Documentation<file_sep>/README.md # angular5sqlcrud angular 5 integration with sql
be59893753f728874a9133f5ce48d8a0d357f371
[ "HTML+Razor", "Markdown" ]
2
HTML+Razor
keyurpatel7758/angular5sqlcrud
924d324e68c34e2674fbe09dda32c7b05ee8db31
d4d5106f583c48e5e4fa66a247495810fe07a66c
refs/heads/master
<repo_name>huhukaka/KKK<file_sep>/README.md # KKK ERER
3cb685ada5fffa393bccd2427b700cd93a80fc82
[ "Markdown" ]
1
Markdown
huhukaka/KKK
5f4ff2e921f085c6c265147859f87187c69f702a
49a2f2e6121e0d3f57f98c1ebb910cc3ba65fe3b
refs/heads/master
<file_sep>namespace 'HlslJs.CodeModel.Declarations', (exports) -> exports.VariableTypeModifier = none: 0 const: 1 rowMajor: 2 columnMajor: 3<file_sep>#= require ./parse_node namespace 'HlslJs.CodeModel', (exports) -> class exports.CompilationUnitNode extends exports.ParseNode constructor: (@declarations) -><file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> exports.ColorWriteMaskFlags = red: 1 green: 2 blue: 4 alpha: 8 all: 1 | 2 | 4 | 8<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> class exports.DepthStencilOperationDescription failOperation: null depthFailOperation: null passOperation: null comparison: null<file_sep>describe 'HlslJs.Parser.Lexer', -> TokenType = HlslJs.CodeModel.Tokens.TokenType testTokenType = (value, expectedTokenType) -> lexer = new HlslJs.Parser.Lexer(null, value) token = lexer.nextToken() expect(token.type).toEqual(expectedTokenType) it 'lexes keywords', -> testTokenType("bool", TokenType.bool) testTokenType("float", TokenType.float) testTokenType("float2", TokenType.float2) testTokenType("float3", TokenType.float3) testTokenType("float4", TokenType.float4) testTokenType("int", TokenType.int) testTokenType("int2", TokenType.int2) testTokenType("int3", TokenType.int3) testTokenType("int4", TokenType.int4) testTokenType("matrix", TokenType.matrix) testTokenType("float1x1", TokenType.float1x1) testTokenType("float1x2", TokenType.float1x2) testTokenType("float1x3", TokenType.float1x3) testTokenType("float1x4", TokenType.float1x4) testTokenType("float2x1", TokenType.float2x1) testTokenType("float2x2", TokenType.float2x2) testTokenType("float2x3", TokenType.float2x3) testTokenType("float2x4", TokenType.float2x4) testTokenType("float3x1", TokenType.float3x1) testTokenType("float3x2", TokenType.float3x2) testTokenType("float3x3", TokenType.float3x3) testTokenType("float3x4", TokenType.float3x4) testTokenType("float4x1", TokenType.float4x1) testTokenType("float4x2", TokenType.float4x2) testTokenType("float4x3", TokenType.float4x3) testTokenType("float4x4", TokenType.float4x4) testTokenType("int1x1", TokenType.int1x1) testTokenType("int1x2", TokenType.int1x2) testTokenType("int1x3", TokenType.int1x3) testTokenType("int1x4", TokenType.int1x4) testTokenType("int2x1", TokenType.int2x1) testTokenType("int2x2", TokenType.int2x2) testTokenType("int2x3", TokenType.int2x3) testTokenType("int2x4", TokenType.int2x4) testTokenType("int3x1", TokenType.int3x1) testTokenType("int3x2", TokenType.int3x2) testTokenType("int3x3", TokenType.int3x3) testTokenType("int3x4", TokenType.int3x4) testTokenType("int4x1", TokenType.int4x1) testTokenType("int4x2", TokenType.int4x2) testTokenType("int4x3", TokenType.int4x3) testTokenType("int4x4", TokenType.int4x4) testTokenType("Texture1D", TokenType.texture1D) testTokenType("Texture2D", TokenType.texture2D) testTokenType("Texture3D", TokenType.texture3D) testTokenType("TextureCube", TokenType.textureCube) testTokenType("SamplerState", TokenType.samplerState) it 'lexes punctuation', -> testTokenType("[", TokenType.openSquare) testTokenType("]", TokenType.closeSquare) testTokenType("{", TokenType.openCurly) testTokenType("}", TokenType.closeCurly) testTokenType("=", TokenType.singleEquals) testTokenType("==", TokenType.doubleEquals) testTokenType("+", TokenType.plus) testTokenType("-", TokenType.minus) testTokenType("*", TokenType.asterisk) testTokenType("/", TokenType.forwardSlash) testTokenType(":", TokenType.colon) testTokenType(",", TokenType.comma) it 'lexes strings', -> testTokenType('"this is a string"', TokenType.literal) it 'lexes identifiers', -> testTokenType("identifier", TokenType.identifier) it 'lexes HLSL code', -> hlslCode = """ float4x4 World; float4x4 View; float4x4 Projection; float4 AmbientColor = float4(1, 1, 1, 1); float AmbientIntensity = 0.1; struct VertexShaderInput { float4 Position : POSITION0; }; struct VertexShaderOutput { float4 Position : POSITION0; }; VertexShaderOutput VertexShaderFunction(VertexShaderInput input) { VertexShaderOutput output; float4 worldPosition = mul(input.Position, World); float4 viewPosition = mul(worldPosition, View); output.Position = mul(viewPosition, Projection); return output; } float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 { return AmbientColor * AmbientIntensity; } """ lexer = new HlslJs.Parser.Lexer(null, hlslCode) tokens = lexer.getTokens() expect(tokens.length).toEqual(111) expected = [ TokenType.float4x4, TokenType.identifier, TokenType.semicolon, TokenType.float4x4, TokenType.identifier, TokenType.semicolon, TokenType.float4x4, TokenType.identifier, TokenType.semicolon, TokenType.float4, TokenType.identifier, TokenType.singleEquals, TokenType.float4, TokenType.openParen, TokenType.literal, TokenType.comma, TokenType.literal, TokenType.comma, TokenType.literal, TokenType.comma, TokenType.literal, TokenType.closeParen, TokenType.semicolon ] for i in [0...tokens.length] if i < expected.length expect(tokens[i].type).toEqual(expected[i])<file_sep>class Rasterizr.Pipeline.OutputMerger.OutputMergerStage renderTargetViews: null depthStencilView: null constructor: (@device) -> getMultiSampleCount: -> 1 # TODO execute: (inputs) => # Loop through all pixels for pixel in inputs # TODO renderTargetIndex = 0 renderTarget = @renderTargetViews[renderTargetIndex] # TODO renderTargetArrayIndex = 0 # Loop through all samples for this pixel for sampleIndex in [0...@getMultiSampleCount()] if !pixel.samples[sampleIndex].covered continue # If this pixel is further away than previously drawn pixels, discard it if @depthStencilView newDepth = pixel.samples[sampleIndex].depth oldDepth = @depthStencilView.getDepth( renderTargetArrayIndex, pixel.x, pixel.y, sampleIndex) if !@depthStencilState.depthTestPasses(newDepth, oldDepth) continue<file_sep># Be sure to restart your server when you modify this file. Rasterizr::Application.config.session_store :cookie_store, key: '_rasterizr_session' <file_sep>namespace 'Rasterizr', (exports) -> exports.Format = R32G32B32_Float: 0<file_sep>namespace 'Rasterizr.Pipeline.InputAssembler', (exports) -> exports.InputClassification = perVertexData: 0 perInstanceData: 1<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> exports.BlendOption = zero: 0 one: 1 sourceColor: 2 inverseSourceColor: 3 sourceAlpha: 4 inverseSourceAlpha: 5 destinationAlpha: 6 inverseDestinationAlpha: 7 destinationColor: 8 inverseDestinationColor: 9 sourceAlphaSaturate: 10 blendFactor: 11 inverseBlendFactor: 12 secondarySourceColor: 13 inverseSecondarySourceColor: 14 secondarySourceAlpha: 15 inverseSecondarySourceAlpha: 16<file_sep>namespace 'HlslJs.Parser', (exports) -> class exports.TextBuffer @isLineSeparator: (ch) -> switch ch when '\r', '\n' then true else false constructor: (@text) -> @column = @line = @offset = 0 isEof: => @remainingLength() == 0 position: => new exports.BufferPosition(@line, @column, @offset) remainingLength: => @text.length - @offset nextChar: => ch = @peekChar() @offset++ @column++ if TextBuffer.isLineSeparator(ch) @column = 0 @line++ if ch == '\r' && @offset < @text.length && @peekChar() == '\n' @offset++ ch peekChar: (index = 0) => if @offset + index >= @text.length return '\0' @text[@offset + index]<file_sep>namespace 'HlslJs.CodeModel.Types', (exports) -> exports.ScalarType = bool: 0 int: 1 uint: 2 half: 3 float: 4 double: 5<file_sep>#= require ./depth_write_mask namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> OutputMerger = Rasterizr.Pipeline.OutputMerger class exports.DepthStencilStateDescription @default: new DepthStencilStateDescription(true, OutputMerger.DepthWriteMask.all) @depthRead: new DepthStencilStateDescription(true, OutputMerger.DepthWriteMask.zero) @none: new DepthStencilStateDescription(false, OutputMerger.DepthWriteMask.zero) depthComparison: Rasterizr.Comparison.less isStencilEnabled: false stencilReadMask: 0 stencilWriteMask: 0 constructor: (@isDepthEnabled, @depthWriteMask) -> @frontFace = new OutputMerger.DepthStencilOperationDescription() @backFace = new OutputMerger.DepthStencilOperationDescription()<file_sep>namespace 'Rasterizr.Pipeline.InputAssembler', (exports) -> class exports.VertexBufferBinding constructor: (@buffer, @offset, @stride) -><file_sep>namespace 'Rasterizr.Pipeline.Rasterizer', (exports) -> class exports.Samples anyCovered: false sample0: null sample1: null sample2: null sample3: null getSample: (index) => switch index when 0 then @sample0 when 1 then @sample1 when 2 then @sample2 when 3 then @sample3 else throw "Out of range"<file_sep>namespace 'Rasterizr.Math', (exports) -> class exports.Vector2 @sizeInBytes: 4 * 2 @zero: new Vector2(0, 0) constructor: (@x, @y) -> <file_sep>namespace 'Rasterizr', (exports) -> class exports.DeviceChild constructor: (@device) -><file_sep>#= require ./token_type namespace 'HlslJs.CodeModel.Tokens', (exports) -> class exports.Token @isDataType: (type) -> type < exports.TokenType.true @isKeyword: (type) -> type < exports.TokenType.identifier @getString: (type) -> 'todo' constructor: (@type, @sourcePath, @position) -> toString: -> Token.getString(@type)<file_sep>#= require ./enum #= require ./namespace #= require_tree ./hlsl<file_sep>namespace 'Rasterizr.ShaderCompiler', (exports) -> class exports.ShaderBytecode @compile: (source) -> result = glsl.compile(source, glsl.mode.vertex) # TODO throw "Compilation failed" unless result glsl.output<file_sep>#= require ./literal_token #= require ./literal_token_type namespace 'HlslJs.CodeModel.Tokens', (exports) -> class exports.StringToken extends exports.LiteralToken constructor: (@value, sourcePath, position) -> super(exports.LiteralTokenType.string, sourcePath, position) toString: -> "\"#{@value}\""<file_sep>namespace 'Rasterizr.Math', (exports) -> class exports.Vector3 @sizeInBytes: 4 * 3 @zero: new Vector3(0, 0, 0) constructor: (@x, @y, @z) -> <file_sep>#= require ./resource namespace 'Rasterizr.Resources', (exports) -> class exports.Buffer extends exports.Resource constructor: (device, @description, data = null) -> super(device) @data = new ArrayBuffer(@description.sizeInBytes) @setData(data) setData: (data) => return unless data # TODO<file_sep>#= require ./token #= require ./token_type namespace 'HlslJs.CodeModel.Tokens', (exports) -> class exports.IdentifierToken extends exports.Token constructor: (@identifier, sourcePath, position) -> super(exports.TokenType.identifier, sourcePath, position) toString: -> @identifier<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> class exports.DepthStencilView extends Rasterizr.Pipeline.ResourceView constructor: (device, resource, @description) -> super(device, resource) switch resource.resourceType when ResourceType.buffer throw "Invalid resource type for depth stencil view: #{resource.resourceType}" getDepth: (arrayIndex, x, y, sampleIndex) -> # TODO 0 setDepth: (arrayIndex, x, y, sampleIndex, depth) -> # TODO clear: (clearFlags, depth, stencil) -> # TODO<file_sep>namespace 'Rasterizr.Pipeline.InputAssembler', (exports) -> class exports.InputAssemblerStage @VERTEX_INPUT_RESOURCE_SLOT_COUNT: 32 constructor: (@device) -> @vertexBufferBindings = new Array(InputAssemblerStage.VERTEX_INPUT_RESOURCE_SLOT_COUNT) getVertexBuffers: (startSlot, numBuffers, vertexBufferBindings) -> for i in [0...numBuffers] vertexBufferBindings[i] = @vertexBufferBindings[i + startSlot] setVertexBuffers: (startSlot, vertexBufferBindings...) -> for i in [0...vertexBufferBindings.length] @vertexBufferBindings[i + startSlot] = vertexBufferBindings[i]<file_sep>describe 'Rasterizr.ShaderCompiler.ShaderBytecode', -> describe '#compile', -> it 'compiles GLSL source code to internal format', -> glslSource = """ attribute vec3 aVertexPosition; uniform mat4 uMVMatrix; uniform mat4 uPMatrix; void main(void) { gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); } """ result = Rasterizr.ShaderCompiler.ShaderBytecode.compile(glslSource) expect(result.body.length).toBe(35)<file_sep>namespace 'HlslJs.Parser', (exports) -> CodeModel = HlslJs.CodeModel Declarations = CodeModel.Declarations Token = CodeModel.Tokens.Token TokenType = CodeModel.Tokens.TokenType Types = CodeModel.Types class exports.Parser constructor: (@tokens) -> @tokenIndex = 0 parse: => @parseCompilationUnit() eat: (type) -> if @peekType() == type @nextToken() else @reportTokenExpectedError(type) @errorToken() peekToken: (index = 0) -> @tokens[@tokenIndex + index] peekType: (index = 0) -> @peekToken(index).type nextToken: -> @tokens[@tokenIndex++] reportTokenExpectedError: (type) -> @reportError("Syntax error: '#{Token.getString(type)}' expected") reportError: (message, token = @peekToken()) -> # TODO errorToken: -> new Token(TokenType.error, null, @peekToken().position) parseCompilationUnit: -> tree = new CodeModel.CompilationUnitNode(@parseGlobalDeclarations()) @eat(TokenType.eof) tree # Global parseGlobalDeclarations: -> # TODO [@parseVariableDeclaration()] # Variables parseVariableDeclaration: -> storageClasses = @parseVariableStorageClasses() typeModifier = @parseVariableTypeModifier() type = @parseVariableType() # TODO new Declarations.VariableDeclarationNode( storageClasses, typeModifier) parseVariableStorageClasses: -> storageClasses = Declarations.VariableStorageClasses.none while true [found, newStorageClass] = @peekVariableStorageClass() break unless found if newStorageClass & storageClasses != 0 @reportError(duplicateModifer) else storageClasses |= newStorageClass @nextToken() storageClasses peekVariableStorageClass: -> storageClass = Parser.toVariableStorageClass(@peekType()) [storageClass != Declarations.VariableStorageClasses.none, storageClass] @toVariableStorageClass: (type) -> switch type when TokenType.extern then Declarations.VariableStorageClasses.extern when TokenType.nointerpolation then Declarations.VariableStorageClasses.nointerpolation when TokenType.shared then Declarations.VariableStorageClasses.shared when TokenType.static then Declarations.VariableStorageClasses.static when TokenType.uniform then Declarations.VariableStorageClasses.uniform when TokenType.volatile then Declarations.VariableStorageClasses.volatile else Declarations.VariableStorageClasses.none parseVariableTypeModifier: -> switch @peekType() when TokenType.const then Declarations.VariableTypeModifier.const when TokenType.rowMajor then Declarations.VariableTypeModifier.rowMajor when TokenType.columnMajor then Declarations.VariableTypeModifier.columnMajor else Declarations.VariableTypeModifier.none parseVariableDatatype: -> switch @peekType() when TokenType.buffer then @parseBufferTypeSpecifier() # Basic Datatypes parseBufferTypeSpecifier: -> @eat(TokenType.buffer) @eat(TokenType.openAngle) typeSpecifier = switch when @peekScalarTypeSpecifier() then @parseScalarTypeSpecifier() when @peekVectorTypeSpecifier() then @parseVectorTypeSpecifier() when @peekMatrixTypeSpecifier() then @parseMatrixTypeSpecifier() else @reportError("Invalid buffer type specifier") @eat(TokenType.closeAngle) new Types.BufferTypeSpecifier(typeSpecifier) peekScalarTypeSpecifier: -> switch @peekType() when TokenType.bool, TokenType.int, TokenType.uint, TokenType.half, TokenType.float, TokenType.double true else false parseScalarTypeSpecifier: -> <file_sep>namespace 'Rasterizr', (exports) -> class exports.Comparison @never: 0 @less: 1 @equal: 2 @lessEqual: 3 @greater: 4 @notEqual: 5 @greaterEqual: 6 @always: 7 @doComparison: (func, source, dest) -> switch func when Comparison.never false when Comparison.less source < dest when Comparison.equal source == dest when Comparison.lessEqual source <= dest when Comparison.greater source > dest when Comparison.notEqual source != dest when Comparison.greaterEqual source >= dest when Comparison.always true else throw "argument out of range"<file_sep>#= require ./text_buffer #= require ../code_model/tokens/token_type #= require ./keywords namespace 'HlslJs.Parser', (exports) -> Tokens = HlslJs.CodeModel.Tokens TokenType = Tokens.TokenType class exports.Lexer @isIdentifierChar: (c) -> /[A-Za-z_0-9]/.test(c) @isWhiteSpace: (c) -> /\s/.test(c) @isDigit: (c) -> /[0-9]/.test(c) constructor: (@path, @text) -> @buffer = new exports.TextBuffer(text) getTokens: => result = new Array() while !@isEof() result.push(@nextToken()) result.push(@nextToken()) # We want EOF as a token. result nextToken: -> @eatWhiteSpace() @startToken() if @peekChar() == '\0' return @newToken(TokenType.eof) c = @nextChar() switch c when '{' then @newToken(TokenType.openCurly) when '}' then @newToken(TokenType.closeCurly) when '(' then @newToken(TokenType.openParen) when ')' then @newToken(TokenType.closeParen) when '[' then @newToken(TokenType.openSquare) when ']' then @newToken(TokenType.closeSquare) when '=' c2 = @peekChar() if c2 == '=' @nextChar() return @newToken(TokenType.doubleEquals) @newToken(TokenType.singleEquals) when '+' then @newToken(TokenType.plus) when '-' then @newToken(TokenType.minus) when '*' then @newToken(TokenType.asterisk) when ',' then @newToken(TokenType.comma) when ':' then @newToken(TokenType.colon) when ';' then @newToken(TokenType.semicolon) when '/' c2 = @peekChar() if c2 == '/' while !@isEof() && !exports.TextBuffer.isLineSeparator(@peekChar()) @nextChar() @takePosition() return @nextToken() @newToken(TokenType.forwardSlash) when '"' value = @eatWhile((c2) -> c2 != '"') @nextChar() # Swallow the end of the string constant new Tokens.StringToken(value, @path, @takePosition()) when '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' # If the number contains a dot or ends with "f", then it's a float. # Otherwise, it's an integer. containsDot = false value = c while !@isEof() && (@peekChar() == '.' || Lexer.isDigit(@peekChar())) c2 = @nextChar() switch c2 when '.' if containsDot @reportError("Unexpected character: '#{c2}'") return @errorToken() containsDot = true break value += c2 floatSuffix = false if @peekChar() == 'f' floatSuffix = true @nextChar() if containsDot || floatSuffix return new Tokens.FloatToken(parseFloat(value), @path, @takePosition()) return new Tokens.IntToken(parseInt(value), @path, @takePosition()) else if Lexer.isIdentifierChar(c) identifier = c + @eatWhile(Lexer.isIdentifierChar) if exports.Keywords.isKeyword(identifier) return new Tokens.Token(exports.Keywords.getKeywordType(identifier), @path, @takePosition()) return new Tokens.IdentifierToken(identifier, @path, @takePosition()) @reportError("Unexpected character: '#{c}'") return @errorToken() errorToken: -> @newToken(TokenType.error) newToken: (type) => new Tokens.Token(type, @path, @takePosition()) isEof: => @buffer.isEof() peekIdentifier: (identifier, startIndex) => for i in [startIndex...identifier.length] if @peekChar(index++) != identifier[i] return false true eatIdentifier: (identifier, startIndex) => @nextChar() for i in [startIndex...identifier.length] eatWhile: (testFunc) => result = '' while !@isEof() && testFunc(@peekChar()) result += @nextChar() result eatWhiteSpace: => while Lexer.isWhiteSpace(@peekChar()) @nextChar() nextChar: => @buffer.nextChar() peekChar: (index = 0) => @buffer.peekChar(index) startToken: => @position = @buffer.position() takePosition: => position = @position @clearPosition() position clearPosition: => @position = new exports.BufferPosition() reportError: (message, args...) => #if (Error != null) # Error(this, new ErrorEventArgs(string.Format(message, args), _buffer.Position)); # TODO<file_sep>namespace 'HlslJs.CodeModel.Types', (exports) -> class exports.TypeSpecifier class exports.BufferTypeSpecifier extends exports.TypeSpecifier constructor: (@typeSpecifier) -> class exports.ScalarTypeSpecifier extends exports.TypeSpecifier constructor: (@scalarType) -> class exports.VectorTypeSpecifier extends exports.TypeSpecifier constructor: (@scalarType, @numComponents) -> class exports.MatrixTypeSpecifier extends exports.TypeSpecifier constructor: (@scalarType, @rows, @columns) -> class exports.StringTypeSpecifier extends exports.TypeSpecifier class exports.StructTypeSpecifier extends exports.TypeSpecifier constructor: (@identifier) -><file_sep>HLSL GRAMMAR ============ Based on O3D's HLSL grammar: http://src.chromium.org/svn/trunk/o3d/compiler/hlsl/HLSL.g Top Level --------- CompilationUnit → (GlobalDeclaration)* GlobalDeclaration → (FunctionStorageClass? FunctionTypeSpecifier ID LPAREN) => FunctionDeclaration | SamplerDeclaration | TextureDeclaration | StructDefinition | TypedefDefinition | VariableDeclaration Variables --------- VariableDeclaration → VariableStorageClass* VaruabkeTypeModifier? VariableDatatype IdDeclaration Semantic? ('=' Initializer)? SEMI VariableStorageClass → 'extern' | 'nointerpolation' | 'shared' | 'static' | 'uniform' | 'volatile' VariableTypeModifier → ('const' | 'row_major' | 'column_major') VariableDatatype → BufferTypeSpecifier | ScalarTypeSpecifier | StringTypeSpecifier | VectorTypeSpecifier | MatrixTypeSpecifier | StructTypeSpecifier IdDeclaration → ID (LBRACKET ConstantExpression RBRACKET)? Functions --------- FunctionDeclaration → FunctionStorageClass? FunctionTypeSpecifier ID LPAREN ArgumentList RPAREN Semantic? FunctionBody (SEMI)? FunctionStorageClass → 'inline' FunctionTypeSpecifier → ScalarTypeSpecifier | VectorTypeSpecifier | MatrixTypeSpecifier | StructTypeSpecifier | 'void' ArgumentList → ( ParamDeclaration (COMMA ParamDeclaration)* )? ParamDeclaration → ParamDirection? ParamVariability? ParamTypeSpecifier IdDeclaration Semantic? | SAMPLER ID ParamDirection → IN | OUT | INOUT ParamVariability → CONST | UNIFORM ParamTypeSpecifier → ScalarTypeSpecifier | VectorTypeSpecifier | MatrixTypeSpecifier | StructTypeSpecifier | StringTypeSpecifier Semantic → COLON SemanticSpecifier FunctionBody → LCURLY (DeclOrStatement)* RCURLY DeclOrStatement → ( (CONST)? VectorTypeSpecifier) => (CONST)? VectorTypeSpecifier InitDeclaratorList SEMI | ( (CONST)? ScalarTypeSpecifier) => (CONST)? ScalarTypeSpecifier InitDeclarationList SEMI | ( STRUCT (ID)? LCURLY ) => StructDefinition InitDeclarationList? SEMI | STRUCT ID InitDeclaratorList SEMI | (ID InitDeclaratorList) => ID InitDeclaratorList SEMI | Statement InitDeclaratorList → InitDeclarator (COMMA InitDeclarator)* InitDeclarator → Declarator (ASSIGN Initializer)? Declarator → ID ( LBRACKET ConstantExpression? RBRACKET )* Statement → (LvalueExpression AssignmentOperator) => AssignmentStatement | (LvalueExpression SelfModifyOperator) => PostModifyStatement | PreModifyStatement | ExpressionStatement | CompoundStatement | SelectionStatement | IterationStatement | JumpStatement | SEMI AssignmentStatement → LvalueExpression AssignmentOperator Expression SEMI PreModifyStatement → PreModifyExpression SEMI PreModifyExpression → SelfModifyOperator LvalueExpression PostModifyStatement → PostModifyExpression SEMI PostModifyExpression → LvalueExpression SelfModifyOperator SelfModifyOperator → PLUSPLUS | MINUSMINUS ExpressionStatement → Expression SEMI CompoundStatement → LCURLY ( ( ID InitDeclaratorList) => ID InitDeclaratorList SEMI | ( CONST? VectorTypeSpecifier ) => CONST? VectorTypeSpecifier InitDeclaratorList SEMI | ( CONST? ScalarTypeSpecifier ) => CONST? ScalarTypeSpecifier InitDeclaratorList SEMI | ( STRUCT ID? LCURLY ) => StructDefinition InitDeclaratorList? SEMI | STRUCT ID InitDeclaratorList SEMI | Statement )* RCURLY SelectionStatement → IF LPAREN Expression RPAREN Statement ( ELSE Statement )? IterationStatement → WHILE LPAREN Expression RPAREN Statement | FOR LPAREN AssignmentStatement EqualityExpression SEMI ModifyExpression RPAREN Statement | DO Statement WHILE LPAREN Expression RPAREN SEMI ModifyExpression → ( LvalueExpression AssignmentOperator ) => LvalueExpression AssignmentOperator Expression | PreModifyExpression | PostModifyExpression Structs ------- StructDefinition → STRUCT ID? LCURLY StructDeclarationList RCURLY ID? SEMI StructDeclarationList → // TODO: Support nested structs. ( StructInterpolationModifier? (ScalarTypeSpecifier|VectorTypeSpecifier) ID (COLON SemanticSpecifier)? SEMI )+ StructInterpolationModifier → 'linear' | 'centroid' | 'nointerpolation' | 'noperspective' Basic Datatypes --------------- BufferTypeSpecifier → 'Buffer' '<' (ScalarTypeSpecifier | VectorTypeSpecifier | MatrixTypeSpecifier) '>' ScalarTypeSpecifier → 'bool' | 'int' | 'uint' | 'half' | 'float' | 'double' VectorTypeSpecifier → 'bool1' | 'bool2' | 'bool3' | 'bool4' | 'int1' | 'int2' | 'int3' | 'int4' | 'uint1' | 'uint2' | 'uint3' | 'uint4' | 'half1' | 'half2' | 'half3' | 'half4' | 'float1' | 'float2' | 'float3' | 'float4' | 'double1' | 'double2' | 'double3' | 'double4' | 'vector' '<' ScalarTypeSpecifier ',' OneToFour '>' MatrixTypeSpecifier → 'float1x1' | 'float1x2' | 'float1x3' | 'float1x4' | 'float2x1' | 'float2x2' | 'float2x3' | 'float2x4' | 'float3x1' | 'float3x2' | 'float3x3' | 'float3x4' | 'float4x1' | 'float4x2' | 'float4x3' | 'float4x4' | // matrix types for other scalar types | 'matrix' '<' ScalarTypeSpecifier ',' OneToFour ',' OneToFour '>' OneToFour → '1'|'2'|'3'|'4' StringTypeSpecifier → 'string' StructTypeSpecifier → ID Shared ------ SemanticSpecifier → ID StructTypeSpecifier → ID | ( STRUCT ID? LCURLY ) => StructDefinition | STRUCT ID License ------- License from O3D grammar: /* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */<file_sep>#= require rasterizr/pipeline/input_assembler/input_element namespace 'TestVertex', (exports) -> Vector2 = Rasterizr.Math.Vector2 Vector3 = Rasterizr.Math.Vector3 InputElement = Rasterizr.Pipeline.InputAssembler.InputElement class exports.PositionNormalTexture @sizeInBytes: Vector3.sizeInBytes + Vector3.sizeInBytes + Vector2.sizeInBytes @inputElements: [ new InputElement("SV_Position", 0, Rasterizr.Format.R32G32B32_Float, 0), new InputElement("NORMAL", 0, Rasterizr.Format.R32G32B32_Float, 0), new InputElement("TEXCOORD", 0, Rasterizr.Format.R32G32_Float, 0) ] constructor: (@position, @normal, @texCoord) -> set: (arrayBuffer, index) -> dataView = new DataView(arrayBuffer, index * TestVertex.PositionNormalTexture.sizeInBytes) dataView.setFloat32(0, @position.x) dataView.setFloat32(4, @position.y) dataView.setFloat32(8, @position.z) dataView.setFloat32(12, @normal.x) dataView.setFloat32(16, @normal.y) dataView.setFloat32(20, @normal.z) dataView.setFloat32(24, @texCoord.x) dataView.setFloat32(28, @texCoord.y)<file_sep>namespace 'HlslJs.CodeModel.Declarations', (exports) -> class exports.VariableDeclarationNode extends HlslJs.CodeModel.ParseNode constructor: (@storageClasses, @typeModifier, @type) -><file_sep>namespace 'Rasterizr.Math', (exports) -> class exports.Vector4 @sizeInBytes: 4 * 4 @zero: new Vector4(0, 0, 0, 0) constructor: (@x, @y, @z, @w) -> equals: (other) -> @x == other.x && @y == other.y && @z == other.z && @w == other.w <file_sep>namespace 'Rasterizr.Resources', (exports) -> class exports.BufferDescription constructor: (@sizeInBytes, @bindFlags) -><file_sep>namespace 'Rasterizr.Resources', (exports) -> exports.BindFlags = none: 0 vertexBuffer: 1 indexBuffer: 2 constantBuffer: 4 shaderResource: 8 streamOutput: 16 renderTarget: 32 depthStencil: 64 unorderedAccess: 128<file_sep>namespace 'Rasterizr.Pipeline.PixelShader', (exports) -> class exports.Pixel constructor: (@x, @y) -> @color = new Color4F() @samples = new Rasterizr.Pipeline.Rasterizer.Samples() @primitiveID = 0<file_sep>#= require jquery #= require ../../app/assets/javascripts/hlsl #= require ../../app/assets/javascripts/rasterizr #= require ./rasterizr/test_vertex #= require_tree ./<file_sep>describe 'Rasterizr.Math.Color4F', -> Color4F = Rasterizr.Math.Color4F describe '::invert', -> it 'subtracts values from 1.0', -> result = Color4F.invert(new Color4F(2.0, 1.0, 0.3, 0.0)) expect(result.r).toEqual(-1.0) expect(result.g).toEqual(0.0) expect(result.b).toEqual(0.7) expect(result.a).toEqual(1.0) describe '::multiply', -> it 'multiplies values', -> result = Color4F.multiply( new Color4F(2.0, 1.0, 0.3, 0.0), new Color4F(1.0, 0.5, -0.5, 0.0)) expect(result.r).toEqual(2.0) expect(result.g).toEqual(0.5) expect(result.b).toEqual(-0.15) expect(result.a).toEqual(0.0) describe '::saturate', -> it 'caps values to between 0.0 and 1.0 inclusive', -> result = Color4F.saturate(new Color4F(2.0, 1.0, -0.3, 0.3)) expect(result.r).toEqual(1.0) expect(result.g).toEqual(1.0) expect(result.b).toEqual(0.0) expect(result.a).toEqual(1.0)<file_sep>namespace 'Rasterizr.Pipeline.Rasterizer', (exports) -> class exports.Sample # Gets or sets a flag which indicates whether this sample location is covered # by the polygon being rasterized. covered: false depth: 0<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> exports.BlendOperation = add: 0 subtract: 1 reverseSubtract: 2 minimum: 3 maximum: 4<file_sep>describe 'HlslJs.Parser.TextBuffer', -> TextBuffer = HlslJs.Parser.TextBuffer buffer = null beforeEach -> buffer = new TextBuffer('This is some text') describe '#peekChar', -> it 'gets the first character if no index is specified', -> expect(buffer.peekChar()).toEqual('T') it 'gets the character at the specified index', -> expect(buffer.peekChar(10)).toEqual('m') it 'detects invalid position', -> expect(buffer.peekChar(20)).toEqual('\0') describe '#nextChar', -> it 'gets the next character', -> expect(buffer.nextChar()).toEqual('T') expect(buffer.nextChar()).toEqual('h') it 'reports column and line on single line', -> buffer.nextChar() buffer.nextChar() expect(buffer.column).toEqual(2) expect(buffer.line).toEqual(0) it 'reports column and line on multiple lines', -> buffer = new TextBuffer("Abc\nDefg\nC") buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() expect(buffer.column).toEqual(1) expect(buffer.line).toEqual(1) describe '#remainingLength', -> it 'reports remaining length', -> buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() expect(buffer.remainingLength()).toEqual(12) describe '#isEof', -> it 'returns false when not at end of buffer', -> buffer = new TextBuffer('Abc') buffer.nextChar() expect(buffer.isEof()).toBe(false) it 'returns true when at end of buffer', -> buffer = new TextBuffer('Abc') buffer.nextChar() buffer.nextChar() buffer.nextChar() expect(buffer.isEof()).toBe(true) describe '#position', -> it 'reports the current position', -> buffer = new TextBuffer("Abc\r\nDefg\r\nC") buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() buffer.nextChar() position = buffer.position() expect(position.column).toEqual(2) expect(position.line).toEqual(1) expect(position.offset).toEqual(7)<file_sep>namespace 'Rasterizr.Pipeline.InputAssembler', (exports) -> class exports.InputLayout extends Rasterizr.DeviceChild constructor: (device, elements, compiledShader) -> super(device) @compiledShader = compiledShader @elements = @_processElements(elements) @slots = @_processSlots(elements) _processElements: (elements) => slotOffsets = new Array(exports.InputAssemblerStage.VERTEX_INPUT_RESOURCE_SLOT_COUNT) result = new Array(elements.length) for i in [0...elements.length] element = elements[i] if element.alignedByteOffset != exports.InputElement.APPEND_ALIGNED slotOffsets[element.InputSlot] = element.alignedByteOffset result[i] = new ProcessedInputElement( _inputSignature.parameters.findRegister(element.semanticName, element.semanticIndex), element.format, element.inputSlot, slotOffsets[element.inputSlot], element.inputSlotClass, element.instanceDataStepRate) slotOffsets[element.inputSlot] += Format.sizeOfInBytes(element.format) result _processSlots: (elements) => result = new Array() for i in [0...elements.length] element = elements[i] existingSlotElement = result.filter((x) -> x.inputSlot == element.inputSlot)[0] if !existingSlotElement result.push(new InputSlotElement( element.InputSlot, element.InputSlotClass, element.InstanceDataStepRate) ) else if element.inputSlotClass != existingSlotElement.inputSlotClass throw "Element[#{i}]'s InputSlotClass is different from the InputSlotClass of a previously defined element at the same input slot. All elements from a given input slot must have the same InputSlotClass and InstanceDataStepRate." if element.InstanceDataStepRate != existingSlotElement.InstanceDataStepRate throw "Element[#{i}]'s InstanceDataStepRate is different from the InstanceDataStepRate of a previously defined element at the same input slot. All elements from a given input slot must have the same InputSlotClass and InstanceDataStepRate." result class ProcessedInputElement constructor: ( @registerIndex, @format, @inputSlot, @alignedByteOffset, @inputSlotClass, @instanceDataStepRate ) -> class InputSlotElement constructor: (@inputSlot, @inputSlotClass, @instanceDataStepRate) -><file_sep>namespace 'HlslJs.Parser', (exports) -> class exports.BufferPosition constructor: (@line, @column, @offset) -> toString: -> if @line == 0 && @column == 0 return '' "(#{@line + 1}, #{@column + 1})"<file_sep>namespace 'Rasterizr.Math', (exports) -> class exports.Color4F @invert: (v) -> new Color4F(1.0 - v.r, 1.0 - v.g, 1.0 - v.b, 1.0 - v.a) @multiply: (l, r) -> new Color4F(l.r * r.r, l.g * r.g, l.b * r.b, l.a * r.a) @saturate: (v) -> new Color4F( Color4F._saturateFloat(v.r), Color4F._saturateFloat(v.g), Color4F._saturateFloat(v.b), 1.0) @_saturateFloat: (v) -> v = if v > 1.0 then 1.0 else v v = if v < 0.0 then 0.0 else v v constructor: (@r, @g, @b, @a) -> <file_sep>#= require ./color_write_mask_flags namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> OutputMerger = Rasterizr.Pipeline.OutputMerger class exports.RenderTargetBlendDescription constructor: ( @isBlendEnabled = false, @sourceBlend = OutputMerger.BlendOption.zero, @destinationBlend = OutputMerger.BlendOption.zero, @blendOperation = OutputMerger.BlendOperation.add, @sourceAlphaBlend = OutputMerger.BlendOption.zero, @destinationAlphaBlend = OutputMerger.BlendOption.zero, @alphaBlendOperation = OutputMerger.BlendOperation.add, @renderTargetWriteMask = OutputMerger.ColorWriteMaskFlags.all ) -><file_sep>namespace 'HlslJs.CodeModel.Tokens', (exports) -> exports.LiteralTokenType = string: 0 int: 1 float: 2<file_sep>namespace 'Rasterizr.Resources', (exports) -> class exports.Resource extends Rasterizr.DeviceChild constructor: (device) -> super(device)<file_sep>namespace 'Rasterizr.Pipeline.InputAssembler', (exports) -> class exports.InputElement @APPEND_ALIGNED: -1 constructor: ( @semanticName, @semanticIndex, @format, @inputSlot, @alignedByteOffset = @constructor.APPEND_ALIGNED, @inputSlotClass = exports.InputClassification.perVertexData, @instanceDataStepRate = 0 ) -><file_sep>namespace 'Rasterizr.Pipeline', (exports) -> class exports.ResourceView extends Rasterizr.DeviceChild constructor: (device, @resource) -> super(device)<file_sep>#= require ./token #= require ./token_type namespace 'HlslJs.CodeModel.Tokens', (exports) -> class exports.LiteralToken extends exports.Token constructor: (@literalType, sourcePath, position) -> super(exports.TokenType.literal, sourcePath, position)<file_sep>describe 'Rasterizr.Pipeline.OutputMerger.BlendState', -> OutputMerger = Rasterizr.Pipeline.OutputMerger Color4F = Rasterizr.Math.Color4F describe '#doBlend', -> describe 'alpha blend', -> blendState = new OutputMerger.BlendState(null, OutputMerger.BlendStateDescription.alphaBlend) it 'blends correctly', -> result = blendState.doBlend(0, new Color4F(1.0, 0.0, 0.0, 0.3), new Color4F(0.0, 1.0, 0.0, 0.4), new Color4F()) expect(result.r).toBeCloseTo(1.0, 2) expect(result.g).toBeCloseTo(0.7, 2) expect(result.b).toBeCloseTo(0.0, 2) expect(result.a).toBeCloseTo(0.3 + (1.0 - 0.3) * 0.4, 2)<file_sep>describe 'HlslJs.Parser.Parser', -> Declarations = HlslJs.CodeModel.Declarations Types = HlslJs.CodeModel.Types parseCode = (hlslCode) -> lexer = new HlslJs.Parser.Lexer(null, hlslCode) parser = new HlslJs.Parser.Parser(lexer.getTokens()) parser.parse() it 'parses variable declarations', -> code = 'extern nointerpolation const float foo[2] : BAR = {3.14, 6.28};' result = parseCode(code) expect(result.declarations.length).toEqual(1) variableDeclaration = result.declarations[0] expect(variableDeclaration.storageClasses).toBe( Declarations.VariableStorageClasses.extern | Declarations.VariableStorageClasses.nointerpolation) expect(variableDeclaration.typeModifier).toBe( Declarations.VariableTypeModifier.const) expect(variableDeclaration.type).toEqual( new Types.ScalarTypeSpecifier(Types.ScalarType.float)) it 'parses HLSL tokens', -> hlslCode = """ float4x4 World; float4x4 View; float4x4 Projection; float4 AmbientColor = float4(1, 1, 1, 1); float AmbientIntensity = 0.1; struct VertexShaderInput { float4 Position : POSITION0; }; struct VertexShaderOutput { float4 Position : POSITION0; }; VertexShaderOutput VertexShaderFunction(VertexShaderInput input) { VertexShaderOutput output; float4 worldPosition = mul(input.Position, World); float4 viewPosition = mul(worldPosition, View); output.Position = mul(viewPosition, Projection); return output; } float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 { return AmbientColor * AmbientIntensity; } """ lexer = new HlslJs.Parser.Lexer(null, hlslCode) tokens = lexer.getTokens() parser = new HlslJs.Parser.Parser(tokens) result = parser.parse() # TODO<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> OutputMerger = Rasterizr.Pipeline.OutputMerger BlendOperation = OutputMerger.BlendOperation BlendOption = OutputMerger.BlendOption Color4F = Rasterizr.Math.Color4F class exports.BlendState extends Rasterizr.DeviceChild constructor: (device, @description) -> super(device) doBlend: (renderTargetIndex, source, destination, blendFactor) => blendDescription = @description.renderTargets[renderTargetIndex] if !blendDescription.isBlendEnabled return source result = new Color4F() # RGB blending colorDestinationBlendFactor = BlendState._getBlendFactor( blendDescription.destinationBlend, source, destination, blendFactor) colorSourceBlendFactor = BlendState._getBlendFactor( blendDescription.sourceBlend, source, destination, blendFactor) colorDestination = Color4F.multiply(destination, colorDestinationBlendFactor) colorSource = Color4F.multiply(source, colorSourceBlendFactor) result.r = BlendState._doBlendOperation(blendDescription.blendOperation, colorSource.r, colorDestination.r) result.g = BlendState._doBlendOperation(blendDescription.blendOperation, colorSource.g, colorDestination.g) result.b = BlendState._doBlendOperation(blendDescription.blendOperation, colorSource.b, colorDestination.b) # Alpha blending alphaDestinationBlendFactor = BlendState._getBlendFactor( blendDescription.destinationAlphaBlend, source, destination, blendFactor) alphaSourceBlendFactor = BlendState._getBlendFactor( blendDescription.sourceAlphaBlend, source, destination, blendFactor) alphaDestination = destination.a * alphaDestinationBlendFactor.a alphaSource = source.a * alphaSourceBlendFactor.a result.a = BlendState._doBlendOperation( blendDescription.alphaBlendOperation, alphaSource, alphaDestination) result @_doBlendOperation: (blendFunction, left, right) -> switch blendFunction when BlendOperation.add left + right else throw "not supported" @_getBlendFactor: (blend, source, destination, blendFactor) -> switch blend when BlendOption.zero new Color4F(0, 0, 0, 0) when BlendOption.one new Color4F(1, 1, 1, 1) when BlendOption.sourceColor source when BlendOption.inverseSourceColor Color4F.invert(source) when BlendOption.sourceAlpha new Color4F(source.a, source.a, source.a, source.a) when BlendOption.inverseSourceAlpha Color4F.invert(new Color4F(source.a, source.a, source.a, source.a)) when BlendOption.destinationAlpha new Color4F(destination.a, destination.a, destination.a, destination.a) when BlendOption.inverseDestinationAlpha Color4F.invert(new Color4F(destination.a, destination.a, destination.a, destination.a)) when BlendOption.destinationColor destination when BlendOption.inverseDestinationColor Color4F.invert(destination) when BlendOption.sourceAlphaSaturate Color4F.saturate(new Color4F(source.a, source.a, source.a, source.a)) when BlendOption.blendFactor blendFactor when BlendOption.inverseBlendFactor Color4F.invert(blendFactor) else throw "not supported"<file_sep>namespace 'Rasterizr', (exports) -> class exports.Device<file_sep>#= require cwebgl #= require ./namespace #= require ./rasterizr/device #= require ./rasterizr/device_child #= require ./rasterizr/pipeline/resource_view #= require_tree ./rasterizr<file_sep>describe 'Rasterizr.Resources.Buffer', -> OutputMerger = Rasterizr.Pipeline.OutputMerger Color4F = Rasterizr.Math.Color4F # describe '#setData and #getData', -> # it 'sets and gets data', -> # bufferDescription = new BufferDescription() # SizeInBytes = Utilities.SizeOf<Matrix3D>() # buffer = new Buffer(null, description) # matrix = Matrix3D.CreateLookAt(new Point3D(1, 2, 3), Vector3D.Forward, Vector3D.Up) # buffer.setData(matrix) # buffer.getData() # [Test] # public void CanSetAndGetMatrix() # { # // Arrange. # var device = new Device(); # var description = new BufferDescription # { # SizeInBytes = Utilities.SizeOf<Matrix3D>() # }; # var buffer = new Buffer(device, description); # var matrix = Matrix3D.CreateLookAt(new Point3D(1, 2, 3), Vector3D.Forward, Vector3D.Up); # // Act. # buffer.SetData(ref matrix); # Matrix3D retrievedMatrix; # buffer.GetData(out retrievedMatrix, 0, Utilities.SizeOf<Matrix3D>()); # // Assert. # Assert.That(retrievedMatrix, Is.EqualTo(matrix)); # }<file_sep>describe 'Rasterizr.Pipeline.InputAssembler.InputAssemblerStage', -> InputAssembler = Rasterizr.Pipeline.InputAssembler Vector2 = Rasterizr.Math.Vector2 Vector3 = Rasterizr.Math.Vector3 describe '#setVertexBuffer and #getVertexBuffers', -> it 'binds single vertex buffer', -> # Arrange. inputAssembler = new InputAssembler.InputAssemblerStage(null) vertices = [ new TestVertex.PositionNormalTexture(Vector3.zero, Vector3.zero, Vector2.zero), new TestVertex.PositionNormalTexture(Vector3.zero, Vector3.zero, Vector2.zero) ] vertexBuffer = new Rasterizr.Resources.Buffer(null, new Rasterizr.Resources.BufferDescription( TestVertex.PositionNormalTexture.sizeInBytes * 2, Rasterizr.Resources.BindFlags.vertexBuffer ), vertices) # Act. inputAssembler.setVertexBuffers(0, new InputAssembler.VertexBufferBinding(vertexBuffer, 0, TestVertex.PositionNormalTexture.sizeInBytes)) # Assert. vertexBufferBindings = new Array(1) inputAssembler.getVertexBuffers(0, 1, vertexBufferBindings) expect(vertexBufferBindings[0].buffer).toEqual(vertexBuffer) it 'binds multiple vertex buffers', -> # Arrange. inputAssembler = new InputAssembler.InputAssemblerStage(null) vertices = [ new TestVertex.PositionNormalTexture(Vector3.zero, Vector3.zero, Vector2.zero), new TestVertex.PositionNormalTexture(Vector3.zero, Vector3.zero, Vector2.zero) ] vertexBuffer1 = new Rasterizr.Resources.Buffer(null, new Rasterizr.Resources.BufferDescription( TestVertex.PositionNormalTexture.sizeInBytes * 2, Rasterizr.Resources.BindFlags.vertexBuffer ), vertices) vertexBuffer2 = new Rasterizr.Resources.Buffer(null, new Rasterizr.Resources.BufferDescription( TestVertex.PositionNormalTexture.sizeInBytes * 2, Rasterizr.Resources.BindFlags.vertexBuffer ), vertices) # Act. inputAssembler.setVertexBuffers(0, new InputAssembler.VertexBufferBinding(vertexBuffer1, 0, TestVertex.PositionNormalTexture.sizeInBytes), new InputAssembler.VertexBufferBinding(vertexBuffer2, 0, TestVertex.PositionNormalTexture.sizeInBytes)) # Assert. vertexBufferBindings = new Array(2) inputAssembler.getVertexBuffers(0, 2, vertexBufferBindings) expect(vertexBufferBindings[0].buffer).toEqual(vertexBuffer1) expect(vertexBufferBindings[1].buffer).toEqual(vertexBuffer2) xdescribe '#getVertexStream', -> glslSource = """ attribute vec3 aVertexPosition; void main(void) { gl_Position = vec4(0, 0, 0, 1.0); } """ it 'gets vertex stream for line list', -> # Arrange. device = new Rasterizr.Device() inputAssembler = new InputAssembler.InputAssemblerStage(device) inputSignature = GetTestVertexPositionNormalTextureShaderBytecode() inputAssembler.InputLayout = new InputAssembler.InputLayout(device, TestVertex.PositionNormalTexture.inputElements, inputSignature) inputAssembler.PrimitiveTopology = InputAssembler.PrimitiveTopology.lineList vertices = [ new TestVertex.PositionNormalTexture(new Vector3(1, 2, 3), new Vector3(3, 2, 1), new Vector2(3, 4)), new TestVertex.PositionNormalTexture(new Vector3(4, 5, 6), new Vector3(4, 6, 8), new Vector2(0.5, 0.3)) ] vertexBuffer = new Rasterizr.Resources.Buffer(device, new Rasterizr.Resources.BufferDescription( TestVertex.PositionNormalTexture.sizeInBytes * 2, BindFlags.VertexBuffer ), vertices) inputAssembler.setVertexBuffers(0, new InputAssembler.VertexBufferBinding(vertexBuffer, 0, TestVertex.PositionNormalTexture.SizeInBytes)) # Act. vertexStream = inputAssembler.getVertexStream(inputSignature, 2, 0).ToList() # Assert. expect(vertexStream).to.have.length(2) expect(vertexStream[0].instanceID).toEqual(0) expect(vertexStream[0].vertexID).toEqual(0) expect(vertexStream[0].data[0]).toEqual(new Vector4(1.0, 2.0, 3.0, 0.0)) expect(vertexStream[0].data[1]).toEqual(new Vector4(3.0, 2.0, 1.0, 0.0)) expect(vertexStream[0].data[2]).toEqual(new Vector4(3.0, 4.0, 0.0, 0.0)) expect(vertexStream[1].instanceID).toEqual(0) expect(vertexStream[1].vertexID).toEqual(1) expect(vertexStream[1].data[0]).toEqual(new Vector4(4.0, 5.0, 6.0, 0.0)) expect(vertexStream[1].data[1]).toEqual(new Vector4(4.0, 6.0, 8.0, 0.0)) expect(vertexStream[1].data[2]).toEqual(new Vector4(0.5, 0.3, 0.0, 0.0))<file_sep>namespace 'HlslJs.CodeModel.Tokens', (exports) -> exports.TokenType = new Enum([ { name: 'buffer', description: 'Buffer' }, 'bool', 'int', 'uint', 'half', 'float', 'double', 'int1', 'int2', 'int3', 'int4', 'float1', 'float2', 'float3', 'float4', 'matrix', 'int1x1', 'int1x2', 'int1x3', 'int1x4', 'int2x1', 'int2x2', 'int2x3', 'int2x4', 'int3x1', 'int3x2', 'int3x3', 'int3x4', 'int4x1', 'int4x2', 'int4x3', 'int4x4', 'float1x1', 'float1x2', 'float1x3', 'float1x4', 'float2x1', 'float2x2', 'float2x3', 'float2x4', 'float3x1', 'float3x2', 'float3x3', 'float3x4', 'float4x1', 'float4x2', 'float4x3', 'float4x4', { name: 'texture1D', description: 'Texture1D' }, { name: 'texture2D', description: 'Texture2D' }, { name: 'texture3D', description: 'Texture3D' }, { name: 'textureCube', description: 'TextureCube' }, { name: 'samplerState', description: 'SamplerState' }, 'bool', 'true', # Everything before this is a data type 'false', 'struct', 'extern', 'nointerpolation', 'shared', 'static', 'uniform', 'volatile', 'const', { name: 'rowMajor', description: 'row_major' }, { name: 'columnMajor', description: 'column_major' }, { name: 'identifier', description: 'Identifier' }, # Everything before this is a keyword { name: 'eof', description: 'EOF' }, { name: 'openSquare', description: '[' }, { name: 'closeSquare', description: ']' }, { name: 'openCurly', description: '{' }, { name: 'closeCurly', description: '}' }, { name: 'openParen', description: '(' }, { name: 'closeParen', description: ')' }, { name: 'openAngle', description: '<' }, { name: 'closeAngle', description: '>' }, { name: 'singleEquals', description: '=' }, { name: 'doubleEquals', description: '==' }, { name: 'plus', description: '+' }, { name: 'minus', description: '-' }, { name: 'asterisk', description: '*' }, { name: 'forwardSlash', description: '/' }, { name: 'comma', description: ',' }, { name: 'colon', description: ':' }, { name: 'semicolon', description: ';' }, { name: 'error', description: 'Error' }, { name: 'literal', description: 'Literal' } ])<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> exports.DepthWriteMask = zero: 0 all: 1<file_sep>namespace 'HlslJs.CodeModel', (exports) -> class exports.ParseNode <file_sep>namespace 'HlslJs.CodeModel.Declarations', (exports) -> exports.VariableStorageClasses = none: 0 extern: 1 nointerpolation: 2 shared: 4 static: 8 uniform: 16 volatile: 32<file_sep>namespace 'HlslJs.Parser', (exports) -> TokenType = HlslJs.CodeModel.Tokens.TokenType keywordMappings = {} for name, value in TokenType.values description = TokenType.getDescription(value) keywordMappings[description] = value exports.Keywords = isKeyword: (value) -> keywordMappings.hasOwnProperty(value) getKeywordType: (value) -> keywordMappings[value]<file_sep>namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> class exports.DepthStencilState extends Rasterizr.DeviceChild constructor: (device, @description) -> super(device) depthTestPasses: (newDepth, currentDepth) => return true unless @description.isDepthEnabled Rasterizr.Comparison.doComparison( @description.depthComparison, newDepth, currentDepth)<file_sep>#= require ./render_target_blend_description namespace 'Rasterizr.Pipeline.OutputMerger', (exports) -> OutputMerger = Rasterizr.Pipeline.OutputMerger class exports.BlendStateDescription @default: new BlendStateDescription(false, OutputMerger.BlendOption.one, OutputMerger.BlendOption.zero) # A built-in state object with settings for additive blend, that is adding # the destination data to the source data without using alpha. @additive: new BlendStateDescription(true, OutputMerger.BlendOption.sourceAlpha, OutputMerger.BlendOption.one) # A built-in state object with settings for alpha blend, that is blending # the source and destination data using alpha. @alphaBlend: new BlendStateDescription(true, OutputMerger.BlendOption.one, OutputMerger.BlendOption.inverseSourceAlpha) # A built-in state object with settings for opaque blend, that is # overwriting the source with the destination data. @opaque: new BlendStateDescription(true, OutputMerger.BlendOption.one, OutputMerger.BlendOption.zero) # A built-in state object with settings for blending with non-premultipled # alpha, that is blending source and destination data using alpha while # assuming the color data contains no alpha information. @nonPremultiplied: new BlendStateDescription(true, OutputMerger.BlendOption.sourceAlpha, OutputMerger.BlendOption.inverseSourceAlpha) alphaToCoverageEnable: true independentBlendEnable: true constructor: (isBlendEnabled, sourceBlend, destinationBlend) -> blendOperation = OutputMerger.BlendOperation.add @renderTargets = [ new OutputMerger.RenderTargetBlendDescription( isBlendEnabled, sourceBlend, destinationBlend, blendOperation, sourceBlend, destinationBlend, blendOperation ) ]<file_sep>namespace 'Rasterizr.Pipeline.VertexShader', (exports) -> class exports.VertexShader constructor: (device, shaderBytecode) -> super(device, shaderBytecode)<file_sep>window.namespace = (name, block) -> target = window top = target target = target[item] ||= {} for item in name.split '.' block target, top<file_sep>describe 'Rasterizr.Pipeline.OutputMerger.DepthStencilState', -> describe '#depthTestPasses', -> OutputMerger = Rasterizr.Pipeline.OutputMerger depthStencilState = new OutputMerger.DepthStencilState(null, OutputMerger.DepthStencilStateDescription.default) it 'returns true if new depth < current depth', -> expect(depthStencilState.depthTestPasses(0.3, 0.5)).toBe(true) it 'returns false if new depth >= current depth', -> expect(depthStencilState.depthTestPasses(0.5, 0.5)).toBe(false) expect(depthStencilState.depthTestPasses(0.7, 0.5)).toBe(false)<file_sep>class window.Enum constructor: (@values) -> for name, value in values actualName = name.name || name this[actualName] = value getName: (value) => @values[value].name || @values[value] getDescription: (value) => @values[value].description || @getName(value)
267f0f49bd327b5dd15d11d25c87f7d12380875d
[ "CoffeeScript", "Markdown", "Ruby" ]
70
CoffeeScript
tgjones/rasterizrjs
77050eef444fa1ed2662c62e1e728df5b02a466d
33127571ccedabe742ad4a6145250498a6d1af4a
refs/heads/main
<repo_name>msastreharo/Balance-server<file_sep>/routes/auth.js const router = require("express").Router(); // ℹ️ Handles password encryption const bcrypt = require("bcryptjs"); const mongoose = require("mongoose"); // How many rounds should bcrypt run the salt (default [10 - 12 rounds]) const saltRounds = 10; // Require the User model in order to interact with the database const User = require("../models/User.model"); const Session = require("../models/Session.model"); const Day = require("../models/Day.model"); // Require necessary middlewares in order to control access to specific routes const shouldNotBeLoggedIn = require("../middlewares/shouldNotBeLoggedIn"); const isLoggedIn = require("../middlewares/isLoggedIn"); router.get("/session", (req, res) => { // we dont want to throw an error, and just maintain the user as null if (!req.headers.authorization) { return res.json(null); } // accessToken is being sent on every request in the headers const accessToken = req.headers.authorization; Session.findById(accessToken) .populate("user") .then((session) => { if (!session) { return res.status(404).json({ errorMessage: "Session does not exist" }); } return res.status(200).json(session); }); }); router.post("/signup", shouldNotBeLoggedIn, (req, res) => { const { username, password, email } = req.body; if (!username) { return res .status(400) .json({ errorMessage: "Please provide your username." }); } if (password.length < 8) { return res.status(400).json({ errorMessage: "Your password needs to be at least 8 characters long.", }); } // Search the database for a user with the username submitted in the form User.findOne({ username }).then((found) => { // If the user is found, send the message username is taken if (found) { return res.status(400).json({ errorMessage: "Username already taken." }); } // if user is not found, create a new user - start with hashing the password return bcrypt .genSalt(saltRounds) .then((salt) => bcrypt.hash(password, salt)) .then((hashedPassword) => { // Create a user and save it in the database return User.create({ username, email, password: <PASSWORD>Password, }); }) .then((user) => { Session.create({ user: user._id, createdAt: Date.now(), }).then((session) => { res.status(201).json({ user, accessToken: session._id }); }); }) .catch((error) => { if (error instanceof mongoose.Error.ValidationError) { return res.status(400).json({ errorMessage: error.message }); } if (error.code === 11000) { return res.status(400).json({ errorMessage: "Username need to be unique. The username you chose is already in use.", }); } return res.status(500).json({ errorMessage: error.message }); }); }); }); router.post("/login", shouldNotBeLoggedIn, (req, res, next) => { const { username, password } = req.body; if (!username) { return res .status(400) .json({ errorMessage: "Please provide your username." }); } // Here we use the same logic as above // - either length based parameters or we check the strength of a password if (password.length < 8) { return res.status(400).json({ errorMessage: "Your password needs to be at least 8 characters long.", }); } // Search the database for a user with the username submitted in the form User.findOne({ username }) .then((user) => { // If the user isn't found, send the message that user provided wrong credentials if (!user) { return res.status(400).json({ errorMessage: "Wrong credentials." }); } // If user is found based on the username, check if the in putted password matches the one saved in the database bcrypt.compare(password, user.password).then((isSamePassword) => { if (!isSamePassword) { return res.status(400).json({ errorMessage: "Wrong credentials." }); } Session.create({ user: user._id, createdAt: Date.now() }).then( (session) => { return res.json({ user, accessToken: session._id }); } ); }); }) .catch((err) => { // in this case we are sending the error handling to the error handling middleware that is defined in the error handling file // you can just as easily run the res.status that is commented out below next(err); // return res.status(500).render("login", { errorMessage: err.message }); }); }); router.delete("/logout", isLoggedIn, (req, res) => { Session.findByIdAndDelete(req.headers.authorization) .then(() => { res.status(200).json({ message: "User was logged out" }); }) .catch((err) => { console.log(err); res.status(500).json({ errorMessage: err.message }); }); }); router.post("/upload", isLoggedIn, (req, res) => { // console.log("HEADERS", req); const { work, sleep, chores, leisure, selfCare, mood, day, month } = req.body; if (+work + +sleep + +chores + +leisure + +selfCare > 24) { return res .status(400) .json({ errorMessage: "Theres Not That Many Hours In The Day!" }); } if (+work + +sleep + +chores + +leisure + +selfCare < 24) { return res.status(400).json({ errorMessage: "Please fill in the information for all the hours in the day", }); } Day.create({ work, sleep, chores, leisure, selfCare, mood, day, month, user: req.user._id, }).then((newDay) => { // console.log("new day post", newDay); res.json({ newDay }); }); }); // Get the daily report (display) router.get("/daily-report", isLoggedIn, (req, res) => { Day.find({ user: req.user._id }) .sort({ _id: -1 }) .then((allDays) => { res.json(allDays); }); }); // Single day get router.get("/:id", (req, res) => { Day.findById(req.params.id) .then((singleDay) => { res.json(singleDay); }) .catch((err) => console.log(err)); }); // Edit single day router.put("/:id", isLoggedIn, (req, res) => { Day.findByIdAndUpdate(req.params.id, req.body, { new: true }).then( (dayUpdated) => { res.json({ message: "okidok", dayUpdated }); } ); }); // Delete single day router.delete("/delete/:id", isLoggedIn, (req, res) => { const { id } = req.params; Day.findByIdAndDelete(id).then((deletedDay) => { console.log(deletedDay); res.json(deletedDay); }); // console.log("dayId: ", dayId); /* Day.findByIdAndDelete(dayId, () => { console.log("Day deleted"); }).then((deletedDay) => { console.log(deletedDay); res.redirect("/Daily-Report"); }); */ }); // Missing some logic in services/auth ??? router.delete("/account", isLoggedIn, (req, res) => { User.findByIdAndDelete(req.user._id).then((data) => res.json(true)); }); module.exports = router;
bb8ce5de1e2b6c34b41edbb6af5f725c8eee08e4
[ "JavaScript" ]
1
JavaScript
msastreharo/Balance-server
edb315bb092732e6770196b61257e872c4a4e968
1e67fc56731bb42ab1b89d8567c6d2dde34b93f7
refs/heads/master
<repo_name>BjornHofsvang/jokul<file_sep>/packages/icons/CHANGELOG.md # Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## 1.2.0 (2021-03-25) ### Features - **icons:** add title and desc as props ([3ed96e6](https://github.com/fremtind/jokul/commit/3ed96e65072b65bc18cd17011c0dbed590a3b35e)), closes [#1811](https://github.com/fremtind/jokul/issues/1811) ## 1.1.0 (2020-08-13) ### Features - add icons package ([24c9748](https://github.com/fremtind/jokul/commit/24c974803b7d705d8a22cec719dbf3873373781f)) <file_sep>/packages/icons-react/CHANGELOG.md # Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. ## 1.4.0 (2021-03-25) ### Bug Fixes - **icons:** use explicit props ([ba0fc21](https://github.com/fremtind/jokul/commit/ba0fc21c7db0d3aebab69c9fa44e7610c77da07c)) ### Features - **icons:** add title and desc as props ([3ed96e6](https://github.com/fremtind/jokul/commit/3ed96e65072b65bc18cd17011c0dbed590a3b35e)), closes [#1811](https://github.com/fremtind/jokul/issues/1811) ## 1.3.5 (2021-02-12) ### Bug Fixes - add react 17 types as valid peerdep ([a074c34](https://github.com/fremtind/jokul/commit/a074c34dcece089ad6b4c581b8c920c8bdd4f1e0)) ## 1.3.0 (2020-12-15) ### Features - display types in portal ([5c62a16](https://github.com/fremtind/jokul/commit/5c62a161c278d3a5a136741aea8dcf9b62338bda)) ## 1.2.0 (2020-11-25) ### Features - update to react 17 ([4639058](https://github.com/fremtind/jokul/commit/4639058067eaa9be222825f8ac4f495a1e74cc0f)) ## 1.1.0 (2020-08-13) ### Features - add icons package ([24c9748](https://github.com/fremtind/jokul/commit/24c974803b7d705d8a22cec719dbf3873373781f))
8f98ff870bf110bb827f68a78de6c919e79433d1
[ "Markdown" ]
2
Markdown
BjornHofsvang/jokul
bca91f7d70be9ed5ee0fc27750d1e2a27893af8d
a467c90e39c50851c677d80cf1853ac149340a97
refs/heads/master
<repo_name>metiscus/KSP_RadarAltimeter<file_sep>/README.md # KSP_RadarAltimeter This is a Kerbal Space Program mod that provides a radar altimeter for use in game. To build it from scratch, you will need MonoDevelop or VisualStudio. http://wiki.kerbalspaceprogram.com/wiki/Setting_up_MonoDevelop http://wiki.kerbalspaceprogram.com/wiki/Setting_up_Visual_Studio Follow the steps from those links and add the source from the source directory of this project to produce an updated binary. <file_sep>/source/RadarAltitude.cs using System; using UnityEngine; namespace KSP_RALT { public class RadarAltitude : PartModule { private Rect windowPos; private double altitude; private double altitudeMax; private bool initialized; private void WindowGUI(int windowID) { GUIStyle mySty = new GUIStyle(GUI.skin.button); mySty.normal.textColor = mySty.focused.textColor = Color.white; mySty.padding = new RectOffset(8, 8, 8, 8); GUILayout.BeginHorizontal(); int meterAlt = (int)Math.Truncate(altitude); String text; if (altitude > altitudeMax) text = "Radar Altitude: MAX"; else text = "Radar Altitude: " + meterAlt; if (!this.isEnabled) text = " Disabled "; if (GUILayout.Button (text, mySty, GUILayout.ExpandWidth (true))) { this.isEnabled = !this.isEnabled; var generator = base.GetComponent<ModuleGenerator> (); if (!isEnabled) generator.Shutdown (); else generator.Activate (); } GUILayout.EndHorizontal(); //DragWindow makes the window draggable. The Rect specifies which part of the window it can by dragged by, and is //clipped to the actual boundary of the window. You can also pass no argument at all and then the window can by //dragged by any part of it. Make sure the DragWindow command is AFTER all your other GUI input stuff, or else //it may "cover up" your controls and make them stop responding to the mouse. GUI.DragWindow(new Rect(0, 0, 10000, 20)); } private void drawGUI() { GUI.skin = HighLogic.Skin; windowPos = GUILayout.Window(1, windowPos, WindowGUI, "Radar Altitude", GUILayout.MinWidth(180)); } public override void OnStart(StartState state) { altitudeMax = 800.0; altitude = 0.0; base.OnStart (state); if (!initialized) { initialized = true; this.isEnabled = false; var generator = base.GetComponent<ModuleGenerator> (); generator.Shutdown (); } if (state != StartState.Editor) { if ((windowPos.x == 0) && (windowPos.y == 0)) {//windowPos is used to position the GUI window, lets set it in the center of the screen windowPos = new Rect (Screen.width / 2, Screen.height / 2, 10, 10); } RenderingManager.AddToPostDrawQueue (3, new Callback (drawGUI));//start the GUI } } public override void OnFixedUpdate() { base.OnFixedUpdate (); altitude = (double)vessel.heightFromTerrain; if (altitude < 0.0) { altitude *= -1.0; } } } }
bf50e12946e4fe246bd87c51d1d5cd318e378b55
[ "C#", "Markdown" ]
2
C#
metiscus/KSP_RadarAltimeter
46684a09186db82ea676b17e6a64e9a718cc19df
9d8e91358a5eee1d27fdf9caa374199066b02358
refs/heads/main
<repo_name>Anshuman-K/UNIT-3-Assignements<file_sep>/02.09.2021/Youtube 1/script.js var count = 0; let maindiv = document.getElementById("content-box"); async function SearchVideos(){ if(count>0){ remove_predata(); } let inputB = document.getElementById("searchbox").value; let res = await fetch(`https://youtube.googleapis.com/youtube/v3/search?q=${inputB}&type=Video&key=<KEY>&maxResults=20`); let data = await res.json(); console.log('data:', data); for({id: { videoId }} of data.items){ console.log('videoId:', videoId) let innerdiv = document.createElement("div"); innerdiv.setAttribute("class","innerdiv"); let video_frame = document.createElement("iframe"); video_frame.src = `https://www.youtube.com/embed/${videoId}`; video_frame.allow = `fullscreen`; innerdiv.appendChild(video_frame); maindiv.append(innerdiv); } document.getElementById("searchbox").value = ""; count++; } function remove_predata(){ let video_frame = document.querySelectorAll("#content-box>div") console.log('video_frame:', video_frame) for(var i = 0; i< video_frame.length; i++){ video_frame[i].remove(); } }<file_sep>/04.09.2021/Components/navbar.js function navbar(){ return ` <ul> <li><a class="active" href="index.html">Home</a></li> <li><a href="ROD.html">Recipe Of Day</a></li> <li><a href="TR.html">Trending Recipe</a></li> </ul> `; } export default navbar;
6adc58049ac17c6765fa41aa1cc13493e2a32029
[ "JavaScript" ]
2
JavaScript
Anshuman-K/UNIT-3-Assignements
6fc622b951b1f17407535b8b1a41b84844f0cf5a
621f007862ea69565c1ba12d7bdda567bda7eb09
refs/heads/main
<repo_name>Clumsynite/send-mail<file_sep>/controllers/v2.js const { transporter } = require("../config/mail"); const template = require("../templates/v2"); exports.sendMail = async (req, res) => { try { const { name, email, message, website, dark } = req.body; const { content, selfHTML, userHTML } = template( name, email, message, website, dark ); if (!name || !email || !website || !message) return res.json({ err: true, msg: "Error sending mail", userHTML }); const mail = { from: name, to: "<EMAIL>", subject: `New Message from Contact Form By ${name} @ ${new Date().toISOString()}`, text: content, html: selfHTML, }; return transporter.sendMail(mail, (err) => { if (err) { return res.json({ status: "fail", err: true, msg: "fail", }); } transporter.sendMail( { from: "<EMAIL>", to: email, subject: `${name}'s Submission was successful @ ${new Date().toISOString()}`, text: `Thank you for contacting me!\n\nForm details\nName: ${name}\nEmail: ${email}\nMessage: ${message}\n\nI'll try to get back to you ASAP.\n\n- Clumsyknight`, html: userHTML, }, (error, info) => { if (error) { return res.json({ err: true, msg: `Error sending mail: {error}`, }); } return res.json({ err: false, msg: `Message sent: ${info.response}`, }); } ); return res.json({ status: "success", err: false, msg: "success", }); }); } catch (error) { return res.json({ err: true, msg: "Failed to send mail", error }); } }; <file_sep>/config/mail.js /* eslint-disable no-console */ require("dotenv").config(); const nodemailer = require("nodemailer"); const transport = { host: "smtp.gmail.com", port: 465, secure: true, auth: { user: process.env.USER, pass: process.env.PASS, }, }; const transporter = nodemailer.createTransport(transport); exports.transporter = transporter; transporter.verify((error, success) => { if (error) { console.log("Error authenticating:", error); } else { console.log("Server is ready to take messages", success); } }); <file_sep>/README.md # send-mail API built using Nodemailer to send emails. Built for contact forms. <file_sep>/templates/v1.js const template = (name, email, message, website) => { const content = `name: ${name}\n email: ${email}\n message: ${message} `; const colors = { heading: "cyan", signature: "#4dff79", link: "#00ffbf", text: "aquamarine", info: "#42babd", }; const fonts = { text: "16px", signature: "19px", info: "12px" }; const selfHTML = ` <body style="background-color: black; padding: 10px;"> <h1 style="width: 100%; text-align: center; color:${colors.heading};"> New Email from <a href="${website}" target="_blank" title=${website} style="color: ${colors.link}; text-decoration: none;"> here</a> </h1> <p style="color: ${colors.text}; font-size: ${fonts.text}"><b>Name: </b> ${name}</p> <p style="color: ${colors.text}; font-size: ${fonts.text}"><b>Email: </b><span style="color: ${colors.link}; text-decoration: none;">${email}</span></p> <p style="color: ${colors.text}; font-size: ${fonts.text};white-space: pre;"><b>Message: </b> ${message}</p> </body>`; const userHTML = ` <div style="padding: 20px;background-color: black;"> <h1 style="width: 100%; text-align: center; color:${colors.heading}; margin-bottom: 5px;">Thank you for contacting me!</h1> <div style="margin-top: 30px;"> <h2 style="color: azure;">Form Details: </h2> <p style="color: ${colors.text}; font-size: ${fonts.text}"><b>Name: </b> ${name}</p> <p style="color: ${colors.text}; font-size: ${fonts.text}"><b>Email: </b><span style="color: ${colors.link}; text-decoration: none;">${email}</span></p> <p style="color: ${colors.text}; font-size: ${fonts.text};white-space: pre;"><b>Message: </b> ${message}</p> <p style="color: ${colors.signature}; font-size: ${fonts.signature}; width: 100%; text-align: right">I'll try to get back to you ASAP<br/> - <em><NAME></em></p> </div> <div style="color:${colors.info}; font-size: ${fonts.info}; width: 100%; text-align: center; margin-top: 40px;"> I apologise If you haven't filled any form and yet received this email.<br/> There might be someone else who has used your email (by mistake). <p> Form address: <a href="${website}" target="_blank" title="Email has sent after filling this form"style=" color: ${colors.link}; text-decoration: none;"> ${website}</a> </p> </div> </div>`; return { content, selfHTML, userHTML }; }; module.exports = template;
6d3c5ffa8eede6e2bf284ace40ac0217d4446fd3
[ "Markdown", "JavaScript" ]
4
Markdown
Clumsynite/send-mail
f6eed533639420e3e307ba3da67325ffefda28ca
2432de8aaf3464056da295f40d4016ea2a6166f8
refs/heads/main
<file_sep># doodle-plateado practica de modelo vista controlador
46cb3b652fdb28aa562cfff72b686983c1eec103
[ "Markdown" ]
1
Markdown
LizethMendieta/doodle-plateado
b17c43ed2c762dfe2f31050c9fcf7435b40ea06c
4c2dd2f4b821b7513375f31ef11f444379f8af7b
refs/heads/master
<file_sep># Microsoft Python Language Server Microsoft Python Language Server implements [Language Server Protocol](https://microsoft.github.io/language-server-protocol/specification). Primary clients are [Python Extension to VS Code](https://github.com/Microsoft/vscode-python) and [Python Tools for Visual Studio](https://github.com/Microsoft/PTVS). Feel free to file issues or ask questions on our [issue tracker](https://github.com/Microsoft/python-language-server/issues), and we welcome code contributions. #<b>The Microsoft Python Language Server can be used with Sublime Text!!</b> Basic Prerequisites are * A build of MPLS *Sublime Text *LSP Plugin(https://github.com/tomv564/LSP) For more information, please see Using_in_sublime_text.md
cae12b06fe810affd1005efff8a183ad52e78f2f
[ "Markdown" ]
1
Markdown
abhi211199/python-language-server
91bc0f73c5e39725f084662ed438587c7a690779
6bb25c0a5f1590f8fbb019a9f3b4c62835df8e0e
refs/heads/master
<repo_name>bubdm/HtmlUi<file_sep>/src/Samotorcan.HtmlUi.Core/BaseApplicationSettings.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Base application settings. /// </summary> public class BaseApplicationSettings { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BaseApplicationSettings"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public BaseApplicationSettings() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="BaseApplicationSettings"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public BaseApplicationSettings(BaseApplicationSettings settings) { Initialize(settings); } #endregion #region Methods #region Private /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "settings", Justification = "Might have additional code in the future.")] private void InitializeSelf(BaseApplicationSettings settings) { } #endregion #region Protected #region Initialize /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected virtual void Initialize(BaseApplicationSettings settings) { InitializeSelf(settings); } /// <summary> /// Initializes this instance. /// </summary> protected virtual void Initialize() { Initialize(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.Tests.Application/Program.cs using Samotorcan.HtmlUi.Core; namespace Samotorcan.Tests.Application { class Program { static void Main(string[] args) { if (HtmlUiRuntime.ApplicationType == ApplicationType.ChildApplication) { HtmlUi.Windows.ChildApplication.Run(); return; } var settings = new HtmlUi.Windows.ApplicationContext(); settings.CommandLineArgsEnabled = true; settings.ChromeViewsEnabled = true; settings.WindowSettings.View = "chrome://about"; HtmlUi.Windows.Application.Run(settings); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/UriUtility.cs using System; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Uri utility. /// </summary> public static class UriUtility { #region Methods #region Public #region IsAbsoluteUri /// <summary> /// Determines whether value is absolute URI. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static bool IsAbsoluteUri(string value) { Uri uri; return Uri.TryCreate(value, UriKind.Absolute, out uri); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.Tests/AllTests.cs using NUnit.Framework; using Samotorcan.Tests.Core; namespace Samotorcan.Tests { /// <summary> /// All tests. /// </summary> [TestFixture] public class AllTests : BaseUnitTest { #region Properties #region Protected #region ApplicationName /// <summary> /// Gets the name of the application. /// </summary> /// <value> /// The name of the application. /// </value> protected override string ApplicationName { get { return "Samotorcan.Tests.Application.exe"; } } #endregion #endregion #endregion #region Tests #region ControllerConstructorTest /// <summary> /// Controller constructor test. /// </summary> [Test] public void ControllerConstructorTest() { Driver.Url = "http://localhost/Views/ControllerConstructorTest.html"; Assert.IsTrue(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "voidNoArguments")); Assert.IsTrue(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "voidArguments")); Assert.IsTrue(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "returnNoArguments")); Assert.IsTrue(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "returnArguments")); Assert.IsFalse(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "privateMethod")); Assert.IsFalse(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "protectedMethod")); Assert.IsFalse(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "overloaded")); Assert.IsFalse(TestUtility.FactoryHasFunction(Driver, "ControllerConstructorTest", "genericMethod")); } #endregion #endregion } } <file_sep>/src/Samotorcan.Tests.Core/TestUtility.cs using OpenQA.Selenium.Chrome; using System; using System.IO; using System.Reflection; namespace Samotorcan.Tests.Core { /// <summary> /// Test utility. /// </summary> public static class TestUtility { #region Properties #region Public #region AssemblyDirectory /// <summary> /// Gets the assembly directory. /// </summary> /// <value> /// The assembly directory. /// </value> public static string AssemblyDirectory { get { return Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).Replace('\\', '/'); } } #endregion #endregion #endregion #region Methods #region Public #region CreateDriverService /// <summary> /// Creates the driver service. /// </summary> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It's returned.")] public static ChromeDriverService CreateDriverService() { var driverService = ChromeDriverService.CreateDefaultService(AssemblyDirectory, "chromedriver.exe"); driverService.Port = 21480; driverService.LogPath = AssemblyDirectory + "/chromedriver.log"; driverService.EnableVerboseLogging = true; driverService.HideCommandPromptWindow = true; driverService.Start(); return driverService; } #endregion #region CreateDriver /// <summary> /// Creates the driver. /// </summary> /// <param name="driverService">The driver service.</param> /// <param name="applicationName">Name of the application.</param> /// <returns></returns> public static ChromeDriver CreateDriver(ChromeDriverService driverService, string applicationName) { return new ChromeDriver(driverService, new ChromeOptions { BinaryLocation = AssemblyDirectory + "/" + applicationName }); } #endregion #region FactoryHasFunction /// <summary> /// Factorie has function. /// </summary> /// <param name="driver">The driver.</param> /// <param name="factory">The factory.</param> /// <param name="function">The function.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "ChromeDriver is better.")] public static bool FactoryHasFunction(ChromeDriver driver, string factory, string function) { if (driver == null) throw new ArgumentNullException("driver"); return (bool)driver.ExecuteScript(string.Format(@" try {{ var factory = angular.element(document.body).injector().get('{0}'); return angular.isFunction(factory['{1}']); }} catch (err) {{ return false; }} ", factory, function)); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Windows/ChildApplicationContext.cs using Samotorcan.HtmlUi.Core; namespace Samotorcan.HtmlUi.Windows { /// <summary> /// Windows child application context. /// </summary> public class ChildApplicationContext : WindowsForms.ChildApplicationContext { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChildApplicationContext"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ChildApplicationContext() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="ChildApplicationContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ChildApplicationContext(ChildApplicationContext settings) { Initialize(settings); } /// <summary> /// Initializes a new instance of the <see cref="ApplicationContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ChildApplicationContext(Core.ChildApplicationContext settings) { if (settings != null) { var windowsChildApplicationSettings = settings as ChildApplicationContext; if (windowsChildApplicationSettings != null) { Initialize(windowsChildApplicationSettings); } else { var windowsFormsChildApplicationSettings = settings as WindowsForms.ChildApplicationContext; if (windowsFormsChildApplicationSettings != null) Initialize(windowsFormsChildApplicationSettings); else Initialize(settings); } } else { Initialize(); } } #endregion #region Methods #region Private #region InitializeSelf /// <summary> /// Initializes this instance. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "settings", Justification = "Might have additional code in the future.")] private void InitializeSelf(ChildApplicationContext settings) { } #endregion #endregion #region Protected #region Initialize /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected virtual void Initialize(ChildApplicationContext settings) { base.Initialize(settings); InitializeSelf(settings); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(BaseApplicationSettings settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(Core.ChildApplicationContext settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(WindowsForms.ChildApplicationContext settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> protected override void Initialize() { Initialize(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerDescription.cs using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller description. /// </summary> internal class ControllerDescription { #region Properties #region Public #region Id /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public int Id { get; set; } #endregion #region Name /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } #endregion #region Methods /// <summary> /// Gets or sets the methods. /// </summary> /// <value> /// The methods. /// </value> public List<ControllerMethodDescription> Methods { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ControllerDescription"/> class. /// </summary> public ControllerDescription() { Methods = new List<ControllerMethodDescription>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/ExceptionUtility.cs using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Logs; using System; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Exception utility. /// </summary> internal static class ExceptionUtility { #region Methods #region Public #region CreateJavascriptException /// <summary> /// Creates the javascript exception. /// </summary> /// <param name="e">The e.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">e</exception> public static JavascriptException CreateJavascriptException(Exception e) { if (e == null) throw new ArgumentNullException("e"); // squash aggregate exception var aggregateException = e as AggregateException; if (aggregateException != null) { if (aggregateException.InnerExceptions.Count == 1) return CreateJavascriptException(aggregateException.InnerExceptions[0]); } // native exception var nativeException = e as INativeException; if (nativeException != null) return nativeException.ToJavascriptException(); // normal exception return new JavascriptException { Type = "Exception", Message = e.Message, InnerException = e.InnerException != null ? CreateJavascriptException(e.InnerException) : null }; } #endregion #region LogException /// <summary> /// Logs the exception. /// </summary> /// <typeparam name="TReturn">The type of the return.</typeparam> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">action</exception> public static TReturn LogException<TReturn>(Func<TReturn> action) { if (action == null) throw new ArgumentNullException("action"); try { return action(); } catch (Exception e) { Logger.Error("Unhandled exception", e); throw; } } /// <summary> /// Logs the exception. /// </summary> /// <param name="action">The action.</param> /// <exception cref="System.ArgumentNullException">action</exception> public static void LogException(Action action) { if (action == null) throw new ArgumentNullException("action"); ExceptionUtility.LogException<object>(() => { action(); return null; }); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/AttributeUtility.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Samotorcan.HtmlUi.Core.Utilities { internal static class AttributeUtility { public static Dictionary<string, TDelegate> GetMethods<TType, TAttribute, TDelegate>(TType obj, BindingFlags flags) where TDelegate : class where TAttribute : Attribute { if (obj == null) throw new ArgumentNullException("obj"); return typeof(TType).GetMethods(flags) .Where(m => m.GetCustomAttribute<TAttribute>() != null) .ToDictionary(m => m.Name, m => m.IsStatic ? (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), m) : (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), obj, m)); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/SourceMap.cs using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// SourceMap /// </summary> internal class SourceMap { #region Properties #region Public #region Version /// <summary> /// Gets or sets the version. /// </summary> /// <value> /// The version. /// </value> public int Version { get; set; } #endregion #region File /// <summary> /// Gets or sets the file. /// </summary> /// <value> /// The file. /// </value> public string File { get; set; } #endregion #region SourceRoot /// <summary> /// Gets or sets the source root. /// </summary> /// <value> /// The source root. /// </value> public string SourceRoot { get; set; } #endregion #region sources /// <summary> /// Gets or sets the sources. /// </summary> /// <value> /// The sources. /// </value> public List<string> sources { get; set; } #endregion #region SourcesContent /// <summary> /// Gets or sets the content of the sources. /// </summary> /// <value> /// The content of the sources. /// </value> public List<string> SourcesContent { get; set; } #endregion #region Names /// <summary> /// Gets or sets the names. /// </summary> /// <value> /// The names. /// </value> public List<string> Names { get; set; } #endregion #region Mappings /// <summary> /// Gets or sets the mappings. /// </summary> /// <value> /// The mappings. /// </value> public string Mappings { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Application.cs using Samotorcan.HtmlUi.Core.Logs; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xilium.CefGlue; using System.Threading; using Samotorcan.HtmlUi.Core.Utilities; using System.Collections.Concurrent; using System.Text.RegularExpressions; using Newtonsoft.Json; using Samotorcan.HtmlUi.Core.Browser; using Samotorcan.HtmlUi.Core.Providers; using Samotorcan.HtmlUi.Core.Messages; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Application. /// </summary> [CLSCompliant(false)] public abstract class Application : BaseApplication { #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static new Application Current { get { return (Application)BaseApplication.Current; } } #endregion #region Window /// <summary> /// Gets or sets the window. /// </summary> /// <value> /// The window. /// </value> public Window Window { get; protected set; } #endregion #region D3D11Enabled /// <summary> /// Gets a value indicating whether D3D11 is enabled. /// </summary> /// <value> /// <c>true</c> if D3D11 is enabled; otherwise, <c>false</c>. /// </value> public bool D3D11Enabled { get; private set; } #endregion #region ContentProvider private IContentProvider _contentProvider; /// <summary> /// Gets or sets the content provider. /// </summary> /// <value> /// The content provider. /// </value> public IContentProvider ContentProvider { get { return _contentProvider; } set { EnsureMainThread(); _contentProvider = value; } } #endregion #region ControllerProvider private IControllerProvider _controllerProvider; /// <summary> /// Gets or sets the controller provider. /// </summary> /// <value> /// The controller provider. /// </value> public IControllerProvider ControllerProvider { get { return _controllerProvider; } set { EnsureMainThread(); _controllerProvider = value; } } #endregion #region MimeTypes /// <summary> /// Gets the MIME types. /// </summary> /// <value> /// The MIME types. /// </value> public Dictionary<string, string> MimeTypes { get; private set; } #endregion #region SyncMaxDepth /// <summary> /// Gets or sets the synchronize maximum depth. /// </summary> /// <value> /// The synchronize maximum depth. /// </value> public int SyncMaxDepth { get; set; } #endregion #region RemoteDebuggingPort /// <summary> /// Gets the remote debugging port. /// </summary> /// <value> /// The remote debugging port. /// </value> public int RemoteDebuggingPort { get; private set; } #endregion #region CommandLineArgsEnabled /// <summary> /// Gets or sets a value indicating whether command line arguments are enabled. /// </summary> /// <value> /// <c>true</c> if command line arguments are enabled; otherwise, <c>false</c>. /// </value> public bool CommandLineArgsEnabled { get; private set; } #endregion #region ChromeViewsEnabled /// <summary> /// Gets or sets a value indicating whether chrome views are enabled. /// </summary> /// <value> /// <c>true</c> if chrome views are enabled; otherwise, <c>false</c>. /// </value> public bool ChromeViewsEnabled { get; set; } #endregion #endregion #region Internal #region IsCefThread /// <summary> /// Gets a value indicating whether this instance is cef thread. /// </summary> /// <value> /// <c>true</c> if this instance is cef thread; otherwise, <c>false</c>. /// </value> internal bool IsCefThread { get { return IsMultiThreadedMessageLoop ? IsMainThread : CefThread != null ? CefThread.ManagedThreadId == Thread.CurrentThread.ManagedThreadId : false; } } #endregion #region IsMultiThreadedMessageLoop /// <summary> /// Gets a value indicating whether this instance is multi threaded message loop. /// </summary> /// <value> /// <c>true</c> if this instance is multi threaded message loop; otherwise, <c>false</c>. /// </value> internal bool IsMultiThreadedMessageLoop { get { return HtmlUiRuntime.Platform == Platform.Windows; } } #endregion internal readonly object SyncPropertiesLock = new object(); internal bool RenderProcessThreadCreated { get; set; } #endregion #region Private #region InvokeQueue /// <summary> /// Gets or sets the invoke queue. /// </summary> /// <value> /// The invoke queue. /// </value> private BlockingCollection<Action> InvokeQueue { get; set; } #endregion #region ExitException /// <summary> /// Gets or sets the exit exception. /// </summary> /// <value> /// The exit exception. /// </value> private Exception ExitException { get; set; } #endregion #region CefThread /// <summary> /// Gets or sets the cef thread. /// </summary> /// <value> /// The cef thread. /// </value> private Thread CefThread { get; set; } #endregion #region SingleThreadedMessageLoopStoped /// <summary> /// Gets or sets the single threaded message loop stoped. /// </summary> /// <value> /// The single threaded message loop stoped. /// </value> private AutoResetEvent SingleThreadedMessageLoopStoped { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Application"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <exception cref="System.InvalidOperationException">Application must be run on main application process.</exception> protected Application(ApplicationContext settings) : base(settings) { if (HtmlUiRuntime.ApplicationType != ApplicationType.Application) throw new InvalidOperationException("Application must be run on main application process."); SynchronizationContext.SetSynchronizationContext(new HtmlUiSynchronizationContext()); InitializeInvokeQueue(); ContentProvider = new FileAssemblyContentProvider(); ControllerProvider = new AssemblyControllerProvider(); RequestHostname = "localhost"; NativeRequestPort = 16556; D3D11Enabled = settings.D3D11Enabled; RemoteDebuggingPort = settings.RemoteDebuggingPort ?? 0; CommandLineArgsEnabled = settings.CommandLineArgsEnabled; ChromeViewsEnabled = settings.ChromeViewsEnabled; IncludeHtmUiScriptMapping = settings.IncludeHtmUiScriptMapping; LogSeverity = settings.LogSeverity; MimeTypes = GetDefaultMimeTypes(); SyncMaxDepth = 10; } /// <summary> /// Initializes a new instance of the <see cref="Application"/> class with default settings. /// </summary> protected Application() : this(new ApplicationContext()) { } #endregion #region Methods #region Public #region InvokeOnMain /// <summary> /// Invokes the specified action on the main thread asynchronous. /// </summary> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">action</exception> /// <exception cref="System.InvalidOperationException">Application is shutting down.</exception> public Task InvokeOnMainAsync(Action action) { if (action == null) throw new ArgumentNullException("action"); if (InvokeQueue.IsAddingCompleted) throw new InvalidOperationException("Application is shutting down."); Logger.Debug("Invoke on main called."); var taskCompletionSource = new TaskCompletionSource<object>(); InvokeQueue.Add(() => { try { action(); Window.SyncControllerChangesToClient(); // TODO: try to fix this taskCompletionSource.SetResult(null); } catch (Exception e) { taskCompletionSource.SetException(e); } }); return taskCompletionSource.Task; } /// <summary> /// Invokes the specified action on the main thread synchronous. /// </summary> /// <param name="action">The action.</param> /// <returns></returns> public void InvokeOnMain(Action action) { if (action == null) throw new ArgumentNullException("action"); if (!IsMainThread) { InvokeOnMainAsync(action).Wait(); } else { action(); Window.SyncControllerChangesToClient(); } } #endregion #region GetContentUrl /// <summary> /// Gets the content URL. /// </summary> /// <param name="contentPath">The content path.</param> /// <returns></returns> public string GetContentUrl(string contentPath) { if (string.IsNullOrWhiteSpace(contentPath)) throw new ArgumentNullException("contentPath"); if (ChromeViewsEnabled && Regex.IsMatch(contentPath, "^chrome://about/?$")) return "chrome://about"; return string.Format("http://{0}/{1}", RequestHostname, ContentProvider.GetUrlFromContentPath(contentPath).TrimStart('/')); } #endregion #region GetContentPath /// <summary> /// Gets the content path. /// </summary> /// <param name="contentUrl">The content URL.</param> /// <returns></returns> public string GetContentPath(string contentUrl) { if (string.IsNullOrWhiteSpace(contentUrl)) throw new ArgumentNullException("contentUrl"); var match = Regex.Match(contentUrl, string.Format("^(http://)?{0}(:80)?/(.+)$", Regex.Escape(RequestHostname)), RegexOptions.IgnoreCase); if (!match.Success) throw new ArgumentException("Invalid url.", "contentUrl"); return ContentProvider.GetContentPathFromUrl(match.Groups.OfType<Group>().Last().Value); } #endregion #region IsContentUrl /// <summary> /// Determines whether the specified URL is content. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">url</exception> public bool IsContentUrl(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); return Regex.IsMatch(url, string.Format("^(http://)?{0}(:80)?(/.*)?$", Regex.Escape(RequestHostname)), RegexOptions.IgnoreCase); } #endregion #endregion #region internal #region Shutdown /// <summary> /// Shutdowns this instance. /// </summary> /// <exception cref="System.InvalidOperationException">Application is not running.</exception> internal void Shutdown() { EnsureMainThread(); if (!IsRunning) throw new InvalidOperationException("Application is not running."); Window.Dispose(); InvokeQueue.CompleteAdding(); Logger.Info("Shutdown."); } #endregion #region ShutdownWithException /// <summary> /// Shutdowns with the exception. /// </summary> /// <param name="e">The e.</param> internal void ShutdownWithException(Exception e) { Shutdown(); ExitException = e; Logger.Info("Shutdown with exception.", e); } #endregion #region IsLocalUrl /// <summary> /// Determines whether the specified URL is local. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">url</exception> internal bool IsLocalUrl(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); return UrlUtility.IsLocalUrl(RequestHostname, NativeRequestPort, url); } #endregion #region IsNativeRequestUrl /// <summary> /// Determines whether the specified URL is native request. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">url</exception> internal bool IsNativeRequestUrl(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); return UrlUtility.IsNativeRequestUrl(RequestHostname, NativeRequestPort, url); } #endregion #region GetNativeRequestPath /// <summary> /// Gets the native request path. /// </summary> /// <param name="absoluteNativeRequestUrl">The absolute native request URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">absoluteNativeRequestUrl</exception> /// <exception cref="System.ArgumentException">Invalid url.;absoluteContentUrl</exception> internal string GetNativeRequestPath(string absoluteNativeRequestUrl) { if (string.IsNullOrWhiteSpace(absoluteNativeRequestUrl)) throw new ArgumentNullException("absoluteNativeRequestUrl"); var match = Regex.Match(absoluteNativeRequestUrl, string.Format("^(http://)?{0}:{1}/(.+)$", Regex.Escape(RequestHostname), NativeRequestPort), RegexOptions.IgnoreCase); if (!match.Success) throw new ArgumentException("Invalid url.", "absoluteNativeRequestUrl"); return match.Groups.OfType<Group>().Last().Value; } #endregion #region GetControllerNames /// <summary> /// Gets the controller names. /// </summary> /// <returns></returns> internal List<string> GetControllerNames() { return Application.Current.ControllerProvider.ControllerTypes .Select(c => c.Name).ToList(); } #endregion #region InvokeOnCef /// <summary> /// Invokes the on cef asynchronous. /// </summary> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">action</exception> internal Task InvokeOnCefAsync(Action action) { if (action == null) throw new ArgumentNullException("action"); var taskCompletionSource = new TaskCompletionSource<object>(); if (IsMultiThreadedMessageLoop) return InvokeOnMainAsync(action); CefUtility.ExecuteTask(CefThreadId.UI, () => { try { action(); taskCompletionSource.SetResult(null); } catch (Exception e) { taskCompletionSource.SetException(e); } }); return taskCompletionSource.Task; } /// <summary> /// Invokes the on cef. /// </summary> /// <param name="action">The action.</param> /// <exception cref="System.ArgumentNullException">action</exception> internal void InvokeOnCef(Action action) { if (action == null) throw new ArgumentNullException("action"); if (!IsCefThread) InvokeOnCefAsync(action).Wait(); else action(); } #endregion #region EnsureCefThread /// <summary> /// Ensures that it's called from the Cef thread. /// </summary> /// <exception cref="System.InvalidOperationException">Must be called from the Cef thread.</exception> internal void EnsureCefThread() { if (!IsCefThread) throw new InvalidOperationException("Must be called from the Cef thread."); } #endregion #endregion #region Protected #region RunInternal /// <summary> /// Run internal. /// </summary> protected sealed override void RunInternal() { try { InitializeCef(); RunMessageLoop(); ShutdownInternal(); } finally { InitializeInvokeQueue(); } // exit the run method with the exception if (ExitException != null) { Dispose(); throw ExitException; } } #endregion #region OnInitialize /// <summary> /// Called when initialize is triggered. /// </summary> protected virtual void OnInitialize() { } #endregion #region OnShutdown /// <summary> /// Called when shutdown is triggered. /// </summary> protected virtual void OnShutdown() { } #endregion protected override void SyncPropertyInternal(string name, object value) { if (RenderProcessThreadCreated) { SyncPropertyWithSendMessage(name, value); } else { lock (SyncPropertiesLock) { if (RenderProcessThreadCreated) { SyncPropertyWithSendMessage(name, value); } } } } #endregion #region Private #region InitializeCef /// <summary> /// Initializes the cef. /// </summary> private void InitializeCef() { if (IsMultiThreadedMessageLoop) { InitializeCefOnCurrentThread(); } else { var cefInitialized = new AutoResetEvent(false); CefThread = new Thread(() => { Logger.Info("CEF main application thread created."); InitializeCefOnCurrentThread(); cefInitialized.Set(); SingleThreadedMessageLoopStoped = new AutoResetEvent(false); Logger.Info("CEF message loop started."); CefRuntime.RunMessageLoop(); CefRuntime.Shutdown(); SingleThreadedMessageLoopStoped.Set(); Logger.Info("CEF main application thread destroyed."); }); CefThread.SetApartmentState(ApartmentState.STA); CefThread.Start(); cefInitialized.WaitOne(); } } /// <summary> /// Initializes the cef on current thread. /// </summary> private void InitializeCefOnCurrentThread() { Logger.Info("Initializing CEF."); CefRuntime.Load(); var cefSettings = new CefSettings { MultiThreadedMessageLoop = IsMultiThreadedMessageLoop, SingleProcess = false, LogSeverity = CefLogSeverity.Warning, LogFile = LogsDirectoryPath + "/cef.log", CachePath = CacheDirectoryPath, ResourcesDirPath = PathUtility.WorkingDirectory, LocalesDirPath = PathUtility.WorkingDirectory + "/locales", RemoteDebuggingPort = RemoteDebuggingPort, NoSandbox = true, CommandLineArgsDisabled = !CommandLineArgsEnabled }; // arguments var arguments = new List<string>(); if (CommandLineArgsEnabled) arguments.AddRange(EnvironmentUtility.GetCommandLineArgs()); if (!D3D11Enabled && !arguments.Contains(Argument.DisableD3D11.Value)) arguments.Add(Argument.DisableD3D11.Value); // initialize var mainArgs = new CefMainArgs(arguments.ToArray()); var app = new App(); app.ContextInitialized += (s, args) => { OnInitialize(); }; CefRuntime.Initialize(mainArgs, cefSettings, app, IntPtr.Zero); Logger.Info("CEF initialized."); } #endregion #region ShutdownInternal /// <summary> /// Shutdowns cef. /// </summary> private void ShutdownInternal() { Logger.Info("CEF shutdown."); InvokeOnCef(() => { if (IsMultiThreadedMessageLoop) CefRuntime.Shutdown(); else CefRuntime.QuitMessageLoop(); }); if (!IsMultiThreadedMessageLoop) SingleThreadedMessageLoopStoped.WaitOne(); } #endregion #region RunMessageLoop /// <summary> /// Runs the message loop. /// </summary> private void RunMessageLoop() { Logger.Info("Message loop started."); foreach (var action in InvokeQueue.GetConsumingEnumerable()) action(); Logger.Info("Message loop stoped."); InvokeQueue.Dispose(); OnShutdown(); } #endregion #region InitializeInvokeQueue /// <summary> /// Initializes the invoke queue. /// </summary> private void InitializeInvokeQueue() { if (InvokeQueue != null) InvokeQueue.Dispose(); InvokeQueue = new BlockingCollection<Action>(new ConcurrentQueue<Action>(), 100); } #endregion #region GetDefaultMimeTypes /// <summary> /// Gets the default MIME types. /// </summary> /// <returns></returns> private Dictionary<string, string> GetDefaultMimeTypes() { return JsonConvert.DeserializeObject<Dictionary<string, string>>(ResourceUtility.GetResourceAsString("MimeTypes.json")); } #endregion private void SyncPropertyWithSendMessage(string name, object value) { MessageUtility.SendMessage(CefProcessId.Renderer, Window.CefBrowser, "syncProperty", new SyncProperty { Name = name, Value = value }); } #endregion #endregion #region IDisposable /// <summary> /// Was dispose already called. /// </summary> private bool _disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { EnsureMainThread(); if (!_disposed) { if (disposing) { if (InvokeQueue != null) InvokeQueue.Dispose(); } _disposed = true; } base.Dispose(disposing); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Windows/WindowContext.cs namespace Samotorcan.HtmlUi.Windows { /// <summary> /// Windows window context. /// </summary> public class WindowContext : WindowsForms.WindowSettings { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="WindowContext"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public WindowContext() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="WindowContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public WindowContext(WindowContext settings) { Initialize(settings); } /// <summary> /// Initializes a new instance of the <see cref="WindowContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public WindowContext(Core.WindowSettings settings) { if (settings != null) { var windowsWindowSettings = settings as WindowContext; if (windowsWindowSettings != null) { Initialize(windowsWindowSettings); } else { var windowsFormsWindowSettings = settings as WindowsForms.WindowSettings; if (windowsFormsWindowSettings != null) Initialize(windowsFormsWindowSettings); else Initialize(settings); } } else { Initialize(); } } #endregion #region Methods #region Private #region InitializeSelf /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "settings", Justification = "Might have additional code in the future.")] private void InitializeSelf(WindowContext settings) { } #endregion #endregion #region Protected #region Initialize /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected virtual void Initialize(WindowContext settings) { base.Initialize(settings); InitializeSelf(settings); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(Core.WindowSettings settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(WindowsForms.WindowSettings settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> protected override void Initialize() { Initialize(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Messages/SyncProperty.cs namespace Samotorcan.HtmlUi.Core.Messages { internal class SyncProperty { public string Name { get; set; } public object Value { get; set; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Attributes/InternalMethodAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Samotorcan.HtmlUi.Core.Attributes { /// <summary> /// Internal method attribute. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] internal sealed class InternalMethodAttribute : Attribute { #region Methods #region Public #region GetMethods /// <summary> /// Gets the methods. /// </summary> /// <typeparam name="TType">The type of the type.</typeparam> /// <typeparam name="TDelegate">The type of the delegate.</typeparam> /// <param name="obj">The object.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">obj</exception> public static Dictionary<string, TDelegate> GetMethods<TType, TDelegate>(TType obj) where TDelegate : class { if (obj == null) throw new ArgumentNullException("obj"); return typeof(TType).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) .Where(m => m.GetCustomAttribute<InternalMethodAttribute>() != null) .ToDictionary(m => m.Name, m => m.IsStatic ? (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), m) : (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), obj, m)); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/CefUtility.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// CEF utility. /// </summary> internal static class CefUtility { #region Methods #region Public #region ExecuteTask /// <summary> /// Executes the task on the selected CEF thread. /// </summary> /// <param name="threadId">The thread identifier.</param> /// <param name="action">The action.</param> /// <exception cref="System.ArgumentNullException">action</exception> public static void ExecuteTask(CefThreadId threadId, Action action) { if (action == null) throw new ArgumentNullException("action"); if (!CefRuntime.CurrentlyOn(threadId)) CefRuntime.PostTask(threadId, new ActionTask(action)); else action(); } #endregion #region RunInContext /// <summary> /// Run in context. /// </summary> /// <typeparam name="TReturn">The type of the return.</typeparam> /// <param name="context">The context.</param> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// context /// or /// action /// </exception> public static TReturn RunInContext<TReturn>(CefV8Context context, Func<TReturn> action) { if (context == null) throw new ArgumentNullException("context"); if (action == null) throw new ArgumentNullException("action"); var contextEntered = false; if (!CefV8Context.InContext || !CefV8Context.GetEnteredContext().IsSame(context)) { context.Enter(); contextEntered = true; } try { return action(); } finally { if (contextEntered) { context.Exit(); contextEntered = false; } } } /// <summary> /// Run in context. /// </summary> /// <param name="context">The context.</param> /// <param name="action">The action.</param> /// <exception cref="System.ArgumentNullException"> /// context /// or /// action /// </exception> public static void RunInContext(CefV8Context context, Action action) { if (context == null) throw new ArgumentNullException("context"); if (action == null) throw new ArgumentNullException("action"); CefUtility.RunInContext<object>(context, () => { action(); return null; }); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/HtmlUiSynchronizationContext.cs using System; using System.Threading; namespace Samotorcan.HtmlUi.Core { /// <summary> /// HtmlUi synchronization context. /// </summary> public class HtmlUiSynchronizationContext : SynchronizationContext { #region Methods #region Public #region Post /// <summary> /// Dispatches an asynchronous message to a synchronization context. /// </summary> /// <param name="d">The <see cref="T:System.Threading.SendOrPostCallback" /> delegate to call.</param> /// <param name="state">The object passed to the delegate.</param> /// <exception cref="System.ArgumentNullException">d</exception> public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); Application.Current.InvokeOnMainAsync(() => { d.Invoke(state); }); } #endregion #region Send /// <summary> /// Dispatches a synchronous message to a synchronization context. /// </summary> /// <param name="d">The <see cref="T:System.Threading.SendOrPostCallback" /> delegate to call.</param> /// <param name="state">The object passed to the delegate.</param> /// <exception cref="System.ArgumentNullException">d</exception> public override void Send(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); Application.Current.InvokeOnMain(() => { d.Invoke(state); }); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerChange.cs using Newtonsoft.Json.Linq; using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller change. /// </summary> internal class ControllerChange { #region Properties #region Public #region Id /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public int Id { get; set; } #endregion #region Properties /// <summary> /// Gets the properties. /// </summary> /// <value> /// The properties. /// </value> public Dictionary<string, JToken> Properties { get; set; } #endregion #region ObservableCollections /// <summary> /// Gets or sets the observable collections. /// </summary> /// <value> /// The observable collections. /// </value> public Dictionary<string, ObservableCollectionChanges> ObservableCollections { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ControllerChange"/> class. /// </summary> public ControllerChange() { Properties = new Dictionary<string, JToken>(); ObservableCollections = new Dictionary<string, ObservableCollectionChanges>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ApplicationType.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Application type. /// </summary> public enum ApplicationType { /// <summary> /// The application. /// </summary> Application, /// <summary> /// The child application. /// </summary> ChildApplication } } <file_sep>/src/Samotorcan.HtmlUi.Core/NativeResponseType.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Native response type. /// </summary> internal enum NativeResponseType { /// <summary> /// The value. /// </summary> Value = 1, /// <summary> /// The undefined. /// </summary> Undefined = 2, /// <summary> /// The exception. /// </summary> Exception = 3 } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/ContentResourceHandler.cs using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.IO; using System.Text; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Content resource handler. /// </summary> internal class ContentResourceHandler : CefResourceHandler { #region Properties #region Private #region Url /// <summary> /// Gets or sets the URL. /// </summary> /// <value> /// The URL. /// </value> private string Url { get; set; } #endregion #region Exception /// <summary> /// Gets or sets the exception. /// </summary> /// <value> /// The exception. /// </value> private Exception Exception { get; set; } #endregion #region Data /// <summary> /// Gets or sets the data. /// </summary> /// <value> /// The data. /// </value> private byte[] Data { get; set; } #endregion #region AllBytesRead /// <summary> /// Gets or sets all bytes read. /// </summary> /// <value> /// All bytes read. /// </value> private int AllBytesRead { get; set; } #endregion #endregion #endregion #region Methods #region Protected #region CanGetCookie /// <summary> /// Cookies are disabled, returns false. /// </summary> /// <param name="cookie"></param> /// <returns></returns> protected override bool CanGetCookie(CefCookie cookie) { return false; } #endregion #region CanSetCookie /// <summary> /// Cookies are disabled, returns false. /// </summary> /// <param name="cookie"></param> /// <returns></returns> protected override bool CanSetCookie(CefCookie cookie) { return false; } #endregion #region Cancel /// <summary> /// Request processing has been canceled. /// </summary> protected override void Cancel() { } #endregion #region GetResponseHeaders /// <summary> /// Gets the response headers. /// </summary> /// <param name="response"></param> /// <param name="responseLength"></param> /// <param name="redirectUrl"></param> protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl) { if (response == null) throw new ArgumentNullException("response"); redirectUrl = null; if (Exception != null) { Data = Encoding.UTF8.GetBytes(string.Format(ResourceUtility.GetResourceAsString("Views/ContentRequestException.html"), Url, Exception.ToString().Replace(Environment.NewLine, "<br>"))); responseLength = Data.Length; response.Status = 500; response.StatusText = "Internal Server Error"; response.MimeType = "text/html"; } else if (Data != null) { responseLength = Data.Length; response.Status = 200; response.StatusText = "OK"; // mime type response.MimeType = "application/octet-stream"; var extension = Path.GetExtension(Url); if (!string.IsNullOrWhiteSpace(extension) && Application.Current.MimeTypes.ContainsKey(extension)) response.MimeType = Application.Current.MimeTypes[extension]; } else { Data = Encoding.UTF8.GetBytes(string.Format(ResourceUtility.GetResourceAsString("Views/ContentNotFound.html"), Url)); responseLength = Data.Length; response.Status = 404; response.StatusText = "Not Found"; response.MimeType = "text/html"; } } #endregion #region ProcessRequest /// <summary> /// Processes the request. /// </summary> /// <param name="request"></param> /// <param name="callback"></param> /// <returns></returns> protected override bool ProcessRequest(CefRequest request, CefCallback callback) { if (request == null) throw new ArgumentNullException("request"); Url = request.Url; var application = Application.Current; Logger.Debug(string.Format("Content request: {0}", Url)); application.InvokeOnMainAsync(() => { try { var path = application.GetContentPath(request.Url); if (application.ContentProvider.ContentExists(path)) Data = application.ContentProvider.GetContent(path); } catch (Exception e) { Data = null; Exception = e; Logger.Error("Content request exception.", e); } callback.Continue(); }); return true; } #endregion #region ReadResponse /// <summary> /// Reads the response. /// </summary> /// <param name="response"></param> /// <param name="bytesToRead"></param> /// <param name="bytesRead"></param> /// <param name="callback"></param> /// <returns></returns> protected override bool ReadResponse(Stream response, int bytesToRead, out int bytesRead, CefCallback callback) { if (response == null) throw new ArgumentNullException("response"); bytesRead = 0; if (AllBytesRead >= Data.Length) return false; bytesRead = Math.Min(bytesToRead, Data.Length - AllBytesRead); response.Write(Data, AllBytesRead, bytesRead); AllBytesRead += bytesRead; return true; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ContentSearch.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Content search. /// </summary> public enum ContentSearch { /// <summary> /// The file and assembly. /// </summary> FileAndAssembly, /// <summary> /// The file. /// </summary> File, /// <summary> /// The assembly. /// </summary> Assembly } } <file_sep>/src/Samotorcan.Examples.TodoList/Controllers/TodoListController.cs using Newtonsoft.Json; using Samotorcan.HtmlUi.Core; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Samotorcan.Examples.TodoList.Controllers { public class TodoListController : ObservableController { private const string _todosFileName = "todos.json"; private ObservableCollection<TodoItem> _todos; public ObservableCollection<TodoItem> Todos { get { return _todos; } set { var oldTodos = _todos; if (SetField(ref _todos, value)) { TodosChanged(); if (oldTodos != null) oldTodos.CollectionChanged -= Todos_CollectionChanged; if (_todos != null) _todos.CollectionChanged += Todos_CollectionChanged; } } } public TodoListController() { if (File.Exists(_todosFileName)) Todos = new ObservableCollection<TodoItem>(JsonConvert.DeserializeObject<List<TodoItem>>(File.ReadAllText(_todosFileName, Encoding.UTF8))); else Todos = new ObservableCollection<TodoItem>(); } public void ClearTodos() { Todos = new ObservableCollection<TodoItem>(); } private void TodosChanged() { Debug.WriteLine("[" + string.Join(", ", Todos.Select(t => "'" + t.Text + "'")) + "]"); } private void Todos_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { TodosChanged(); } protected override void Dispose(bool disposing) { File.WriteAllText(_todosFileName, JsonConvert.SerializeObject(Todos), Encoding.UTF8); base.Dispose(disposing); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Providers/FileAssemblyContentProvider.cs using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.IO; using System.Linq; using System.Reflection; namespace Samotorcan.HtmlUi.Core.Providers { /// <summary> /// File and assembly content provider. /// </summary> public class FileAssemblyContentProvider : IContentProvider { #region Properties #region Public #region ContentSearch /// <summary> /// Gets or sets the content search. /// </summary> /// <value> /// The content search. /// </value> public ContentSearch ContentSearch { get; set; } #endregion #endregion #endregion #region Methods #region Public #region GetContent /// <summary> /// Gets the content. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "It's ok.")] public byte[] GetContent(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); if (!path.StartsWith("/")) throw new ArgumentException("Must be an absolute path.", "path"); if (!PathUtility.IsFullFileName(path)) throw new ArgumentException("Invalid path.", "path"); // actual file if (ContentSearch == ContentSearch.FileAndAssembly || ContentSearch == ContentSearch.File) { var filePath = PathUtility.WorkingDirectory + path; if (File.Exists(filePath)) return File.ReadAllBytes(filePath); } // assembly file if (ContentSearch == ContentSearch.FileAndAssembly || ContentSearch == ContentSearch.Assembly) { var assembly = Assembly.GetEntryAssembly(); var resourceName = assembly.GetName().Name + path.Replace('/', '.'); if (assembly.GetManifestResourceNames().Contains(resourceName)) { using (var stream = assembly.GetManifestResourceStream(resourceName)) { using(var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } } } // HtmlUi resource if (ResourceUtility.ResourceExists(path)) return ResourceUtility.GetResourceAsBytes(path); throw new ContentNotFoundException(path); } #endregion #region ContentExists /// <summary> /// Content exists. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public bool ContentExists(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); if (!path.StartsWith("/")) throw new ArgumentException("Must be an absolute path.", "path"); if (!PathUtility.IsFullFileName(path)) throw new ArgumentException("Invalid path.", "path"); // actual file if (ContentSearch == ContentSearch.FileAndAssembly || ContentSearch == ContentSearch.File) { var filePath = PathUtility.WorkingDirectory + path; if (File.Exists(filePath)) return true; } // assembly file if (ContentSearch == ContentSearch.FileAndAssembly || ContentSearch == ContentSearch.Assembly) { var assembly = Assembly.GetEntryAssembly(); var resourceName = assembly.GetName().Name + path.Replace('/', '.'); if (assembly.GetManifestResourceNames().Contains(resourceName)) return true; } // HtmlUi resource if (ResourceUtility.ResourceExists(path)) return true; return false; } #endregion #region GetUrlFromContentPath /// <summary> /// Gets the URL from content path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public string GetUrlFromContentPath(string path) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); if (!path.StartsWith("/")) throw new ArgumentException("Must be an absolute path.", "path"); if (!PathUtility.IsFullFileName(path)) throw new ArgumentException("Invalid path.", "path"); return path; } #endregion #region GetContentPathFromUrl /// <summary> /// Gets the content path from URL. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> public string GetContentPathFromUrl(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); if (!PathUtility.IsFullFileName(url)) throw new ArgumentException("Invalid url.", "url"); return "/" + url.TrimStart('/'); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Logs/LogType.cs using System; namespace Samotorcan.HtmlUi.Core.Logs { /// <summary> /// Log type. /// </summary> internal sealed class LogType { #region LogTypes #region Logger /// <summary> /// The logger. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It's immutable.")] public static readonly LogType Logger = new LogType("Logger"); #endregion #endregion #region Properties #region Public #region Value /// <summary> /// Gets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="LogType"/> class. /// </summary> /// <param name="value">The value.</param> private LogType(string value) { Value = value; } #endregion #region Methods #region Public #region Parse /// <summary> /// Parses the specified log type. /// </summary> /// <param name="logType">The log type.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">logType</exception> /// <exception cref="System.ArgumentException">Invalid log type.;logType</exception> public static LogType Parse(string logType) { if (string.IsNullOrWhiteSpace(logType)) throw new ArgumentNullException("logType"); if (logType == Logger.Value) return Logger; throw new ArgumentException("Invalid log type.", "logType"); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Windows/ChildApplication.cs namespace Samotorcan.HtmlUi.Windows { /// <summary> /// Windows child application. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1052:StaticHolderTypesShouldBeSealed", Justification = "It might not contain only static methods in the future.")] public class ChildApplication : WindowsForms.ChildApplication { #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static new ChildApplication Current { get { return (ChildApplication)WindowsForms.ChildApplication.Current; } } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChildApplication"/> class. /// </summary> private ChildApplication(ChildApplicationContext settings) : base(settings) { } #endregion #region Methods #region Public #region Run /// <summary> /// Runs the application. /// </summary> /// <param name="settings">The settings.</param> public static void Run(ChildApplicationContext settings) { if (settings == null) settings = new ChildApplicationContext(); using (var application = new ChildApplication(settings)) { application.RunApplication(); } } /// <summary> /// Runs the application. /// </summary> public static void Run() { Run(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.Tests.Core/BaseUnitTest.cs using OpenQA.Selenium.Chrome; using System; using NUnit.Framework; namespace Samotorcan.Tests.Core { /// <summary> /// Base unit test. /// </summary> public abstract class BaseUnitTest { #region Properties #region Protected #region DriverService /// <summary> /// Gets or sets the driver service. /// </summary> /// <value> /// The driver service. /// </value> protected ChromeDriverService DriverService { get; set; } #endregion #region Driver /// <summary> /// Gets or sets the driver. /// </summary> /// <value> /// The driver. /// </value> protected ChromeDriver Driver { get; set; } #endregion #region ApplicationName /// <summary> /// Gets the name of the application. /// </summary> /// <value> /// The name of the application. /// </value> protected abstract string ApplicationName { get; } #endregion #endregion #endregion #region Methods #region Public #region Initialize /// <summary> /// Initializes this instance. /// </summary> [TestFixtureSetUp] public virtual void Initialize() { DriverService = TestUtility.CreateDriverService(); Driver = TestUtility.CreateDriver(DriverService, ApplicationName); Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(1)); } #endregion #region Cleanup /// <summary> /// Cleanups this instance. /// </summary> [TestFixtureTearDown] public virtual void Cleanup() { Driver.Quit(); DriverService.Dispose(); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/JsonUtility.cs using Newtonsoft.Json; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// JSON utility. /// </summary> internal static class JsonUtility { #region Properties #region Public #region Serializer /// <summary> /// Gets or sets the serializer. /// </summary> /// <value> /// The serializer. /// </value> public static JsonSerializer Serializer { get; private set; } #endregion #region JsonSerializerSettings /// <summary> /// Gets or sets the json serializer settings. /// </summary> /// <value> /// The json serializer settings. /// </value> public static JsonSerializerSettings JsonSerializerSettings { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes the <see cref="JsonUtility"/> class. /// </summary> static JsonUtility() { JsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new List<JsonConverter> { new KeyValuePairConverter() } }; Serializer = JsonSerializer.Create(JsonSerializerSettings); } #endregion #region Methods #region Public #region SerializeToBson /// <summary> /// Serializes to BSON. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">value</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "It's not.")] public static byte[] SerializeToBson(object value) { if (value == null) throw new ArgumentNullException("value"); using (var memoryStream = new MemoryStream()) { using (BsonWriter writer = new BsonWriter(memoryStream)) Serializer.Serialize(writer, value); return memoryStream.ToArray(); } } #endregion #region DeserializeFromBson /// <summary> /// Deserializes from BSON. /// </summary> /// <typeparam name="TType">The type of the type.</typeparam> /// <param name="value">The value.</param> /// <param name="readRootValueAsArray">if set to <c>true</c> read root value as array.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">value</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "It's not.")] public static TType DeserializeFromBson<TType>(byte[] value, bool readRootValueAsArray) { if (value == null) throw new ArgumentNullException("value"); using (var memoryStream = new MemoryStream(value)) { using (BsonReader reader = new BsonReader(memoryStream, readRootValueAsArray, DateTimeKind.Utc)) return Serializer.Deserialize<TType>(reader); } } /// <summary> /// Deserializes from BSON. /// </summary> /// <typeparam name="TType">The type of the type.</typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static TType DeserializeFromBson<TType>(byte[] value) { return JsonUtility.DeserializeFromBson<TType>(value, false); } #endregion #region SerializeToJson /// <summary> /// Serializes to json. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string SerializeToJson(object value) { return JsonConvert.SerializeObject(value, Formatting.Indented, JsonSerializerSettings); } #endregion #region SerializeToByteJson /// <summary> /// Serializes to byte json. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static byte[] SerializeToByteJson(object value) { return Encoding.UTF8.GetBytes(JsonUtility.SerializeToJson(value)); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Windows/Window.cs using System; using System.Windows.Forms; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Windows { /// <summary> /// Windows window. /// </summary> [CLSCompliant(false)] public class Window : WindowsForms.Window { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="settings">The settings.</param> public Window(WindowContext settings) : base(settings) { Resize += Window_Resize; } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class with default settings. /// </summary> public Window() : this(new WindowContext()) { } #endregion #region Methods #region Private #region Window_Resize /// <summary> /// Handles the Resize event of the Window control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void Window_Resize(object sender, EventArgs e) { if (CefBrowser != null) { if (Form.WindowState == FormWindowState.Minimized) { // hide the browser NativeMethods.SetWindowPos(CefBrowser.GetHost().GetWindowHandle(), IntPtr.Zero, 0, 0, 0, 0, NativeMethods.SetWindowPosFlags.NoMove | NativeMethods.SetWindowPosFlags.NoZOrder | NativeMethods.SetWindowPosFlags.NoActivate); } else { // resize the browser var width = Form.ClientSize.Width; var height = Form.ClientSize.Height; NativeMethods.SetWindowPos(CefBrowser.GetHost().GetWindowHandle(), IntPtr.Zero, 0, 0, width, height, NativeMethods.SetWindowPosFlags.NoMove | NativeMethods.SetWindowPosFlags.NoZOrder); } } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/JavascriptException.cs using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Javascript exception. /// </summary> internal class JavascriptException { #region Properties #region Public #region Type /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> public string Type { get; set; } #endregion #region Message /// <summary> /// Gets or sets the message. /// </summary> /// <value> /// The message. /// </value> public string Message { get; set; } #endregion #region AdditionalData /// <summary> /// Gets or sets the additional data. /// </summary> /// <value> /// The additional data. /// </value> public Dictionary<string, object> AdditionalData { get; set; } #endregion #region InnerException /// <summary> /// Gets or sets the inner exception. /// </summary> /// <value> /// The inner exception. /// </value> public JavascriptException InnerException { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/RequestHandler.cs using System; using Samotorcan.HtmlUi.Core.Logs; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Request handler. /// </summary> internal class RequestHandler : CefRequestHandler { #region Methods #region Protected #region OnBeforeBrowse /// <summary> /// Called on the UI thread before browser navigation. Return true to cancel /// the navigation or false to allow the navigation to proceed. The |request| /// object cannot be modified in this callback. /// CefLoadHandler::OnLoadingStateChange will be called twice in all cases. /// If the navigation is allowed CefLoadHandler::OnLoadStart and /// CefLoadHandler::OnLoadEnd will be called. If the navigation is canceled /// CefLoadHandler::OnLoadError will be called with an |errorCode| value of /// ERR_ABORTED. /// </summary> /// <param name="browser"></param> /// <param name="frame"></param> /// <param name="request"></param> /// <param name="isRedirect"></param> /// <returns></returns> protected override bool OnBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, bool isRedirect) { return false; } #endregion #region OnRenderProcessTerminated /// <summary> /// Called on the browser process UI thread when the render process /// terminates unexpectedly. |status| indicates how the process /// terminated. /// </summary> /// <param name="browser"></param> /// <param name="status"></param> protected override void OnRenderProcessTerminated(CefBrowser browser, CefTerminationStatus status) { } #endregion #region GetResourceHandler /// <summary> /// Called on the IO thread before a resource is loaded. To allow the resource /// to load normally return NULL. To specify a handler for the resource return /// a CefResourceHandler object. The |request| object should not be modified in /// this callback. /// </summary> /// <param name="browser"></param> /// <param name="frame"></param> /// <param name="request"></param> /// <returns></returns> protected override CefResourceHandler GetResourceHandler(CefBrowser browser, CefFrame frame, CefRequest request) { if (request == null) throw new ArgumentNullException("request"); if (Application.Current.IsContentUrl(request.Url)) return new ContentResourceHandler(); if (Application.Current.IsNativeRequestUrl(request.Url)) return new NativeRequestResourceHandler(); Logger.Debug(string.Format("External request: {0}", request.Url)); return null; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Providers/IControllerProvider.cs using System; using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core.Providers { /// <summary> /// Controller provider interface. /// </summary> public interface IControllerProvider { /// <summary> /// Gets controller types. /// </summary> /// <returns></returns> IEnumerable<Type> ControllerTypes { get; } /// <summary> /// Creates the controller. /// </summary> /// <param name="name">The name.</param> /// <param name="id">The identifier.</param> /// <returns></returns> Controller CreateController(string name, int id); /// <summary> /// Creates the observable controller. /// </summary> /// <param name="name">The name.</param> /// <param name="id">The identifier.</param> /// <returns></returns> ObservableController CreateObservableController(string name, int id); /// <summary> /// Controller exists. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> bool ControllerExists(string name); } } <file_sep>/src/Samotorcan.HtmlUi.Core/Exceptions/CallFunctionException.cs using Newtonsoft.Json.Linq; using System; using System.Runtime.Serialization; using System.Security.Permissions; namespace Samotorcan.HtmlUi.Core.Exceptions { /// <summary> /// Call function exception. /// </summary> [Serializable] public class CallFunctionException : Exception { #region Properties #region Public #region JavaScriptException /// <summary> /// Gets the javascript exception. /// </summary> /// <value> /// The javascript exception. /// </value> public JToken JavaScriptException { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CallFunctionException"/> class. /// </summary> public CallFunctionException() : base("Call function exception.") { } /// <summary> /// Initializes a new instance of the <see cref="CallFunctionException"/> class. /// </summary> /// <param name="javaScriptException">The javascript exception.</param> public CallFunctionException(JToken javaScriptException) : base("Call function exception.") { JavaScriptException = javaScriptException; } /// <summary> /// Initializes a new instance of the <see cref="CallFunctionException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="javaScriptException">The javascript exception.</param> public CallFunctionException(string message, JToken javaScriptException) : base(message) { JavaScriptException = javaScriptException; } /// <summary> /// Initializes a new instance of the <see cref="CallFunctionException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public CallFunctionException(string format, params object[] args) : base(string.Format(format, args)) { } /// <summary> /// Initializes a new instance of the <see cref="CallFunctionException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public CallFunctionException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="CallFunctionException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="innerException">The inner exception.</param> /// <param name="args">The arguments.</param> public CallFunctionException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyNotFoundException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="System.ArgumentNullException">info</exception> protected CallFunctionException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) throw new ArgumentNullException("info"); JavaScriptException = (JToken)info.GetValue("JavascriptException", typeof(JToken)); } #endregion #region Methods #region Public #region GetObjectData /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="System.ArgumentNullException">info</exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter" /> /// </PermissionSet> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); if (info == null) throw new ArgumentNullException("info"); info.AddValue("JavascriptException", JavaScriptException); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.WindowsForms/Form.cs using System.Windows.Forms; namespace Samotorcan.HtmlUi.WindowsForms { /// <summary> /// Form. /// </summary> internal class Form : System.Windows.Forms.Form { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Form"/> class. /// </summary> public Form() : base() { SetStyle( ControlStyles.ContainerControl | ControlStyles.ResizeRedraw | ControlStyles.FixedWidth | ControlStyles.FixedHeight | ControlStyles.StandardClick | ControlStyles.UserMouse | ControlStyles.SupportsTransparentBackColor | ControlStyles.StandardDoubleClick | ControlStyles.CacheText | ControlStyles.EnableNotifyMessage | ControlStyles.UseTextForAccessibility | ControlStyles.OptimizedDoubleBuffer | ControlStyles.DoubleBuffer | ControlStyles.Opaque, false); SetStyle( ControlStyles.Selectable | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/NormalizeType.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Normalize type. /// </summary> internal enum NormalizeType { /// <summary> /// The none. /// </summary> None, /// <summary> /// The pascal case, /// </summary> PascalCase, /// <summary> /// The camel case. /// </summary> CamelCase } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/EnvironmentUtility.cs using System; using System.Linq; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// EnvironmentUtility /// </summary> internal static class EnvironmentUtility { #region Methods #region Public #region GetCommandLineArgs /// <summary> /// Gets the command line arguments. /// </summary> /// <returns></returns> public static string[] GetCommandLineArgs() { var args = Environment.GetCommandLineArgs().AsEnumerable(); if (HtmlUiRuntime.Platform == Platform.Windows) args = args.Skip(1); return args.ToArray(); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/KeyboardHandler.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Keyboard handler. /// </summary> internal class KeyboardHandler : CefKeyboardHandler { #region Methods #region Protected #region OnPreKeyEvent /// <summary> /// Called before a keyboard event is sent to the renderer. |event| contains /// information about the keyboard event. |os_event| is the operating system /// event message, if any. Return true if the event was handled or false /// otherwise. If the event will be handled in OnKeyEvent() as a keyboard /// shortcut set |is_keyboard_shortcut| to true and return false. /// </summary> /// <param name="browser"></param> /// <param name="keyEvent"></param> /// <param name="os_event"></param> /// <param name="isKeyboardShortcut"></param> /// <returns></returns> protected override bool OnPreKeyEvent(CefBrowser browser, CefKeyEvent keyEvent, IntPtr os_event, out bool isKeyboardShortcut) { if (keyEvent == null) throw new ArgumentNullException("keyEvent"); isKeyboardShortcut = false; Application.Current.Window.TriggerKeyPress(keyEvent.WindowsKeyCode, keyEvent.Modifiers, keyEvent.EventType); return false; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.Examples.TodoList/Program.cs using Samotorcan.HtmlUi.Core; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.OS; namespace Samotorcan.Examples.TodoList { class Program { static void Main(string[] args) { if (HtmlUiRuntime.ApplicationType == ApplicationType.ChildApplication) { OSChildApplication.Run(); return; } OSApplication.Run(new ApplicationContext { LogSeverity = LogSeverity.Debug }); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Exceptions/PropertyMismatchException.cs using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; namespace Samotorcan.HtmlUi.Core.Exceptions { /// <summary> /// Property mismatch exception. /// </summary> [Serializable] public class PropertyMismatchException : Exception, INativeException { #region Properties #region Public #region ControllerName /// <summary> /// Gets or sets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } #endregion #region PropertyName /// <summary> /// Gets the name of the property. /// </summary> /// <value> /// The name of the property. /// </value> public string PropertyName { get; private set; } #endregion #region ExpectedType /// <summary> /// Gets the expected type. /// </summary> /// <value> /// The expected type. /// </value> public string ExpectedType { get; private set; } #endregion #region GotType /// <summary> /// Gets the type of the got. /// </summary> /// <value> /// The type of the got. /// </value> public string GotType { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> public PropertyMismatchException() : base("Property mismatch.") { } /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="expectedType">The expected type.</param> /// <param name="gotType">Type of the got.</param> public PropertyMismatchException(string controllerName, string propertyName, string expectedType, string gotType) : base("Property mismatch.") { ControllerName = controllerName; PropertyName = propertyName; ExpectedType = expectedType; GotType = gotType; } /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="expectedType">The expected type.</param> /// <param name="gotType">Type of the got.</param> public PropertyMismatchException(string message, string controllerName, string propertyName, string expectedType, string gotType) : base(message) { ControllerName = controllerName; PropertyName = propertyName; ExpectedType = expectedType; GotType = gotType; } /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public PropertyMismatchException(string format, params object[] args) : base(string.Format(format, args)) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public PropertyMismatchException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="innerException">The inner exception.</param> /// <param name="args">The arguments.</param> public PropertyMismatchException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyMismatchException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="System.ArgumentNullException">info</exception> protected PropertyMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) throw new ArgumentNullException("info"); ControllerName = info.GetString("ControllerName"); PropertyName = info.GetString("PropertyName"); ExpectedType = info.GetString("ExpectedType"); GotType = info.GetString("GotType"); } #endregion #region Methods #region Public #region GetObjectData /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="System.ArgumentNullException">info</exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter" /> /// </PermissionSet> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); if (info == null) throw new ArgumentNullException("info"); info.AddValue("ControllerName", ControllerName); info.AddValue("PropertyName", PropertyName); info.AddValue("ExpectedType", ExpectedType); info.AddValue("GotType", GotType); } #endregion #endregion #region Internal #region ToJavascriptException /// <summary> /// To the javascript exception. /// </summary> /// <returns></returns> JavascriptException INativeException.ToJavascriptException() { return new JavascriptException { Message = Message, Type = "PropertyMismatchException", InnerException = InnerException != null ? ExceptionUtility.CreateJavascriptException(InnerException) : null, AdditionalData = new Dictionary<string, object> { { "ControllerName", ControllerName }, { "PropertyName", PropertyName }, { "ExpectedType", ExpectedType }, { "GotType", GotType } } }; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Providers/AssemblyControllerProvider.cs using Samotorcan.HtmlUi.Core.Exceptions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Reflection; namespace Samotorcan.HtmlUi.Core.Providers { /// <summary> /// Assembly controller provider. /// </summary> public class AssemblyControllerProvider : IControllerProvider { #region Properties #region Public #region Assemblies /// <summary> /// Gets the assemblies. /// </summary> /// <value> /// The assemblies. /// </value> public ObservableCollection<Assembly> Assemblies { get; private set; } #endregion #region ControllerTypes /// <summary> /// Gets controller types. /// </summary> /// <returns></returns> public IEnumerable<Type> ControllerTypes { get { return ControllerTypesInternal.ToList(); } } #endregion #endregion #region Private #region ControllerTypesInternal /// <summary> /// Gets or sets the controller types internal. /// </summary> /// <value> /// The controller types internal. /// </value> private List<Type> ControllerTypesInternal { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="AssemblyControllerProvider"/> class. /// </summary> public AssemblyControllerProvider() { ControllerTypesInternal = new List<Type>(); Assemblies = new ObservableCollection<Assembly>(); Assemblies.CollectionChanged += Assemblies_CollectionChanged; // add entry assembly as default Assemblies.Add(Assembly.GetEntryAssembly()); } #endregion #region Methods #region Public #region CreateController /// <summary> /// Creates the controller. /// </summary> /// <param name="name">The name.</param> /// <param name="id">The identifier.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> public Controller CreateController(string name, int id) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); var controller = (Controller)Activator.CreateInstance(GetControllerType(name)); controller.Initialize(id); return controller; } #endregion #region CreateObservableController /// <summary> /// Creates the observable controller. /// </summary> /// <param name="name">The name.</param> /// <param name="id">The identifier.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> public ObservableController CreateObservableController(string name, int id) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); var observableController = (ObservableController)Activator.CreateInstance(GetObservableControllerType(name)); observableController.Initialize(id); return observableController; } #endregion #region IsUniqueControllerName /// <summary> /// Determines whether the specified controller name is unique. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public bool IsUniqueControllerName(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); var controllerTypesCount = ControllerTypesInternal.Where(c => c.Name == name).Count(); if (controllerTypesCount == 0) throw new ControllerNotFoundException(name); return controllerTypesCount == 1; } #endregion #region ControllerExists /// <summary> /// Controller exists. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> public bool ControllerExists(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); return ControllerTypesInternal.Where(c => c.Name == name).Count() > 0; } #endregion #endregion #region Private #region IsControllerType /// <summary> /// Determines whether type is controller type. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private bool IsControllerType(Type type) { // can't create an abstract type if (type.IsAbstract) return false; // is extended from Controller while ((type = type.BaseType) != null) { if (type == typeof(Controller)) return true; } return false; } #endregion #region IsObservableControllerType /// <summary> /// Determines whether [is observable controller type] [the specified type]. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private bool IsObservableControllerType(Type type) { // can't create an abstract type if (type.IsAbstract) return false; // is extended from Controller while ((type = type.BaseType) != null) { if (type == typeof(ObservableController)) return true; } return false; } #endregion #region GetControllerType /// <summary> /// Gets the controller type. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// Found more than one controller with the same name.;path /// or /// Controller was not found.;path /// </exception> private Type GetControllerType(string name) { var controllerTypes = ControllerTypesInternal.Where(c => c.Name == name).ToList(); if (controllerTypes.Count > 1) throw new MoreThanOneControllerFoundException(name); if (!controllerTypes.Any()) throw new ControllerNotFoundException(name); return controllerTypes.FirstOrDefault(); } #endregion #region GetObservableControllerType /// <summary> /// Gets the controller type. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// Found more than one controller with the same name.;path /// or /// Controller was not found.;path /// </exception> private Type GetObservableControllerType(string name) { var controllerTypes = ControllerTypesInternal.Where(c => c.Name == name).ToList(); if (controllerTypes.Count > 1) throw new MoreThanOneControllerFoundException(name); if (!controllerTypes.Any()) throw new ControllerNotFoundException(name); var controllerType = controllerTypes.First(); if (!IsObservableControllerType(controllerType)) throw new ControllerNotFoundException(name); return controllerType; } #endregion #region Assemblies_CollectionChanged /// <summary> /// Handles the CollectionChanged event of the Assemblies control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param> private void Assemblies_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // set controller types ControllerTypesInternal.Clear(); foreach (var type in Assemblies.SelectMany(a => a.GetTypes())) { if (IsControllerType(type)) ControllerTypesInternal.Add(type); } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ClientFunction.cs using Newtonsoft.Json; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Client function. /// </summary> internal class ClientFunction { #region Properties #region Public #region ControllerId /// <summary> /// Gets or sets the controller identifier. /// </summary> /// <value> /// The controller identifier. /// </value> public int ControllerId { get; set; } #endregion #region Name /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } #endregion #region Arguments /// <summary> /// Gets or sets the arguments. /// </summary> /// <value> /// The arguments. /// </value> [JsonProperty(PropertyName = "args")] public object[] Arguments { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Messages/CallNativeResult.cs using System; namespace Samotorcan.HtmlUi.Core.Messages { internal class CallNativeResult { public Guid? CallbackId { get; set; } public string JsonResult { get; set; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Value.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Value. /// </summary> internal static class Value { #region Properties #region Public #region Undefined /// <summary> /// Gets the undefined. /// </summary> /// <value> /// The undefined. /// </value> public static UndefinedValue Undefined { get { return UndefinedValue.Value; } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ClientFunctionResultType.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Client function result type. /// </summary> internal enum ClientFunctionResultType : int { /// <summary> /// The value. /// </summary> Value = 1, /// <summary> /// The undefined. /// </summary> Undefined = 2, /// <summary> /// The exception. /// </summary> Exception = 3, /// <summary> /// The function not found. /// </summary> FunctionNotFound = 4 } } <file_sep>/src/Samotorcan.HtmlUi.Core/Controller.cs using Newtonsoft.Json.Linq; using Samotorcan.HtmlUi.Core.Attributes; using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors", Justification = "All classes that extend Controller must have this exact constructor.")] public abstract class Controller : IDisposable { #region Properties #region Public #region Id /// <summary> /// Gets the identifier. /// </summary> /// <value> /// The identifier. /// </value> [Exclude] public int Id { get; private set; } #endregion #region Name /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> [Exclude] public string Name { get; private set; } #endregion #endregion #region Internal #region ControllerTypeInfo /// <summary> /// Gets or sets the controller type information. /// </summary> /// <value> /// The controller type information. /// </value> internal ControllerTypeInfo ControllerTypeInfo { get; set; } #endregion #region ControllerTypeInfos /// <summary> /// Gets or sets the controller type informations. /// </summary> /// <value> /// The controller type informations. /// </value> internal static Dictionary<Type, ControllerTypeInfo> ControllerTypeInfos { get; set; } #endregion #endregion #region Protected #region ControllerType /// <summary> /// Gets or sets the type of the controller. /// </summary> /// <value> /// The type of the controller. /// </value> protected Type ControllerType { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes the <see cref="Controller"/> class. /// </summary> static Controller() { ControllerTypeInfos = new Dictionary<Type, ControllerTypeInfo>(); } /// <summary> /// Initializes a new instance of the <see cref="Controller"/> class. /// </summary> public Controller() { } #endregion #region Methods #region Public #region CallFunction /// <summary> /// Calls the function asynchronous. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="name">The name.</param> /// <param name="arguments">The arguments.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> [Exclude] public Task<TResult> CallFunctionAsync<TResult>(string name, params object[] arguments) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(name); if (arguments == null) arguments = new object[0]; Application.Current.EnsureMainThread(); var resultAction = Application.Current.Window.CallFunctionAsync("callClientFunction", new ClientFunction { ControllerId = Id, Name = name, Arguments = arguments }); return resultAction.ContinueWith((task) => { var result = task.Result.ToObject<ClientFunctionResult>(JsonUtility.Serializer); if (result.Type == ClientFunctionResultType.Exception) throw new CallFunctionException(result.Exception); if (result.Type == ClientFunctionResultType.FunctionNotFound) throw new FunctionNotFoundException(name); if (result.Type == ClientFunctionResultType.Undefined) return default(TResult); return result.Value.ToObject<TResult>(); }); } /// <summary> /// Calls the function asynchronous. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="name">The name.</param> /// <returns></returns> [Exclude] public Task<TResult> CallFunctionAsync<TResult>(string name) { return CallFunctionAsync<TResult>(name, null); } /// <summary> /// Calls the function asynchronous. /// </summary> /// <param name="name">The name.</param> /// <param name="arguments">The arguments.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> [Exclude] public Task CallFunctionAsync(string name, params object[] arguments) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(name); if (arguments == null) arguments = new object[0]; Application.Current.EnsureMainThread(); return Application.Current.Window.CallFunctionAsync("callClientFunction", new ClientFunction { ControllerId = Id, Name = name, Arguments = arguments }); } /// <summary> /// Calls the function asynchronous. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> [Exclude] public Task CallFunctionAsync(string name) { return CallFunctionAsync(name, null); } #endregion #endregion #region Internal #region Initialize /// <summary> /// Initializes the controller. /// </summary> /// <param name="id">The identifier.</param> internal virtual void Initialize(int id) { Id = id; ControllerType = GetType(); Name = ControllerType.Name; LoadControllerTypeInfoIfNeeded(); ControllerTypeInfo = ControllerTypeInfos[ControllerType]; } #endregion #region WarmUp /// <summary> /// Warms up the native calls. /// </summary> /// <param name="warmUp">The warm up.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "warmUp", Justification = "Warm up method.")] [InternalMethod] internal object WarmUp(string warmUp) { return new object(); } #endregion #region GetMethods /// <summary> /// Gets the methods. /// </summary> /// <returns></returns> internal List<ControllerMethodDescription> GetMethods() { return ControllerTypeInfo.Methods.Values.Select(m => new ControllerMethodDescription { Name = m.Name }) .ToList(); } #endregion #region GetControllerDescription /// <summary> /// Gets the controller description. /// </summary> /// <returns></returns> internal ControllerDescription GetControllerDescription() { return new ControllerDescription { Id = Id, Name = Name, Methods = GetMethods() }; } #endregion #region CallMethod /// <summary> /// Calls the method. /// </summary> /// <param name="methodName">The method name.</param> /// <param name="arguments">The arguments.</param> /// <param name="internalMethod">if set to <c>true</c> [internal method].</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> /// <exception cref="MethodNotFoundException"></exception> /// <exception cref="ParameterCountMismatchException"></exception> internal object CallMethod(string methodName, JArray arguments, bool internalMethod) { if (string.IsNullOrWhiteSpace(methodName)) throw new ArgumentNullException("methodName"); if (arguments == null) arguments = new JArray(); var method = FindMethod(methodName, internalMethod); if (method == null) throw new MethodNotFoundException(methodName, Name); if (method.ParameterTypes.Count != arguments.Count) throw new ParameterCountMismatchException(method.Name, Name); // parse parameters var parameters = method.ParameterTypes .Select((t, i) => { try { return arguments[i].ToObject(t); } catch (FormatException) { throw new ParameterMismatchException(i, t.Name, Enum.GetName(typeof(JTokenType), arguments[i].Type), method.Name, Name); } }) .ToList(); // return result var delegateParameters = new List<object> { this }; delegateParameters.AddRange(parameters); if (method.MethodType == MethodType.Action) { method.Delegate.DynamicInvoke(delegateParameters.ToArray()); return Value.Undefined; } else { return method.Delegate.DynamicInvoke(delegateParameters.ToArray()); } } /// <summary> /// Calls the method. /// </summary> /// <param name="methodName">The method name.</param> /// <param name="arguments">The arguments.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> /// <exception cref="MethodNotFoundException"></exception> /// <exception cref="ParameterCountMismatchException"></exception> internal object CallMethod(string methodName, JArray arguments) { return CallMethod(methodName, arguments, false); } #endregion #endregion #region Private #region IsValidMethod /// <summary> /// Determines whether the method is valid. /// </summary> /// <param name="methodInfo">The method information.</param> /// <param name="methodInfos">The method infos.</param> /// <returns></returns> private bool IsValidMethod(MethodInfo methodInfo, IEnumerable<MethodInfo> methodInfos) { bool isValid = true; if (methodInfos.Count(m => m.Name == methodInfo.Name) > 1) { Logger.Warn(string.Format("Overloaded methods are not supported. (controller = \"{0}\", method = \"{1}\")", Name, methodInfo.Name)); isValid = false; } else if (methodInfo.GetParameters().Any(p => p.ParameterType.IsByRef)) { Logger.Warn(string.Format("Ref parameters are not supported. (controller = \"{0}\", method = \"{1}\")", Name, methodInfo.Name)); isValid = false; } else if (methodInfo.GetParameters().Any(p => p.IsOut)) { Logger.Warn(string.Format("Out parameters are not supported. (controller = \"{0}\", method = \"{1}\")", Name, methodInfo.Name)); isValid = false; } else if (methodInfo.IsGenericMethod) { Logger.Warn(string.Format("Generic methods are not supported. (controller = \"{0}\", method = \"{1}\")", Name, methodInfo.Name)); isValid = false; } return isValid; } #endregion #region MethodInfoToControllerMethod /// <summary> /// Method info to controller method. /// </summary> /// <param name="method">The method.</param> /// <returns></returns> private ControllerMethod MethodInfoToControllerMethod(MethodInfo method) { return new ControllerMethod { Name = method.Name, Delegate = ExpressionUtility.CreateMethodDelegate(method), MethodType = method.ReturnType == typeof(void) ? MethodType.Action : MethodType.Function, ParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToList() }; } #endregion #region FindMethods /// <summary> /// Finds the methods. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private Dictionary<string, ControllerMethod> FindMethods(Type type) { var methods = new Dictionary<string, ControllerMethod>(); while (type != typeof(object)) { var methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(m => !m.IsSpecialName && m.GetCustomAttribute<ExcludeAttribute>() == null) .ToList(); foreach (var methodInfo in methodInfos) { if (IsValidMethod(methodInfo, methodInfos)) { var controllerMethod = MethodInfoToControllerMethod(methodInfo); methods.Add(controllerMethod.Name, controllerMethod); } } type = type.BaseType; } return methods; } #endregion #region FindInternalMethods /// <summary> /// Finds the internal methods. /// </summary> /// <returns></returns> private Dictionary<string, ControllerMethod> FindInternalMethods() { return typeof(Controller).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(m => !m.IsSpecialName && m.GetCustomAttribute<InternalMethodAttribute>() != null) .Select(m => MethodInfoToControllerMethod(m)) .ToDictionary(m => m.Name, m => m); } #endregion #region FindMethod /// <summary> /// Finds the method. /// </summary> /// <param name="methodName">Name of the method.</param> /// <param name="internalMethod">if set to <c>true</c> [internal method].</param> /// <returns></returns> private ControllerMethod FindMethod(string methodName, bool internalMethod) { var methods = internalMethod ? ControllerTypeInfo.InternalMethods : ControllerTypeInfo.Methods; ControllerMethod method = null; if (methods.TryGetValue(methodName, out method)) return method; if (methods.TryGetValue(StringUtility.PascalCase(methodName), out method)) return method; if (methods.TryGetValue(StringUtility.CamelCase(methodName), out method)) return method; return null; } /// <summary> /// Finds the method. /// </summary> /// <param name="methodName">Name of the method.</param> /// <returns></returns> private ControllerMethod FindMethod(string methodName) { return FindMethod(methodName, false); } #endregion #region LoadControllerTypeInfoIfNeeded /// <summary> /// Loads the controller type information if needed. /// </summary> private void LoadControllerTypeInfoIfNeeded() { if (!ControllerTypeInfos.ContainsKey(ControllerType)) { ControllerTypeInfos.Add(ControllerType, new ControllerTypeInfo { Methods = FindMethods(ControllerType), InternalMethods = FindInternalMethods() }); } } #endregion #endregion #endregion #region IDisposable /// <summary> /// Was dispose already called. /// </summary> private bool _disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { } _disposed = true; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> [Exclude] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/DisplayHandler.cs using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Display handler. /// </summary> internal class DisplayHandler : CefDisplayHandler { } } <file_sep>/src/Samotorcan.HtmlUi.Core/JavascriptFunction.cs using Newtonsoft.Json.Linq; using Samotorcan.HtmlUi.Core.Utilities; using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Javascript function. /// </summary> internal class JavascriptFunction { #region Properties #region Public #region Id /// <summary> /// Gets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public Guid Id { get; private set; } #endregion #region Function /// <summary> /// Gets the function. /// </summary> /// <value> /// The function. /// </value> public CefV8Value Function { get; private set; } #endregion #region Context /// <summary> /// Gets the context. /// </summary> /// <value> /// The context. /// </value> public CefV8Context Context { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="JavascriptFunction"/> class. /// </summary> /// <param name="function">The function.</param> /// <param name="context">The context.</param> /// <exception cref="System.ArgumentNullException"> /// function /// or /// context /// </exception> public JavascriptFunction(CefV8Value function, CefV8Context context) { if (function == null) throw new ArgumentNullException("function"); if (context == null) throw new ArgumentNullException("context"); Id = Guid.NewGuid(); Function = function; Context = context; } #endregion #region Methods #region Public #region Execute /// <summary> /// Executes the function. /// </summary> public JToken Execute() { return ParseCefV8Value(Function.ExecuteFunctionWithContext(Context, null, new CefV8Value[0])); } /// <summary> /// Executes the function with data. /// </summary> /// <param name="data">The data.</param> public JToken Execute(object data) { return ParseCefV8Value(Function.ExecuteFunctionWithContext(Context, null, new CefV8Value[] { CefV8Value.CreateString(JsonUtility.SerializeToJson(data)) })); } /// <summary> /// Executes the function with json. /// </summary> /// <param name="json">The json.</param> public JToken Execute(string json) { return ParseCefV8Value(Function.ExecuteFunctionWithContext(Context, null, new CefV8Value[] { CefV8Value.CreateString(json) })); } #endregion #endregion #region Private #region ParseCefV8Value /// <summary> /// Parses the cef v8 value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> private JToken ParseCefV8Value(CefV8Value value) { if (value == null) return null; return CefUtility.RunInContext(Context, () => { if (value.IsInt) return JToken.FromObject(value.GetIntValue()); if (value.IsUInt) return JToken.FromObject(value.GetUIntValue()); if (value.IsDouble) return JToken.FromObject(value.GetDoubleValue()); if (value.IsBool) return JToken.FromObject(value.GetBoolValue()); if (value.IsDate) return JToken.FromObject(value.GetDateValue()); if (value.IsString) return JToken.FromObject(value.GetStringValue()); if (value.IsUndefined) return JValue.CreateUndefined(); if (value.IsArray) { var array = new JArray(); for (var i = 0; i < value.GetArrayLength(); i++) array.Add(ParseCefV8Value(value.GetValue(i))); return array; } if (value.IsObject) { var obj = new JObject(); foreach (var propertyName in value.GetKeys()) obj.Add(propertyName, ParseCefV8Value(value.GetValue(propertyName))); return obj; } return JValue.CreateNull(); }); } #endregion #endregion #endregion } } <file_sep>/README.md # HtmlUi HtmlUi is a framework for creating desktop C# applications with HTML user interface. ## Overview The framework uses [CEF](https://bitbucket.org/chromiumembedded/cef) library to render the UI and C# to connect controllers with the UI. For client side on the UI the framework curently only support [AngularJS](https://angularjs.org/). Every AngularJS controller is linked with the C# controller and so every property changed in the C# controller gets updated to the AngularJS controller and vice versa. Methods on the C# controller are also linked to to the AngularJS side so they can be called from the UI. ## CEF binaries CEF binaries can be compiled from the [CEF sources](https://bitbucket.org/chromiumembedded/cef/wiki/BranchesAndBuilding) or downloaded from the [CEF Builds](https://cefbuilds.com/). HtmlUi currently uses CEF version 3.2357.1281. The required files for CEF to run are listed [here](https://code.google.com/p/chromiumembedded/source/browse/trunk/cef3/tools/distrib/win/README.redistrib.txt). The repository also includes the Windows x86 and Linux x64 binaries to run examples without the need to search and download the right CEF. ## CefGlue To use CEF in C# the framework uses a library called [CefGlue](https://bitbucket.org/xilium/xilium.cefglue) to P/Invoke calls to CEF. Which CEF version the framework uses is conditional with the CefGlue library. When the CefGlue library gets updated so will the framework be upadated to use the newest CEF version. ## Usage The framework was only tested with Visual Studio 2015. To create a new application first create a new Console Application in Visual Studio. The minimum C# supported version by the framework is 4.5. ![new console application](docs/NewConsoleApplication.jpg) To debug the application with CEF `Enable the Visual Studio hosting process` must be unchecked in the project properties. If this is enabled you will only get a white screen when running the application in debug mode. ![new console application](docs/HostingProcess.jpg) Next the output type in project options must be changed to Windows Application so the console window is not started. ![new console application](docs/ApplicationType.jpg) The Platform Target must also be set to either x86 or x64 and the correct bit version of CEF must be copied next to the application. Windows x86 and Linux x64 CEF binaries can be found in the [repository](src/References/cef). ![new console application](docs/PlatformTarget.jpg) The framework will start multiple processes where the first started process will be the main application process. To correctly run child processes the main method of the application should look like something like this. ```C# static void Main(string[] args) { if (HtmlUiRuntime.ApplicationType == ApplicationType.ChildApplication) { OSChildApplication.Run(); return; } OSApplication.Run(); } ``` At this part the HtmlUi must be added in references to correctly find HtmlUi classes. The framework currently supports only one main window. To add the view for the main window create a folder named Views and add Index.html file. This file will contain the html for the UI part. Next you have to mark the Index.html file as Embedded Resource or Copy always in the file properties. ![new console application](docs/IndexProperties.jpg) From here on now you can start the application and you should get an empty white window. To edit the UI simply add all your html in the Index.html and rerun the application. If you selected that Index.html is Copy always you can edit the file and refresh (F5) the window without restarting the application. The Developer Tools can be accessed by pressing F12 or clicking the top left corner of the application and selecting Developer Tools. To connect a C# controller with the AngularJS controller create an angular module and include the `htmlUi` module. Next in the AngularJS controller request a service `htmlUi.controller` and create the C# controller with `htmlUiController.createObservableController('controllerName', $scope);`. Now the `$scope` will contain all the properties and methods that are defined in the C# controller. ```JavaScript var app = angular.module('myApp', ['htmlUi']); app.controller('exampleController', ['$scope', 'htmlUi.controller', function ($scope, htmlUiController) { htmlUiController.createObservableController('exampleController', $scope); // controller code ... }); ``` To create a C# controller simply create a class that extends either [Controller](src/Samotorcan.HtmlUi.Core/Controller.cs) or [ObservableController](src/Samotorcan.HtmlUi.Core/ObservableController.cs). The controllers that are extended from Controller will only have methods linked to the AngularJS controller and properties will be ignored. Controllers created this way are used where the AngularJS scope is not created like services. ```C# public class ExampleController : Controller { public void DoSomething() { // this method can be called from JavaScript } } ``` Controllers that extend ObservableController are used where the AngularJS scope is created like the AngularJS controller. The scope will contain all the methods and the properties that are defined in the C# controller. The properties are also linked and every property changed in scope or C# controller will be sync back. In AngularJS the framework adds watches to all the controller properties to watch for changes and sync them back to C# controller. In C# controller the framework must be notified of property changes by calling the [INotifyPropertyChanged.PropertyChanged](https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged) event or `SetField` in controller. ```C# public class ExampleController : ObservableController { public string SomeProperty { get; set; } // only changes from JavaScript to C# are synced private string _someOtherProperty; public string SomeOtherProperty // changes are synced both ways { get { return _someOtherProperty; } set { SetField(ref _someOtherProperty, value); } } } ``` ## Windows The create an application for Windows only the CEF binaries must be copied next to the application tu run properly. No additional steps are needed. ## Linux The run the application on Linux [Mono](http://www.mono-project.com/) is required. After Mono is installed on Linux the application must be packed into a bundle with [mkbundle](http://www.mono-project.com/archived/guiderunning_mono_applications/#bundles). The CEF library must be linked before `libc.so`. To achieve this you can run the application with `LD_PRELOAD` like this `LD_PRELOAD=LD_PRELOAD=/path/to/libcef.so /path/to/your/app` or by modifying the link part in mkbundle process. An example of how to modify the mkbundle process to include the `libcef.so` before `libc.so`. ```Shell mkbundle -c -o host.c -oo bundles.o yourApp.exe cc -ggdb -o yourApp -Wall host.c -Wl,-rpath=. libcef.so `pkg-config --cflags --libs mono-2` bundles.o rm host.c bundles.o ``` The CEF bit version is dependent on the bit version of Mono. If you have a x86 version of Mono you will need a x86 version of CEF and if you have a x64 version of Mono you will need a x64 version of CEF. ## Examples The sources contain one example application [TodoList](src/Samotorcan.Examples.TodoList). The application shows how to use the HtmlUi framework to sync todo items from UI to C# and load and save todo items in a JSON file. To run the example application the required CEF version must be copied next to the example application and for Linux the example application must also be packed with mkbundle. ![new console application](docs/TodoList.jpg) <file_sep>/src/Samotorcan.HtmlUi.Core/HtmlUiRuntime.cs using System.Linq; using Samotorcan.HtmlUi.Core.Utilities; using Xilium.CefGlue; using System; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Html UI runtime. /// </summary> public static class HtmlUiRuntime { #region Properties #region Public #region ApplicationType private static ApplicationType? _applicationType; /// <summary> /// Gets the type of the application. /// </summary> /// <value> /// The type of the application. /// </value> public static ApplicationType ApplicationType { get { if (_applicationType == null) { var processArguments = EnvironmentUtility.GetCommandLineArgs(); _applicationType = processArguments.Any(a => a.StartsWith("--type=")) ? ApplicationType.ChildApplication : ApplicationType.Application; } return _applicationType.Value; } } #endregion #region Platform /// <summary> /// Gets the platform. /// </summary> /// <value> /// The platform. /// </value> /// <exception cref="System.InvalidOperationException">Unknown platform.</exception> public static Platform Platform { get { switch (CefRuntime.Platform) { case CefRuntimePlatform.Windows: return Platform.Windows; case CefRuntimePlatform.Linux: return Platform.Linux; case CefRuntimePlatform.MacOSX: return Platform.OSX; default: throw new InvalidOperationException("Unknown platform."); } } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Logs/LogMessageType.cs using System; namespace Samotorcan.HtmlUi.Core.Logs { /// <summary> /// Log message type. /// </summary> public sealed class LogMessageType { #region LogTypes #region Debug /// <summary> /// The debug. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It's immutable.")] public static readonly LogMessageType Debug = new LogMessageType("Debug"); #endregion #region Info /// <summary> /// The info. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It's immutable.")] public static readonly LogMessageType Info = new LogMessageType("Info"); #endregion #region Warn /// <summary> /// The warn. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It's immutable.")] public static readonly LogMessageType Warn = new LogMessageType("Warn"); #endregion #region Error /// <summary> /// The error. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It's immutable.")] public static readonly LogMessageType Error = new LogMessageType("Error"); #endregion #endregion #region Properties #region Public #region Value /// <summary> /// Gets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="LogMessageType"/> class. /// </summary> /// <param name="value">The value.</param> private LogMessageType(string value) { Value = value; } #endregion #region Methods #region Public #region Parse /// <summary> /// Parses the specified log message type. /// </summary> /// <param name="logMessageType">The log message type.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">log message type</exception> /// <exception cref="System.ArgumentException">Invalid log message type.;logMessageType</exception> public static LogMessageType Parse(string logMessageType) { if (string.IsNullOrWhiteSpace(logMessageType)) throw new ArgumentNullException("logMessageType"); if (logMessageType == Debug.Value) return Debug; if (logMessageType == Info.Value) return Info; if (logMessageType == Warn.Value) return Warn; if (logMessageType == Error.Value) return Error; throw new ArgumentException("Invalid log message type.", "logMessageType"); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/LoadHandler.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Load handler. /// </summary> internal class LoadHandler : CefLoadHandler { #region Properties #region Protected #region OnLoadStart /// <summary> /// Called when the browser begins loading a frame. The |frame| value will /// never be empty -- call the IsMain() method to check if this frame is the /// main frame. Multiple frames may be loading at the same time. Sub-frames may /// start or continue loading after the main frame load has ended. This method /// may not be called for a particular frame if the load request for that frame /// fails. For notification of overall browser load status use /// OnLoadingStateChange instead. /// </summary> /// <param name="browser"></param> /// <param name="frame"></param> protected override void OnLoadStart(CefBrowser browser, CefFrame frame) { if (frame == null) throw new ArgumentNullException("frame"); if (frame.IsMain) { Application.Current.InvokeOnMain(() => { Application.Current.Window.DestroyControllers(); }); } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/App.cs using Samotorcan.HtmlUi.Core.Browser.Handlers; using System; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Events; namespace Samotorcan.HtmlUi.Core.Browser { /// <summary> /// Browser app. /// </summary> internal class App : CefApp { #region Events #region ContextInitialized /// <summary> /// Occurs when context is initialized. /// </summary> public event EventHandler<ContextInitializedEventArgs> ContextInitialized; #endregion #endregion #region Properties #region Private #region BrowserProcessHandler /// <summary> /// Gets or sets the browser process handler. /// </summary> /// <value> /// The browser process handler. /// </value> private ProcessHandler BrowserProcessHandler { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="App"/> class. /// </summary> public App() : base() { BrowserProcessHandler = new ProcessHandler(); BrowserProcessHandler.ContextInitialized += (s, args) => { if (ContextInitialized != null) ContextInitialized(this, new ContextInitializedEventArgs()); }; } #endregion #region Methods #region Protected #region OnBeforeCommandLineProcessing /// <summary> /// Called before command line processing. /// </summary> /// <param name="processType">Type of the process.</param> /// <param name="commandLine">The command line.</param> protected override void OnBeforeCommandLineProcessing(string processType, CefCommandLine commandLine) { if (commandLine == null) throw new ArgumentNullException("commandLine"); } #endregion #region GetBrowserProcessHandler /// <summary> /// Gets the browser process handler. /// </summary> /// <returns></returns> protected override CefBrowserProcessHandler GetBrowserProcessHandler() { return BrowserProcessHandler; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Messages/CallNative.cs using System; namespace Samotorcan.HtmlUi.Core.Messages { internal class CallNative { public Guid? CallbackId { get; set; } public string Name { get; set; } public string Json { get; set; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Resources/TypeScript/htmlUi.run.ts /// <reference path="references.ts" /> // run namespace htmlUi { native.loadInternalScript('lodash.min.js'); export var _: _.LoDashStatic = window['_'].noConflict(); }<file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/NativeMessageHandler.cs using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Messages; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using System.Threading.Tasks; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Attributes; using Newtonsoft.Json; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { internal class NativeMessageHandler { private delegate object NativeFunctionDelegate(string json); private delegate void ProcessMessageDelegate(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage); private Dictionary<string, NativeFunctionDelegate> NativeFunctionDelegates { get; set; } private Dictionary<string, ProcessMessageDelegate> ProcessMessageDelegates { get; set; } public NativeMessageHandler() { NativeFunctionDelegates = NativeFunctionAttribute.GetHandlers<NativeMessageHandler, NativeFunctionDelegate>(this); ProcessMessageDelegates = ProcessMessageAttribute.GetHandlers<NativeMessageHandler, ProcessMessageDelegate>(this); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "sourceProcess", Justification = "I want it to match to OnProcessMessageReceived method.")] public bool ProcessMessage(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { if (processMessage == null) throw new ArgumentNullException("processMessage"); if (string.IsNullOrWhiteSpace(processMessage.Name)) throw new ArgumentException("ProcessMessage.Name is null or white space."); Logger.Debug(string.Format("Process message: {0}", processMessage.Name)); ProcessMessageDelegate handler; ProcessMessageDelegates.TryGetValue(processMessage.Name, out handler); if (handler != null) { handler(browser, sourceProcess, processMessage); return true; } return false; } [ProcessMessage("syncProperty")] private void ProcessMessageSyncProperty(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var syncProperty = MessageUtility.DeserializeMessage<SyncProperty>(processMessage); ChildApplication.Current.SetSyncProperty(syncProperty.Name, syncProperty.Value); } [ProcessMessage("callFunctionResult")] private void ProcessMessageCallFunction(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var message = MessageUtility.DeserializeMessage<CallFunctionResult>(processMessage); Application.Current.Window.SetCallFunctionResult(message.CallbackId, message.Result); } [ProcessMessage("native")] private void ProcessMessageNative(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var callNative = MessageUtility.DeserializeMessage<CallNative>(processMessage); Application.Current.InvokeOnMainAsync(() => { object returnData = null; Exception exception = null; NativeFunctionDelegate handler; NativeFunctionDelegates.TryGetValue(callNative.Name, out handler); // function call if (handler != null) { try { returnData = handler(callNative.Json); } catch (Exception e) { exception = e; } } else { exception = new NativeNotFoundException(callNative.Name); } // callback if (callNative.CallbackId != null) { var nativeResponse = new NativeResponse(); if (exception != null) { nativeResponse.Exception = ExceptionUtility.CreateJavascriptException(exception); nativeResponse.Type = NativeResponseType.Exception; nativeResponse.Value = null; } else { if (returnData == Value.Undefined) { nativeResponse.Exception = null; nativeResponse.Type = NativeResponseType.Undefined; nativeResponse.Value = null; } else { nativeResponse.Exception = null; nativeResponse.Type = NativeResponseType.Value; nativeResponse.Value = returnData; } } var returnJson = JsonUtility.SerializeToJson(nativeResponse); MessageUtility.SendMessage(CefProcessId.Renderer, browser, "native", new CallNativeResult { JsonResult = returnJson, CallbackId = callNative.CallbackId }); } }).ContinueWith(t => { Logger.Error("Native call exception.", t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); } [NativeFunction("syncControllerChanges")] private object NativeFunctionSyncControllerChanges(string json) { var controllerChanges = JsonConvert.DeserializeObject<List<ControllerChange>>(json); Application.Current.Window.SyncControllerChangesToNative(controllerChanges); return Value.Undefined; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "json", Justification = "It has to match to the delegate.")] [NativeFunction("getControllerNames")] private object NativeFunctionGetControllerNames(string json) { return Application.Current.GetControllerNames(); } [NativeFunction("createController")] private object NativeFunctionCreateController(string json) { var createController = JsonConvert.DeserializeObject<CreateController>(json); var controller = Application.Current.Window.CreateController(createController.Name); return controller.GetControllerDescription(); } [NativeFunction("createObservableController")] private object NativeFunctionCreateObservableController(string json) { var createController = JsonConvert.DeserializeObject<CreateController>(json); var observableController = Application.Current.Window.CreateObservableController(createController.Name); return observableController.GetObservableControllerDescription(); } [NativeFunction("destroyController")] private object NativeFunctionDestroyController(string json) { var controllerId = JsonConvert.DeserializeObject<int>(json); Application.Current.Window.DestroyController(controllerId); return Value.Undefined; } [NativeFunction("callMethod")] private object NativeFunctionCallMethod(string json) { var methodData = JsonConvert.DeserializeObject<CallMethod>(json); return Application.Current.Window.CallMethod(methodData.Id, methodData.Name, methodData.Arguments, methodData.InternalMethod); } } } <file_sep>/src/Samotorcan.HtmlUi.Windows/ApplicationContext.cs using Samotorcan.HtmlUi.Core; namespace Samotorcan.HtmlUi.Windows { /// <summary> /// Windows application context. /// </summary> public class ApplicationContext : WindowsForms.ApplicationContext { #region Properties #region Public #region WindowSettings /// <summary> /// Gets the window settings. /// </summary> /// <value> /// The window settings. /// </value> public new WindowContext WindowSettings { get { return (WindowContext)base.WindowSettings; } protected set { base.WindowSettings = value; } } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ApplicationContext"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ApplicationContext() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="ApplicationContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ApplicationContext(ApplicationContext settings) { Initialize(settings); } /// <summary> /// Initializes a new instance of the <see cref="ApplicationContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ApplicationContext(Core.ApplicationContext settings) { if (settings != null) { var windowsApplicationSettings = settings as ApplicationContext; if (windowsApplicationSettings != null) { Initialize(windowsApplicationSettings); } else { var windowsFormsApplicationSettings = settings as WindowsForms.ApplicationContext; if (windowsFormsApplicationSettings != null) Initialize(windowsFormsApplicationSettings); else Initialize(settings); } } else { Initialize(); } } #endregion #region Methods #region Private #region InitializeSelf /// <summary> /// Initializes this instance. /// </summary> private void InitializeSelf(ApplicationContext settings) { if (settings != null) { WindowSettings = settings.WindowSettings; } else { WindowSettings = new WindowContext(base.WindowSettings); } } #endregion #endregion #region Protected #region Initialize /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected virtual void Initialize(ApplicationContext settings) { base.Initialize(settings); InitializeSelf(settings); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(BaseApplicationSettings settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(Core.ApplicationContext settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(WindowsForms.ApplicationContext settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> protected override void Initialize() { Initialize(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/UndefinedValue.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Undefined value. /// </summary> internal sealed class UndefinedValue { #region Properties #region Public #region Value /// <summary> /// Gets the value. /// </summary> /// <value> /// The value. /// </value> public static UndefinedValue Value { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes the <see cref="UndefinedValue"/> class. /// </summary> static UndefinedValue() { Value = new UndefinedValue(); } /// <summary> /// Prevents a default instance of the <see cref="UndefinedValue"/> class from being created. /// </summary> private UndefinedValue() { } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Linux/NativeMethods.cs using System; using System.Runtime.InteropServices; namespace Samotorcan.HtmlUi.Linux { /// <summary> /// Native methods /// </summary> internal static class NativeMethods { private const string CefDllName = "libcef"; private const string XLibDllName = "libX11"; private const CallingConvention CefCall = CallingConvention.Cdecl; /// <summary> /// Return the singleton X11 display shared with Chromium. The display is not /// thread-safe and must only be accessed on the browser process UI thread. /// </summary> /// <returns>XDisplay</returns> [DllImport(CefDllName, EntryPoint = "cef_get_xdisplay", CallingConvention = CefCall)] public static extern IntPtr get_xdisplay(); /// <summary> /// Resize the window. /// </summary> /// <param name="display">The display.</param> /// <param name="window">The window.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> [DllImport(XLibDllName)] extern public static void XResizeWindow(IntPtr display, IntPtr window, uint width, uint height); } } <file_sep>/src/Samotorcan.HtmlUi.Core/ClientFunctionResult.cs using Newtonsoft.Json.Linq; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Client function result. /// </summary> internal class ClientFunctionResult { #region Properties #region Public #region Type /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> public ClientFunctionResultType Type { get; set; } #endregion #region Exception /// <summary> /// Gets or sets the exception. /// </summary> /// <value> /// The exception. /// </value> public JToken Exception { get; set; } #endregion #region Value /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public JToken Value { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/MethodType.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Method type. /// </summary> internal enum MethodType { /// <summary> /// The action. /// </summary> Action, /// <summary> /// The function. /// </summary> Function } } <file_sep>/src/Samotorcan.HtmlUi.Core/Renderer/Handlers/DeveloperToolsRequestHandler.cs using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Renderer.Handlers { /// <summary> /// Developer tools request handler. /// </summary> internal class DeveloperToolsRequestHandler : CefRequestHandler { #region Methods #region Protected #region GetResourceHandler /// <summary> /// Gets the resource handler. /// </summary> /// <param name="browser">The browser.</param> /// <param name="frame">The frame.</param> /// <param name="request">The request.</param> /// <returns></returns> protected override CefResourceHandler GetResourceHandler(CefBrowser browser, CefFrame frame, CefRequest request) { return null; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Messages/CallFunction.cs using System; namespace Samotorcan.HtmlUi.Core.Messages { internal class CallFunction { public Guid CallbackId { get; set; } public string Name { get; set; } public object Data { get; set; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerMethodDescription.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller method description. /// </summary> internal class ControllerMethodDescription : ControllerMethodBase { } } <file_sep>/src/Samotorcan.HtmlUi.Core/ObservableController.cs using Newtonsoft.Json.Linq; using Samotorcan.HtmlUi.Core.Attributes; using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Observable controller. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors", Justification = "All classes that extend ObservableController must have this exact constructor.")] public abstract class ObservableController : Controller, INotifyPropertyChanged { #region Properties #region Internal #region PropertyChanges /// <summary> /// Gets or sets the property changes. /// </summary> /// <value> /// The property changes. /// </value> internal HashSet<string> PropertyChanges { get; set; } #endregion #region ObservableCollectionChanges /// <summary> /// Gets or sets the observable collection changes. /// </summary> /// <value> /// The observable collection changes. /// </value> internal Dictionary<string, ObservableCollectionChanges> ObservableCollectionChanges { get; set; } #endregion #region ObservableControllerTypeInfo /// <summary> /// Gets or sets the observable controller type information. /// </summary> /// <value> /// The observable controller type information. /// </value> internal ObservableControllerTypeInfo ObservableControllerTypeInfo { get; set; } #endregion #region ObservableControllerTypeInfos /// <summary> /// Gets or sets the observable controller type infos. /// </summary> /// <value> /// The observable controller type infos. /// </value> internal static Dictionary<Type, ObservableControllerTypeInfo> ObservableControllerTypeInfos { get; set; } #endregion #endregion #region Private #region SyncChanges /// <summary> /// Gets or sets a value indicating whether to synchronize changes. /// </summary> /// <value> /// <c>true</c> to synchronize changes; otherwise, <c>false</c>. /// </value> private bool SyncChanges { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes the <see cref="ObservableController"/> class. /// </summary> static ObservableController() { ObservableControllerTypeInfos = new Dictionary<Type, ObservableControllerTypeInfo>(); } #endregion #region Methods #region Internal #region Initialize /// <summary> /// Initializes the observable controller. /// </summary> /// <param name="id">The identifier.</param> internal override void Initialize(int id) { base.Initialize(id); PropertyChanges = new HashSet<string>(); ObservableCollectionChanges = new Dictionary<string, ObservableCollectionChanges>(); LoadObservableControllerTypeInfoIfNeeded(); ObservableControllerTypeInfo = ObservableControllerTypeInfos[ControllerType]; SyncChanges = true; PropertyChanged += PropertyChangedHandle; foreach (var property in ObservableControllerTypeInfo.Properties.Values) { if (property.IsObservableCollection) AddObservableCollection(property); } } #endregion #region GetProperties /// <summary> /// Gets the properties. /// </summary> /// <param name="access">The access.</param> /// <returns></returns> internal List<ControllerPropertyDescription> GetProperties(Access access) { return ObservableControllerTypeInfo.Properties.Values.Where(p => p.Access.HasFlag(access)) .Select(p => new ControllerPropertyDescription { Name = p.Name, Value = p.Access.HasFlag(Access.Read) ? p.GetDelegate.DynamicInvoke(this) : null }) .ToList(); } /// <summary> /// Gets the properties. /// </summary> /// <returns></returns> internal List<ControllerPropertyDescription> GetProperties() { return GetProperties(Access.Read | Access.Write); } #endregion #region GetObservableControllerDescription /// <summary> /// Gets the observable controller description. /// </summary> /// <returns></returns> internal ObservableControllerDescription GetObservableControllerDescription() { return new ObservableControllerDescription { Id = Id, Name = Name, Properties = GetProperties(), Methods = GetMethods() }; } #endregion #region SetPropertyValue /// <summary> /// Sets the property value. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <param name="sync">if set to <c>true</c> synchronize changes.</param> /// <exception cref="System.ArgumentNullException">propertyName</exception> /// <exception cref="PropertyNotFoundException"></exception> /// <exception cref="PropertyMismatchException"> /// null /// or /// </exception> internal void SetPropertyValue(string propertyName, JToken value, bool sync) { if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentNullException("propertyName"); var property = FindProperty(propertyName); if (property == null) throw new PropertyNotFoundException(propertyName, Name); if (!property.Access.HasFlag(Access.Write)) throw new ReadOnlyPropertyException(property.Name, Name); if (value == null) { if (!property.PropertyType.IsValueType || Nullable.GetUnderlyingType(property.PropertyType) != null) SetPropertyValueInternal(property, value, sync); else throw new PropertyMismatchException(Name, property.Name, property.PropertyType.Name, "null"); } else { try { SetPropertyValueInternal(property, value.ToObject(property.PropertyType), sync); } catch (ArgumentException) { throw new PropertyMismatchException(Name, property.Name, property.PropertyType.Name, Enum.GetName(typeof(JTokenType), value.Type)); } catch (FormatException) { throw new PropertyMismatchException(Name, property.Name, property.PropertyType.Name, Enum.GetName(typeof(JTokenType), value.Type)); } } } /// <summary> /// Sets the property value. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> internal void SetPropertyValue(string propertyName, JToken value) { SetPropertyValue(propertyName, value, false); } #endregion #region GetPropertyValue /// <summary> /// Gets the property value. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">propertyName</exception> /// <exception cref="PropertyNotFoundException"></exception> /// <exception cref="Samotorcan.HtmlUi.Core.Exceptions.WriteOnlyPropertyException"></exception> internal object GetPropertyValue(string propertyName) { if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentNullException("propertyName"); var property = FindProperty(propertyName); if (property == null) throw new PropertyNotFoundException(propertyName, Name); if (!property.Access.HasFlag(Access.Read)) throw new WriteOnlyPropertyException(property.Name, Name); return property.GetDelegate.DynamicInvoke(this); } #endregion #region SetObservableCollectionChanges /// <summary> /// Sets the observable collection changes. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="changes">The changes.</param> /// <param name="sync">if set to <c>true</c> synchronize changes.</param> /// <exception cref="System.ArgumentNullException"> /// propertyName /// or /// changes /// </exception> /// <exception cref="PropertyNotFoundException"></exception> /// <exception cref="PropertyMismatchException"></exception> /// <exception cref="WriteOnlyPropertyException"></exception> internal void SetObservableCollectionChanges(string propertyName, ObservableCollectionChanges changes, bool sync) { if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentNullException("propertyName"); if (changes == null) throw new ArgumentNullException("changes"); var property = FindProperty(propertyName); if (property == null) throw new PropertyNotFoundException(propertyName, Name); if (!property.IsCollection) throw new PropertyMismatchException(Name, property.Name, string.Format("{0}/{1}", typeof(IList).Name, typeof(IList<>).Name), property.PropertyType.Name); if (!property.Access.HasFlag(Access.Read)) throw new WriteOnlyPropertyException(property.Name, Name); var collection = property.GetDelegate.DynamicInvoke(this); if (collection != null) { if (property.IsArray) SetArrayChanges((Array)collection, property, changes, sync); else if (property.IsIList) SetIListChanges((IList)collection, property, changes, sync); else SetGenericIListChanges(collection, property, changes, sync); } } /// <summary> /// Sets the observable collection changes. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="changes">The changes.</param> internal void SetObservableCollectionChanges(string propertyName, ObservableCollectionChanges changes) { SetObservableCollectionChanges(propertyName, changes, false); } #endregion #endregion #region Private #region LoadObservableControllerTypeInfoIfNeeded /// <summary> /// Loads the observable controller type information if needed. /// </summary> private void LoadObservableControllerTypeInfoIfNeeded() { if (!ObservableControllerTypeInfos.ContainsKey(ControllerType)) { ObservableControllerTypeInfos.Add(ControllerType, new ObservableControllerTypeInfo { Properties = FindProperties(ControllerType) }); } } #endregion #region SetPropertyValueInternal /// <summary> /// Sets the property value. /// </summary> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <param name="sync">if set to <c>true</c> synchronize changes.</param> private void SetPropertyValueInternal(ControllerProperty property, object value, bool sync) { try { SyncChanges = sync; property.SetDelegate.DynamicInvoke(this, value); } finally { SyncChanges = true; } } #endregion #region FindProperties /// <summary> /// Finds the properties. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private Dictionary<string, ControllerProperty> FindProperties(Type type) { var properties = new Dictionary<string, ControllerProperty>(); foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { // ignore properties with exclude attribute if (property.GetCustomAttribute<ExcludeAttribute>() == null) { var getMethod = property.GetGetMethod(false); var setMethod = property.GetSetMethod(false); Access? access = null; // access if (property.CanRead && getMethod != null && property.CanWrite && setMethod != null) access = Access.Read | Access.Write; else if (property.CanRead && getMethod != null) access = Access.Read; else if (property.CanWrite && setMethod != null) access = Access.Write; // add if (access != null) { var controllerProperty = new ControllerProperty { Name = property.Name, PropertyType = property.PropertyType, IsObservableCollection = IsObservableCollection(property.PropertyType), IsCollection = IsCollection(property.PropertyType), IsIList = IsIList(property.PropertyType), IsGenericIList = IsGenericIList(property.PropertyType), IsArray = property.PropertyType.IsArray, GetDelegate = getMethod != null ? ExpressionUtility.CreateMethodDelegate(getMethod) : null, SetDelegate = setMethod != null ? ExpressionUtility.CreateMethodDelegate(setMethod) : null, Access = access.Value }; if (controllerProperty.IsArray) AddArrayInfo(controllerProperty); if (controllerProperty.IsGenericIList) AddGenericIListInfo(controllerProperty); if (controllerProperty.IsObservableCollection) AddObservableCollection(controllerProperty); properties.Add(controllerProperty.Name, controllerProperty); } } } return properties; } #endregion #region IsObservableCollection /// <summary> /// Determines whether type is observable collection. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private bool IsObservableCollection(Type type) { return typeof(INotifyCollectionChanged).IsAssignableFrom(type) && IsCollection(type); } #endregion #region IsCollection /// <summary> /// Determines whether the specified type is collection. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private bool IsCollection(Type type) { return (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)) || typeof(IList).IsAssignableFrom(type)); } #endregion #region IsIList /// <summary> /// Determines whether the specified type is IsIList. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private bool IsIList(Type type) { return typeof(IList).IsAssignableFrom(type) && !type.IsArray; } #endregion #region IsGenericIList /// <summary> /// Determines whether the specified type is generic IList. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private bool IsGenericIList(Type type) { return type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)) && !type.IsArray; } #endregion #region AddGenericIListInfo /// <summary> /// Adds the generic IList info. /// </summary> /// <param name="property">The property.</param> private void AddGenericIListInfo(ControllerProperty property) { property.GenericIListAddDelegate = ExpressionUtility.CreateMethodDelegate(property.PropertyType.GetMethod("Add")); property.GenericIListRemoveAtDelegate = ExpressionUtility.CreateMethodDelegate(property.PropertyType.GetMethod("RemoveAt")); property.GenericIListCountDelegate = ExpressionUtility.CreateMethodDelegate(property.PropertyType.GetProperty("Count").GetGetMethod()); property.GenericIListInsertDelegate = ExpressionUtility.CreateMethodDelegate(property.PropertyType.GetMethod("Insert")); var indexMethod = property.PropertyType.GetProperties() .Single(p => p.GetIndexParameters().Length == 1 && p.GetIndexParameters()[0].ParameterType == typeof(int)) .GetSetMethod(false); property.GenericIListReplaceDelegate = ExpressionUtility.CreateMethodDelegate(indexMethod); property.GenericIListType = property.PropertyType.GetGenericArguments()[0]; } #endregion #region AddArrayInfo /// <summary> /// Adds the array information. /// </summary> /// <param name="property">The property.</param> private void AddArrayInfo(ControllerProperty property) { property.ArrayType = property.PropertyType.GetElementType(); } #endregion #region PadIList /// <summary> /// Pads the IList. /// </summary> /// <param name="list">The list.</param> /// <param name="toIndex">To index.</param> /// <param name="itemType">Type of the item.</param> private void PadIList(IList list, int toIndex, Type itemType) { while (list.Count < toIndex) list.Add(GetDefaultValue(itemType)); } #endregion #region PadGenericIList /// <summary> /// Pads the generic IList. /// </summary> /// <param name="list">The list.</param> /// <param name="property">The property.</param> /// <param name="toIndex">To index.</param> private void PadGenericIList(object list, ControllerProperty property, int toIndex) { while (property.GenericIListCount(list) < toIndex) property.GenericIListAdd(list, GetDefaultValue(property.GenericIListType)); } #endregion #region GetDefaultValue /// <summary> /// Gets the default value. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> private object GetDefaultValue(Type type) { if (type.IsValueType) return Activator.CreateInstance(type); return null; } #endregion #region SetIListChanges /// <summary> /// Sets the IList changes. /// </summary> /// <param name="list">The list.</param> /// <param name="property">The property.</param> /// <param name="changes">The changes.</param> /// <param name="sync">if set to <c>true</c> synchronize changes.</param> private void SetIListChanges(IList list, ControllerProperty property, ObservableCollectionChanges changes, bool sync) { try { SyncChanges = sync; var itemType = property.IsGenericIList ? property.GenericIListType : typeof(object); foreach (var change in changes.Actions) { if (change.Action == ObservableCollectionChangeAction.Add) { var startIndex = change.NewStartingIndex.Value; foreach (var item in change.NewItems) { PadIList(list, startIndex, itemType); if (startIndex >= list.Count) list.Add(item.ToObject(itemType)); else list.Insert(startIndex, item.ToObject(itemType)); startIndex++; } } else if (change.Action == ObservableCollectionChangeAction.Remove) { var removeIndex = change.OldStartingIndex.Value; if (list.Count > removeIndex) list.RemoveAt(removeIndex); } else if (change.Action == ObservableCollectionChangeAction.Replace) { var startIndex = change.NewStartingIndex.Value; foreach (var item in change.NewItems) { PadIList(list, startIndex, itemType); if (startIndex >= list.Count) list.Add(item.ToObject(itemType)); else list[startIndex] = item.ToObject(itemType); startIndex++; } } } } finally { SyncChanges = true; } } #endregion #region SetArrayChanges /// <summary> /// Sets the Array changes. /// </summary> /// <param name="array">The array.</param> /// <param name="property">The property.</param> /// <param name="changes">The changes.</param> /// <param name="sync">if set to <c>true</c> synchronize changes.</param> private void SetArrayChanges(Array array, ControllerProperty property, ObservableCollectionChanges changes, bool sync) { // TODO; fix throw exceptions try { SyncChanges = sync; foreach (var change in changes.Actions) { if (change.Action == ObservableCollectionChangeAction.Add) { throw new PropertyMismatchException(Name, property.Name, string.Format("{0}/{1}", typeof(IList).Name, typeof(IList<>).Name), property.PropertyType.Name); } else if (change.Action == ObservableCollectionChangeAction.Remove) { throw new PropertyMismatchException(Name, property.Name, string.Format("{0}/{1}", typeof(IList).Name, typeof(IList<>).Name), property.PropertyType.Name); } else if (change.Action == ObservableCollectionChangeAction.Replace) { var startIndex = change.NewStartingIndex.Value; foreach (var item in change.NewItems) { if (startIndex >= array.Length) throw new PropertyMismatchException(Name, property.Name, string.Format("{0}/{1}", typeof(IList).Name, typeof(IList<>).Name), property.PropertyType.Name); array.SetValue(item.ToObject(property.ArrayType), startIndex); startIndex++; } } } } finally { SyncChanges = true; } } #endregion #region SetGenericIListChanges /// <summary> /// Sets the generic IList changes. /// </summary> /// <param name="list">The list.</param> /// <param name="property">The property.</param> /// <param name="changes">The changes.</param> /// <param name="sync">if set to <c>true</c> synchronize changes.</param> private void SetGenericIListChanges(object list, ControllerProperty property, ObservableCollectionChanges changes, bool sync) { try { SyncChanges = sync; foreach (var change in changes.Actions) { if (change.Action == ObservableCollectionChangeAction.Add) { var startIndex = change.NewStartingIndex.Value; foreach (var item in change.NewItems) { PadGenericIList(list, property, startIndex); if (startIndex >= property.GenericIListCount(list)) property.GenericIListAdd(list, item.ToObject(property.GenericIListType)); else property.GenericIListInsert(list, startIndex, item.ToObject(property.GenericIListType)); startIndex++; } } else if (change.Action == ObservableCollectionChangeAction.Remove) { var removeIndex = change.OldStartingIndex.Value; if (property.GenericIListCount(list) > removeIndex) property.GenericIListRemoveAt(list, removeIndex); } else if (change.Action == ObservableCollectionChangeAction.Replace) { var startIndex = change.NewStartingIndex.Value; foreach (var item in change.NewItems) { PadGenericIList(list, property, startIndex); if (startIndex >= property.GenericIListCount(list)) property.GenericIListAdd(list, item.ToObject(property.GenericIListType)); else property.GenericIListReplace(list, startIndex, item.ToObject(property.GenericIListType)); startIndex++; } } } } finally { SyncChanges = true; } } #endregion #region FindProperty /// <summary> /// Finds the property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> private ControllerProperty FindProperty(string propertyName) { ControllerProperty property = null; if (ObservableControllerTypeInfo.Properties.TryGetValue(propertyName, out property)) return property; if (ObservableControllerTypeInfo.Properties.TryGetValue(StringUtility.PascalCase(propertyName), out property)) return property; if (ObservableControllerTypeInfo.Properties.TryGetValue(StringUtility.CamelCase(propertyName), out property)) return property; return null; } #endregion #region AddObservableCollection /// <summary> /// Adds the observable collection. /// </summary> /// <param name="property">The property.</param> /// <returns></returns> private void AddObservableCollection(ControllerProperty property) { RemoveObservableCollection(property); property.ObservableCollection = (INotifyCollectionChanged)property.GetDelegate.DynamicInvoke(this); if (property.ObservableCollection != null) { property.NotifyCollectionChangedEventHandler = new NotifyCollectionChangedEventHandler((sender, e) => { CollectionChangedHandle(sender, e, property); }); property.ObservableCollection.CollectionChanged += property.NotifyCollectionChangedEventHandler; } } #endregion #region RemoveObservableCollection /// <summary> /// Removes the observable collection. /// </summary> /// <param name="property">The property.</param> private void RemoveObservableCollection(ControllerProperty property) { if (property.ObservableCollection != null) property.ObservableCollection.CollectionChanged -= property.NotifyCollectionChangedEventHandler; property.NotifyCollectionChangedEventHandler = null; property.ObservableCollection = null; } #endregion #region PropertyChangedHandle /// <summary> /// Property changed handle. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param> private void PropertyChangedHandle(object sender, PropertyChangedEventArgs e) { var property = FindProperty(e.PropertyName); if (property.IsObservableCollection) AddObservableCollection(property); if (SyncChanges) PropertyChanges.Add(e.PropertyName); } #endregion #region CollectionChangedHandle /// <summary> /// Collection changed handle. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param> /// <param name="property">The property.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "sender", Justification = "I want it to be the same as the event parameters.")] private void CollectionChangedHandle(object sender, NotifyCollectionChangedEventArgs e, ControllerProperty property) { if (!SyncChanges) return; if (!ObservableCollectionChanges.ContainsKey(property.Name)) ObservableCollectionChanges.Add(property.Name, new ObservableCollectionChanges { Name = property.Name }); var changes = ObservableCollectionChanges[property.Name]; if (!changes.IsReset) { switch (e.Action) { case NotifyCollectionChangedAction.Add: changes.Actions.Add(new ObservableCollectionChange { NewItems = new JArray(e.NewItems), NewStartingIndex = e.NewStartingIndex, Action = ObservableCollectionChangeAction.Add }); break; case NotifyCollectionChangedAction.Move: changes.Actions.Add(new ObservableCollectionChange { OldStartingIndex = e.OldStartingIndex, NewStartingIndex = e.NewStartingIndex, Action = ObservableCollectionChangeAction.Move }); break; case NotifyCollectionChangedAction.Remove: changes.Actions.Add(new ObservableCollectionChange { OldStartingIndex = e.OldStartingIndex, Action = ObservableCollectionChangeAction.Remove }); break; case NotifyCollectionChangedAction.Replace: changes.Actions.Add(new ObservableCollectionChange { NewItems = new JArray(e.NewItems), NewStartingIndex = e.NewStartingIndex, Action = ObservableCollectionChangeAction.Replace }); break; case NotifyCollectionChangedAction.Reset: changes.Actions = new List<ObservableCollectionChange>(); changes.IsReset = true; break; } } } #endregion #endregion #endregion #region IDisposable /// <summary> /// Was dispose already called. /// </summary> private bool _disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (!_disposed) { if (disposing) { PropertyChanged -= PropertyChangedHandle; foreach (var property in ObservableControllerTypeInfo.Properties.Values) { if (property.ObservableCollection != null && property.NotifyCollectionChangedEventHandler != null) property.ObservableCollection.CollectionChanged -= property.NotifyCollectionChangedEventHandler; } } _disposed = true; } } #endregion #region INotifyPropertyChanged /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Sets the field. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Used for CallerMemberName.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#", Justification = "It must be a ref field.")] protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { Application.Current.EnsureMainThread(); if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } /// <summary> /// Called when property changed. /// </summary> /// <param name="propertyName">Name of the property.</param> private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerTypeInfo.cs using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller type info. /// </summary> internal class ControllerTypeInfo { #region Properties #region Public #region Methods /// <summary> /// Gets or sets the methods. /// </summary> /// <value> /// The methods. /// </value> public Dictionary<string, ControllerMethod> Methods { get; set; } #endregion #region InternalMethods /// <summary> /// Gets or sets the internal methods. /// </summary> /// <value> /// The internal methods. /// </value> public Dictionary<string, ControllerMethod> InternalMethods { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ControllerTypeInfo"/> class. /// </summary> public ControllerTypeInfo() { Methods = new Dictionary<string, ControllerMethod>(); InternalMethods = new Dictionary<string, ControllerMethod>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.OS/Windows.cs using Samotorcan.HtmlUi.Windows; namespace Samotorcan.HtmlUi.OS { /// <summary> /// Windows only methods. If you call any method in this class the Windows assembly gets loaded. /// </summary> internal static class Windows { public static void RunApplication(Core.ApplicationContext settings) { Application.Run(new ApplicationContext(settings)); } public static void RunChildApplication(Core.ChildApplicationContext settings) { ChildApplication.Run(new ChildApplicationContext(settings)); } } } <file_sep>/src/Samotorcan.Examples.TodoList/Services/DatabaseService.cs using Newtonsoft.Json; using Samotorcan.HtmlUi.Core; using System.Collections.Generic; using System.IO; using System.Text; namespace Samotorcan.Examples.TodoList.Controllers { public class DatabaseService : Controller { private const string _todosFileName = "todos.json"; public void SaveTodos(IEnumerable<TodoItem> todos) { if (todos == null) todos = new List<TodoItem>(); File.WriteAllText(_todosFileName, JsonConvert.SerializeObject(todos), Encoding.UTF8); } public List<TodoItem> LoadTodos() { if (File.Exists(_todosFileName)) return JsonConvert.DeserializeObject<List<TodoItem>>(File.ReadAllText(_todosFileName, Encoding.UTF8)); return new List<TodoItem>(); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/ConvertUtility.cs using System; namespace Samotorcan.HtmlUi.Core.Utilities { internal static class ConvertUtility { public static object ChangeType(object value, Type conversionType) { if (conversionType.IsEnum) return Enum.ToObject(conversionType, value); return Convert.ChangeType(value, conversionType); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerMethodBase.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller method base. /// </summary> internal class ControllerMethodBase { #region Properties #region Public #region Name /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/StringUtility.cs using System; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// String utility. /// </summary> internal static class StringUtility { #region Methods #region Public #region Normalize /// <summary> /// Normalizes the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="normalizeType">The normalize type.</param> /// <returns></returns> public static string Normalize(string value, NormalizeType normalizeType) { if (string.IsNullOrWhiteSpace(value)) return value; if (normalizeType == NormalizeType.CamelCase) return Char.ToLowerInvariant(value[0]) + value.Substring(1); else if (normalizeType == NormalizeType.PascalCase) return Char.ToUpperInvariant(value[0]) + value.Substring(1); return value; } #endregion #region CamelCase /// <summary> /// Camel case. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string CamelCase(string value) { return StringUtility.Normalize(value, NormalizeType.CamelCase); } #endregion #region PascalCase /// <summary> /// Pascal case. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string PascalCase(string value) { return StringUtility.Normalize(value, NormalizeType.PascalCase); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/ProcessHandler.cs using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Samotorcan.HtmlUi.Core.Attributes; using Samotorcan.HtmlUi.Core.Events; using Samotorcan.HtmlUi.Core.Metadata; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Browser process handler. /// </summary> internal class ProcessHandler : CefBrowserProcessHandler { #region Events #region ContextInitialized /// <summary> /// Occurs when context is initialized. /// </summary> public event EventHandler<ContextInitializedEventArgs> ContextInitialized; #endregion #endregion private Dictionary<string, SyncProperty> SyncProperties { get; set; } public ProcessHandler() : base() { SyncProperties = SyncPropertyAttribute.GetProperties<Application>(); } #region Methods #region Protected #region OnBeforeChildProcessLaunch /// <summary> /// Called before child process launch. /// </summary> /// <param name="commandLine">The command line.</param> protected override void OnBeforeChildProcessLaunch(CefCommandLine commandLine) { if (commandLine == null) throw new ArgumentNullException("commandLine"); if (!Application.Current.D3D11Enabled && !commandLine.GetArguments().Contains(Argument.DisableD3D11.Value)) commandLine.AppendArgument(Argument.DisableD3D11.Value); } #endregion #region OnRenderProcessThreadCreated /// <summary> /// Called on the browser process IO thread after the main thread has been /// created for a new render process. Provides an opportunity to specify extra /// information that will be passed to /// CefRenderProcessHandler::OnRenderThreadCreated() in the render process. Do /// not keep a reference to |extra_info| outside of this method. /// </summary> /// <param name="extraInfo"></param> protected override void OnRenderProcessThreadCreated(CefListValue extraInfo) { if (extraInfo == null) throw new ArgumentNullException("extraInfo"); var app = Application.Current; lock (app.SyncPropertiesLock) { var properties = SyncProperties.ToDictionary(p => p.Key, p => p.Value.GetDelegate.DynamicInvoke(app)); extraInfo.SetString(0, JsonConvert.SerializeObject(properties)); Application.Current.RenderProcessThreadCreated = true; } } #endregion #region OnContextInitialized /// <summary> /// Called when context is initialized. /// </summary> protected override void OnContextInitialized() { if (ContextInitialized != null) ContextInitialized(this, new ContextInitializedEventArgs()); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Exceptions/UnknownUrlException.cs using System; using System.Runtime.Serialization; namespace Samotorcan.HtmlUi.Core.Exceptions { /// <summary> /// Unknown url exception. /// </summary> [Serializable] public class UnknownUrlException : Exception { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="UnknownUrlException"/> class. /// </summary> public UnknownUrlException() : base() { } /// <summary> /// Initializes a new instance of the <see cref="UnknownUrlException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public UnknownUrlException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="UnknownUrlException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public UnknownUrlException(string format, params object[] args) : base(string.Format(format, args)) { } /// <summary> /// Initializes a new instance of the <see cref="UnknownUrlException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public UnknownUrlException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="UnknownUrlException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="innerException">The inner exception.</param> /// <param name="args">The arguments.</param> public UnknownUrlException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException) { } /// <summary> /// Initializes a new instance of the <see cref="UnknownUrlException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> protected UnknownUrlException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Events/OnLoadEndEventArgs.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Events { /// <summary> /// On load end event arguments. /// </summary> internal class OnLoadEndEventArgs : EventArgs { #region Properties #region Public #region Browser /// <summary> /// Gets the browser. /// </summary> /// <value> /// The browser. /// </value> public CefBrowser Browser { get; private set; } #endregion #region Frame /// <summary> /// Gets the frame. /// </summary> /// <value> /// The frame. /// </value> public CefFrame Frame { get; private set; } #endregion #region HttpStatusCode /// <summary> /// Gets the HTTP status code. /// </summary> /// <value> /// The HTTP status code. /// </value> public int HttpStatusCode { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="OnLoadEndEventArgs"/> class. /// </summary> /// <param name="browser">The browser.</param> /// <param name="frame">The frame.</param> /// <param name="httpStatusCode">The HTTP status code.</param> public OnLoadEndEventArgs(CefBrowser browser, CefFrame frame, int httpStatusCode) { Browser = browser; Frame = frame; HttpStatusCode = httpStatusCode; } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Logs/LogSeverity.cs namespace Samotorcan.HtmlUi.Core.Logs { /// <summary> /// Log severity. /// </summary> public enum LogSeverity { /// <summary> /// The disabled. /// </summary> Disabled, /// <summary> /// The debug. /// </summary> Debug, /// <summary> /// The info. /// </summary> Info, /// <summary> /// The warn. /// </summary> Warn, /// <summary> /// The error. /// </summary> Error } } <file_sep>/src/Samotorcan.HtmlUi.Core/Renderer/Handlers/NativeMessageHandler.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Messages; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Attributes; namespace Samotorcan.HtmlUi.Core.Renderer.Handlers { internal class NativeMessageHandler : CefV8Handler { public CefBrowser CefBrowser { get; set; } private delegate void JavascriptFunctionDelegate(CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue); private delegate void ProcessMessageDelegate(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage); private Dictionary<string, JavascriptFunctionDelegate> JavascriptFunctionDelegates { get; set; } private Dictionary<string, ProcessMessageDelegate> ProcessMessageDelegates { get; set; } private Dictionary<Guid, JavascriptFunction> Callbacks { get; set; } private Dictionary<string, JavascriptFunction> Functions { get; set; } private ChildApplication Application { get { return ChildApplication.Current; } } public NativeMessageHandler() { Callbacks = new Dictionary<Guid, JavascriptFunction>(); Functions = new Dictionary<string, JavascriptFunction>(); JavascriptFunctionDelegates = JavascriptFunctionAttribute.GetHandlers<NativeMessageHandler, JavascriptFunctionDelegate>(this); ProcessMessageDelegates = ProcessMessageAttribute.GetHandlers<NativeMessageHandler, ProcessMessageDelegate>(this); } public void Reset() { Callbacks.Clear(); Functions.Clear(); } public bool ProcessMessage(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { if (processMessage == null) throw new ArgumentNullException("processMessage"); if (string.IsNullOrWhiteSpace(processMessage.Name)) throw new ArgumentException("ProcessMessage.Name is null or white space."); Logger.Debug(string.Format("Process message: {0}", processMessage.Name)); ProcessMessageDelegate handler; ProcessMessageDelegates.TryGetValue(processMessage.Name, out handler); if (handler != null) { handler(browser, sourceProcess, processMessage); return true; } return false; } protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); Logger.Debug(string.Format("Javascript function call: {0}", name)); returnValue = null; exception = null; JavascriptFunctionDelegate handler; JavascriptFunctionDelegates.TryGetValue(name, out handler); if (handler != null) { try { handler(obj, arguments, out returnValue); } catch (Exception e) { exception = e.Message; } return true; } return false; } private Guid? AddCallback(CefV8Value callbackFunction, CefV8Context context) { if (callbackFunction != null) { if (context == null) throw new ArgumentNullException("context"); if (!callbackFunction.IsFunction) throw new ArgumentException("Not a function.", "callbackFunction"); var callback = new JavascriptFunction(callbackFunction, context); Callbacks.Add(callback.Id, callback); return callback.Id; } return null; } private JavascriptFunction GetCallback(Guid id) { JavascriptFunction callback; Callbacks.TryGetValue(id, out callback); if (callback != null) { Callbacks.Remove(id); return callback; } return null; } [JavascriptFunction("native")] private void JavascriptFunctionNative(CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue) { if (arguments == null) throw new ArgumentNullException("arguments"); if (arguments.Length < 2 || !arguments[0].IsString || !arguments[1].IsString || arguments.Length > 2 && !arguments[2].IsFunction) throw new ArgumentException("Invalid arguments.", "arguments"); returnValue = null; var functionName = arguments[0].GetStringValue(); var jsonData = arguments[1].GetStringValue(); var callbackFunction = arguments.Length > 2 && arguments[2].IsFunction ? arguments[2] : null; var callbackId = AddCallback(callbackFunction, CefV8Context.GetCurrentContext()); MessageUtility.SendMessage(CefProcessId.Browser, CefBrowser, "native", new CallNative { Name = functionName, Json = jsonData, CallbackId = callbackId }); } [ProcessMessage("native")] private void ProcessMessageNative(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var callNativeResult = MessageUtility.DeserializeMessage<CallNativeResult>(processMessage); if (callNativeResult.CallbackId != null) { var callback = GetCallback(callNativeResult.CallbackId.Value); if (callback == null) throw new InvalidOperationException(string.Format("Callback '{0}' not found.", callNativeResult.CallbackId.Value)); callback.Execute(callNativeResult.JsonResult); } } [JavascriptFunction("registerFunction")] private void JavascriptFunctionRegisterFunction(CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue) { if (arguments == null) throw new ArgumentNullException("arguments"); if (arguments.Length < 2 || !arguments[0].IsString || !arguments[1].IsFunction) throw new ArgumentException("Invalid arguments.", "arguments"); returnValue = null; var functionName = arguments[0].GetStringValue(); var function = arguments[1]; if (Functions.ContainsKey(functionName)) throw new InvalidOperationException(string.Format("Function '{0}' is already registered.", functionName)); Functions.Add(functionName, new JavascriptFunction(function, CefV8Context.GetCurrentContext())); } [ProcessMessage("callFunction")] private void ProcessMessageCallFunction(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var callFunction = MessageUtility.DeserializeMessage<CallFunction>(processMessage); if (!Functions.ContainsKey(callFunction.Name)) throw new InvalidOperationException(string.Format("Function '{0}' not found.", callFunction.Name)); JToken returnValue = null; if (callFunction.Data != Value.Undefined) returnValue = Functions[callFunction.Name].Execute(callFunction.Data); else returnValue = Functions[callFunction.Name].Execute(); MessageUtility.SendMessage(CefProcessId.Browser, CefBrowser, "callFunctionResult", new CallFunctionResult { Result = returnValue, CallbackId = callFunction.CallbackId }); } [JavascriptFunction("loadInternalScript")] private void JavascriptFunctionLoadInternalScript(CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue) { if (arguments == null) throw new ArgumentNullException("arguments"); if (arguments.Length < 1 || !arguments[0].IsString) throw new ArgumentException("Invalid arguments.", "arguments"); returnValue = null; var scriptName = "Scripts/" + arguments[0].GetStringValue(); if (!ResourceUtility.ResourceExists(scriptName)) throw new InvalidOperationException(string.Format("Script '{0}' not found.", scriptName)); CefV8Value evalReturnValue = null; CefV8Exception evalException = null; string script = ResourceUtility.GetResourceAsString(scriptName); var context = CefV8Context.GetCurrentContext(); if (!context.TryEval(script, out evalReturnValue, out evalException)) throw new InvalidOperationException(string.Format("Javascript exception: {0}.", JsonConvert.SerializeObject(evalException))); } [ProcessMessage("syncProperty")] private void ProcessMessageSyncProperty(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var syncProperty = MessageUtility.DeserializeMessage<SyncProperty>(processMessage); Application.SetSyncProperty(syncProperty.Name, syncProperty.Value); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Events/KeyPressEventArgs.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Events { /// <summary> /// Key press event arguments. /// </summary> [CLSCompliant(false)] public class KeyPressEventArgs : EventArgs { #region Properties #region Public #region NativeKeyCode /// <summary> /// Gets the native key code. /// </summary> /// <value> /// The native key code. /// </value> public int NativeKeyCode { get; private set; } #endregion #region Modifiers /// <summary> /// Gets or sets the modifiers. /// </summary> /// <value> /// The modifiers. /// </value> public CefEventFlags Modifiers { get; set; } #endregion #region KeyEventType /// <summary> /// Gets or sets the type of the key event. /// </summary> /// <value> /// The type of the key event. /// </value> public CefKeyEventType KeyEventType { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="KeyPressEventArgs"/> class. /// </summary> /// <param name="nativeKeyCode">The native key code.</param> /// <param name="modifiers">The modifiers.</param> /// <param name="keyEventType">Type of the key event.</param> public KeyPressEventArgs(int nativeKeyCode, CefEventFlags modifiers, CefKeyEventType keyEventType) { NativeKeyCode = nativeKeyCode; Modifiers = modifiers; KeyEventType = keyEventType; } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Linux/Window.cs using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Windows.Forms; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Linux { /// <summary> /// Linux window /// </summary> [CLSCompliant(false)] public class Window : WindowsForms.Window { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="settings">The settings.</param> public Window(WindowContext settings) : base(settings) { Resize += Window_Resize; } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class with default settings. /// </summary> public Window() : this(new WindowContext()) { } #endregion #region Methods #region Private #region Window_Resize /// <summary> /// Handles the Resize event of the Window control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void Window_Resize(object sender, EventArgs e) { if (CefBrowser != null) { CefUtility.ExecuteTask(CefThreadId.UI, () => { var display = NativeMethods.get_xdisplay(); if (Form.WindowState != FormWindowState.Minimized) { // resize the browser NativeMethods.XResizeWindow(display, CefBrowser.GetHost().GetWindowHandle(), (uint)Form.ClientSize.Width, (uint)Form.ClientSize.Height); } }); } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/LogUtility.cs using Samotorcan.HtmlUi.Core.Logs; using System; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Log utility. /// </summary> internal static class LogUtility { #region Methods #region Public #region LogUtility /// <summary> /// Logs the action run. /// </summary> /// <typeparam name="TReturn">The type of the return.</typeparam> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// start /// or /// end /// or /// action /// </exception> public static TReturn Log<TReturn>(string start, string end, Func<TReturn> action) { if (string.IsNullOrWhiteSpace(start)) throw new ArgumentNullException("start"); if (string.IsNullOrWhiteSpace(end)) throw new ArgumentNullException("end"); if (action == null) throw new ArgumentNullException("action"); Logger.Debug(start); try { return ExceptionUtility.LogException<TReturn>(action); } finally { Logger.Debug(end); } } /// <summary> /// Logs the action run. /// </summary> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <param name="action">The action.</param> /// <exception cref="System.ArgumentNullException"> /// start /// or /// end /// or /// action /// </exception> public static void Log(string start, string end, Action action) { if (string.IsNullOrWhiteSpace(start)) throw new ArgumentNullException("start"); if (string.IsNullOrWhiteSpace(end)) throw new ArgumentNullException("end"); if (action == null) throw new ArgumentNullException("action"); LogUtility.Log<object>(start, end, () => { action(); return null; }); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Events/OnLoadStartEventArgs.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Events { /// <summary> /// On load start event arguments. /// </summary> internal class OnLoadStartEventArgs : EventArgs { #region Properties #region Public #region Browser /// <summary> /// Gets the browser. /// </summary> /// <value> /// The browser. /// </value> public CefBrowser Browser { get; private set; } #endregion #region Frame /// <summary> /// Gets the frame. /// </summary> /// <value> /// The frame. /// </value> public CefFrame Frame { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="OnLoadStartEventArgs"/> class. /// </summary> /// <param name="browser">The browser.</param> /// <param name="frame">The frame.</param> public OnLoadStartEventArgs(CefBrowser browser, CefFrame frame) { Browser = browser; Frame = frame; } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Linux/Application.cs using System; namespace Samotorcan.HtmlUi.Linux { /// <summary> /// Linux application. /// </summary> [CLSCompliant(false)] public class Application : WindowsForms.Application { #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static new Application Current { get { return (Application)WindowsForms.Application.Current; } } #endregion #endregion #region Internal #region Window /// <summary> /// Gets or sets the window. /// </summary> /// <value> /// The window. /// </value> public new Window Window { get { return (Window)base.Window; } protected set { base.Window = value; } } #endregion #endregion #region Protected #region Settings /// <summary> /// Gets or sets the settings. /// </summary> /// <value> /// The settings. /// </value> protected new ApplicationContext Settings { get { return (ApplicationContext)base.Settings; } set { base.Settings = value; } } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Application"/> class. /// </summary> /// <param name="settings">The settings.</param> public Application(ApplicationContext settings) : base(settings) { } /// <summary> /// Initializes a new instance of the <see cref="Application"/> class. /// </summary> public Application() : this(new ApplicationContext()) { } #endregion #region Methods #region Public #region Run /// <summary> /// Runs the application. /// </summary> /// <param name="settings">The settings.</param> public static void Run(ApplicationContext settings) { if (settings == null) settings = new ApplicationContext(); using (var application = new Application(settings)) { application.RunApplication(); } } /// <summary> /// Runs the application. /// </summary> public static void Run() { Run(null); } #endregion #endregion #region Protected #region OnInitialize /// <summary> /// Called when the application is initialized. /// </summary> protected override void OnInitialize() { InvokeOnUiAsync(() => { Window = new Window(Settings.WindowSettings); Window.Form.Show(); }); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Client.cs using Samotorcan.HtmlUi.Core.Browser.Handlers; using Samotorcan.HtmlUi.Core.Events; using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser { /// <summary> /// Client. /// </summary> internal class Client : CefClient { #region Events #region BrowserCreated /// <summary> /// Occurs when the browser is created. /// </summary> public event EventHandler<BrowserCreatedEventArgs> BrowserCreated; #endregion #endregion #region Properties #region Private #region LifeSpanHandler /// <summary> /// Gets or sets the life span handler. /// </summary> /// <value> /// The life span handler. /// </value> private LifeSpanHandler LifeSpanHandler { get; set; } #endregion #region DisplayHandler /// <summary> /// Gets or sets the display handler. /// </summary> /// <value> /// The display handler. /// </value> private DisplayHandler DisplayHandler { get; set; } #endregion #region LoadHandler /// <summary> /// Gets or sets the load handler. /// </summary> /// <value> /// The load handler. /// </value> private LoadHandler LoadHandler { get; set; } #endregion #region RequestHandler /// <summary> /// Gets or sets the request handler. /// </summary> /// <value> /// The request handler. /// </value> private RequestHandler RequestHandler { get; set; } #endregion #region KeyboardHandler /// <summary> /// Gets or sets the keyboard handler. /// </summary> /// <value> /// The keyboard handler. /// </value> private KeyboardHandler KeyboardHandler { get; set; } #endregion #region NativeMessageHandler /// <summary> /// Gets or sets the native message handler. /// </summary> /// <value> /// The native message handler. /// </value> private NativeMessageHandler NativeMessageHandler { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Client"/> class. /// </summary> public Client() : base() { LifeSpanHandler = new LifeSpanHandler(); DisplayHandler = new DisplayHandler(); LoadHandler = new LoadHandler(); RequestHandler = new RequestHandler(); KeyboardHandler = new KeyboardHandler(); // set events LifeSpanHandler.BrowserCreated += (sender, e) => { if (BrowserCreated != null) BrowserCreated(this, e); }; // native calls NativeMessageHandler = new NativeMessageHandler(); } #endregion #region Methods #region Protected #region GetLifeSpanHandler /// <summary> /// Return the handler for browser life span events. /// </summary> /// <returns></returns> protected override CefLifeSpanHandler GetLifeSpanHandler() { return LifeSpanHandler; } #endregion #region GetDisplayHandler /// <summary> /// Return the handler for browser display state events. /// </summary> /// <returns></returns> protected override CefDisplayHandler GetDisplayHandler() { return DisplayHandler; } #endregion #region GetLoadHandler /// <summary> /// Return the handler for browser load status events. /// </summary> /// <returns></returns> protected override CefLoadHandler GetLoadHandler() { return LoadHandler; } #endregion #region GetRequestHandler /// <summary> /// Return the handler for browser request events. /// </summary> /// <returns></returns> protected override CefRequestHandler GetRequestHandler() { return RequestHandler; } #endregion #region GetKeyboardHandler /// <summary> /// Return the handler for keyboard events. /// </summary> /// <returns></returns> protected override CefKeyboardHandler GetKeyboardHandler() { return KeyboardHandler; } #endregion #region OnProcessMessageReceived /// <summary> /// Called when a new message is received from a different process. Return true /// if the message was handled or false otherwise. Do not keep a reference to /// or attempt to access the message outside of this callback. /// </summary> /// <param name="browser"></param> /// <param name="sourceProcess"></param> /// <param name="message"></param> /// <returns></returns> protected override bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message) { if (message == null) throw new ArgumentNullException("message"); return NativeMessageHandler.ProcessMessage(browser, sourceProcess, message); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Window.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Samotorcan.HtmlUi.Core.Browser; using Samotorcan.HtmlUi.Core.Events; using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Messages; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Window. /// </summary> [CLSCompliant(false)] public abstract class Window : IDisposable { #region Events #region BrowserCreated /// <summary> /// Occurs when browser is created. /// </summary> internal event EventHandler<BrowserCreatedEventArgs> BrowserCreated; #endregion #region KeyPress /// <summary> /// Occurs when a key is pressed. /// </summary> protected event EventHandler<KeyPressEventArgs> KeyPress; #endregion #endregion #region Properties #region Public #region View /// <summary> /// Gets or sets the view. /// </summary> /// <value> /// The view. /// </value> public string View { get; private set; } #endregion #endregion #region Internal #region IsBrowserCreated /// <summary> /// Gets a value indicating whether browser is created. /// </summary> /// <value> /// <c>true</c> if browser is created; otherwise, <c>false</c>. /// </value> internal bool IsBrowserCreated { get; private set; } #endregion #region CefBrowser /// <summary> /// Gets or sets the cef browser. /// </summary> /// <value> /// The cef browser. /// </value> internal CefBrowser CefBrowser { get; set; } #endregion #region Controllers /// <summary> /// Gets or sets the controllers. /// </summary> /// <value> /// The controllers. /// </value> internal Dictionary<int, Controller> Controllers { get; set; } #endregion #region ObservableControllers /// <summary> /// Gets or sets the observable controllers. /// </summary> /// <value> /// The observable controllers. /// </value> internal Dictionary<int, ObservableController> ObservableControllers { get; set; } #endregion #endregion #region Protected #endregion #region Private #region WaitingCallFunction /// <summary> /// Gets or sets the waiting call function. /// </summary> /// <value> /// The waiting call function. /// </value> private ConcurrentDictionary<Guid, TaskCompletionSource<JToken>> WaitingCallFunction { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="settings">The settings.</param> protected Window(WindowSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); View = settings.View; Controllers = new Dictionary<int, Controller>(); ObservableControllers = new Dictionary<int, ObservableController>(); WaitingCallFunction = new ConcurrentDictionary<Guid, TaskCompletionSource<JToken>>(); } #endregion #region Methods #region Internal #region TriggerKeyPress /// <summary> /// Triggers the key press. /// </summary> /// <param name="nativeKeyCode">The native key code.</param> /// <param name="modifiers">The modifiers.</param> /// <param name="keyEventType">Type of the key event.</param> internal void TriggerKeyPress(int nativeKeyCode, CefEventFlags modifiers, CefKeyEventType keyEventType) { if (KeyPress != null) KeyPress(this, new KeyPressEventArgs(nativeKeyCode, modifiers, keyEventType)); } #endregion #region CallFunctionAsync /// <summary> /// Calls the function asynchronous. /// </summary> /// <param name="name">The name.</param> /// <param name="data">The data.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> internal Task<JToken> CallFunctionAsync(string name, object data) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); var callbackId = Guid.NewGuid(); var taskCompletionSource = new TaskCompletionSource<JToken>(); WaitingCallFunction.TryAdd(callbackId, taskCompletionSource); MessageUtility.SendMessage(CefProcessId.Renderer, CefBrowser, "callFunction", new CallFunction { Name = name, Data = data, CallbackId = callbackId }); return taskCompletionSource.Task; } /// <summary> /// Calls the function asynchronous. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> internal Task<JToken> CallFunctionAsync(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); var callbackId = Guid.NewGuid(); var taskCompletionSource = new TaskCompletionSource<JToken>(); WaitingCallFunction.TryAdd(callbackId, taskCompletionSource); MessageUtility.SendMessage(CefProcessId.Renderer, CefBrowser, "callFunction", new CallFunction { Name = name, Data = Value.Undefined, CallbackId = callbackId }); return taskCompletionSource.Task; } #endregion #region SetCallFunctionResult /// <summary> /// Sets the call function result. /// </summary> /// <param name="id">The identifier.</param> /// <param name="value">The value.</param> /// <exception cref="System.ArgumentException">Invalid id.;id</exception> internal void SetCallFunctionResult(Guid id, JToken value) { TaskCompletionSource<JToken> taskCompletionSource = null; if (!WaitingCallFunction.TryRemove(id, out taskCompletionSource)) throw new ArgumentException("Invalid id.", "id"); taskCompletionSource.SetResult(value); } #endregion #region CreateController /// <summary> /// Creates the controller. /// </summary> internal Controller CreateController(string name) { var controllerProvider = Application.Current.ControllerProvider; var id = FindNextFreeControllerId(); var controller = controllerProvider.CreateController(name, id); Controllers.Add(id, controller); return controller; } #endregion #region CreateObservableController /// <summary> /// Creates the observable controller. /// </summary> internal ObservableController CreateObservableController(string name) { var controllerProvider = Application.Current.ControllerProvider; var id = FindNextFreeControllerId(); var observableController = controllerProvider.CreateObservableController(name, id); ObservableControllers.Add(id, observableController); return observableController; } #endregion #region DestroyController /// <summary> /// Destroys the controller. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> internal bool DestroyController(int id) { if (Controllers.ContainsKey(id)) { var controller = Controllers[id]; controller.Dispose(); Controllers.Remove(id); return true; } if (ObservableControllers.ContainsKey(id)) { var observableController = ObservableControllers[id]; observableController.Dispose(); ObservableControllers.Remove(id); return true; } return false; } #endregion #region DestroyControllers /// <summary> /// Destroys the controllers. /// </summary> internal void DestroyControllers() { foreach (var controller in Controllers.Values) controller.Dispose(); Controllers.Clear(); foreach (var observableController in ObservableControllers.Values) observableController.Dispose(); ObservableControllers.Clear(); } #endregion #region SyncControllerChangesToNative /// <summary> /// Synchronizes the controller changes to native. /// </summary> /// <param name="controllerChanges">The controller changes.</param> /// <exception cref="ControllerNotFoundException"></exception> internal void SyncControllerChangesToNative(IEnumerable<ControllerChange> controllerChanges) { Application.Current.EnsureMainThread(); Logger.Debug(string.Format("Sync controller changes to native: {0}", JsonConvert.SerializeObject(controllerChanges))); foreach (var controllerChange in controllerChanges) { if (!ObservableControllers.ContainsKey(controllerChange.Id)) throw new ControllerNotFoundException(); var observableController = ObservableControllers[controllerChange.Id]; foreach (var changeProperty in controllerChange.Properties) observableController.SetPropertyValue(changeProperty.Key, changeProperty.Value); foreach (var observableCollectionChanges in controllerChange.ObservableCollections) observableController.SetObservableCollectionChanges(observableCollectionChanges.Key, observableCollectionChanges.Value); } } #endregion #region SyncControllerChangesToClient /// <summary> /// Synchronizes the controller changes to client. /// </summary> internal void SyncControllerChangesToClient() { var application = Application.Current; application.EnsureMainThread(); var controllerChanges = GetControllerChanges(); if (controllerChanges.Any()) { Logger.Debug(string.Format("Sync controller changes to client: {0}", JsonConvert.SerializeObject(controllerChanges))); CallFunctionAsync("syncControllerChanges", controllerChanges); } } #endregion #region CallMethod /// <summary> /// Calls the method. /// </summary> /// <param name="controllerId">The controller identifier.</param> /// <param name="methodName">Name of the method.</param> /// <param name="arguments">The arguments.</param> /// <param name="internalMethod">if set to <c>true</c> [internal method].</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">methodName</exception> /// <exception cref="ControllerNotFoundException"></exception> internal object CallMethod(int controllerId, string methodName, JArray arguments, bool internalMethod) { if (string.IsNullOrWhiteSpace(methodName)) throw new ArgumentNullException("methodName"); if (Controllers.ContainsKey(controllerId)) return Controllers[controllerId].CallMethod(methodName, arguments, internalMethod); if (ObservableControllers.ContainsKey(controllerId)) return ObservableControllers[controllerId].CallMethod(methodName, arguments, internalMethod); throw new ControllerNotFoundException(); } /// <summary> /// Calls the method. /// </summary> /// <param name="controllerId">The controller identifier.</param> /// <param name="methodName">Name of the method.</param> /// <param name="arguments">The arguments.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">methodName</exception> /// <exception cref="ControllerNotFoundException"></exception> internal object CallMethod(int controllerId, string methodName, JArray arguments) { return CallMethod(controllerId, methodName, arguments, false); } #endregion #endregion #region Protected #region CreateBrowser /// <summary> /// Creates the browser. /// </summary> /// <param name="handle">The handle.</param> /// <param name="position">The position.</param> protected void CreateBrowser(IntPtr handle, CefRectangle position) { Application.Current.EnsureCefThread(); if (IsBrowserCreated) throw new InvalidOperationException("Browser already created."); Logger.Info("Creating browser."); var cefWindowInfo = CefWindowInfo.Create(); cefWindowInfo.SetAsChild(handle, position); var cefClient = new Client(); cefClient.BrowserCreated += (sender, e) => { CefBrowser = e.CefBrowser; if (BrowserCreated != null) BrowserCreated(this, e); }; var cefSettings = new CefBrowserSettings(); CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefSettings, Application.Current.GetContentUrl(View)); IsBrowserCreated = true; Logger.Info("Browser created."); } #endregion #endregion #region Private #region GetControllerChanges /// <summary> /// Gets the controller changes. /// </summary> /// <returns></returns> private Dictionary<int, ControllerChange> GetControllerChanges() { return GetControllerChanges(1); } /// <summary> /// Gets the controller changes. /// </summary> /// <param name="depth">The depth.</param> /// <returns></returns> /// <exception cref="Samotorcan.HtmlUi.Core.Exceptions.SyncMaxDepthException"></exception> private Dictionary<int, ControllerChange> GetControllerChanges(int depth) { if (depth > Application.Current.SyncMaxDepth) throw new SyncMaxDepthException(Application.Current.SyncMaxDepth); var controllerChanges = new Dictionary<int, ControllerChange>(); // controller changes foreach (var observableController in ObservableControllers.Values) { // property changes if (observableController.PropertyChanges.Any()) { var propertyChanges = new HashSet<string>(observableController.PropertyChanges); observableController.PropertyChanges = new HashSet<string>(); controllerChanges.Add(observableController.Id, new ControllerChange { Id = observableController.Id, Properties = propertyChanges .ToDictionary(p => p, p => JToken.FromObject(observableController.GetPropertyValue(p))) }); } // observable collection changes if (observableController.ObservableCollectionChanges.Any()) { if (!controllerChanges.ContainsKey(observableController.Id)) controllerChanges.Add(observableController.Id, new ControllerChange { Id = observableController.Id }); var controllerChange = controllerChanges[observableController.Id]; controllerChange.ObservableCollections = new Dictionary<string, ObservableCollectionChanges>(observableController.ObservableCollectionChanges); observableController.ObservableCollectionChanges = new Dictionary<string, ObservableCollectionChanges>(); // change reset to property change foreach (var observableCollection in controllerChange.ObservableCollections.Values) { if (observableCollection.IsReset && !controllerChange.Properties.Keys.Contains(observableCollection.Name)) controllerChange.Properties.Add(observableCollection.Name, JToken.FromObject(observableController.GetPropertyValue(observableCollection.Name))); } } // remove observable collection changes if not needed if (controllerChanges.ContainsKey(observableController.Id)) { var controllerChange = controllerChanges[observableController.Id]; var removeObservableCollectionKeys = controllerChange.ObservableCollections .Where(o => controllerChange.Properties.ContainsKey(o.Value.Name) || o.Value.IsReset) .Select(o => o.Key) .ToList(); foreach (var removeObservableCollectionKey in removeObservableCollectionKeys) controllerChange.ObservableCollections.Remove(removeObservableCollectionKey); } } // next changes triggered by getter for property if (controllerChanges.Any(c => c.Value.Properties.Any())) { // add next controller changes foreach (var nextControllerChange in GetControllerChanges(++depth).Values) { if (!controllerChanges.ContainsKey(nextControllerChange.Id)) controllerChanges.Add(nextControllerChange.Id, new ControllerChange { Id = nextControllerChange.Id }); var controllerChange = controllerChanges[nextControllerChange.Id]; // properties foreach (var nextProperty in nextControllerChange.Properties.Keys) { if (!controllerChange.Properties.ContainsKey(nextProperty)) controllerChange.Properties.Add(nextProperty, null); controllerChange.Properties[nextProperty] = nextControllerChange.Properties[nextProperty]; } } } return controllerChanges; } #endregion #region FindNextFreeControllerId /// <summary> /// Finds the next free controller identifier. /// </summary> /// <returns></returns> private int FindNextFreeControllerId() { return Math.Max(Controllers.Keys.DefaultIfEmpty().Max(), ObservableControllers.Keys.DefaultIfEmpty().Max()) + 1; } #endregion #endregion #endregion #region IDisposable /// <summary> /// Was dispose already called. /// </summary> private bool _disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { Application.Current.EnsureMainThread(); if (!_disposed) { if (disposing) { // CEF browser if (CefBrowser != null) { var host = CefBrowser.GetHost(); if (host != null) { host.CloseBrowser(true); host.Dispose(); } CefBrowser.Dispose(); } DestroyControllers(); } _disposed = true; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerPropertyDescription.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller property description. /// </summary> internal class ControllerPropertyDescription : ControllerPropertyBase { #region Properties #region Public #region Value /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public object Value { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.WindowsForms/WindowSettings.cs namespace Samotorcan.HtmlUi.WindowsForms { /// <summary> /// Windows forms window settings. /// </summary> public class WindowSettings : Core.WindowSettings { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="WindowSettings"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public WindowSettings() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="WindowSettings"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public WindowSettings(WindowSettings settings) { Initialize(settings); } /// <summary> /// Initializes a new instance of the <see cref="WindowSettings"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public WindowSettings(Core.WindowSettings settings) { if (settings != null) { var windowSettings = settings as WindowSettings; if (windowSettings != null) Initialize(windowSettings); else Initialize(settings); } else { Initialize(); } } #endregion #region Methods #region Private #region InitializeSelf /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "settings", Justification = "Might have additional code in the future.")] private void InitializeSelf(WindowSettings settings) { } #endregion #endregion #region Protected #region Initialize /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected virtual void Initialize(WindowSettings settings) { base.Initialize(settings); InitializeSelf(settings); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(Core.WindowSettings settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> protected override void Initialize() { Initialize(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Argument.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Argument. /// </summary> public sealed class Argument { #region Arguments #region DisableD3D11 /// <summary> /// The disable d3d11 argument. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "It's immutable.")] public static readonly Argument DisableD3D11 = new Argument("--disable-d3d11"); #endregion #endregion #region Properties #region Public #region Value /// <summary> /// Gets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Argument"/> class. /// </summary> /// <param name="value">The value.</param> private Argument(string value) { Value = value; } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Exceptions/ParameterMismatchException.cs using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; namespace Samotorcan.HtmlUi.Core.Exceptions { /// <summary> /// Parameter mismatch exception. /// </summary> [Serializable] public class ParameterMismatchException : Exception, INativeException { #region Properties #region Public #region Parameter /// <summary> /// Gets the parameter. /// </summary> /// <value> /// The parameter. /// </value> public int Parameter { get; private set; } #endregion #region ExpectedType /// <summary> /// Gets the expected type. /// </summary> /// <value> /// The expected type. /// </value> public string ExpectedType { get; private set; } #endregion #region GotType /// <summary> /// Gets the type of the got. /// </summary> /// <value> /// The type of the got. /// </value> public string GotType { get; private set; } #endregion #region MethodName /// <summary> /// Gets the name of the method. /// </summary> /// <value> /// The name of the method. /// </value> public string MethodName { get; private set; } #endregion #region ControllerName /// <summary> /// Gets or sets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> public ParameterMismatchException() : base("Parameter mismatch.") { } /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="expectedType">The expected type.</param> /// <param name="gotType">Type of the got.</param> /// <param name="methodName">Name of the method.</param> /// <param name="controllerName">Name of the controller.</param> public ParameterMismatchException(int parameter, string expectedType, string gotType, string methodName, string controllerName) : base("Parameter mismatch.") { Parameter = parameter; ExpectedType = expectedType; GotType = gotType; MethodName = methodName; ControllerName = controllerName; } /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="parameter">The parameter.</param> /// <param name="expectedType">The expected type.</param> /// <param name="gotType">Type of the got.</param> /// <param name="methodName">Name of the method.</param> /// <param name="controllerName">Name of the controller.</param> public ParameterMismatchException(string message, int parameter, string expectedType, string gotType, string methodName, string controllerName) : base(message) { Parameter = parameter; ExpectedType = expectedType; GotType = gotType; MethodName = methodName; ControllerName = controllerName; } /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The arguments.</param> public ParameterMismatchException(string format, params object[] args) : base(string.Format(format, args)) { } /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public ParameterMismatchException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> /// <param name="format">The format.</param> /// <param name="innerException">The inner exception.</param> /// <param name="args">The arguments.</param> public ParameterMismatchException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException) { } /// <summary> /// Initializes a new instance of the <see cref="ParameterMismatchException"/> class. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="System.ArgumentNullException">info</exception> protected ParameterMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) throw new ArgumentNullException("info"); Parameter = info.GetInt32("Parameter"); ExpectedType = info.GetString("ExpectedType"); GotType = info.GetString("GotType"); MethodName = info.GetString("MethodName"); ControllerName = info.GetString("ControllerName"); } #endregion #region Methods #region Public #region GetObjectData /// <summary> /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="System.ArgumentNullException">info</exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter" /> /// </PermissionSet> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); if (info == null) throw new ArgumentNullException("info"); info.AddValue("Parameter", Parameter); info.AddValue("ExpectedType", ExpectedType); info.AddValue("GotType", GotType); info.AddValue("MethodName", MethodName); info.AddValue("ControllerName", ControllerName); } #endregion #endregion #region Internal #region ToJavascriptException /// <summary> /// To the javascript exception. /// </summary> /// <returns></returns> JavascriptException INativeException.ToJavascriptException() { return new JavascriptException { Message = Message, Type = "ParameterMismatchException", InnerException = InnerException != null ? ExceptionUtility.CreateJavascriptException(InnerException) : null, AdditionalData = new Dictionary<string, object> { { "Parameter", Parameter }, { "ExpectedType", ExpectedType }, { "GotType", GotType }, { "MethodName", MethodName }, { "ControllerName", ControllerName } } }; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Providers/IContentProvider.cs namespace Samotorcan.HtmlUi.Core.Providers { /// <summary> /// Content provider interface. /// </summary> public interface IContentProvider { /// <summary> /// Gets the content. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> byte[] GetContent(string path); /// <summary> /// Gets the URL from content path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> string GetUrlFromContentPath(string path); /// <summary> /// Gets the content path from URL. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> string GetContentPathFromUrl(string url); /// <summary> /// Content exists. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> bool ContentExists(string path); } } <file_sep>/src/Samotorcan.HtmlUi.Core/ObservableCollectionChangeAction.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// ObservableCollectionChangeAction /// </summary> internal enum ObservableCollectionChangeAction { /// <summary> /// The add. /// </summary> Add = 1, /// <summary> /// The remove. /// </summary> Remove = 2, /// <summary> /// The replace. /// </summary> Replace = 3, /// <summary> /// The move. /// </summary> Move = 4 } } <file_sep>/src/Samotorcan.HtmlUi.Core/Metadata/SyncProperty.cs using System; namespace Samotorcan.HtmlUi.Core.Metadata { internal class SyncProperty { public string Name { get; set; } public Delegate GetDelegate { get; set; } public Delegate SetDelegate { get; set; } public Type SyncPropertyType { get; set; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Attributes/ExcludeAttribute.cs using System; namespace Samotorcan.HtmlUi.Core.Attributes { /// <summary> /// Exclude property or method from binding. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class ExcludeAttribute : Attribute { } } <file_sep>/src/Samotorcan.HtmlUi.Core/Attributes/SyncPropertyAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Samotorcan.HtmlUi.Core.Metadata; using Samotorcan.HtmlUi.Core.Utilities; namespace Samotorcan.HtmlUi.Core.Attributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] internal sealed class SyncPropertyAttribute : Attribute { public static Dictionary<string, SyncProperty> GetProperties<TType>() { return typeof(TType).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Where(p => p.GetCustomAttribute<SyncPropertyAttribute>() != null) .ToDictionary(p => p.Name, p => new SyncProperty { Name = p.Name, SetDelegate = ExpressionUtility.CreateMethodDelegate(p.GetSetMethod(true)), GetDelegate = ExpressionUtility.CreateMethodDelegate(p.GetGetMethod(true)), SyncPropertyType = p.PropertyType }); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/PathUtility.cs using System; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Path utility. /// </summary> public static class PathUtility { #region Properties #region Public #region WorkingDirectory private static string _workingDirectory; /// <summary> /// Gets the working directory. /// </summary> /// <value> /// The working directory. /// </value> public static string WorkingDirectory { get { if (string.IsNullOrEmpty(_workingDirectory)) _workingDirectory = Path.GetDirectoryName(PathUtility.Application).Replace('\\', '/'); return _workingDirectory; } } #endregion #region Application private static string _application; /// <summary> /// Gets the application path. /// </summary> /// <value> /// The application. /// </value> public static string Application { get { if (string.IsNullOrEmpty(_application)) _application = new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath.Replace('\\', '/'); return _application; } } #endregion #endregion #endregion #region Methods #region Public #region IsFileName /// <summary> /// Determines whether file name is valid. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns></returns> public static bool IsFileName(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) return false; return Regex.IsMatch(fileName, @"^[a-zA-Z0-9_\-\.]+$"); } #endregion #region IsFilePath /// <summary> /// Determines whether file path is valid. /// </summary> /// <param name="filePath">The file path.</param> /// <returns></returns> public static bool IsFilePath(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) return false; return Regex.IsMatch(filePath, @"^/?([a-zA-Z0-9]+/?)+$"); } #endregion #region IsFullFileName /// <summary> /// Determines whether full file name is valid. /// </summary> /// <param name="fullFileName">Full name of the file.</param> /// <returns></returns> public static bool IsFullFileName(string fullFileName) { if (string.IsNullOrWhiteSpace(fullFileName)) return false; var fileParts = fullFileName.Split('/'); var fileName = fileParts.Last(); var filePath = string.Join(string.Empty, fileParts.Take(fileParts.Length - 1)); return PathUtility.IsFileName(fileName) && (string.IsNullOrEmpty(filePath) || PathUtility.IsFilePath(filePath)); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerProperty.cs using System; using System.Collections.Specialized; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller property. /// </summary> internal class ControllerProperty : ControllerPropertyBase { #region Properties #region Public #region Access /// <summary> /// Gets or sets the access. /// </summary> /// <value> /// The access. /// </value> public Access Access { get; set; } #endregion #region PropertyType /// <summary> /// Gets or sets the type of the property. /// </summary> /// <value> /// The type of the property. /// </value> public Type PropertyType { get; set; } #endregion #region GetDelegate /// <summary> /// Gets or sets the get delegate. /// </summary> /// <value> /// The get delegate. /// </value> public Delegate GetDelegate { get; set; } #endregion #region SetDelegate /// <summary> /// Gets or sets the set delegate. /// </summary> /// <value> /// The set delegate. /// </value> public Delegate SetDelegate { get; set; } #endregion #region IsObservableCollection /// <summary> /// Gets or sets a value indicating whether this instance is observable collection. /// </summary> /// <value> /// <c>true</c> if this instance is observable collection; otherwise, <c>false</c>. /// </value> public bool IsObservableCollection { get; set; } #endregion #region IsCollection /// <summary> /// Gets or sets a value indicating whether this instance is collection. /// </summary> /// <value> /// <c>true</c> if this instance is collection; otherwise, <c>false</c>. /// </value> public bool IsCollection { get; set; } #endregion #region IsIList /// <summary> /// Gets or sets a value indicating whether this instance is IList. /// </summary> /// <value> /// <c>true</c> if this instance is IList; otherwise, <c>false</c>. /// </value> public bool IsIList { get; set; } #endregion #region IsGenericIList /// <summary> /// Gets or sets a value indicating whether this instance is generic IList. /// </summary> /// <value> /// <c>true</c> if this instance is generic IList; otherwise, <c>false</c>. /// </value> public bool IsGenericIList { get; set; } #endregion #region IsArray /// <summary> /// Gets or sets a value indicating whether this instance is array. /// </summary> /// <value> /// <c>true</c> if this instance is array; otherwise, <c>false</c>. /// </value> public bool IsArray { get; set; } #endregion #region ArrayType /// <summary> /// Gets or sets the type of the array. /// </summary> /// <value> /// The type of the array. /// </value> public Type ArrayType { get; set; } #endregion #region GenericIListAddDelegate /// <summary> /// Gets or sets the generic IList add delegate. /// </summary> /// <value> /// The generic IList add delegate. /// </value> public Delegate GenericIListAddDelegate { get; set; } #endregion #region GenericIListRemoveAtDelegate /// <summary> /// Gets or sets the generic IList remove at delegate. /// </summary> /// <value> /// The generic IList remove at delegate. /// </value> public Delegate GenericIListRemoveAtDelegate { get; set; } #endregion #region GenericIListReplaceDelegate /// <summary> /// Gets or sets the generic IList replace delegate. /// </summary> /// <value> /// The generic IList replace delegate. /// </value> public Delegate GenericIListReplaceDelegate { get; set; } #endregion #region GenericIListCountDelegate /// <summary> /// Gets or sets the generic IList count delegate. /// </summary> /// <value> /// The generic IList count delegate. /// </value> public Delegate GenericIListCountDelegate { get; set; } #endregion #region GenericIListInsertDelegate /// <summary> /// Gets or sets the generic IList insert delegate. /// </summary> /// <value> /// The generic IList insert delegate. /// </value> public Delegate GenericIListInsertDelegate { get; set; } #endregion #region GenericIListType /// <summary> /// Gets or sets the type of the generic IList. /// </summary> /// <value> /// The type of the generic IList. /// </value> public Type GenericIListType { get; set; } #endregion #region ObservableCollection /// <summary> /// Gets or sets the observable collection. /// </summary> /// <value> /// The observable collection. /// </value> public INotifyCollectionChanged ObservableCollection { get; set; } #endregion #region NotifyCollectionChangedEventHandler /// <summary> /// Gets or sets the notify collection changed event handler. /// </summary> /// <value> /// The notify collection changed event handler. /// </value> public NotifyCollectionChangedEventHandler NotifyCollectionChangedEventHandler { get; set; } #endregion #endregion #endregion #region Methods #region Public #region GenericIListCount /// <summary> /// Generic IList count. /// </summary> /// <param name="list">The list.</param> /// <returns></returns> public int GenericIListCount(object list) { return (int)GenericIListCountDelegate.DynamicInvoke(list); } #endregion #region GenericIListInsert /// <summary> /// Generic IList insert. /// </summary> /// <param name="list">The list.</param> /// <param name="index">The index.</param> /// <param name="item">The item.</param> public void GenericIListInsert(object list, int index, object item) { GenericIListInsertDelegate.DynamicInvoke(list, index, item); } #endregion #region GenericIListReplace /// <summary> /// Generic IList replace. /// </summary> /// <param name="list">The list.</param> /// <param name="index">The index.</param> /// <param name="item">The item.</param> public void GenericIListReplace(object list, int index, object item) { GenericIListReplaceDelegate.DynamicInvoke(list, index, item); } #endregion #region GenericIListRemoveAt /// <summary> /// Generic IList remove at. /// </summary> /// <param name="list">The list.</param> /// <param name="index">The index.</param> public void GenericIListRemoveAt(object list, int index) { GenericIListRemoveAtDelegate.DynamicInvoke(list, index); } #endregion #region GenericIListAdd /// <summary> /// Generic IList add. /// </summary> /// <param name="list">The list.</param> /// <param name="item">The item.</param> public void GenericIListAdd(object list, object item) { GenericIListAddDelegate.DynamicInvoke(list, item); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Exceptions/INativeException.cs namespace Samotorcan.HtmlUi.Core.Exceptions { /// <summary> /// Native exception interface /// </summary> internal interface INativeException { /// <summary> /// To the javascript exception. /// </summary> /// <returns></returns> JavascriptException ToJavascriptException(); } } <file_sep>/src/Samotorcan.HtmlUi.Core/Renderer/App.cs using Samotorcan.HtmlUi.Core.Renderer.Handlers; using System; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Events; namespace Samotorcan.HtmlUi.Core.Renderer { /// <summary> /// Renderer app. /// </summary> internal class App : CefApp { public event EventHandler<BrowserCreatedEventArgs> BrowserCreated; #region Properties #region Private #region RenderProcessHandler /// <summary> /// Gets or sets the render process handler. /// </summary> /// <value> /// The render process handler. /// </value> private ProcessHandler RenderProcessHandler { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="App"/> class. /// </summary> public App() : base() { RenderProcessHandler = new ProcessHandler(); RenderProcessHandler.BrowserCreated += (s, e) => { if (BrowserCreated != null) BrowserCreated(this, new BrowserCreatedEventArgs(e.CefBrowser)); }; } #endregion #region Methods #region Protected #region OnBeforeCommandLineProcessing /// <summary> /// Called before command line processing. /// </summary> /// <param name="processType">Type of the process.</param> /// <param name="commandLine">The command line.</param> protected override void OnBeforeCommandLineProcessing(string processType, CefCommandLine commandLine) { if (commandLine == null) throw new ArgumentNullException("commandLine"); } #endregion #region GetRenderProcessHandler /// <summary> /// Gets the render process handler. /// </summary> /// <returns></returns> protected override CefRenderProcessHandler GetRenderProcessHandler() { return RenderProcessHandler; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.OS/OSChildApplication.cs using System; using Samotorcan.HtmlUi.Core; namespace Samotorcan.HtmlUi.OS { /// <summary> /// OS child application. /// </summary> public static class OSChildApplication { #region Methods #region Public #region Run /// <summary> /// Runs the application. /// </summary> /// <param name="settings">The settings.</param> public static void Run(ChildApplicationContext settings) { switch (HtmlUiRuntime.Platform) { case Platform.Windows: Windows.RunChildApplication(settings); break; case Platform.Linux: Linux.RunChildApplication(settings); break; case Platform.OSX: throw new NotSupportedException(); } } /// <summary> /// Runs the application. /// </summary> public static void Run() { Run(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/UrlUtility.cs using System; using System.Text.RegularExpressions; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Url utility, /// </summary> internal static class UrlUtility { #region Methods #region Public #region IsNativeRequestUrl /// <summary> /// Determines whether URL is native request. /// </summary> /// <param name="requestHostname">The request hostname.</param> /// <param name="nativeRequestPort">The native request port.</param> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">url</exception> public static bool IsNativeRequestUrl(string requestHostname, int nativeRequestPort, string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); return Regex.IsMatch(url, string.Format("^(http://)?{0}:{1}(/.*)?$", Regex.Escape(requestHostname), nativeRequestPort), RegexOptions.IgnoreCase); } #endregion #region IsLocalUrl /// <summary> /// Determines whether URL is local request. /// </summary> /// <param name="requestHostname">The request hostname.</param> /// <param name="nativeRequestPort">The native request port.</param> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">url</exception> public static bool IsLocalUrl(string requestHostname, int nativeRequestPort, string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); return Regex.IsMatch(url, string.Format("^(http://)?{0}((:80)?|:{1})(/.*)?$", Regex.Escape(requestHostname), nativeRequestPort), RegexOptions.IgnoreCase); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Messages/CallFunctionResult.cs using System; using Newtonsoft.Json.Linq; namespace Samotorcan.HtmlUi.Core.Messages { internal class CallFunctionResult { public Guid CallbackId { get; set; } public JToken Result { get; set; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/ObservableControllerTypeInfo.cs using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { internal class ObservableControllerTypeInfo { #region Properties #region Public #region Properties /// <summary> /// Gets or sets the properties. /// </summary> /// <value> /// The properties. /// </value> public Dictionary<string, ControllerProperty> Properties { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ObservableControllerTypeInfo"/> class. /// </summary> public ObservableControllerTypeInfo() { Properties = new Dictionary<string, ControllerProperty>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.OS/OSApplication.cs using System; using Samotorcan.HtmlUi.Core; namespace Samotorcan.HtmlUi.OS { /// <summary> /// OS application. /// </summary> public static class OSApplication { #region Methods #region Public #region Run /// <summary> /// Runs the application. /// </summary> /// <param name="settings">The settings.</param> public static void Run(ApplicationContext settings) { switch (HtmlUiRuntime.Platform) { case Platform.Windows: Windows.RunApplication(settings); break; case Platform.Linux: Linux.RunApplication(settings); break; case Platform.OSX: throw new NotSupportedException(); } } /// <summary> /// Runs the application. /// </summary> public static void Run() { Run(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.Tests.Application/Controllers/ControllerConstructorTest.cs using Samotorcan.HtmlUi.Core; using System.Collections.Generic; namespace Samotorcan.Tests.Application.Controllers { /// <summary> /// Controller constructor test. /// </summary> public class ControllerConstructorTest : Controller { /// <summary> /// Void no arguments. /// </summary> public void VoidNoArguments() { } /// <summary> /// Void arguments. /// </summary> /// <param name="arg1">The arg1.</param> /// <param name="arg2">The arg2.</param> /// <param name="arg3">The arg3.</param> /// <param name="arg4">The arg4.</param> /// <param name="arg5">The arg5.</param> public void VoidArguments(string arg1, int arg2, int? arg3, List<string> arg4, ArgObject arg5) { } /// <summary> /// Return no arguments. /// </summary> /// <returns></returns> public int ReturnNoArguments() { return 123; } /// <summary> /// Return arguments. /// </summary> /// <param name="arg1">The arg1.</param> /// <param name="arg2">The arg2.</param> /// <param name="arg3">The arg3.</param> /// <param name="arg4">The arg4.</param> /// <param name="arg5">The arg5.</param> /// <returns></returns> public string ReturnArguments(string arg1, int arg2, int? arg3, List<string> arg4, ArgObject arg5) { return "empty"; } /// <summary> /// Overloaded. /// </summary> public void Overloaded() { } /// <summary> /// Overloaded. /// </summary> /// <param name="arg">The argument.</param> public void Overloaded(int arg) { } /// <summary> /// Private method. /// </summary> private void PrivateMethod() { } /// <summary> /// Protected method. /// </summary> protected void ProtectedMethod() { } /// <summary> /// Generic method. /// </summary> /// <typeparam name="TSomething">The type of something.</typeparam> public void GenericMethod<TSomething>() { } /// <summary> /// Arg object. /// </summary> public class ArgObject { /// <summary> /// Gets or sets the property1. /// </summary> /// <value> /// The property1. /// </value> public string Property1 { get; set; } } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Platform.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Platform. /// </summary> public enum Platform { /// <summary> /// The windows. /// </summary> Windows, /// <summary> /// The linux. /// </summary> Linux, /// <summary> /// The OSX. /// </summary> OSX } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/LifeSpanHandler.cs using Samotorcan.HtmlUi.Core.Events; using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { /// <summary> /// Life span handler. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "LifeSpan", Justification = "The base class has the same name.")] internal class LifeSpanHandler : CefLifeSpanHandler { #region Events #region BrowserCreated /// <summary> /// Occurs when the browser is created. /// </summary> public event EventHandler<BrowserCreatedEventArgs> BrowserCreated; #endregion #endregion #region Methods #region Protected #region OnBeforeClose /// <summary> /// Called just before a browser is destroyed. Release all references to the /// browser object and do not attempt to execute any methods on the browser /// object after this callback returns. If this is a modal window and a custom /// modal loop implementation was provided in RunModal() this callback should /// be used to exit the custom modal loop. See DoClose() documentation for /// additional usage information. /// </summary> /// <param name="browser"></param> protected override void OnBeforeClose(CefBrowser browser) { } #endregion #region OnAfterCreated /// <summary> /// Called after a new browser is created. /// </summary> /// <param name="browser"></param> protected override void OnAfterCreated(CefBrowser browser) { if (BrowserCreated != null) BrowserCreated(this, new BrowserCreatedEventArgs(browser)); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Renderer/Handlers/ProcessHandler.cs using Newtonsoft.Json; using Samotorcan.HtmlUi.Core.Events; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Renderer.Handlers { /// <summary> /// Render process handler. /// </summary> internal class ProcessHandler : CefRenderProcessHandler { public event EventHandler<BrowserCreatedEventArgs> BrowserCreated; #region Properties #region Private #region NativeMessageHandler /// <summary> /// Gets or sets the native message handler. /// </summary> /// <value> /// The native message handler. /// </value> private NativeMessageHandler NativeMessageHandler { get; set; } #endregion #region LoadHandler /// <summary> /// Gets or sets the load handler. /// </summary> /// <value> /// The load handler. /// </value> private LoadHandler LoadHandler { get; set; } #endregion private ChildApplication Application { get { return ChildApplication.Current; } } #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ProcessHandler"/> class. /// </summary> public ProcessHandler() { NativeMessageHandler = new NativeMessageHandler(); LoadHandler = new LoadHandler(); LoadHandler.OnLoadStartEvent += OnLoadStart; } #endregion #region Methods #region Protected #region OnContextCreated /// <summary> /// Called when context created. /// </summary> /// <param name="browser">The browser.</param> /// <param name="frame">The frame.</param> /// <param name="context">The context.</param> protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { if (frame == null) throw new ArgumentNullException("frame"); } #endregion #region OnContextReleased /// <summary> /// Called when context released. /// </summary> /// <param name="browser">The browser.</param> /// <param name="frame">The frame.</param> /// <param name="context">The context.</param> protected override void OnContextReleased(CefBrowser browser, CefFrame frame, CefV8Context context) { } #endregion #region OnProcessMessageReceived /// <summary> /// Called when process message received. /// </summary> /// <param name="browser">The browser.</param> /// <param name="sourceProcess">The source process.</param> /// <param name="message">The process message.</param> /// <returns></returns> protected override bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message) { if (message == null) throw new ArgumentNullException("message"); return NativeMessageHandler.ProcessMessage(browser, sourceProcess, message); } #endregion #region OnBrowserCreated /// <summary> /// Called after a browser has been created. When browsing cross-origin a new /// browser will be created before the old browser with the same identifier is /// destroyed. /// </summary> /// <param name="browser"></param> protected override void OnBrowserCreated(CefBrowser browser) { NativeMessageHandler.CefBrowser = browser; if (BrowserCreated != null) BrowserCreated(this, new BrowserCreatedEventArgs(browser)); } #endregion #region OnBrowserDestroyed /// <summary> /// Called before a browser is destroyed. /// </summary> /// <param name="browser"></param> protected override void OnBrowserDestroyed(CefBrowser browser) { } #endregion #region OnWebKitInitialized /// <summary> /// Called after WebKit has been initialized. /// </summary> protected override void OnWebKitInitialized() { Logger.Info("WebKit initialized."); CefRuntime.RegisterExtension("htmlUi.native", GetHtmlUiScript("native", false), NativeMessageHandler); if (!Application.IncludeHtmUiScriptMapping) CefRuntime.RegisterExtension("htmlUi.main", GetHtmlUiScript("main", false), NativeMessageHandler); } #endregion #region OnRenderThreadCreated /// <summary> /// Called after the render process main thread has been created. /// </summary> /// <param name="extraInfo"></param> protected override void OnRenderThreadCreated(CefListValue extraInfo) { if (extraInfo == null) throw new ArgumentNullException("extraInfo"); var syncProperties = JsonConvert.DeserializeObject<Dictionary<string, object>>(extraInfo.GetString(0)); foreach (var propertyName in syncProperties.Keys) Application.SetSyncProperty(propertyName, syncProperties[propertyName]); Logger.Info("Render process thread created."); } #endregion #region OnLoadStart /// <summary> /// Called when load start. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="OnLoadStartEventArgs"/> instance containing the event data.</param> protected void OnLoadStart(object sender, OnLoadStartEventArgs e) { var frame = e.Frame; var context = e.Frame.V8Context; if (frame.IsMain && IsLocalUrl(frame.Url)) { if (NativeMessageHandler != null) NativeMessageHandler.Reset(); if (Application.IncludeHtmUiScriptMapping) EvalHtmlUiScript("main", context); EvalHtmlUiScript("run", context, false); } } #endregion #region GetLoadHandler /// <summary> /// Return the handler for browser load status events. /// </summary> /// <returns></returns> protected override CefLoadHandler GetLoadHandler() { return LoadHandler; } #endregion #region OnUncaughtException /// <summary> /// Called for global uncaught exceptions in a frame. Execution of this /// callback is disabled by default. To enable set /// CefSettings.uncaught_exception_stack_size &gt; 0. /// </summary> /// <param name="browser"></param> /// <param name="frame"></param> /// <param name="context"></param> /// <param name="exception"></param> /// <param name="stackTrace"></param> protected override void OnUncaughtException(CefBrowser browser, CefFrame frame, CefV8Context context, CefV8Exception exception, CefV8StackTrace stackTrace) { if (exception == null) throw new ArgumentNullException("exception"); Logger.Error(string.Format("Unhandled exception: {0}", JsonConvert.SerializeObject(exception))); } #endregion #endregion #region Private #region CreateConstant /// <summary> /// Creates the constant. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> private string CreateConstant(string name, string value) { return string.Format("{0} = {1};", name, value); } #endregion #region CreateStringConstant /// <summary> /// Creates the string constant. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> private string CreateStringConstant(string name, string value) { return string.Format("{0} = '{1}';", name, value); } #endregion #region GetHtmlUiScript /// <summary> /// Gets the HTML UI script. /// </summary> /// <param name="name">The name.</param> /// <param name="mapping">if set to <c>true</c> include mapping.</param> /// <returns></returns> private string GetHtmlUiScript(string name, bool mapping) { var scriptName = string.Format("Scripts/htmlUi.{0}.js", name); var script = ResourceUtility.GetResourceAsString(scriptName); var constants = new string[] { CreateStringConstant("_nativeRequestUrl", Application.NativeRequestUrl) }; var processedExtensionResource = script .Replace("// !native ", "native ") .Replace("// !inject-constants", string.Join(Environment.NewLine, constants)); processedExtensionResource = Regex.Replace(processedExtensionResource, @"^/// <reference path=.*$", string.Empty, RegexOptions.Multiline); if (mapping) { var typescriptName = string.Format("TypeScript/htmlUi.{0}.ts", name); var typescript = ResourceUtility.GetResourceAsString(typescriptName); processedExtensionResource = Regex.Replace(processedExtensionResource, @"^//# sourceMappingURL=.*$", (match) => { var sourceMappingURL = match.Groups[0].Value.Substring("//# sourceMappingURL=".Length); var map = JsonConvert.DeserializeObject<SourceMap>(ResourceUtility.GetResourceAsString(string.Format("Scripts/{0}", sourceMappingURL))); map.SourcesContent = new List<string> { typescript }; map.File = null; map.SourceRoot = "/Scripts"; return string.Format("//# sourceMappingURL=data:application/octet-stream;base64,{0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonUtility.SerializeToJson(map)))); }, RegexOptions.Multiline); } else { processedExtensionResource = Regex.Replace(processedExtensionResource, @"^//# sourceMappingURL=.*$", string.Empty, RegexOptions.Multiline); } return processedExtensionResource; } /// <summary> /// Gets the HTML UI script. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> private string GetHtmlUiScript(string name) { return GetHtmlUiScript(name, true); } #endregion #region EvalHtmlUiScript /// <summary> /// Evals the HTML UI script. /// </summary> /// <param name="name">The name.</param> /// <param name="context">The context.</param> private void EvalHtmlUiScript(string name, CefV8Context context, bool mapping) { CefV8Value returnValue = null; CefV8Exception exception = null; if (!context.TryEval(GetHtmlUiScript(name, mapping), out returnValue, out exception)) Logger.Error(string.Format("Register html ui script exception: {0}.", JsonConvert.SerializeObject(exception))); } /// <summary> /// Evals the HTML UI script. /// </summary> /// <param name="name">The name.</param> /// <param name="context">The context.</param> private void EvalHtmlUiScript(string name, CefV8Context context) { EvalHtmlUiScript(name, context, true); } #endregion #region IsLocalUrl /// <summary> /// Determines whether the specified URL is local. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">url</exception> internal bool IsLocalUrl(string url) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url"); return UrlUtility.IsLocalUrl(Application.RequestHostname, Application.NativeRequestPort, url); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Resources/TypeScript/htmlUi.native.ts /// <reference path="references.ts" /> namespace htmlUi.native { export function syncControllerChanges(controllerChanges: IControllerChange[]): void { callNativeSync('syncControllerChanges', controllerChanges); } export function syncControllerChangesAsync(controllerChanges: IControllerChange[], callback?: (nativeResponse: NativeResponse<Object>) => void): void { callNativeAsync('syncControllerChanges', controllerChanges, callback); } export function getControllerNames(): string[] { return callNativeSync<string[]>('getControllerNames'); } export function getControllerNamesAsync(callback?: (nativeResponse: NativeResponse<string[]>) => void): void { callNativeAsync('getControllerNames', null, callback); } export function createController(name: string): IControllerDescription { return callNativeSync<IControllerDescription>('createController', { name: name }); } export function createControllerAsync(name: string, callback?: (nativeResponse: NativeResponse<IControllerDescription>) => void): void { callNativeAsync('createController', { name: name }, callback); } export function createObservableController(name: string): IObservableControllerDescription { return callNativeSync<IObservableControllerDescription>('createObservableController', { name: name }); } export function createObservableControllerAsync(name: string, callback?: (nativeResponse: NativeResponse<IObservableControllerDescription>) => void): void { callNativeAsync('createObservableController', { name: name }, callback); } export function destroyController(id: number): void { callNativeSync('destroyController', id); } export function destroyControllerAsync(id: number, callback?: (nativeResponse: NativeResponse<Object>) => void): void { callNativeAsync('destroyController', id, callback); } export function callMethod<TValue>(id: number, name: string, args: Object[]): TValue { return callNativeSync<TValue>('callMethod', { id: id, name: name, args: args }); } export function callMethodAsync<TValue>(id: number, name: string, args: Object[], callback?: (nativeResponse: NativeResponse<TValue>) => void): void { callNativeAsync('callMethod', { id: id, name: name, args: args }, callback); } export function callInternalMethod<TValue>(id: number, name: string, args: Object[]): TValue { return callNativeSync<TValue>('callMethod', { id: id, name: name, args: args, internalMethod: true }); } export function callInternalMethodAsync<TValue>(id: number, name: string, args: Object[], callback?: (nativeResponse: NativeResponse<TValue>) => void): void { callNativeAsync('callMethod', { id: id, name: name, args: args, internalMethod: true }, callback); } export function registerFunction(name: string, func: Function): void { // !native function registerFunction(); registerFunction(name, func); } export function log(type: string, messageType: string, message: string): void { callNativeSync('log', { type: type, messageType: messageType, message: message }); } export function loadInternalScript(scriptName: string): void { // !native function loadInternalScript(); loadInternalScript(scriptName); } export function callNativeAsync<TValue>(name: string, data: Object, callback?: (nativeResponse: NativeResponse<TValue>) => void): void { var jsonData = JSON.stringify(data); var internalCallback = (jsonResponse: string): void => { if (callback != null) callback(new NativeResponse<TValue>(jsonResponse)); }; native(name, jsonData, internalCallback); } function native(name: string, jsonData: string, callback?: (jsonResponse: string) => void): Object { // !native function native(); return native(name, jsonData, callback); } export function callNativeSync<TValue>(action: string, data?: Object): TValue { var xhr = new XMLHttpRequest(); var url = htmlUi.settings.nativeRequestUrl + action; if (data != null) { xhr.open('POST', url, false); xhr.send(JSON.stringify(data)); } else { xhr.open('GET', url, false); xhr.send(); } var response = <INativeResponse<TValue>>JSON.parse(xhr.responseText); if (response.type == NativeResponseType.Value) return response.value; if (response.type == NativeResponseType.Exception) throw response.exception; } export class NativeResponse<TValue> implements INativeResponse<TValue> { type: NativeResponseType; exception: IJavascriptException; value: TValue; getValue(): TValue { if (this.type == NativeResponseType.Exception) throw this.exception; if (this.type == NativeResponseType.Value) return this.value; return undefined; } constructor(jsonResponse: string) { var nativeResponse = <INativeResponse<TValue>>JSON.parse(jsonResponse); this.type = nativeResponse.type; this.exception = nativeResponse.exception; this.value = nativeResponse.value; } } }<file_sep>/src/Samotorcan.HtmlUi.Core/Events/BrowserCreatedEventArgs.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Events { /// <summary> /// Browser created event arguments. /// </summary> [CLSCompliant(false)] public class BrowserCreatedEventArgs : EventArgs { #region Properties #region Public #region CefBrowser /// <summary> /// Gets or sets the CEF browser. /// </summary> /// <value> /// The CEF browser. /// </value> public CefBrowser CefBrowser { get; private set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BrowserCreatedEventArgs"/> class. /// </summary> /// <param name="cefBrowser">The cef browser.</param> /// <exception cref="System.ArgumentNullException">cefBrowser</exception> public BrowserCreatedEventArgs(CefBrowser cefBrowser) { if (cefBrowser == null) throw new ArgumentNullException("cefBrowser"); CefBrowser = cefBrowser; } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/NativeResponse.cs namespace Samotorcan.HtmlUi.Core { /// <summary> /// Native response. /// </summary> internal class NativeResponse { #region Properties #region Public #region Type /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> public NativeResponseType Type { get; set; } #endregion #region Exception /// <summary> /// Gets or sets the exception. /// </summary> /// <value> /// The exception. /// </value> public JavascriptException Exception { get; set; } #endregion #region Value /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public object Value { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Events/ContextInitializedEventArgs.cs using System; namespace Samotorcan.HtmlUi.Core.Events { /// <summary> /// Context initialized event arguments. /// </summary> internal class ContextInitializedEventArgs : EventArgs { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ContextInitializedEventArgs"/> class. /// </summary> public ContextInitializedEventArgs() { } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ApplicationContext.cs using Samotorcan.HtmlUi.Core.Logs; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Application context. /// </summary> public class ApplicationContext : BaseApplicationSettings { #region Properties #region Public #region D3D11Enabled /// <summary> /// Gets a value indicating whether D3D11 is enabled. /// </summary> /// <value> /// <c>true</c> if D3D11 is enabled; otherwise, <c>false</c>. /// </value> public bool D3D11Enabled { get; set; } #endregion #region CommandLineArgsEnabled /// <summary> /// Gets or sets a value indicating whether command line arguments are enabled. /// </summary> /// <value> /// <c>true</c> if command line arguments are enabled; otherwise, <c>false</c>. /// </value> public bool CommandLineArgsEnabled { get; set; } #endregion #region RemoteDebuggingPort /// <summary> /// Gets or sets the remote debugging port. Set 0 to disable. /// </summary> /// <value> /// The remote debugging port. /// </value> public int? RemoteDebuggingPort { get; set; } #endregion #region ChromeViewsEnabled /// <summary> /// Gets or sets a value indicating whether chrome views are enabled. /// </summary> /// <value> /// <c>true</c> if chrome views are enabled; otherwise, <c>false</c>. /// </value> public bool ChromeViewsEnabled { get; set; } #endregion #region IncludeHtmUiScriptMapping /// <summary> /// Gets or sets a value indicating whether to include HTM UI script mapping. /// </summary> /// <value> /// <c>true</c> to include HTM UI script mapping; otherwise, <c>false</c>. /// </value> public bool IncludeHtmUiScriptMapping { get; set; } #endregion #region LogSeverity /// <summary> /// Gets or sets the log severity. /// </summary> /// <value> /// The log severity. /// </value> public LogSeverity LogSeverity { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ApplicationContext"/> class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ApplicationContext() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="ApplicationContext"/> class. /// </summary> /// <param name="settings">The settings.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Using Initialize instead of a call to base constructor.")] public ApplicationContext(ApplicationContext settings) { Initialize(settings); } #endregion #region Methods #region Private #region InitializeSelf /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> private void InitializeSelf(ApplicationContext settings) { if (settings != null) { D3D11Enabled = settings.D3D11Enabled; CommandLineArgsEnabled = settings.CommandLineArgsEnabled; RemoteDebuggingPort = settings.RemoteDebuggingPort; ChromeViewsEnabled = settings.ChromeViewsEnabled; IncludeHtmUiScriptMapping = settings.IncludeHtmUiScriptMapping; LogSeverity = settings.LogSeverity; } else { D3D11Enabled = false; CommandLineArgsEnabled = false; RemoteDebuggingPort = null; ChromeViewsEnabled = false; IncludeHtmUiScriptMapping = false; LogSeverity = LogSeverity.Error; } } #endregion #endregion #region Protected #region Initialize /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected virtual void Initialize(ApplicationContext settings) { base.Initialize(settings); InitializeSelf(settings); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="settings">The settings.</param> protected override void Initialize(BaseApplicationSettings settings) { base.Initialize(settings); InitializeSelf(null); } /// <summary> /// Initializes this instance. /// </summary> protected override void Initialize() { Initialize(null); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Resources/TypeScript/htmlUi.main.ts /// <reference path="references.ts" /> // definitions namespace htmlUi { export const enum ClientFunctionResultType { Value = 1, Undefined = 2, Exception = 3, FunctionNotFound = 4 } export interface IClientFunctionResult { type: ClientFunctionResultType; exception: Object; value: Object; } export interface IClientFunction { controllerId: number; name: string; args: Array<Object>; } export interface IControllerChange { id: number; properties: { [name: string]: Object }; observableCollections: { [name: string]: IObservableCollectionChanges }; } export interface IObservableCollectionChanges { name: string; actions: IObservableCollectionChange[]; } export interface IObservableCollectionChange { action: ObservableCollectionChangeAction; newItems: Object[]; newStartingIndex: number; oldStartingIndex: number; } export const enum ObservableCollectionChangeAction { Add = 1, Remove = 2, Replace = 3, Move = 4 } export interface INativeResponse<TValue> { type: NativeResponseType; exception: IJavascriptException; value: TValue; } export const enum NativeResponseType { Value = 1, Undefined = 2, Exception = 3 } export interface IJavascriptException { type: string; message: string; additionalData: { [name: string]: Object }; innerException: IJavascriptException; } export interface IControllerDescription { id: number; name: string; methods: IControllerMethodDescription[]; } export interface IObservableControllerDescription extends IControllerDescription { properties: IControllerPropertyDescription[]; } export interface IControllerPropertyDescription extends IControllerPropertyBase { value: Object; } export interface IControllerPropertyBase { name: string; } export interface IControllerMethodDescription extends IControllerMethodBase { } export interface IControllerMethodBase { name: string; } } // utility namespace htmlUi.utility { export function inject(func: Function, inject: Function): Function { return (...args: any[]) => { inject.apply(this, args); return func.apply(this, args); }; } export function shallowCopyCollection<T>(collection: T[]): T[] { if (collection == null) return null; var newCollection: T[] = []; _.forEach(collection, function (value, index) { newCollection[index] = value; }); return newCollection; } export function isArrayShallowEqual<T>(firstArray: T[], secondArray: T[]): boolean { if (firstArray === secondArray) return true; if (firstArray == null || secondArray == null) return false; if (firstArray.length != secondArray.length) return false; return !_.any(firstArray, function (value, index) { return value !== secondArray[index]; }); } } // settings namespace htmlUi.settings { // constants declare var _nativeRequestUrl: string; var _settings = (() => { // !inject-constants return { nativeRequestUrl: _nativeRequestUrl } })(); export var nativeRequestUrl = _settings.nativeRequestUrl; } // main namespace htmlUi { export function domReady(func: () => void): void { if (document.readyState === 'complete') setTimeout(func, 0); else document.addEventListener("DOMContentLoaded", func); } export function includeScript(scriptName: string, onload?: (ev: Event) => any): void { var scriptElement = document.createElement('script'); document.body.appendChild(scriptElement); if (onload != null) scriptElement.onload = onload; scriptElement.src = scriptName; } }<file_sep>/src/Samotorcan.HtmlUi.OS/Linux.cs using Samotorcan.HtmlUi.Linux; namespace Samotorcan.HtmlUi.OS { /// <summary> /// Linux only methods. If you call any method in this class the Linux assembly gets loaded. /// </summary> internal static class Linux { public static void RunApplication(Core.ApplicationContext settings) { Application.Run(new ApplicationContext(settings)); } public static void RunChildApplication(Core.ChildApplicationContext settings) { ChildApplication.Run(new ChildApplicationSettings(settings)); } } } <file_sep>/src/Samotorcan.HtmlUi.WindowsForms/ChildApplication.cs namespace Samotorcan.HtmlUi.WindowsForms { /// <summary> /// Windows forms child application. /// </summary> public abstract class ChildApplication : Core.ChildApplication { #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static new ChildApplication Current { get { return (ChildApplication)Core.ChildApplication.Current; } } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChildApplication"/> class. /// </summary> protected ChildApplication(ChildApplicationContext settings) : base(settings) { } /// <summary> /// Initializes a new instance of the <see cref="ChildApplication"/> class with default settings. /// </summary> protected ChildApplication() : this(new ChildApplicationContext()) { } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/BaseApplication.cs using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.IO; using System.Threading; using System.Collections.Generic; using Samotorcan.HtmlUi.Core.Attributes; using Samotorcan.HtmlUi.Core.Metadata; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Base application. /// </summary> public abstract class BaseApplication : IDisposable { #region Constants #region LogsDirectory /// <summary> /// The logs directory. /// </summary> internal const string LogsDirectory = "Logs"; #endregion #region CacheDirectory /// <summary> /// The cache directory. /// </summary> internal const string CacheDirectory = "Cache"; #endregion #endregion #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static BaseApplication Current { get; private set; } #endregion #region IsMainThread /// <summary> /// Gets a value indicating whether current thread is main thread. /// </summary> /// <value> /// <c>true</c> if current thread is main thread; otherwise, <c>false</c>. /// </value> public bool IsMainThread { get { return Thread.CurrentThread.ManagedThreadId == ThreadId; } } #endregion #region IsRunning /// <summary> /// Gets or sets a value indicating whether this instance is running. /// </summary> /// <value> /// <c>true</c> if this instance is running; otherwise, <c>false</c>. /// </value> public bool IsRunning { get; private set; } #endregion #region RequestHostname private string _requestHostname; /// <summary> /// Gets or sets the request hostname. /// </summary> /// <value> /// The request hostname. /// </value> /// <exception cref="System.ArgumentException">Invalid request hostname.;RequestHostname</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Hostname", Justification = "Hostname is better.")] [SyncProperty] public string RequestHostname { get { return _requestHostname; } set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("value"); if (Uri.CheckHostName(value) != UriHostNameType.Dns) throw new ArgumentException("Invalid request hostname.", "value"); if (_requestHostname != value) { _requestHostname = value; SyncProperty("RequestHostname", _requestHostname); } } } #endregion #region IncludeHtmUiScriptMapping private bool _includeHtmUiScriptMapping; /// <summary> /// Gets or sets a value indicating whether to include HTM UI script mapping. /// </summary> /// <value> /// <c>true</c> to include HTM UI script mapping; otherwise, <c>false</c>. /// </value> [SyncProperty] public bool IncludeHtmUiScriptMapping { get { return _includeHtmUiScriptMapping; } protected set { if (_includeHtmUiScriptMapping != value) { _includeHtmUiScriptMapping = value; SyncProperty("IncludeHtmUiScriptMapping", _includeHtmUiScriptMapping); } } } #endregion [SyncProperty] public LogSeverity LogSeverity { get { return Logger.LogSeverity; } protected set { if (Logger.LogSeverity != value) { Logger.LogSeverity = value; SyncProperty("LogSeverity", Logger.LogSeverity); } } } #endregion #region Internal #region LogsDirectoryPath /// <summary> /// Gets or sets the logs directory path. /// </summary> /// <value> /// The logs directory path. /// </value> internal string LogsDirectoryPath { get; set; } #endregion #region CacheDirectoryPath /// <summary> /// Gets or sets the cache directory path. /// </summary> /// <value> /// The cache directory path. /// </value> internal string CacheDirectoryPath { get; set; } #endregion #region NativeRequestPort private int _nativeRequestPort; /// <summary> /// Gets or sets the native request port. /// </summary> /// <value> /// The native request port. /// </value> /// <exception cref="System.ArgumentException">Invalid port.;Port</exception> [SyncProperty] internal int NativeRequestPort { get { return _nativeRequestPort; } set { if (value < 0 || value > 65535) throw new ArgumentException("Invalid port.", "value"); if (_nativeRequestPort != value) { _nativeRequestPort = value; SyncProperty("NativeRequestPort", _nativeRequestPort); } } } #endregion #region NativeRequestUrl /// <summary> /// Gets the native request URL. /// </summary> /// <value> /// The native request URL. /// </value> public string NativeRequestUrl { get { return string.Format("http://{0}:{1}/", RequestHostname, NativeRequestPort); } } #endregion #endregion #region Private #region ThreadId /// <summary> /// Gets or sets the thread identifier. /// </summary> /// <value> /// The thread identifier. /// </value> private int ThreadId { get; set; } #endregion #region OneApplicationCheckLock /// <summary> /// The one application check lock. /// </summary> private static object OneApplicationCheckLock = new object(); #endregion private bool SyncPropertyDisabled { get; set; } private Dictionary<string, SyncProperty> SyncProperties { get; set; } #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BaseApplication"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <exception cref="System.InvalidOperationException">You can only have one instance of Application at any given time.</exception> protected BaseApplication(BaseApplicationSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); lock (OneApplicationCheckLock) { if (Current != null) throw new InvalidOperationException("You can only have one instance of Application at any given time."); Current = this; } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; LogsDirectoryPath = PathUtility.WorkingDirectory + "/" + LogsDirectory; EnsureLogsDirectory(); InitializeLog4Net(); CacheDirectoryPath = PathUtility.WorkingDirectory + "/" + CacheDirectory; EnsureCacheDirectory(); ThreadId = Thread.CurrentThread.ManagedThreadId; SyncProperties = SyncPropertyAttribute.GetProperties<BaseApplication>(); } /// <summary> /// Initializes a new instance of the <see cref="BaseApplication"/> class with default settings. /// </summary> protected BaseApplication() : this(new BaseApplicationSettings()) { } #endregion #region Methods #region Internal #region EnsureMainThread /// <summary> /// Ensures that it's called from the main thread. /// </summary> /// <exception cref="System.InvalidOperationException">Must be called from the main thread.</exception> internal void EnsureMainThread() { if (Thread.CurrentThread.ManagedThreadId != ThreadId) throw new InvalidOperationException("Must be called from the main thread."); } #endregion #region RunApplication /// <summary> /// Runs the application. /// </summary> /// <exception cref="System.InvalidOperationException">Application is already running.</exception> internal void RunApplication() { EnsureMainThread(); if (IsRunning) throw new InvalidOperationException("Application is already running."); IsRunning = true; Logger.Info("Application Run started."); try { RunInternal(); } finally { IsRunning = false; } Logger.Info("Application Run ended."); } #endregion internal void SetSyncProperty(string name, object value) { EnsureMainThread(); SyncPropertyDisabled = true; try { SyncProperty property; SyncProperties.TryGetValue(name, out property); if (property == null) throw new ArgumentException("Sync property not found.", "name"); try { property.SetDelegate.DynamicInvoke(this, ConvertUtility.ChangeType(value, property.SyncPropertyType)); } catch { throw new ArgumentException("Invalid sync property value.", "value"); } } finally { SyncPropertyDisabled = false; } } #endregion #region Protected #region RunInternal /// <summary> /// Run internal. /// </summary> protected abstract void RunInternal(); #endregion protected abstract void SyncPropertyInternal(string name, object value); protected void SyncProperty(string name, object value) { EnsureMainThread(); if (!SyncPropertyDisabled) SyncPropertyInternal(name, value); } #endregion #region Private #region EnsureLogsDirectory /// <summary> /// Ensures the logs directory. /// </summary> private void EnsureLogsDirectory() { if (!Directory.Exists(LogsDirectoryPath)) Directory.CreateDirectory(LogsDirectoryPath); } #endregion #region EnsureCacheDirectory /// <summary> /// Ensures the cache directory. /// </summary> private void EnsureCacheDirectory() { if (!Directory.Exists(CacheDirectoryPath)) Directory.CreateDirectory(CacheDirectoryPath); } #endregion #region CurrentDomain_UnhandledException /// <summary> /// Handles the UnhandledException event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param> private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Logger.Error("Unhandled exception.", e.ExceptionObject as Exception); } #endregion #region InitializeLog4Net /// <summary> /// Initializes the log4net. /// </summary> private void InitializeLog4Net() { using (var stream = ResourceUtility.GetResourceAsStream("log4net.config")) { log4net.Config.XmlConfigurator.Configure(stream); } log4net.GlobalContext.Properties["process"] = HtmlUiRuntime.ApplicationType == ApplicationType.Application ? "MAIN" : "RENDER"; } #endregion #endregion #endregion #region IDisposable /// <summary> /// Was dispose already called. /// </summary> private bool _disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { EnsureMainThread(); if (!_disposed) { if (disposing) { Current = null; AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; } _disposed = true; } } /// <summary> /// Finalizes an instance of the <see cref="BaseApplication"/> class. /// </summary> ~BaseApplication() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(false); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Renderer/Handlers/LoadHandler.cs using Samotorcan.HtmlUi.Core.Events; using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Renderer.Handlers { /// <summary> /// LoadHandler /// </summary> internal class LoadHandler : CefLoadHandler { #region Events #region OnLoadEnd /// <summary> /// Occurs on load end. /// </summary> public event EventHandler<OnLoadEndEventArgs> OnLoadEndEvent; #endregion #region OnLoadStart /// <summary> /// Occurs on load start. /// </summary> public event EventHandler<OnLoadStartEventArgs> OnLoadStartEvent; #endregion #endregion #region Methods #region Protected #region OnLoadEnd /// <summary> /// Called when the browser is done loading a frame. The |frame| value will /// never be empty -- call the IsMain() method to check if this frame is the /// main frame. Multiple frames may be loading at the same time. Sub-frames may /// start or continue loading after the main frame load has ended. This method /// will always be called for all frames irrespective of whether the request /// completes successfully. /// </summary> /// <param name="browser"></param> /// <param name="frame"></param> /// <param name="httpStatusCode"></param> protected override void OnLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode) { if (OnLoadEndEvent != null) OnLoadEndEvent(this, new OnLoadEndEventArgs(browser, frame, httpStatusCode)); } #endregion #region OnLoadStart /// <summary> /// Called when the browser begins loading a frame. The |frame| value will /// never be empty -- call the IsMain() method to check if this frame is the /// main frame. Multiple frames may be loading at the same time. Sub-frames may /// start or continue loading after the main frame load has ended. This method /// may not be called for a particular frame if the load request for that frame /// fails. For notification of overall browser load status use /// OnLoadingStateChange instead. /// </summary> /// <param name="browser"></param> /// <param name="frame"></param> protected override void OnLoadStart(CefBrowser browser, CefFrame frame) { if (OnLoadStartEvent != null) OnLoadStartEvent(this, new OnLoadStartEventArgs(browser, frame)); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.WindowsForms/Application.cs using Samotorcan.HtmlUi.Core.Logs; using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using FormsApplication = System.Windows.Forms.Application; namespace Samotorcan.HtmlUi.WindowsForms { /// <summary> /// Windows forms application. /// </summary> [CLSCompliant(false)] public abstract class Application : Core.Application { #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static new Application Current { get { return (Application)Core.Application.Current; } } #endregion #region IsUiThread /// <summary> /// Gets a value indicating whether current thread is main thread. /// </summary> /// <value> /// <c>true</c> if current thread is main thread; otherwise, <c>false</c>. /// </value> public bool IsUiThread { get { return Thread.CurrentThread.ManagedThreadId == UiThread.ManagedThreadId; } } #endregion #endregion #region Internal #region Window /// <summary> /// Gets or sets the window. /// </summary> /// <value> /// The window. /// </value> public new Window Window { get { return (Window)base.Window; } protected set { base.Window = value; } } #endregion #endregion #region Protected #region Settings /// <summary> /// Gets or sets the settings. /// </summary> /// <value> /// The settings. /// </value> protected ApplicationContext Settings { get; set; } #endregion #endregion #region Private #region UiThread /// <summary> /// Gets or sets the UI thread. /// </summary> /// <value> /// The UI thread. /// </value> private Thread UiThread { get; set; } #endregion #region UiSynchronizationContext /// <summary> /// Gets or sets the UI synchronization context. /// </summary> /// <value> /// The UI synchronization context. /// </value> private WindowsFormsSynchronizationContext UiSynchronizationContext { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Application"/> class. /// </summary> protected Application(ApplicationContext settings) : base(settings) { Settings = settings; var uiSynchronizationContextCreated = new AutoResetEvent(false); UiThread = new Thread(() => { FormsApplication.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); FormsApplication.ThreadException += new ThreadExceptionEventHandler(Forms_UiUnhandledException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Forms_UnhandledException); FormsApplication.EnableVisualStyles(); FormsApplication.SetCompatibleTextRenderingDefault(false); SynchronizationContext.SetSynchronizationContext(UiSynchronizationContext = new WindowsFormsSynchronizationContext()); uiSynchronizationContextCreated.Set(); FormsApplication.Run(); }); UiThread.SetApartmentState(ApartmentState.STA); UiThread.Start(); uiSynchronizationContextCreated.WaitOne(); } /// <summary> /// Initializes a new instance of the <see cref="Application"/> class with default settings. /// </summary> protected Application() : this(new ApplicationContext()) { } #endregion #region Methods #region Public #region InvokeOnUi /// <summary> /// Invokes the specified action on the UI thread asynchronous. /// </summary> /// <param name="action">The action.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">action</exception> public Task InvokeOnUiAsync(Action action) { if (action == null) throw new ArgumentNullException("action"); var taskCompletionSource = new TaskCompletionSource<object>(); UiSynchronizationContext.Post((state) => { try { action(); taskCompletionSource.SetResult(null); } catch (Exception e) { taskCompletionSource.SetException(e); } }, null); return taskCompletionSource.Task; } /// <summary> /// Invokes the specified action on the UI thread synchronous. /// </summary> /// <param name="action">The action.</param> public void InvokeOnUi(Action action) { if (action == null) throw new ArgumentNullException("action"); if (!IsUiThread) InvokeOnUiAsync(action).Wait(); else action(); } #endregion #endregion #region internal #region EnsureUiThread /// <summary> /// Ensures that it's called from the Ui thread. /// </summary> /// <exception cref="System.InvalidOperationException">Must be called from the Ui thread.</exception> internal void EnsureUiThread() { if (Thread.CurrentThread.ManagedThreadId != UiThread.ManagedThreadId) throw new InvalidOperationException("Must be called from the Ui thread."); } #endregion #endregion #region Protected #region OnShutdown /// <summary> /// Called when the application is shutdown. /// </summary> protected override void OnShutdown() { InvokeOnUi(() => { FormsApplication.Exit(); FormsApplication.ThreadException -= new ThreadExceptionEventHandler(Forms_UiUnhandledException); AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(Forms_UnhandledException); }); } #endregion #endregion #region Private #region Forms_UnhandledException /// <summary> /// Handles the UnhandledException event of the Forms control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param> private void Forms_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var exception = e.ExceptionObject as Exception; Logger.Error("Unhandled exception.", exception); InvokeOnMainAsync(() => { ShutdownWithException(exception); }); } #endregion #region Forms_UiUnhandledException /// <summary> /// Handles the UiUnhandledException event of the Forms control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="ThreadExceptionEventArgs"/> instance containing the event data.</param> private void Forms_UiUnhandledException(object sender, ThreadExceptionEventArgs e) { Logger.Error("Unhandled exception.", e.Exception); InvokeOnMainAsync(() => { ShutdownWithException(e.Exception); }); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Renderer/DeveloperToolsClient.cs using Samotorcan.HtmlUi.Core.Renderer.Handlers; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Renderer { /// <summary> /// Developer tools CEF client. /// </summary> internal class DeveloperToolsClient : CefClient { #region Properties #region Private #region RequestHandler /// <summary> /// Gets or sets the request handler. /// </summary> /// <value> /// The request handler. /// </value> private CefRequestHandler RequestHandler { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DeveloperToolsClient"/> class. /// </summary> public DeveloperToolsClient() : base() { RequestHandler = new DeveloperToolsRequestHandler(); } #endregion #region Methods #region Protected #region GetRequestHandler /// <summary> /// Gets the request handler. /// </summary> /// <returns></returns> protected override CefRequestHandler GetRequestHandler() { return RequestHandler; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ObservableControllerDescription.cs using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { internal class ObservableControllerDescription : ControllerDescription { #region Properties #region Public #region Properties /// <summary> /// Gets or sets the properties. /// </summary> /// <value> /// The properties. /// </value> public List<ControllerPropertyDescription> Properties { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ObservableControllerDescription"/> class. /// </summary> public ObservableControllerDescription() { Properties = new List<ControllerPropertyDescription>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Resources/TypeScript/htmlUi.angular.ts /// <reference path="references.ts" /> // definitions namespace htmlUi.angular { export class ControllerChange implements htmlUi.IControllerChange { id: number; properties: { [name: string]: Object }; observableCollections: { [name: string]: ObservableCollectionChanges }; get hasChanges(): boolean { return _.keys(this.properties).length != 0 || (_.keys(this.observableCollections).length != 0 && _.any(this.observableCollections,(changes) => { return changes.hasChanges; })); } constructor(controllerId: number) { this.id = controllerId; this.properties = {}; this.observableCollections = {}; } getObservableCollection(propertyName: string): ObservableCollectionChanges { var observableCollections = _.find(this.observableCollections,(observableCollection) => { observableCollection.name == propertyName; }); if (observableCollections == null) { observableCollections = new ObservableCollectionChanges(); this.observableCollections[propertyName] = observableCollections; } return observableCollections; } setProperty(propertyName: string, value: any): void { this.properties[propertyName] = value; } getProperty(propertyName: string): any { return this.properties[propertyName]; } hasProperty(propertyName: string): boolean { return _.has(this.properties, propertyName); } removeProperty(propertyName: string): void { if (this.hasProperty(propertyName)) delete this.properties[propertyName]; } addObservableCollectionChange(propertyName: string, action: ObservableCollectionChangeAction, newItem: Object, newStartingIndex: number, oldStartingIndex: number): void { this.getObservableCollection(propertyName).actions .push(new ObservableCollectionChange(action, newItem, newStartingIndex, oldStartingIndex)); } hasObservableCollection(propertyName: string): boolean { return _.has(this.observableCollections, propertyName); } removeObservableCollection(propertyName: string): void { if (this.hasObservableCollection(propertyName)) delete this.observableCollections[propertyName]; } clear(): void { this.properties = {}; this.observableCollections = {}; } } export class ObservableCollectionChanges implements htmlUi.IObservableCollectionChanges { name: string; actions: ObservableCollectionChange[]; constructor() { this.actions = []; } get hasChanges(): boolean { return _.keys(this.actions).length != 0; } } export class ObservableCollectionChange implements htmlUi.IObservableCollectionChange { action: ObservableCollectionChangeAction; newItems: Object[]; newStartingIndex: number; oldStartingIndex: number; constructor(action: ObservableCollectionChangeAction, newItem: Object, newStartingIndex: number, oldStartingIndex: number) { this.action = action; this.newItems = [newItem]; this.newStartingIndex = newStartingIndex; this.oldStartingIndex = oldStartingIndex; if (this.newItems == null) this.newItems = []; } } export class ControllerDataContainer { data: { [controllerId: number]: ControllerData }; controllerChanges: ControllerChange[]; get hasControllerChanges(): boolean { return _.any(this.controllerChanges,(controllerChange) => { return controllerChange.hasChanges; }); } constructor() { this.data = {}; this.controllerChanges = []; } addClientControllerData(controllerId: number): ControllerData { var controllerData: ControllerData = null; this.data[controllerId] = controllerData = new ControllerData(controllerId); return controllerData; } addControllerData(controllerId: number): ControllerData { var controllerData: ControllerData = this.addClientControllerData(controllerId); this.controllerChanges.push(controllerData.change); return controllerData; } getControllerData(controllerId: number): ControllerData { return this.data[controllerId]; } getControllerDataByScopeId(scopeId: number): ControllerData { return _.find(<_.Dictionary<ControllerData>>this.data,(controllerData) => { return controllerData.scopeId == scopeId; }); } clearControllerChanges(): void { _.forEach(this.controllerChanges,(controllerChange) => { controllerChange.clear(); }); } } export interface IClientController { destroy: () => void; } export class ControllerData { controllerId: number; name: string; clientController: IClientController; $scope: ng.IScope; scopeId: number; propertyValues: { [name: string]: Object }; observableCollectionValues: { [name: string]: Object[] }; watches: { [name: string]: Function }; change: ControllerChange; constructor(controllerId: number) { this.controllerId = controllerId; this.propertyValues = {}; this.observableCollectionValues = {}; this.watches = {}; this.change = new ControllerChange(controllerId); } hasProperty(propertyName: string): boolean { return _.has(this.propertyValues, propertyName) } hasPropertyValue(propertyName: string, propertyValue: any): boolean { return this.hasProperty(propertyName) && this.propertyValues[propertyName] === propertyValue; } setPropertyValue(propertyName: string, propertyValue: any): void { this.propertyValues[propertyName] = propertyValue; } removePropertyValue(propertyName: string): void { if (this.hasProperty(propertyName)) delete this.propertyValues[propertyName]; } hasObservableCollection(propertyName: string): boolean { return _.has(this.observableCollectionValues, propertyName) } hasObservableCollectionValue(propertyName: string, observableCollectionValue: Object[]): boolean { return this.hasObservableCollection(propertyName) && utility.isArrayShallowEqual(this.observableCollectionValues[propertyName], observableCollectionValue); } setObservableCollectionValue(propertyName: string, observableCollectionValue: Object[]): void { this.observableCollectionValues[propertyName] = observableCollectionValue; } removeObservableCollectionValue(propertyName: string): void { if (this.hasObservableCollection(propertyName)) delete this.observableCollectionValues[propertyName]; } setControllerPropertyValue(propertyName: string, propertyValue: any): void { this.$scope[propertyName] = propertyValue; } hasWatch(propertyName: string): boolean { return _.has(this.watches, propertyName); } removeWatch(propertyName: string): void { if (this.hasWatch(propertyName)) { this.watches[propertyName](); delete this.watches[propertyName]; } } addWatch(propertyName: string, watch: Function): void { this.removeWatch(propertyName); this.watches[propertyName] = watch; } } } // services namespace htmlUi.angular { var _angular: ng.IAngularStatic = window['angular']; var _$q: ng.IQService = null; export var services = { get $q(): ng.IQService { if (_$q == null) _$q = _angular.injector(['ng']).get('$q'); return _$q; } }; } // native namespace htmlUi.angular.native { export function syncControllerChanges(controllerChanges: ControllerChange[]): void { htmlUi.native.callNativeSync('syncControllerChanges', controllerChanges); } export function syncControllerChangesAsync(controllerChanges: ControllerChange[]): ng.IPromise<Object> { return callNativeAsync<Object>('syncControllerChanges', controllerChanges); } export function getControllerNames(): string[] { return htmlUi.native.callNativeSync<string[]>('getControllerNames'); } export function getControllerNamesAsync(): ng.IPromise<string[]> { return callNativeAsync<string[]>('getControllerNames', null); } export function createController(name: string): IControllerDescription { return htmlUi.native.callNativeSync<IControllerDescription>('createController', { name: name }); } export function createControllerAsync(name: string): ng.IPromise<IControllerDescription> { return callNativeAsync<IControllerDescription>('createController', { name: name }); } export function createObservableController(name: string): IObservableControllerDescription { return htmlUi.native.callNativeSync<IObservableControllerDescription>('createObservableController', { name: name }); } export function createObservableControllerAsync(name: string): ng.IPromise<IObservableControllerDescription> { return callNativeAsync<IObservableControllerDescription>('createObservableController', { name: name }); } export function destroyController(id: number): void { htmlUi.native.callNativeSync('destroyController', id); } export function destroyControllerAsync(id: number): ng.IPromise<Object> { return callNativeAsync<Object>('destroyController', id); } export function callMethod<TValue>(id: number, name: string, args: Object[]): TValue { return htmlUi.native.callNativeSync<TValue>('callMethod', { id: id, name: name, args: args }); } export function callMethodAsync<TValue>(id: number, name: string, args: Object[]): ng.IPromise<TValue> { return callNativeAsync<TValue>('callMethod', { id: id, name: name, args: args }); } export function callInternalMethod<TValue>(id: number, name: string, args: Object[]): TValue { return htmlUi.native.callNativeSync<TValue>('callMethod', { id: id, name: name, args: args, internalMethod: true }); } export function callInternalMethodAsync<TValue>(id: number, name: string, args: Object[]): ng.IPromise<TValue> { return callNativeAsync('callMethod', { id: id, name: name, args: args, internalMethod: true }); } export function registerFunction(name: string, func: Function): void { htmlUi.native.registerFunction(name, func); } export function log(type: string, messageType: string, message: string): void { htmlUi.native.callNativeSync('log', { type: type, messageType: messageType, message: message }); } function callNativeAsync<TValue>(name: string, data?: Object): ng.IPromise<TValue> { var deferred = services.$q.defer<Object>(); htmlUi.native.callNativeAsync<TValue>(name, data, function (response) { if (response.type == NativeResponseType.Value) deferred.resolve(response.value); else if (response.type == NativeResponseType.Exception) deferred.reject(response.exception); else deferred.resolve(); }); return deferred.promise; } } // main namespace htmlUi.angular { var _angular: ng.IAngularStatic = window['angular']; var _controllerDataContainer = new ControllerDataContainer(); init(); function init(): void { // register functions native.registerFunction('syncControllerChanges', syncControllerChanges); native.registerFunction('callClientFunction', callClientFunction); // module var htmlUiModule = _angular.module('htmlUi', []); // run htmlUiModule.run(['$rootScope', ($rootScope: ng.IRootScopeService) => { $rootScope['htmlUiControllerChanges'] = _controllerDataContainer.controllerChanges; addHtmlUiControllerChangesWatch($rootScope); }]); // controller service htmlUiModule.factory('htmlUi.controller', [() => { var createController = (controllerName: string): Object => { // create controller var controller = native.createController(controllerName); var controllerData = _controllerDataContainer.addClientControllerData(controller.id); controllerData.name = controllerName; var clientController = controllerData.clientController = { destroy: (): void => { native.destroyController(controller.id); } }; // methods _.forEach(controller.methods, (method) => { clientController[method.name] = (...args: any[]) => { return native.callMethod<Object>(controller.id, method.name, args); }; }); // warm up native calls native.callInternalMethodAsync<Object>(controller.id, 'warmUp', ['warmUp']).then(() => { }); return clientController; }; var createObservableController = (controllerName: string, $scope: ng.IScope): ng.IScope => { var scopeId = $scope.$id; // create observable controller var observableController = native.createObservableController(controllerName); var controllerData = _controllerDataContainer.addControllerData(observableController.id); controllerData.name = controllerName; controllerData.$scope = $scope; controllerData.scopeId = $scope.$id; // properties _.forEach(observableController.properties,(property) => { var propertyName = property.name; $scope[propertyName] = property.value; // watch observable collection if (_.isArray(property.value)) addCollectionWatch(propertyName, $scope); // watch property addPropertyWatch(propertyName, $scope); }); // methods _.forEach(observableController.methods,(method) => { $scope[method.name] = (...args: any[]) => { return native.callMethod<Object>(observableController.id, method.name, args); }; }); // destroy controller $scope.$on('$destroy',() => { native.destroyController(observableController.id); }); // warm up native calls native.callInternalMethodAsync<Object>($scope.$id, 'warmUp', ['warmUp']).then(() => { }); return $scope; }; return { createController: createController, createObservableController: createObservableController }; }]); } function addHtmlUiControllerChangesWatch($rootScope: ng.IRootScopeService): void { $rootScope.$watch('htmlUiControllerChanges',() => { if (!_controllerDataContainer.hasControllerChanges) return; try { native.syncControllerChanges(_controllerDataContainer.controllerChanges); } finally { _controllerDataContainer.clearControllerChanges(); } }, true); } function addPropertyWatch(propertyName: string, $scope: ng.IScope): void { var scopeId = $scope.$id; var controllerData = _controllerDataContainer.getControllerDataByScopeId(scopeId); $scope.$watch(propertyName,(newValue, oldValue) => { if (newValue !== oldValue && !controllerData.hasPropertyValue(propertyName, newValue)) { controllerData.change.setProperty(propertyName, newValue); if (_.isArray(oldValue)) removeCollectionWatch(propertyName, $scope); if (_.isArray(newValue)) addCollectionWatch(propertyName, $scope); controllerData.change.removeObservableCollection(propertyName); } controllerData.removePropertyValue(propertyName); }); } function addCollectionWatch(propertyName: string, $scope: ng.IScope): void { var scopeId = $scope.$id; var controllerData = _controllerDataContainer.getControllerDataByScopeId(scopeId); controllerData.addWatch(propertyName, $scope.$watchCollection(propertyName,(newCollection: any[], oldCollection: any[]) => { if (newCollection !== oldCollection && !utility.isArrayShallowEqual(newCollection, oldCollection) && !controllerData.hasObservableCollectionValue(propertyName, newCollection) && !controllerData.change.hasProperty(propertyName)) { var compareValues = _.zip(oldCollection, newCollection); _.forEach(compareValues,(compareValue, index) => { var oldValue = compareValue[0]; var newValue = compareValue[1]; if (index < oldCollection.length && index < newCollection.length) { // replace if (oldValue !== newValue) { controllerData.change.addObservableCollectionChange(propertyName, ObservableCollectionChangeAction.Replace, newValue, index, null); } } else if (index < oldCollection.length && index >= newCollection.length) { // remove controllerData.change.addObservableCollectionChange(propertyName, ObservableCollectionChangeAction.Remove, null, null, index); } else { // add controllerData.change.addObservableCollectionChange(propertyName, ObservableCollectionChangeAction.Add, newValue, index, null); } }); } controllerData.removeObservableCollectionValue(propertyName); })); } function removeCollectionWatch(propertyName: string, $scope: ng.IScope): void { var scopeId = $scope.$id; var controllerData = _controllerDataContainer.getControllerDataByScopeId(scopeId); controllerData.removeWatch(propertyName); } function syncControllerChanges(json: string): void { var controllerChanges = <ControllerChange[]>JSON.parse(json); _.forEach(controllerChanges,(controllerChange) => { var controllerId = controllerChange.id; var controllerData = _controllerDataContainer.getControllerData(controllerId); var controller = controllerData.$scope; controller.$apply(() => { // properties _.forEach(controllerChange.properties,(value, propertyName) => { var propertyName = _.camelCase(propertyName); controllerData.setControllerPropertyValue(propertyName, value); controllerData.setPropertyValue(propertyName, value); }); // observable collections _.forEach(controllerChange.observableCollections,(changes, propertyName) => { var propertyName = _.camelCase(propertyName); if (!_.isArray(controller[propertyName])) controller[propertyName] = []; var collection: any[] = controller[propertyName]; _.forEach(changes.actions,(change) => { switch (change.action) { case ObservableCollectionChangeAction.Add: observableCollectionAddAction(collection, change); break; case ObservableCollectionChangeAction.Remove: observableCollectionRemoveAction(collection, change); break; case ObservableCollectionChangeAction.Replace: observableCollectionReplaceAction(collection, change); break; case ObservableCollectionChangeAction.Move: observableCollectionMoveAction(collection, change); break; } }); controllerData.setObservableCollectionValue(propertyName, utility.shallowCopyCollection(collection)); }); }); }); } function observableCollectionAddAction(collection: any[], change: ObservableCollectionChange): void { var insertIndex = change.newStartingIndex; var insertItems = change.newItems; _.forEach(insertItems,(insertItem) => { collection.splice(insertIndex, 0, insertItem); insertIndex++; }); } function observableCollectionRemoveAction(collection: any[], change: ObservableCollectionChange): void { var removeIndex = change.oldStartingIndex; collection.splice(removeIndex, 1); } function observableCollectionReplaceAction(collection: any[], change: ObservableCollectionChange): void { var replaceIndex = change.newStartingIndex; var replaceItems = change.newItems; _.forEach(replaceItems,(replaceItem) => { collection[replaceIndex] = replaceItem; replaceIndex++; }); } function observableCollectionMoveAction(collection: any[], change: ObservableCollectionChange): void { var fromIndex = change.oldStartingIndex; var toIndex = change.newStartingIndex; if (fromIndex == toIndex) return; var removedItems = collection.splice(fromIndex, 1); if (removedItems.length == 1) { var removedItem = removedItems[0]; collection.splice(toIndex, 0, removedItem); } } function callClientFunction(json: string): IClientFunctionResult { var clientFunction = <IClientFunction>JSON.parse(json); var controllerData = _controllerDataContainer.getControllerData(clientFunction.controllerId); var runFunction = (func: Function): IClientFunctionResult => { var result: IClientFunctionResult = { type: ClientFunctionResultType.Value, exception: null, value: null }; if (_.isFunction(func)) { try { result.value = func.apply({}, clientFunction.args); } catch (err) { result.type = ClientFunctionResultType.Exception; result.exception = err; } if (result.value === undefined) result.type = ClientFunctionResultType.Undefined; } else { result.type = ClientFunctionResultType.FunctionNotFound; } return result; }; if (controllerData.clientController != null) return runFunction(controllerData.clientController[clientFunction.name]); return runFunction(controllerData.$scope[clientFunction.name]); } }<file_sep>/src/Samotorcan.HtmlUi.Core/ObservableCollectionChange.cs using Newtonsoft.Json.Linq; namespace Samotorcan.HtmlUi.Core { /// <summary> /// ObservableCollectionChange /// </summary> internal class ObservableCollectionChange { #region Properties #region Public #region Action /// <summary> /// Gets or sets the action. /// </summary> /// <value> /// The action. /// </value> public ObservableCollectionChangeAction Action { get; set; } #endregion #region NewItems /// <summary> /// Gets or sets the new items. /// </summary> /// <value> /// The new items. /// </value> public JArray NewItems { get; set; } #endregion #region NewStartingIndex /// <summary> /// Gets or sets the new index of the starting. /// </summary> /// <value> /// The new index of the starting. /// </value> public int? NewStartingIndex { get; set; } #endregion #region OldStartingIndex /// <summary> /// Gets or sets the old index of the starting. /// </summary> /// <value> /// The old index of the starting. /// </value> public int? OldStartingIndex { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.WindowsForms/Window.cs using System; using System.Windows.Forms; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Utilities; using Samotorcan.HtmlUi.Core.Renderer; namespace Samotorcan.HtmlUi.WindowsForms { /// <summary> /// Windows forms window. /// </summary> [CLSCompliant(false)] public class Window : Core.Window { #region Events #region Resize /// <summary> /// Occurs on resize. /// </summary> protected event EventHandler<EventArgs> Resize; #endregion #endregion #region Properties #region Internal #region Form /// <summary> /// Gets the form. /// </summary> /// <value> /// The form. /// </value> internal Form Form { get; private set; } #endregion #endregion #region Private #region FormHandle /// <summary> /// Gets or sets the form handle. /// </summary> /// <value> /// The form handle. /// </value> private IntPtr FormHandle { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="settings">The settings.</param> public Window(WindowSettings settings) : base(settings) { Application.Current.InvokeOnUi(() => { Form = new Form(); // default values Form.SetBounds(0, 0, 800, 600); // events Form.HandleCreated += Form_HandleCreated; Form.GotFocus += Form_GotFocus; Form.Resize += Form_Resize; Form.FormClosed += Form_FormClosed; }); KeyPress += Window_KeyPress; } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class with default settings. /// </summary> public Window() : this(new WindowSettings()) { } #endregion #region Methods #region Private #region Form_HandleCreated /// <summary> /// Handles the HandleCreated event of the Form control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void Form_HandleCreated(object sender, EventArgs e) { FormHandle = Form.Handle; var width = Form.ClientSize.Width; var height = Form.ClientSize.Height; Application.Current.InvokeOnCef(() => { CreateBrowser(FormHandle, new CefRectangle(0, 0, width, height)); }); } #endregion #region Form_Resize /// <summary> /// Handles the Resize event of the Form control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void Form_Resize(object sender, EventArgs e) { if (Resize != null) Resize(this, new EventArgs()); } #endregion #region Form_GotFocus /// <summary> /// Handles the GotFocus event of the Form control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void Form_GotFocus(object sender, EventArgs e) { if (CefBrowser != null) { CefUtility.ExecuteTask(CefThreadId.UI, () => { CefBrowser.GetHost().SetFocus(true); }); } } #endregion #region Form_FormClosed /// <summary> /// Handles the FormClosed event of the Form control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="FormClosedEventArgs"/> instance containing the event data.</param> private void Form_FormClosed(object sender, FormClosedEventArgs e) { Application.Current.InvokeOnMain(() => { Application.Current.Shutdown(); }); } #endregion #region Window_KeyPress /// <summary> /// Handles the KeyPress event of the Window control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Core.Events.KeyPressEventArgs"/> instance containing the event data.</param> private void Window_KeyPress(object sender, Core.Events.KeyPressEventArgs e) { if (e.KeyEventType == CefKeyEventType.RawKeyDown) { if (e.NativeKeyCode == (int)Keys.F12) OpenDeveloperTools(); else if (e.NativeKeyCode == (int)Keys.F5) RefreshView(e.Modifiers == CefEventFlags.ControlDown); } } #endregion #region OpenDeveloperTools /// <summary> /// Opens the developer tools. /// </summary> private void OpenDeveloperTools() { Application.Current.InvokeOnMain(() => { var windowInfo = CefWindowInfo.Create(); windowInfo.SetAsPopup(IntPtr.Zero, "Developer tools"); windowInfo.Width = 1200; windowInfo.Height = 500; CefBrowser.GetHost().ShowDevTools(windowInfo, new DeveloperToolsClient(), new CefBrowserSettings(), new CefPoint(0, 0)); }); } #endregion #region RefreshView /// <summary> /// Refreshes the view. /// </summary> /// <param name="ignoreCache">if set to <c>true</c> ignore cache.</param> private void RefreshView(bool ignoreCache) { if (CefBrowser != null) { Application.Current.InvokeOnMain(() => { if (ignoreCache) CefBrowser.ReloadIgnoreCache(); else CefBrowser.Reload(); }); } } /// <summary> /// Refreshes the view. /// </summary> private void RefreshView() { RefreshView(false); } #endregion #endregion #endregion #region IDisposable /// <summary> /// Was dispose already called. /// </summary> private bool _disposed = false; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); Application.Current.EnsureMainThread(); if (!_disposed) { if (disposing) { Application.Current.InvokeOnUiAsync(() => { Form.Dispose(); }); } } } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ChildApplication.cs using Samotorcan.HtmlUi.Core.Renderer; using System; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Utilities; using Samotorcan.HtmlUi.Core.Messages; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Child application. /// </summary> public abstract class ChildApplication : BaseApplication { #region Properties #region Public #region Current /// <summary> /// Gets the current application. /// </summary> /// <value> /// The current. /// </value> public static new ChildApplication Current { get { return (ChildApplication)BaseApplication.Current; } } #endregion private CefBrowser CefBrowser { get; set; } #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChildApplication"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <exception cref="System.InvalidOperationException">Application must be run on child application process.</exception> protected ChildApplication(ChildApplicationContext settings) : base(settings) { if (HtmlUiRuntime.ApplicationType != ApplicationType.ChildApplication) throw new InvalidOperationException("Application must be run on child application process."); } /// <summary> /// Initializes a new instance of the <see cref="ChildApplication"/> class with default settings. /// </summary> protected ChildApplication() : this(new ChildApplicationContext()) { } #endregion #region Methods #region Protected #region RunInternal /// <summary> /// Run internal. /// </summary> protected override void RunInternal() { CefRuntime.Load(); var mainArgs = new CefMainArgs(EnvironmentUtility.GetCommandLineArgs()); var app = new App(); app.BrowserCreated += (s, e) => { CefBrowser = e.CefBrowser; }; CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero); } #endregion protected override void SyncPropertyInternal(string name, object value) { MessageUtility.SendMessage(CefProcessId.Browser, CefBrowser, "syncProperty", new SyncProperty { Name = name, Value = value }); } #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Resources/TypeScript/references.ts /// <reference path="angular.d.ts" /> /// <reference path="htmlUi.angular.ts" /> /// <reference path="htmlUi.main.ts" /> /// <reference path="htmlUi.native.ts" /> /// <reference path="htmlUi.run.ts" /> /// <reference path="lodash.d.ts" /><file_sep>/src/Samotorcan.HtmlUi.Core/Messages/CallMethod.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Samotorcan.HtmlUi.Core.Messages { /// <summary> /// CallMethod /// </summary> internal class CallMethod { #region Properties #region Public #region Id /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public int Id { get; set; } #endregion #region Name /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } #endregion #region Arguments /// <summary> /// Gets or sets the arguments. /// </summary> /// <value> /// The arguments. /// </value> [JsonProperty(PropertyName = "args")] public JArray Arguments { get; set; } #endregion #region InternalMethod /// <summary> /// Gets or sets a value indicating whether [internal method]. /// </summary> /// <value> /// <c>true</c> if [internal method]; otherwise, <c>false</c>. /// </value> public bool InternalMethod { get; set; } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ObservableCollectionChanges.cs using Newtonsoft.Json; using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// ObservableCollectionChanges /// </summary> internal class ObservableCollectionChanges { #region Properties #region Public #region Name /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> public string Name { get; set; } #endregion #region Actions /// <summary> /// Gets or sets the actions. /// </summary> /// <value> /// The actions. /// </value> public List<ObservableCollectionChange> Actions { get; set; } #endregion #region IsReset /// <summary> /// Gets or sets a value indicating whether this instance is reset. /// </summary> /// <value> /// <c>true</c> if this instance is reset; otherwise, <c>false</c>. /// </value> [JsonIgnore] public bool IsReset { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ObservableCollectionChanges"/> class. /// </summary> public ObservableCollectionChanges() { Actions = new List<ObservableCollectionChange>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/ExpressionUtility.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Expression utility. /// </summary> internal static class ExpressionUtility { #region Methods #region Public #region CreateMethodDelegate /// <summary> /// Creates the method delegate. /// </summary> /// <param name="methodInfo">The method information.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">methodInfo</exception> public static Delegate CreateMethodDelegate(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo"); var actionTypeArgs = new List<Type> { methodInfo.ReflectedType }; actionTypeArgs.AddRange(methodInfo.GetParameters() .Select(p => p.ParameterType) .ToList()); var instanceParameter = Expression.Parameter(methodInfo.ReflectedType, "o"); var methodArgumentParameters = methodInfo.GetParameters() .Select(p => Expression.Parameter(p.ParameterType, p.Name)) .ToList(); var lambdaParameters = new List<ParameterExpression> { instanceParameter }; lambdaParameters.AddRange(methodArgumentParameters); Type actionType = null; if (methodInfo.ReturnType == typeof(void)) { actionType = Expression.GetActionType(actionTypeArgs.ToArray()); } else { actionTypeArgs.Add(methodInfo.ReturnType); actionType = Expression.GetFuncType(actionTypeArgs.ToArray()); } return Expression.Lambda(actionType, Expression.Call(instanceParameter, methodInfo, methodArgumentParameters), lambdaParameters) .Compile(); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Logs/Logger.cs using log4net; using log4net.Appender; using System; namespace Samotorcan.HtmlUi.Core.Logs { /// <summary> /// Logger. /// </summary> public static class Logger { #region Properties #region Public #region LogSeverity /// <summary> /// Gets or sets the log severity. /// </summary> /// <value> /// The log severity. /// </value> public static LogSeverity LogSeverity { get; set; } #endregion #endregion #region Private #region InternalLogger private static ILog _internalLogger; /// <summary> /// Gets the internal logger. /// </summary> /// <value> /// The internal logger. /// </value> private static ILog InternalLogger { get { if (_internalLogger == null) _internalLogger = LogManager.GetLogger("GeneralLog"); return _internalLogger; } } #endregion #endregion #endregion static Logger() { LogSeverity = LogSeverity.Debug; } #region Methods #region Public #region Log /// <summary> /// Logs the specified message type. /// </summary> /// <param name="messageType">Type of the message.</param> /// <param name="message">The message.</param> /// <param name="exception">The exception.</param> public static void Log(LogMessageType messageType, object message, Exception exception) { if (messageType == LogMessageType.Debug) { if (LogSeverity == LogSeverity.Debug) { InternalLogger.Debug(message, exception); } } else if (messageType == LogMessageType.Info) { if (LogSeverity == LogSeverity.Debug || LogSeverity == LogSeverity.Info) { InternalLogger.Info(message, exception); } } else if (messageType == LogMessageType.Warn) { if (LogSeverity == LogSeverity.Debug || LogSeverity == LogSeverity.Info || LogSeverity == LogSeverity.Warn) { InternalLogger.Warn(message, exception); } } else if (messageType == LogMessageType.Error) { if (LogSeverity == LogSeverity.Debug || LogSeverity == LogSeverity.Info || LogSeverity == LogSeverity.Warn || LogSeverity == LogSeverity.Error) { InternalLogger.Error(message, exception); } } } /// <summary> /// Logs the specified message. /// </summary> /// <param name="messageType">Type of the message.</param> /// <param name="message">The message.</param> public static void Log(LogMessageType messageType, object message) { Log(messageType, message, null); } #endregion #region Debug /// <summary> /// Log a message object with the log4net.Core.Level.Debug level. /// </summary> /// <param name="message">The message object to log.</param> public static void Debug(object message) { Log(LogMessageType.Debug, message); } /// <summary> /// Log a message object with the log4net.Core.Level.Debug level including the stack trace of the System.Exception passed as a parameter. /// </summary> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> public static void Debug(object message, Exception exception) { Log(LogMessageType.Debug, message, exception); } #endregion #region Info /// <summary> /// Log a message object with the log4net.Core.Level.Info level. /// </summary> /// <param name="message">The message object to log.</param> public static void Info(object message) { Log(LogMessageType.Info, message); } /// <summary> /// Log a message object with the log4net.Core.Level.Info level including the stack trace of the System.Exception passed as a parameter. /// </summary> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> public static void Info(object message, Exception exception) { Log(LogMessageType.Info, message, exception); } #endregion #region Warn /// <summary> /// Log a message object with the log4net.Core.Level.Warn level. /// </summary> /// <param name="message">The message object to log.</param> public static void Warn(object message) { Log(LogMessageType.Warn, message); } /// <summary> /// Log a message object with the log4net.Core.Level.Warn level including the stack trace of the System.Exception passed as a parameter. /// </summary> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> public static void Warn(object message, Exception exception) { Log(LogMessageType.Warn, message, exception); } #endregion #region Error /// <summary> /// Log a message object with the log4net.Core.Level.Error level. /// </summary> /// <param name="message">The message object to log.</param> public static void Error(object message) { Log(LogMessageType.Error, message); } /// <summary> /// Log a message object with the log4net.Core.Level.Error level including the stack trace of the System.Exception passed as a parameter. /// </summary> /// <param name="message">The message object to log.</param> /// <param name="exception">The exception to log, including its stack trace.</param> public static void Error(object message, Exception exception) { Log(LogMessageType.Error, message, exception); } #endregion #region Flush /// <summary> /// Flushes this instance. /// </summary> public static void Flush() { var rep = LogManager.GetRepository(); foreach (var appender in rep.GetAppenders()) { var buffered = appender as BufferingAppenderSkeleton; if (buffered != null) buffered.Flush(); } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/ResourceUtility.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Resource utility. /// </summary> internal static class ResourceUtility { #region Methods #region Public #region ResourceExists /// <summary> /// Resource exists. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public static bool ResourceExists(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); name = ResourceUtility.GetFullResourceName(name); var assembly = typeof(ResourceUtility).Assembly; return assembly.GetManifestResourceNames().Contains(name); } #endregion #region GetResourceAsString /// <summary> /// Gets the resource as string. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "It's ok.")] public static string GetResourceAsString(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); name = ResourceUtility.GetFullResourceName(name); var assembly = typeof(ResourceUtility).Assembly; using (var stream = assembly.GetManifestResourceStream(name)) { if (stream == null) throw new ArgumentException("Resource not found.", "name"); using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } #endregion #region GetResourceAsBytes /// <summary> /// Gets the resource as bytes. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> public static byte[] GetResourceAsBytes(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); name = ResourceUtility.GetFullResourceName(name); var assembly = typeof(ResourceUtility).Assembly; using (var stream = assembly.GetManifestResourceStream(name)) { if (stream == null) throw new ArgumentException("Resource not found.", "name"); using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } } #endregion #region GetResourceAsStream /// <summary> /// Gets the resource as stream. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">name</exception> /// <exception cref="System.ArgumentException">Resource not found.;name</exception> public static Stream GetResourceAsStream(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name"); name = ResourceUtility.GetFullResourceName(name); var assembly = typeof(ResourceUtility).Assembly; var stream = assembly.GetManifestResourceStream(name); if (stream == null) throw new ArgumentException("Resource not found.", "name"); return stream; } #endregion #region GetResourceNames /// <summary> /// Gets the resource names. /// </summary> /// <returns></returns> public static List<string> GetResourceNames() { var assembly = typeof(ResourceUtility).Assembly; return assembly.GetManifestResourceNames() .Where(r => r.StartsWith("Samotorcan.HtmlUi.Core.Resources.")) .Select(r => r.Substring("Samotorcan.HtmlUi.Core.Resources.".Length)) .ToList(); } #endregion #endregion #region Private #region GetFullResourceName /// <summary> /// Gets the full name of the resource. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> private static string GetFullResourceName(string name) { return "Samotorcan.HtmlUi.Core.Resources." + name.Replace('/', '.').TrimStart('.'); } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Browser/Handlers/NativeRequestResourceHandler.cs using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Samotorcan.HtmlUi.Core.Exceptions; using Samotorcan.HtmlUi.Core.Logs; using Samotorcan.HtmlUi.Core.Messages; using Samotorcan.HtmlUi.Core.Utilities; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Text; using Xilium.CefGlue; using Samotorcan.HtmlUi.Core.Attributes; namespace Samotorcan.HtmlUi.Core.Browser.Handlers { internal class NativeRequestResourceHandler : CefResourceHandler { private string Url { get; set; } public string Path { get; set; } private Exception Exception { get; set; } private byte[] Data { get; set; } private object ResponseValue { get; set; } private int AllBytesRead { get; set; } private delegate object NativeFunctionDelegate(CefRequest request); private Dictionary<string, NativeFunctionDelegate> NativeFunctions { get; set; } private Application Application { get { return Application.Current; } } public NativeRequestResourceHandler() : base() { NativeFunctions = NativeFunctionAttribute.GetHandlers<NativeRequestResourceHandler, NativeFunctionDelegate>(this); } protected override bool CanGetCookie(CefCookie cookie) { return false; } protected override bool CanSetCookie(CefCookie cookie) { return false; } protected override void Cancel() { } protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl) { if (response == null) throw new ArgumentNullException("response"); redirectUrl = null; response.Status = 200; response.StatusText = "OK"; response.MimeType = "application/json"; response.SetHeaderMap(new NameValueCollection { { "Access-Control-Allow-Origin", string.Format("http://{0}", Application.RequestHostname) } }); var nativeResponse = new NativeResponse(); if (Exception != null) { nativeResponse.Type = NativeResponseType.Exception; nativeResponse.Value = null; nativeResponse.Exception = ExceptionUtility.CreateJavascriptException(Exception); } else { if (ResponseValue == Value.Undefined) { nativeResponse.Type = NativeResponseType.Undefined; nativeResponse.Value = null; } else { nativeResponse.Type = NativeResponseType.Value; nativeResponse.Value = ResponseValue; } nativeResponse.Exception = null; } Data = JsonUtility.SerializeToByteJson(nativeResponse); responseLength = Data.Length; } protected override bool ProcessRequest(CefRequest request, CefCallback callback) { if (request == null) throw new ArgumentNullException("request"); if (callback == null) throw new ArgumentNullException("callback"); Url = request.Url; Path = Application.GetNativeRequestPath(Url); Logger.Debug(string.Format("Native request: {0}", Url)); try { var nativeFunction = FindNativeFunction(Path); if (nativeFunction != null) ResponseValue = nativeFunction(request); else Exception = new NativeNotFoundException(Path); } catch (Exception e) { ResponseValue = null; Exception = e; } callback.Continue(); return true; } protected override bool ReadResponse(Stream response, int bytesToRead, out int bytesRead, CefCallback callback) { if (response == null) throw new ArgumentNullException("response"); bytesRead = 0; if (AllBytesRead >= Data.Length) return false; bytesRead = Math.Min(bytesToRead, Data.Length - AllBytesRead); response.Write(Data, AllBytesRead, bytesRead); AllBytesRead += bytesRead; return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "It has to match to the delegate.")] [NativeFunction("getControllerNames")] private object NativeFunctionGetControllerNames(CefRequest request) { List<string> controllerNames = null; Application.InvokeOnMain(() => { controllerNames = Application.GetControllerNames(); }); return controllerNames; } [NativeFunction("createController")] private object NativeFunctionCreateController(CefRequest request) { var controllerData = GetPostData<CreateController>(request); ControllerDescription controllerDescription = null; Application.InvokeOnMain(() => { var controller = Application.Window.CreateController(controllerData.Name); controllerDescription = controller.GetControllerDescription(); // camel case method names foreach (var method in controllerDescription.Methods) method.Name = StringUtility.CamelCase(method.Name); }); return controllerDescription; } [NativeFunction("createObservableController")] private object NativeFunctionCreateObservableController(CefRequest request) { var controllerData = GetPostData<CreateController>(request); ObservableControllerDescription observableControllerDescription = null; Application.InvokeOnMain(() => { var observableController = Application.Window.CreateObservableController(controllerData.Name); observableControllerDescription = observableController.GetObservableControllerDescription(); // camel case property and method names foreach (var property in observableControllerDescription.Properties) property.Name = StringUtility.CamelCase(property.Name); foreach (var method in observableControllerDescription.Methods) method.Name = StringUtility.CamelCase(method.Name); }); return observableControllerDescription; } [NativeFunction("destroyController")] private object NativeFunctionDestroyController(CefRequest request) { var controllerId = GetPostData<int>(request); Application.InvokeOnMain(() => { Application.Window.DestroyController(controllerId); }); return Value.Undefined; } [NativeFunction("syncControllerChanges")] private object NativeFunctionSyncControllerChanges(CefRequest request) { var controllerChanges = GetPostData<List<ControllerChange>>(request); Application.InvokeOnMain(() => { Application.Window.SyncControllerChangesToNative(controllerChanges); }); return Value.Undefined; } [NativeFunction("callMethod")] private object NativeFunctionCallMethod(CefRequest request) { var methodData = GetPostData<CallMethod>(request); object response = null; Application.InvokeOnMain(() => { response = Application.Window.CallMethod(methodData.Id, methodData.Name, methodData.Arguments, methodData.InternalMethod); }); return response; } [NativeFunction("log")] private object NativeFunctionLog(CefRequest request) { var jsonToken = GetPostJsonToken(request); var type = LogType.Parse((string)jsonToken["type"]); var messageType = LogMessageType.Parse((string)jsonToken["messageType"]); var message = jsonToken["message"].ToString(); if (type == LogType.Logger) Logger.Log(messageType, message); else throw new ArgumentException("Invalid log type."); return Value.Undefined; } private TData GetPostData<TData>(CefRequest request) { var json = GetPostJson(request); return JsonConvert.DeserializeObject<TData>(json); } private TData GetAnonymousPostData<TData>(CefRequest request, TData anonymousObject) { var json = GetPostJson(request); return JsonConvert.DeserializeAnonymousType(json, anonymousObject); } private string GetPostJson(CefRequest request) { return Encoding.UTF8.GetString(request.PostData.GetElements()[0].GetBytes()); } private JToken GetPostJsonToken(CefRequest request) { var json = GetPostJson(request); return JToken.Parse(json); } private NativeFunctionDelegate FindNativeFunction(string name) { NativeFunctionDelegate nativeFunction = null; if (NativeFunctions.TryGetValue(name, out nativeFunction)) return nativeFunction; if (NativeFunctions.TryGetValue(StringUtility.PascalCase(name), out nativeFunction)) return nativeFunction; if (NativeFunctions.TryGetValue(StringUtility.CamelCase(name), out nativeFunction)) return nativeFunction; return null; } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Access.cs using System; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Access. /// </summary> [Flags] internal enum Access { /// <summary> /// The read. /// </summary> Read = 1, /// <summary> /// The write. /// </summary> Write = 2 } } <file_sep>/src/Samotorcan.HtmlUi.Core/Utilities/MessageUtility.cs using System; using Xilium.CefGlue; namespace Samotorcan.HtmlUi.Core.Utilities { /// <summary> /// Message utility. /// </summary> internal class MessageUtility { #region Properties #region Public #region SendMessage /// <summary> /// Sends the message. /// </summary> /// <param name="process">The process.</param> /// <param name="cefBrowser">The cef browser.</param> /// <param name="name">The name.</param> /// <param name="data">The data.</param> /// <exception cref="System.ArgumentNullException"> /// cefBrowser /// or /// name /// </exception> public static void SendMessage(CefProcessId process, CefBrowser cefBrowser, string name, object data) { if (cefBrowser == null) throw new ArgumentNullException("cefBrowser"); if (string.IsNullOrWhiteSpace("name")) throw new ArgumentNullException("name"); var message = JsonUtility.SerializeToBson(data); SendBinaryMessage(process, cefBrowser, name, message); } #endregion #region DeserializeMessage /// <summary> /// Deserializes the message. /// </summary> /// <typeparam name="TType">The type of the type.</typeparam> /// <param name="processMessage">The process message.</param> /// <returns></returns> public static TType DeserializeMessage<TType>(CefProcessMessage processMessage) { return JsonUtility.DeserializeFromBson<TType>(processMessage.Arguments.GetBinary(0).ToArray()); } /// <summary> /// Deserializes the message. /// </summary> /// <typeparam name="TType">The type of the type.</typeparam> /// <param name="processMessage">The process message.</param> /// <param name="anonymousObject">The anonymous object.</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "anonymousObject", Justification = "The type for anonymous object.")] public static TType DeserializeMessage<TType>(CefProcessMessage processMessage, TType anonymousObject) { return JsonUtility.DeserializeFromBson<TType>(processMessage.Arguments.GetBinary(0).ToArray()); } #endregion #endregion #region Private #region SendBinaryMessage /// <summary> /// Sends the binary message. /// </summary> /// <param name="process">The process.</param> /// <param name="cefBrowser">The cef browser.</param> /// <param name="name">The name.</param> /// <param name="message">The message.</param> private static void SendBinaryMessage(CefProcessId process, CefBrowser cefBrowser, string name, byte[] message) { using (var processMessage = CefProcessMessage.Create(name)) { try { using (var binaryValue = CefBinaryValue.Create(message)) { processMessage.Arguments.SetBinary(0, binaryValue); cefBrowser.SendProcessMessage(process, processMessage); } } finally { processMessage.Arguments.Dispose(); } } } #endregion #endregion #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/ControllerMethod.cs using System; using System.Collections.Generic; namespace Samotorcan.HtmlUi.Core { /// <summary> /// Controller method. /// </summary> internal class ControllerMethod : ControllerMethodBase { #region Properties #region Public #region Delegate /// <summary> /// Gets or sets the delegate. /// </summary> /// <value> /// The delegate. /// </value> public Delegate Delegate { get; set; } #endregion #region ParameterTypes /// <summary> /// Gets or sets the parameter types. /// </summary> /// <value> /// The parameter types. /// </value> public List<Type> ParameterTypes { get; set; } #endregion #region MethodType /// <summary> /// Gets or sets the type of the method. /// </summary> /// <value> /// The type of the method. /// </value> public MethodType MethodType { get; set; } #endregion #endregion #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ControllerMethod"/> class. /// </summary> public ControllerMethod() { ParameterTypes = new List<Type>(); } #endregion } } <file_sep>/src/Samotorcan.HtmlUi.Core/Attributes/JavascriptFunctionAttribute.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Samotorcan.HtmlUi.Core.Attributes { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] internal sealed class JavascriptFunctionAttribute : Attribute { private string Handle { get; set; } public JavascriptFunctionAttribute(string handle) { Handle = handle; } public static Dictionary<string, TDelegate> GetHandlers<TType, TDelegate>(TType obj) where TDelegate : class { return typeof(TType).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public) .Select(m => new { Attribute = m.GetCustomAttribute<JavascriptFunctionAttribute>(), Method = m }) .Where(i => i.Attribute != null) .ToDictionary(i => i.Attribute.Handle, i => i.Method.IsStatic ? (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), i.Method) : (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), obj, i.Method)); } } } <file_sep>/src/Samotorcan.HtmlUi.Core/Diagnostics/Stopwatch.cs using Samotorcan.HtmlUi.Core.Logs; using System; using System.Globalization; using System.Runtime.CompilerServices; namespace Samotorcan.HtmlUi.Core.Diagnostics { /// <summary> /// Stopwatch. /// </summary> internal static class Stopwatch { #region Methods #region Public #region Measure /// <summary> /// Measures the specified action. /// </summary> /// <param name="action">The action.</param> /// <param name="name">The name.</param> /// <exception cref="System.ArgumentNullException">action</exception> public static void Measure(Action action, [CallerMemberName] string name = null) { if (action == null) throw new ArgumentNullException("action"); var stopwatch = System.Diagnostics.Stopwatch.StartNew(); try { action(); } finally { stopwatch.Stop(); Stopwatch.LogMeasure(stopwatch, name); } } /// <summary> /// Measures the specified action. /// </summary> /// <typeparam name="TReturn">The type of the return.</typeparam> /// <param name="action">The action.</param> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">action</exception> public static TReturn Measure<TReturn>(Func<TReturn> action, [CallerMemberName] string name = null) { if (action == null) throw new ArgumentNullException("action"); var stopwatch = System.Diagnostics.Stopwatch.StartNew(); try { return action(); } finally { stopwatch.Stop(); Stopwatch.LogMeasure(stopwatch, name); } } /// <summary> /// Measures the specified action. /// </summary> /// <param name="action">The action.</param> /// <param name="name">The name.</param> /// <exception cref="System.ArgumentNullException">action</exception> public static void Measure(Action<System.Diagnostics.Stopwatch> action, [CallerMemberName] string name = null) { if (action == null) throw new ArgumentNullException("action"); var stopwatch = System.Diagnostics.Stopwatch.StartNew(); try { action(stopwatch); } finally { stopwatch.Stop(); Stopwatch.LogMeasure(stopwatch, name); } } /// <summary> /// Measures the specified action. /// </summary> /// <typeparam name="TReturn">The type of the return.</typeparam> /// <param name="action">The action.</param> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">action</exception> public static TReturn Measure<TReturn>(Func<System.Diagnostics.Stopwatch, TReturn> action, [CallerMemberName] string name = null) { if (action == null) throw new ArgumentNullException("action"); var stopwatch = System.Diagnostics.Stopwatch.StartNew(); try { return action(stopwatch); } finally { stopwatch.Stop(); Stopwatch.LogMeasure(stopwatch, name); } } #endregion #endregion #region Private #region LogMeasure /// <summary> /// Logs the measure. /// </summary> /// <param name="stopwatch">The stopwatch.</param> /// <param name="name">The name.</param> private static void LogMeasure(System.Diagnostics.Stopwatch stopwatch, string name) { Logger.Debug(string.Format("[{0}ms] - {1}", stopwatch.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture), name)); } #endregion #endregion #endregion } }
864d120917afe3f4933680221c5f9c8af9c22ac6
[ "TypeScript", "C#", "Markdown" ]
132
TypeScript
bubdm/HtmlUi
656e7c720a003c05a9256d8acacb6d6aedb216c1
91fc1b4035fda3dff8cda0dce7c02f819ab8f872
refs/heads/master
<file_sep>class CreateCompItems < ActiveRecord::Migration def change create_table :comp_items do |t| t.string :company_title t.boolean :founder t.boolean :full_time t.integer :base_salary t.integer :bonus t.float :percent_of_shares t.datetime :company_founded t.references :head_count, index: true, foreign_key: true t.references :revenue, index: true, foreign_key: true t.references :capital_raised, index: true, foreign_key: true t.references :funding_round, index: true, foreign_key: true t.references :development_stage, index: true, foreign_key: true t.references :industry, index: true, foreign_key: true t.references :employee_region, index: true, foreign_key: true t.references :primary_title, index: true, foreign_key: true t.timestamps null: false end end end <file_sep>class HeadCount < ActiveRecord::Base end <file_sep><!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <table class="table table-bordered"> <tr> <th>Title</th> <th># Founders</th> <th>Percentile</th> <th>Base Salary</th> <th>Target Bonus / Commission</th> <th>Total Target Pay</th> <th>Total Diluted Shares</th> </tr> <% @primary_titles.each do |title| %> <% items = CompItem.where(primary_title: title) %> <tr> <td style="max-width: 100px; vertical-align: middle; word-wrap: break-word;"><%= link_to title.name, primary_title_path(title) %></td> <td style="vertical-align: middle;"><%= items.where(founder: true).count %></td> <td><table> <tr><td><span>25th Percentile</span></td></tr> <tr><td><span>50th Percentile</span></td></tr> <tr><td><span>75th Percentile</span></td></tr> </table></td> <td><table style="width: 100%;"> <% base = items.map(&:base_salary) %> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(25).round(0), delimiter: ',') %></span></td></tr> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(50).round(0), delimiter: ',') %></span></td></tr> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(75).round(0), delimiter: ',') %></span></td></tr> </table></td> <td><table style="width: 100%;"> <% base = items.map(&:bonus) %> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(25).round(0), delimiter: ',') %></span></td></tr> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(50).round(0), delimiter: ',') %></span></td></tr> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(75).round(0), delimiter: ',') %></span></td></tr> </table></td> <td><table style="width: 100%;"> <% base = items.map {|item| item.base_salary + item.bonus} %> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(25).round(0), delimiter: ',') %></span></td></tr> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(50).round(0), delimiter: ',') %></span></td></tr> <tr><td style="text-align: center;"><span>$<%= number_with_delimiter(base.percentile(75).round(0), delimiter: ',') %></span></td></tr> </table></td> <td><table style="width: 100%;"> <% base = items.map(&:percent_of_shares) %> <tr><td style="text-align: center;"><span><%= number_with_delimiter((base.percentile(25) * 100).round(3), delimiter: ',') %>%</span></td></tr> <tr><td style="text-align: center;"><span><%= number_with_delimiter((base.percentile(50) * 100).round(3), delimiter: ',') %>%</span></td></tr> <tr><td style="text-align: center;"><span><%= number_with_delimiter((base.percentile(75) * 100).round(3), delimiter: ',') %>%</span></td></tr> </table></td> </tr> <% end %> </div> </div> <!-- /.row --> </div> <!-- /.container --> <file_sep>class FundingRound < ActiveRecord::Base end <file_sep>FactoryGirl.define do factory :comp_item do company_title "MyString" founder false full_time false base_salary 1 bonus 1 percent_of_shares 1.5 company_founded "2016-02-25 11:12:32" head_count nil revenue nil capital_raised nil funding_round nil development_stage nil industry nil employee_region nil primary_title nil end end <file_sep>class PrimaryTitlesController < ApplicationController def show @title = PrimaryTitle.find(params[:id]) @items = CompItem.where(primary_title: @title) end end <file_sep>Rails.application.routes.draw do root to: 'visitors#index' resources :primary_titles, only: [:show] #devise_for :users #resources :users end <file_sep>class CapitalRaised < ActiveRecord::Base end <file_sep>class VisitorsController < ApplicationController def index @primary_titles = PrimaryTitle.all end end <file_sep>FactoryGirl.define do factory :revenue do name "MyString" end end <file_sep>class CompItem < ActiveRecord::Base belongs_to :head_count belongs_to :revenue belongs_to :capital_raised belongs_to :funding_round belongs_to :development_stage belongs_to :industry belongs_to :employee_region belongs_to :primary_title end <file_sep><div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <table> <tr> <th>Company Title</th> <th>Founder</th> <th>Status</th> <th>Employee Region</th> <th>Base Salary</th> <th>Target Bonus</th> <th>Total Pay</th> <th>% Fully Diluted Shares</th> <th>Company Founded On</th> <th>Industry</th> <th>Development Stage</th> <th>Capital Raised</th> <th>Funding Round</th> <th>Revenue</th> <th>Headcount</th> </tr> <% @items.each do |item| %> <tr> <td><%= item.company_title %></td> <td><%= item.founder? ? "Yes" : "No" %></td> <td><%= item.full_time? ? "Full Time" : "Part Time" %></td> <td><%= item.employee_region.name %></td> <td>$<%= number_with_delimiter(item.base_salary, delimiter: ',') %></td> <td>$<%= number_with_delimiter(item.bonus, delimiter: ',') %></td> <td>$<%= number_with_delimiter(item.base_salary + item.bonus, delimiter: ',') %></td> <td><%= (item.percent_of_shares * 100).round(2) %>%</td> <td><%= item.company_founded.year %></td> <td><%= item.industry.name %></td> <td><%= item.development_stage.name %></td> <td><%= item.funding_round.name %></td> <td><%= item.capital_raised.name %></td> <td><%= item.revenue.name %></td> <td><%= item.head_count.name %></td> </tr> <% end %> </table> </div> </div> </div> <file_sep>class EmployeeRegion < ActiveRecord::Base end <file_sep> # Stores excel parsed data in doc doc = SimpleXlsxReader.open('2014 VC Exec Comp Survey - Tech (1).xlsx') # Takes the array from 2-29 and cuts out everything else doc.sheets.slice(0..1) doc.sheets.slice(27) #applies below process for every sheet doc.sheets[2..29].each do |sheet| #removes nil data from sheet sheet.rows.delete_if {|x| x[1] == nil} sheet.rows[11..-1].each do |row| next if row[1].nil? comp_item = CompItem.new #primary title as comp_item.primary_title = PrimaryTitle.find_or_create_by(name: sheet.name) comp_item.company_title = row[1] #if yes, set boolean if row[2] == "Yes" comp_item.founder = true else comp_item.founder = false; end #if full time, set boolean if row[3] == "Full Time" comp_item.full_time = true else comp_item.full_time = false; end comp_item.employee_region = EmployeeRegion.find_or_create_by(name: row[4]) comp_item.base_salary = row[6] comp_item.bonus = row[8] comp_item.percent_of_shares = row[12] * 100 comp_item.company_founded = DateTime.new(row[13].to_i, 1, 1) comp_item.industry = Industry.find_or_create_by(name: row[14]) comp_item.development_stage = DevelopmentStage.find_or_create_by(name: row[15]) comp_item.funding_round = FundingRound.find_or_create_by(name: row[16]) comp_item.capital_raised = CapitalRaised.find_or_create_by(name: row[17]) comp_item.revenue = Revenue.find_or_create_by(name: row[18]) comp_item.head_count = HeadCount.find_or_create_by(name: row[19]) comp_item.save end end <file_sep>class PrimaryTitle < ActiveRecord::Base end <file_sep>FactoryGirl.define do factory :funding_round do name "MyString" end end
5b7c437b7093002886e281c70d963f39bf097f7e
[ "HTML+ERB", "Ruby" ]
16
HTML+ERB
Machoman1850/Comp-Plan
edaba04b99eaa8207be2de5528c2a7d1225369a8
f35090677bea9867503f6c1f589831962fda1884
refs/heads/master
<file_sep>package com.ncatz.yeray.deafmutehelper.presenter; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.speech.tts.TextToSpeech; import android.text.TextUtils; import java.util.HashMap; import java.util.Locale; import com.ncatz.yeray.deafmutehelper.interfaces.IMvp; /** * Created by yeray697 on 21/11/16. */ public class Main_Presenter implements IMvp.Presenter { IMvp.View view; Context context; TextToSpeech textToSpeech; Locale language; public Main_Presenter(IMvp.View view){ this.view = view; this.context = (Context) view; textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) textToSpeech.setLanguage(language); } }); } @Override public void textToSpeech(String text) { if (!TextUtils.isEmpty(text)){ speak(text); } else { //TODO Show error } } //Fuente: http://stackoverflow.com/questions/27968146/texttospeech-with-api-21/28000527#28000527 public void speak(String toSpeak){ if (textToSpeech != null){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ttsGreater21(toSpeak); } else { ttsUnder20(toSpeak); } } } @SuppressWarnings("deprecation") private void ttsUnder20(String text) { HashMap<String, String> map = new HashMap<>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId"); textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, map); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void ttsGreater21(String text) { String utteranceId=this.hashCode() + ""; textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId); } public void stopSpeaking(){ if(textToSpeech != null){ textToSpeech.stop(); } } public void shutdown(){ if(textToSpeech != null){ textToSpeech.stop(); textToSpeech.shutdown(); } } public Locale getLanguage() { return this.language; } public void setLanguage(Locale language) { this.language = language; stopSpeaking(); textToSpeech.setLanguage(this.language); } } <file_sep>package com.ncatz.yeray.deafmutehelper.model; import java.util.Locale; /** * Created by YeraY on 18/07/2016. */ public class Idiomas { public static final Locale ENGLISH_LOCALE = Locale.ENGLISH; public static final Locale FRENCH_LOCALE = Locale.FRENCH; public static final Locale SPANISH_LOCALE = new Locale("es"); public static final Locale GERMAN_LOCALE = Locale.GERMAN; public static final String ENGLISH_ACRONYM = "en"; public static final String FRENCH_ACRONYM = "fr"; public static final String SPANISH_ACRONYM = "es"; public static final String GERMAN_ACRONYM = "de"; public static final String ENGLISH_LANGUAGE = "English"; public static final String FRENCH_LANGUAGE = "Français"; public static final String SPANISH_LANGUAGE = "Español"; public static final String GERMAN_LANGUAGE = "Deutsch"; public static final String[]LANGUAGES = new String[]{ENGLISH_LANGUAGE,FRENCH_LANGUAGE, GERMAN_LANGUAGE, SPANISH_LANGUAGE}; }
ab96d826292a1f09aaeb8dfd71a2fa6f1a11d460
[ "Java" ]
2
Java
yeray697/DeafMuteHelper
7268c6a3bdccddb1db62386bce0a3bbda1163421
e262b7a196dde16f46e8c98532b8910d74508b28
refs/heads/master
<file_sep># multiselect-react React Library for Multiselect dropdown # Installation ``` npm i @pramodkumar115/multiselect-react ``` Example ``` import React, { Component } from 'react' import MultiSelect from 'multiselect-react' export default class App extends Component { handleChange = (e) => { console.log(e) } render() { const valueList = [{ id: 1, value: "One" }, { id: 2, value: "Two" }, { id: 3, value: "Three" }, { id: 4, value: "Four" }, { id: 5, value: "Five" }, { id: 6, value: "Six" }, { id: 7, value: "Seven" }, { id: 8, value: "Eight" }, { id: 9, value: "Nine" }, { id: 10, value: "Ten" }] const selectedValues = [{ id: 8, value: "Eight" }, { id: 9, value: "Nine" }, { id: 10, value: "Ten" }] return ( <div style={{ padding: "10px", width: "400px" }}> <!-- By Default display field is considered to be value.--> <MultiSelect valueList={valueList} onChange={this.handleChange} /> <!-- If you have array of objects where you want to change the displayField, you can do so as in below snippet. You can pass the selected values to preselect the values --> <MultiSelect valueList={valueList} displayField="value" selectedValues={selectedValues} onChange={this.handleChange2} /> </div> ) } } ``` <file_sep>import React, { Component } from 'react' import MultiSelect from 'multiselect-react' export default class App extends Component { handleChange = (e) => { console.log(e) } handleChange2 = (e) => { console.log("2: ", e) } render() { const valueList = [{ id: 1, value: "One" }, { id: 2, value: "Two" }, { id: 3, value: "Three" }, { id: 4, value: "Four" }, { id: 5, value: "Five" }, { id: 6, value: "Six" }, { id: 7, value: "Seven" }, { id: 8, value: "Eight" }, { id: 9, value: "Nine" }, { id: 10, value: "Ten" }] const selectedValues = [{ id: 8, value: "Eight" }, { id: 9, value: "Nine" }, { id: 10, value: "Ten" }]; return ( <div style={{ padding: "10px" }}> <input type="text"></input> <MultiSelect valueList={valueList} onChange={this.handleChange} /> <input type="text"></input> <MultiSelect valueList={valueList} displayField="value" selectedValues={selectedValues} onChange={this.handleChange2} /> <div>Hello</div> </div> ) } } <file_sep>/** * @class MultiSelect */ import * as React from 'react' import styles from './styles.css' export type Props = { valueList: any[], displayField: string, selectedValues?: any[], onChange: Function } export type State = { items: any[], filterInput: string, selectedValues: Set<any>, currentFocus: number } export default class MultiSelect extends React.Component<Props, State> { public static defaultProps = { displayField: "value" }; private dropdownRef = React.createRef<HTMLDivElement>() private wrapperRef = React.createRef<HTMLDivElement>() private dropdownSearchRef = React.createRef<HTMLInputElement>() constructor(props: Props) { super(props); let selectedValues = new Set<any>() if(props.selectedValues != null) { props.selectedValues.forEach(s => { props.valueList.forEach(v => { if(v[props.displayField] === s[props.displayField]) { selectedValues.add(v); } }) }) } console.log("selectedValueList::", selectedValues); this.state = { items: selectedValues.size > 0 ? this.props.valueList.filter(i => !selectedValues.has(i)): this.props.valueList, filterInput: "", selectedValues: selectedValues, currentFocus: -1 } } componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); document.addEventListener('keydown', this.handleKeyboardEvent); document.addEventListener("focus", this.onFocus); //document.addEventListener('keyup', this.handleClick) } componentWillUnmount() { document.removeEventListener('mousedown', this.handleClickOutside); document.removeEventListener('keydown', this.handleKeyboardEvent); document.removeEventListener("focus", this.onFocus); } onFocus = (event: any) => { console.log("On focus", event); } handleKeyboardEvent = (event: KeyboardEvent) => { if (this.wrapperRef && (this.wrapperRef as any).current.contains(event.target)) { let scrollTop = 0 if(this.dropdownRef && this.dropdownRef.current) scrollTop = this.dropdownRef.current.scrollTop if (event.keyCode == 40) { this.state.currentFocus < this.state.items.length - 1 && this.setState({ currentFocus: this.state.currentFocus + 1 }) if(this.dropdownRef && this.dropdownRef.current && this.state.currentFocus >= 9) this.dropdownRef.current.scrollTop = scrollTop + 53 } else if (event.keyCode == 38) { this.state.currentFocus > -1 && this.setState({ currentFocus: this.state.currentFocus - 1 }) if(this.dropdownRef && this.dropdownRef.current && this.state.currentFocus <= 9) this.dropdownRef.current.scrollTop = scrollTop - 53 } else if (event.keyCode == 27) { const node = this.dropdownRef.current node != null && node.classList.contains(styles.active) && node.classList.remove(styles.active) } else if (event.keyCode == 13) { /*If the ENTER key is pressed, prevent the form from being submitted,*/ event.preventDefault(); if (this.state.currentFocus > -1) { /*and simulate a click on the "active" item:*/ this.selectItem(this.state.items[this.state.currentFocus]); } } this.handleClick() } else { this.handleClickOutside(event) } } handleClick = () => { const node = this.dropdownRef.current; node != null && !node.classList.contains(styles.active) && node.classList.add(styles.active) this.dropdownSearchRef && this.dropdownSearchRef.current && this.dropdownSearchRef.current.focus() }; handleClickOutside = (event: any) => { if (this.wrapperRef && !(this.wrapperRef as any).current.contains(event.target)) { const node = this.dropdownRef.current node != null && node.classList.contains(styles.active) && node.classList.remove(styles.active) } } filterRecords = (e: React.KeyboardEvent | React.MouseEvent | React.ChangeEvent) => { const value = ((e.target) as any).value const valueList = this.state.selectedValues.size > 0 ? this.props.valueList.filter(i => !this.state.selectedValues.has(i)) : this.props.valueList if (this.state.filterInput != value) { this.setState({currentFocus: -1}) this.setState({ filterInput: value }, () => { if (this.state.filterInput != null) { this.setState({ items: valueList.filter(v => (v[this.props.displayField] as string) .toLowerCase() .indexOf(this.state.filterInput.toLowerCase()) != -1) }) } else { console.log("this.state.selectedValues::", this.state.selectedValues) console.log("this.props.valueList::", this.props.valueList) this.setState({ items: valueList }) } }) } } selectItem = (selected: any) => { const { selectedValues } = this.state; selectedValues.add(selected) this.setState({ selectedValues: selectedValues, items: this.props.valueList.filter(i => !selectedValues.has(i)) }, this.props.onChange(Array.from(this.state.selectedValues))); this.setState({currentFocus: -1}) } removeItem = (selected: any) => { const { selectedValues } = this.state; selectedValues.delete(selected) this.setState({ selectedValues: selectedValues, items: this.props.valueList.filter(i => !selectedValues.has(i)) }, this.props.onChange(Array.from(this.state.selectedValues))); } render() { return ( <div className={styles.multiSelect} ref={this.wrapperRef}> <input style={{opacity: 0, position: "absolute"}}></input> <div className={styles.multiSelectBox} onClick={this.handleClick} > <div className={styles.multiSelectBoxContents}> {this.state.selectedValues != null && Array.from(this.state.selectedValues).map((v, index) => <div className={styles.multiSelectBoxContentItem} key={`msv_${index}`}> <span>{v[this.props.displayField]}</span> <label style={{ cursor: "pointer" }} onClick={() => this.removeItem(v)}>&#9938;</label> </div>)} </div> <span className={styles.multiSelectArrow}>&#11206;</span> </div> <div className={styles.multiSelectItems} ref={this.dropdownRef}> <ul> <li><input type="search" placeholder="Search" ref={this.dropdownSearchRef} onKeyUp={this.filterRecords} onChange={this.filterRecords}/></li> {this.state.items.map((v, key) => <li className={key === this.state.currentFocus ? styles.multiSelectItemfocus : ""} key={`ms_${key}`} onClick={() => this.selectItem(v)}> {v[this.props.displayField]} </li> )} </ul> </div> </div> ) } }
1f79f3b5e24469894e71881642517901ca3d83b0
[ "Markdown", "JavaScript", "TSX" ]
3
Markdown
pramodkumar115/multiselect-react
838c0307c4ccfe8d3c0e35da4511e81d4dbb336e
4e32f5186e5b370039eb7f73659bf34028a74323
refs/heads/master
<repo_name>Jaludi/contactAPp<file_sep>/app/src/main/java/com/example/android/contactapp/dbhelper.java package com.example.android.contactapp; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.security.PrivateKey; /** * Created by Android on 5/30/2017. */ public class dbhelper extends SQLiteOpenHelper{ private static final String DATABASE_NAME = "contacts.db"; private static final String CONTACTS_TABLE_NAME = "contacts"; private static final String CONTACTS_COLUMN_ID = "ID"; private static final String CONTACTS_COLUMN_FNAME = "First"; private static final String CONTACTS_COLUMN_LNAME = "Last"; private static final String CONTACTS_COLUMN_FPATH = "Path"; public dbhelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table contactlist" + "(id integer primary key, first text, last text, file_path text)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void insertContact(String first, String last, String path){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(CONTACTS_COLUMN_FNAME, first); cv.put(CONTACTS_COLUMN_LNAME, last); cv.put(CONTACTS_COLUMN_FPATH, path); } public String getThatShit(){ SQLiteDatabase db = this.getReadableDatabase(); ContentValues cv = new ContentValues(); cv.get(CONTACTS_COLUMN_FNAME); return ""; } } <file_sep>/app/src/main/java/com/example/android/contactapp/DataBaseHelper.java package com.example.android.contactapp; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; import java.security.PublicKey; /** * Created by Android on 5/30/2017. */ public class DataBaseHelper extends SQLiteOpenHelper { private static final String TAG = "DatabaseHelper"; private static final String DATABASE_NAME = "contacts.db"; private static final String TABLE_NAME = "contacts"; private static final String COL1 = "ID"; private static final String COL2 = "FIRSTNAME"; private static final String COL3 = "LASTNAME"; private static final String COL4 = "PATH"; public DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " FIRSTNAME TEXT, LASTNAME TEXT, PATH TEXT)"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME); onCreate(db); } public Cursor getData(){ SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_NAME; Cursor data = db.rawQuery(query, null); return data; } public boolean addData(String fname, String lname, String path){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL2, fname); cv.put(COL3, lname); cv.put(COL4, path); Log.d(TAG, "addData: "+ cv.size()); Log.d(TAG, "addData: ADDING " + fname + " " + lname + " " + path + " To " + TABLE_NAME); long result = db.insert(TABLE_NAME, null, cv); if(result == -1){ return false;} else{ return true;} } }
0d52f242469e115fdc3e2e6e28bdd2d57e2f8279
[ "Java" ]
2
Java
Jaludi/contactAPp
cf2f4a34678e7e7fbd7bae0614920bde006fc4dc
7fbc3d6b1a0b755887cc9355cf4cc802dca0cb3e
refs/heads/master
<repo_name>samanthagatt/Sprint-Challenge--Intro-C-Processes<file_sep>/ANSWERS.md **1. List all of the main states a process may be in at any point in time on a standard Unix system. Briefly explain what each of these states means.** - A process can either be running, stopped, asleep, orphaned, or in a zombie state. When a process starts running it's reading and executing the code. It goes to sleep if it's waiting for an outside event to occur and/or complete, and it can become a zombie when there's nothing more to execute but the parent doesn't clean it up. If a process continues running after its parent has finished executing, it's considered an orphan. Either init or a parent process will reap the finished process to stop it. **2. What is a zombie process?** - When there's nothing more for the process to execute but the parent doesn't clean it up / reap it, it is considered a zombie process. **3. How does a zombie process get created? How does one get destroyed?** - They get created when its parent doesn't call wait() and takes longer to execute than its child. They get destroyed by init which adopts the zombie process after its parent is reaped and periodically calls wait(). **4. What are some of the benefits of working in a compiled language versus a non-compiled language? More specifically, what benefits are there to be had from taking the extra time to compile our code?** - Non-compiled languages get to skip a step and are more easily readable by computers. Thus, they can take a lot less time to start executing.<file_sep>/lsls/lsls.c #include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #define MAX_COMMAND_CHARS 107 /** * Main */ int main(int argc, char **argv) { // Parse command line if (argc != 2 || strcmp(argv[1], "--help") == 0) { fprintf(stderr, "usage: enter a path to a directory (cannot exceed 100 characters)\n"); exit(1); } char *path = argv[1]; // Open directory DIR *dir = opendir(path); if (dir == NULL) { fprintf(stderr, "error: couldn't open desired directory\n"); exit(1); } // Repeatly read and print entries struct dirent *direntbuff = readdir(dir); while (direntbuff != NULL) { char path[100]; sprintf(path, "%s/%s", argv[1], direntbuff->d_name); struct stat statbuff; int success = stat(path, &statbuff); success != -1 ? printf("\t%lld", statbuff.st_size) : printf("\t"); printf("\t%s\n", direntbuff->d_name); direntbuff = readdir(dir); } // Close directory closedir(dir); return 0; }
16228bf610f1ed3e0ee11676a1414831bd6025d2
[ "Markdown", "C" ]
2
Markdown
samanthagatt/Sprint-Challenge--Intro-C-Processes
002aa623d604a40652dce5d85b7ba9c02dde526e
ce1af1c71bac92b4e535357cf23b9fd06fed8c3c
refs/heads/master
<file_sep>#!/usr/bin/env python3 """ Class """ def binary(num): return bin(num)[2:] def msb_index(n): msb_p = -1 while (n > 0): n = n >> 1 msb_p += 1 return msb_p def raised(num): return 2**num class Class: def __init__(self): super().__init__() def rangeBitwiseAnd(self, m: int, n: int) -> int: result = 0 while m > 0 and n > 0 and msb_index(m) == msb_index(n) : num = raised(msb_index(m)) result += num m -= num n -= num return result def main(args): c = Class() result = c.rangeBitwiseAnd(5, 7) print(result) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-a', '--arg1', help="An argument.", type=str, default='default') args = parser.parse_args() main(args)
48a2c1e6be4437ea200356cbfca513da4bd91c95
[ "Python" ]
1
Python
simonfong6/leetcode
df3b3235d391c26e4d0b607347081979aaa81f28
3d849bf16e9acf0097757e7ad32ea8360c5ad7ac
refs/heads/master
<repo_name>pythonanywhere/sudospawner<file_sep>/README.md # SudoSpawner Enables [JupyterHub](https://github.com/jupyter/jupyterhub) to run without being root, by spawning an intermediate process via `sudo`, which takes actions on behalf of the user. The sudospawner mediator can only do two things: 1. signal processes via os.kill 2. spawn single-user servers The only thing the Hub user needs sudo access for is launching the sudospawner script itself. ## setup Install: pip install -e . [Add sudo access to the script](https://github.com/jupyter/jupyterhub/wiki/Using-sudo-to-run-JupyterHub-without-root-privileges). Tell JupyterHub to use SudoSpawner, by adding the following to your `jupyterhub_config.py`: c.JupyterHub.spawner_class='sudospawner.SudoSpawner' ## example The Dockerfile in this repo contains an example config for setting up a JupyterHub system, without any need to run anything as root. <file_sep>/sudospawner/spawner.py """A Spawner for JupyterHub to allow the Hub to be run as non-root. This spawns a mediator process with sudo, which then takes actions on behalf of the user. """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import sys sys.path.append("/etc") from anywhere_server_details import server_id from pystalkd.Beanstalkd import Connection import json import os from tornado import gen from tornado.process import Subprocess from traitlets import List, Unicode, Bool from jupyterhub.spawner import LocalProcessSpawner from jupyterhub.utils import random_port class SudoSpawner(LocalProcessSpawner): sudospawner_path = Unicode('sudospawner', config=True, help="Path to sudospawner script" ) sudo_args = List(['-nH'], config=True, help="Extra args to pass to sudo" ) debug_mediator = Bool(False, config=True, help="Extra log output from the mediator process for debugging", ) @gen.coroutine def do(self, action, **kwargs): """Instruct the mediator process to take a given action""" kwargs['action'] = action try: os.makedirs("/sys/fs/cgroup/cpu,cpuacct/users/" + self.user.name) except FileExistsError: pass cmd = ["/usr/bin/cgexec", "-g", "cpu,cpuacct:users/" + self.user.name, 'sudo', '-u', self.user.name] cmd.extend(self.sudo_args) cmd.append(self.sudospawner_path) if self.debug_mediator: cmd.append('--logging=debug') p = Subprocess(cmd, stdin=Subprocess.STREAM, stdout=Subprocess.STREAM) yield p.stdin.write(json.dumps(kwargs).encode('utf8')) p.stdin.close() data = yield p.stdout.read_until_close() if p.returncode: raise RuntimeError("Spawner subprocess failed with exit code: %r" % p.returncode) try: return json.loads(data.decode('utf8')) except: print("Spawner child process returned:", data.decode('utf-8')) raise @gen.coroutine def start(self): self.user.server.ip = self.ip self.user.server.port = random_port() self.db.commit() # only args, not the base command reply = yield self.do(action='spawn', args=self.get_args(), env=self.env) connection = Connection("localhost") connection.use("tarpit_queue_for_server_{}".format(server_id)) connection.put(json.dumps(dict(username=self.user.name))) self.pid = reply['pid'] @gen.coroutine def _signal(self, sig): reply = yield self.do('kill', pid=self.pid, signal=sig) return reply['alive']
6e3607524dace450b3ad1b7e0f858bd38e72b79e
[ "Markdown", "Python" ]
2
Markdown
pythonanywhere/sudospawner
022d8d7f735ef5914cf26588bc85aa14eaf1213f
dac8702d8e689a924c18c9c66cdafc5de6ba11c2
refs/heads/master
<file_sep># jakrofi.github.io javascript sockets
20fe411fffa6e8ec422f38ea8164e41d241b8e6d
[ "Markdown" ]
1
Markdown
jakrofi/jakrofi.github.io
e90d0de37083c038b516f6b60d088a3649192aca
3016851717348a315c52ef353961cdd15836d5b5
refs/heads/main
<file_sep>asgiref==3.3.1 Django==3.1.6 Pillow==8.1.0 psycopg2==2.8.6 pytz==2021.1 sqlparse==0.4.1 stripe==2.57.0<file_sep>$(document).ready(function () { $(".cart-table__form").each(function(index) { const btn_minus = $(this).children(".cart-table__form-button_left"); const btn_plus = $(this).children(".cart-table__form-button_right"); const qty = $(this).children(".cart-table__input"); btn_minus.click(function() { if (qty.val() > 1) { qty.val(qty.val() - 1) } }) btn_plus.click(function() { if (qty.val() < 99) { qty.val(+qty.val() + 1) } }) }); })<file_sep>$(document).ready(function () { //Модальное окно бургер $(".header-button").on("click", function () { $(".header-links").removeClass("header-links_visible"); }); $(".menu-button").on("click", function () { $(".header-links").addClass("header-links_visible"); }); //Модальное окно логин $(".header__login").on("click", function () { $(".header-login").slideToggle(300); }) })<file_sep>from django.apps import AppConfig class OnlineShopConfig(AppConfig): name = 'online_shop' <file_sep>$(document).ready(function () { $(".forms__form").each(function () { $(this).validate({ errorClass: "invalid", messages: { username: { required: "Логин обязателен", minlength: "Логин слишком короткий", }, password: { required: "Пароль обязателен", minlength: "Пароль слишком короткий", }, confirm_password: { required: "Подтвердите пароль", minlength: "Пароль слишком короткий", }, first_name: { required: "Имя обязательно", minlength: "Имя слишком короткое", }, last_name: { required: "Фамилия обязательна", minlength: "Фамилия слишком короткая", }, phone: { required: "Телефон обязателен", minlength: "Введите телефон полностью", maxlength: "Слишком много символов", }, email: { required: "Email обязателен", email: "Ваш email должен быть в формате <EMAIL>", }, }, }); }); $("[type=tel]").each(function () { $(this).mask("+7 (000) 000-00-00"); }); })<file_sep>from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse from django.utils import timezone User = get_user_model() class Category(models.Model): name = models.CharField(max_length=256, verbose_name='Имя категории') slug = models.SlugField(unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'slug': self.slug}) class Developer(models.Model): name = models.CharField(max_length=256, verbose_name='Название компании разрабатывающая продукты') slug = models.SlugField(unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('developer', kwargs={'slug': self.slug}) class Product(models.Model): category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.CASCADE) developer = models.ForeignKey(Developer, verbose_name='Разработчик', on_delete=models.CASCADE) title = models.CharField(max_length=255, verbose_name='Наименование') slug = models.SlugField(unique=True) image = models.ImageField(verbose_name='Изображение') price = models.DecimalField(max_digits=9, decimal_places=0, verbose_name='Цена') sale = models.BooleanField(default=False, verbose_name='Акционный товар') sale_price = models.DecimalField(max_digits=9, decimal_places=0, verbose_name='Цена со скидкой', null=True, blank=True) description = models.TextField(verbose_name='Описание', null=True) os = models.CharField(max_length=256, verbose_name='Операционные системы') ui_languages = models.CharField(max_length=256, verbose_name='Языки интерфейса') license_time = models.CharField(max_length=256, verbose_name='Время лицензии') def __str__(self): return self.title def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) class CartProduct(models.Model): user = models.ForeignKey('Customer', verbose_name='Покупатель', on_delete=models.CASCADE, null=True) cart = models.ForeignKey('Cart', verbose_name='Корзина', on_delete=models.CASCADE, related_name='related_products') product = models.ForeignKey(Product, verbose_name='Товар', on_delete=models.CASCADE) qty = models.PositiveIntegerField(default=1) final_price = models.DecimalField(max_digits=9, decimal_places=0, verbose_name='Общая цена') def __str__(self): return "Продукт: {} (для корзины)".format(self.product.title) def save(self, *args, **kwargs): self.final_price = self.qty * self.product.price super().save(*args, **kwargs) class Cart(models.Model): owner = models.ForeignKey('Customer', null=True, verbose_name='Владелец', on_delete=models.CASCADE) products = models.ManyToManyField(CartProduct, blank=True, related_name='related_cart') total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, default=0, decimal_places=0, verbose_name='Общая цена') in_order = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) def __str__(self): return str(self.id) class Customer(models.Model): user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) phone = models.CharField(max_length=20, verbose_name='Номер телефона', null=True, blank=True) orders = models.ManyToManyField('Order', verbose_name='Заказы покупателя', related_name='related_customer', blank=True) def __str__(self): return "Покупатель: {} {}".format(self.user.first_name, self.user.last_name) class Order(models.Model): STATUS_NEW = 'new' STATUS_IN_PROGRESS = 'in_progress' STATUS_READY = 'is_ready' STATUS_COMPLETED = 'completed' STATUS_PAYED = 'payed' STATUS_CHOICES = ( (STATUS_NEW, 'Новый заказ'), (STATUS_IN_PROGRESS, 'Заказ в обработке'), (STATUS_PAYED, 'Заказ оплачен'), (STATUS_READY, 'Заказ готов'), (STATUS_COMPLETED, 'Заказ выполнен') ) cart = models.ForeignKey(Cart, verbose_name='Корзина', on_delete=models.CASCADE, null=True, blank=True) customer = models.ForeignKey(Customer, verbose_name='Покупатель', related_name='related_orders', on_delete=models.CASCADE) first_name = models.CharField(max_length=255, verbose_name='Имя') last_name = models.CharField(max_length=255, verbose_name='Фамилия') phone = models.CharField(max_length=20, verbose_name='Телефон') email = models.CharField(max_length=256, verbose_name='Email') comment = models.TextField(verbose_name='Комментарий к заказу', null=True, blank=True) status = models.CharField(max_length=100, verbose_name='Статус заказа', choices=STATUS_CHOICES, default=STATUS_NEW) create_date = models.DateTimeField(auto_now=True, verbose_name='Дата создания заказа') order_date = models.DateField(verbose_name='Дата получения заказа', default=timezone.now) def __str__(self): return str(self.id) class Mailing(models.Model): email = models.EmailField(verbose_name='Почта для рассылки') def __str__(self): return self.email<file_sep>import stripe from django.db import transaction from django.shortcuts import render from django.contrib import messages from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect, JsonResponse from django.views.generic import DetailView, View from .models import Category, Developer, Customer, CartProduct, Product, Order, Cart, Mailing from .mixins import CartMixin from .forms import LoginForm, RegistrationForm, PasswordCustomChangeForm, MailingForm, OrderForm from .utils import recalc_cart past_page = None class BaseView(CartMixin, View): def get(self, request, *args, **kwargs): new_products = Product.objects.all().order_by('-id')[:5] microsoft = Developer.objects.get(slug='microsoft') microsoft_products = Product.objects.filter(developer=microsoft)[:5] mailing_form = MailingForm(request.POST or None) context = { 'new_products': new_products, 'microsoft_products': microsoft_products, 'cart': self.cart, 'mailing_form': mailing_form } global past_page past_page = None return render(request, 'online_shop/index.html', context) class ProductDetailView(CartMixin, DetailView): model = Product queryset = Product.objects.all() context_object_name = 'product' template_name = 'online_shop/product.html' slug_url_kwarg = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = self.cart context['past_page'] = past_page return context class CategoryDetailView(CartMixin, DetailView): model = Category queryset = Category.objects.all() context_object_name = 'info' template_name = 'online_shop/catalog.html' slug_url_kwarg = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = self.cart context['info_products'] = Product.objects.filter(category=self.get_object()) global past_page past_page = self.get_object() return context class DeveloperDetailView(CartMixin, DetailView): model = Developer queryset = Developer.objects.all() context_object_name = 'info' template_name = 'online_shop/catalog.html' slug_url_kwarg = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = self.cart context['info_products'] = Product.objects.filter(developer=self.get_object()) global past_page past_page = self.get_object() return context class AddToCartView(CartMixin, View): def get(self, request, *args, **kwargs): product_slug = kwargs.get('slug') product = Product.objects.get(slug=product_slug) cart_product, created = CartProduct.objects.get_or_create( user=self.cart.owner, cart=self.cart, product=product ) if created: self.cart.products.add(cart_product) else: cart_product.qty += 1 cart_product.save() recalc_cart(self.cart) return HttpResponseRedirect(product.get_absolute_url()) class DeleteFromCartView(CartMixin, View): def get(self, request, *args, **kwargs): product_slug = kwargs.get('slug') product = Product.objects.get(slug=product_slug) cart_product = CartProduct.objects.get( user=self.cart.owner, cart=self.cart, product=product ) self.cart.products.remove(cart_product) cart_product.delete() recalc_cart(self.cart) return HttpResponseRedirect('/cart/') class ChangeQTYView(CartMixin, View): def post(self, request, *args, **kwargs): product_slug = kwargs.get('slug') product = Product.objects.get(slug=product_slug) cart_product = CartProduct.objects.get( user=self.cart.owner, cart=self.cart, product=product ) qty = int(request.POST.get('qty')) cart_product.qty = qty cart_product.save() recalc_cart(self.cart) return HttpResponseRedirect('/cart/') class CartView(CartMixin, View): def get(self, request, *args, **kwargs): categories = Category.objects.all() context = { 'cart': self.cart, 'categories': categories, } global past_page past_page = None return render(request, 'online_shop/cart.html', context) class LoginView(CartMixin, View): def get(self, request, *args, **kwargs): form = LoginForm(None) context = { 'form': form, 'cart': self.cart } global past_page past_page = None return render(request, 'online_shop/enter.html', context) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['<PASSWORD>'] user = authenticate(username=username, password=<PASSWORD>) if user: login(request, user) return HttpResponseRedirect('/') context = {'form': form, 'cart': self.cart} return render(request, 'online_shop/enter.html', context) class RegistrationView(CartMixin, View): def get(self, request, *args, **kwargs): form = RegistrationForm(request.POST or None) context = { 'form': form, 'cart': self.cart } global past_page past_page = None return render(request, 'online_shop/registration.html', context) def post(self, request, *args, **kwargs): form = RegistrationForm(request.POST or None) if form.is_valid(): new_user = form.save(commit=False) new_user.username = form.cleaned_data['username'] new_user.first_name = form.cleaned_data['first_name'] new_user.last_name = form.cleaned_data['last_name'] new_user.email = form.cleaned_data['email'] new_user.save() new_user.set_password(form.cleaned_data['password']) new_user.save() Customer.objects.create( user=new_user, phone=form.cleaned_data['phone'], ) user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) login(request, user) return HttpResponseRedirect('/') context = {'form': form, 'cart': self.cart} return render(request, 'online_shop/registration.html', context) class OrdersView(CartMixin, View): def get(self, request, *args, **kwargs): customer = Customer.objects.get(user=request.user) orders = Order.objects.filter(customer=customer) context = {'orders': orders, 'cart': self.cart} return render(request, 'online_shop/orders.html', context) class UserSettingsView(CartMixin, View): def get(self, request, *args, **kwargs): form = PasswordCustomChangeForm(request.POST or None) context = { 'form': form, 'cart': self.cart } global past_page past_page = None return render(request, 'online_shop/userSettings.html', context) def post(self, request, *args, **kwargs): form = PasswordCustomChangeForm(request.user, request.POST) successful_message = None if form.is_valid(): user = request.user user.set_password(form.cleaned_data["<PASSWORD>"]) user.save() login(request, user) successful_message = "Пароль изменен" context = {'form': form, "successful_message": successful_message, 'cart': self.cart} return render(request, 'online_shop/userSettings.html', context) class CheckoutView(CartMixin, View): def get(self, request, *args, **kwargs): stripe.api_key = "<KEY>" intent = stripe.PaymentIntent.create( amount=int(self.cart.final_price * 100), currency='rub', # Verify your integration in this guide by including this parameter metadata={'integration_check': 'accept_a_payment'}, ) form = OrderForm(request.POST or None) context = { 'cart': self. cart, 'form': form, 'client_secret': intent.client_secret } return render(request, 'online_shop/checkout.html', context) class MakeOrderView(CartMixin, View): @transaction.atomic def post(self, request, *args, **kwargs): form = OrderForm(request.POST or None) user = request.user customer = Customer.objects.get(user=user) if form.is_valid(): new_order = form.save(commit=False) new_order.customer = customer new_order.first_name = user.first_name new_order.last_name = user.last_name new_order.phone = customer.phone new_order.email = user.email new_order.order_date = form.cleaned_data['order_date'] new_order.comment = form.cleaned_data['comment'] new_order.save() self.cart.in_order = True self.cart.save() new_order.cart = self.cart new_order.save() customer.orders.add(new_order) return HttpResponseRedirect('/') return HttpResponseRedirect('/checkout/') class PayedOnlineOrderView(CartMixin, View): @transaction.atomic def post(self, request, *args, **kwargs): user = request.user customer = Customer.objects.get(user=user) new_order = Order() new_order.customer = customer new_order.first_name = user.first_name new_order.last_name = user.last_name new_order.phone = customer.phone new_order.email = user.email new_order.save() self.cart.in_order = True self.cart.save() new_order.cart = self.cart new_order.status = Order.STATUS_PAYED new_order.save() customer.orders.add(new_order) return JsonResponse({"status": "payed"}) class SearchView(CartMixin, View): def post(self, request, *args, **kwargs): search = request.POST.get("search") info_products = Product.objects.filter(title__icontains=search) info = { "name": "Поиск" } context = {"info": info, "info_products": info_products} return render(request, 'online_shop/catalog.html', context) class MailingView(View): def post(self, request, *args, **kwargs): form = MailingForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] Mailing.objects.create(email=email) messages.add_message(request, messages.ERROR, form.non_field_errors()) return HttpResponseRedirect('/') <file_sep>var form = document.getElementById('payment-form'); var stripe = Stripe('<KEY>'); var elements = stripe.elements(); var style = {base: {color: "#32325d",}}; var card = elements.create("card", { style: style }); card.mount("#card-element"); card.on('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = '';}}); form.addEventListener('submit', function(ev) { ev.preventDefault(); var clientSecret = document.getElementById('card-button') stripe.confirmCardPayment(clientSecret.dataset.secret, { payment_method: { card: card, billing_details: { name: document.getElementById('card-button').dataset.username } } }).then(function(result) { if (result.error) { var error = document.getElementById('card-error'); alert(result.error.message); } else { if (result.paymentIntent.status === 'succeeded') { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var formData = new FormData(document.forms.order); formData.append("first_name", document.getElementById('card-button').dataset.username); formData.append("csrfmiddlewaretoken", csrftoken) var xhr = new XMLHttpRequest(); xhr.open("POST", "/payed-online-order/"); xhr.send(formData); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { window.location.replace("http://127.0.0.1:8000"); alert('Ваш заказ успешно оплачен! Менеджер с Вами свяжется') } } } } }); });<file_sep>$(document).ready(function () { $(".modal__button").click(function() { dataAttr = $(this).data("target") $(dataAttr).addClass("modal-open") }) $(".modal__close").click(function() { $(".modal").removeClass("modal-open"); }) })<file_sep>$(document).ready(function () { var saleSwiper = new Swiper(".sale-slider", { loop: true, spaceBetween: 60, centeredSlides: true, navigation: { nextEl: ".sale-slider__button--next", prevEl: ".sale-slider__button--prev", }, }) var commentsSwiper = new Swiper(".comments__swiper-container", { loop: true, spaceBetween: 60, centeredSlides: true, pagination: { el: ".comments__swiper-pagination", renderBullet: function (index, className) { return '<span class="' + className + '"></span>'; }, bulletClass: "comments__swiper-pagination-bullet", bulletActiveClass: "comments__swiper-pagination-bullet-active", clickable: true, }, autoplay: { delay: 7000, disableOnInteraction: false, }, }); var commentsSwiperSlide = $(".comments__swiper-container"); commentsSwiperSlide.on("mouseover", function () { commentsSwiper.autoplay.stop(); }); commentsSwiperSlide.on("mouseout", function () { commentsSwiper.autoplay.start(); }); })
8933309db67fa729a27b8f5137f25983ab739da4
[ "Text", "JavaScript", "Python" ]
10
Text
Rom555/Usoftwave
61662cbac2e8a460e3cbe2fda709115cbb14cf59
0050c132b2aecffdafce91be0619c396f3eaec40
refs/heads/master
<repo_name>desham05/Array-1<file_sep>/Problem1.java // Time Complexity : O(N) // Space Complexity : O(1) // Did this code successfully run on Leetcode : Yes // Three line explanation of solution in plain english // Your code here along with comments explaining your approach // in first iteration take left side product of all the elements // next time take the right side product starting from right side(end) of the array and multipy with current left side product of the array // return result /* * Given an array nums of n integers where n > 1, return an array output such * that output[i] is equal to the product of all the elements of nums except * nums[i]. * * Example: * * Input: [1,2,3,4] Output: [24,12,8,6] Note: Please solve it without division * and in O(n). * * Follow up: Could you solve it with constant space complexity? (The output * array does not count as extra space for the purpose of space complexity * analysis.) */ class Solution { public int[] productExceptSelf(int[] nums) { if(nums == null || nums.length == 0){ return new int[] {0}; } int[] output = new int[nums.length]; int product = 1; for(int i =0;i< nums.length;i++){ output[i] = product; product *= nums[i]; } product =1; for(int i = nums.length -1;i>=0;i--){ output[i] = output[i] * product; product *= nums[i]; } return output; } }
e23e83360afe75f7845bd4bcbd5aa874c8a1ed0c
[ "Java" ]
1
Java
desham05/Array-1
29e277f53b3dded819c11209b231fce1a67e9208
99ca78cd62a49db5b778915ff20e5e5eca1c853c
refs/heads/main
<file_sep># user1sarvin.github.io
c8d40cb7de9b331a433b6f50273d71e32771187f
[ "Markdown" ]
1
Markdown
user1sarvin/user1sarvin.github.io
36d5baa4579362f6f2b23057dbd5099877623ba0
7cad1a06727fed7ada774d16fee3191c4dd7f667
refs/heads/master
<repo_name>kyungsooim/227-HW4-starter<file_sep>/README.md # EGR227-SP21-HW4-Anagrams-Starter
a739dcceb01979d99635c84cfb192c51537c892f
[ "Markdown" ]
1
Markdown
kyungsooim/227-HW4-starter
ed6ad0872dca7d3aef77aea0a458c7f0d4356db8
66769b41781e770f74b9a5f6ee23cac1a725f759
refs/heads/master
<file_sep>--- title: "Possibilidades" date: 2018-03-08 --- Dessa forma, com um site de acesso aberto, talvez os colegas possam acessar mais facilmente as análises e fazer comentários.<file_sep>--- title: "Perfil de Morbidade dos pacientes de duas Equipes de Saúde da Família do CMS João Barros Barreto, em Copacabana, Rio de Janeiro" author: "<NAME>" date: "21 de fevereiro de 2018" output: pdf_document --- ```{r setup, include=FALSE, warnings = FALSE} knitr::opts_chunk$set(echo = TRUE) setwd("G:\\copacabana") library(plyr) library(tidyverse) library(knitr) library(janitor) copa <- read.csv("teste.csv", header = TRUE, sep = ";", dec = ",") ``` ### Pessoal, aqui estão algumas análises que fiz apenas sobre alguns dados de morbidade. Ainda há muito mais para se analisar referente a encaminhamentos, solicitação de exames laboratoriais e prescrição de medicamentos. Vou explicando abaixo cada etapa do que fiz. # Cálculo da Idade ```{r, warning = FALSE, echo = FALSE} # C?lculo da Idade library(lubridate) ddn <- copa$nascimento # separando data de nascimento do banco nascimento <- as.Date(ddn, "%d.%m.%Y") # convertendo a data para formato YYYY-mm-dd head(nascimento) head(copa$nascimento) # transforma??o funcionou # criando fun??o para calcular a idade baseado no dia de hoje calcula_idade <- function(nascimento, dia = today(), units = "years", floor = TRUE) { calc.idade = new_interval(nascimento, dia) / duration(num = 1, units = units) if (floor) return(as.integer(floor(calc.idade))) return(calc.idade) } idade <- calcula_idade(nascimento, floor = FALSE) copa$idade <- calcula_idade(nascimento, floor = FALSE) summary(copa$idade) ``` Graficamente a informação de idade para cada uma das equipes pode ser vista na tabela abaixo, na qual se observa que a equipes Ceci atendeu uma população mais nova, com dois grupos priorit?rios: crian?as e adultos. A equipe Curumim atendeu prioritariamente idosos, com uma concentração significativa de adultos. ```{r} p <- ggplot(copa, aes(factor(equipe), idade, color = equipe)) p + geom_violin() + geom_jitter(height = 0, width = 0.1) + ggtitle("Distribuição das Idades dos Pacientes no CMS JBB") + xlab("Equipe de Saúde da Família") + ylab("Idade") ``` # DIABETES Foram consideradas como diabéticos aqueles pacientes que apresentaram os CID "E10", "E11", "E12", "E14" na vari?vel CIDs. ```{r, echo = FALSE} diabetes <- c("E10", "E11", "E12", "E14") copa$DM <- grepl(paste(diabetes, collapse = "|"), copa$CID) copa$DM <- as.factor(ifelse(copa$DM == TRUE, 1,0)) # 29 diab?ticos no total diabet <- copa %>% group_by(equipe) %>% count(DM) %>% mutate(prop = prop.table(n)*100) kable(diabet) diabeta <- summary(copa$DM[copa$equipe == "curumim"]) diabetb <- summary(copa$DM[copa$equipe == "ceci"]) diabetc <- matrix(c(diabeta,diabetb), ncol=2) nome <- c("ausente", "presente") diabetm <- as.data.frame(cbind(nome, diabetc)) names(diabetm)[names(diabetm) == 'nome'] <- 'DIABETES' names(diabetm)[names(diabetm) == 'V2'] <- 'Curumim' names(diabetm)[names(diabetm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de Diabéticos entre as equipes. Existe diferença significativa na proporção de pacientes atendidos por Diabetes ```{r} kable(diabetm) chisq.test(diabetc) ``` # HIPERTENSÃO Foi considerado como "hipertenso" apenas as pessoas que receberam o CID I10 ```{r, echo = FALSE} copa$HAS <- grepl("I10", copa$CID) copa$HAS <- as.factor(ifelse(copa$HAS == TRUE, 1,0)) # 101 hipertensos no total hiper <- copa %>% group_by(equipe) %>% count(HAS) %>% mutate(prop = prop.table(n)*100) kable(hiper) hipera <- summary(copa$HAS[copa$equipe == "curumim"]) hiperb <- summary(copa$HAS[copa$equipe == "ceci"]) hiperc <- matrix(c(hipera,hiperb), ncol=2) nome <- c("ausente", "presente") hiperm <- as.data.frame(cbind(nome, hiperc)) names(hiperm)[names(hiperm) == 'nome'] <- 'HIPERTENSÃO' names(hiperm)[names(hiperm) == 'V2'] <- 'Curumim' names(hiperm)[names(hiperm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de Hipertensos entre as equipes. Existe diferença significativa na proporção de pacientes atendidos por Hipertensão. ```{r} kable(hiperm) chisq.test(hiperc) ``` # DEPRESSÃO Foi considerado como "depressão" apenas as pessoas que receberam o CID R32 ```{r, echo = FALSE} copa$depress <- grepl("F32", copa$CID) copa$depress <- as.factor(ifelse(copa$depress == TRUE, 1,0)) # 17 com depress?o dep <- copa %>% group_by(equipe) %>% count(depress) %>% mutate(prop = prop.table(n)*100) kable(dep) depa <- summary(copa$depress[copa$equipe == "curumim"]) depb <- summary(copa$depress[copa$equipe == "ceci"]) depc <- matrix(c(depa,depb), ncol=2) nome <- c("ausente", "presente") depm <- as.data.frame(cbind(nome, depc)) names(depm)[names(depm) == 'nome'] <- 'Depressão' names(depm)[names(depm) == 'V2'] <- 'Curumim' names(depm)[names(depm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de transtornos da tireóide entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Depressão ```{r} kable(depm) chisq.test(depc) ``` # ANSIEDADE Apoenas o CID F41 ```{r, echo = FALSE} copa$anx <- grepl("F41", copa$CID) copa$anx <- as.factor(ifelse(copa$anx == TRUE, 1,0)) # 23 com ansiedade anxi <- copa %>% group_by(equipe) %>% count(anx) %>% mutate(prop = prop.table(n)*100) kable(anxi) anxia <- summary(copa$anx[copa$equipe == "curumim"]) anxib <- summary(copa$anx[copa$equipe == "ceci"]) anxic <- matrix(c(anxia,anxib), ncol=2) nome <- c("ausente", "presente") anxim <- as.data.frame(cbind(nome, anxic)) names(anxim)[names(anxim) == 'nome'] <- 'Transtorno de Ansiedade' names(anxim)[names(anxim) == 'V2'] <- 'Curumim' names(anxim)[names(anxim) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de transtornos da tireóide entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Transtorno de Ansiedade ```{r} kable(anxim) chisq.test(anxic) ``` # MUSCULAR Todas as pessoas que receberma algum CID entre "M10" at? "M99" ```{r, echo = FALSE} muscular <- c("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9") copa$musc <- grepl(paste(muscular, collapse = "|"), copa$CID) copa$musc <- as.factor(ifelse(copa$musc == TRUE, 1,0)) # 39 com algum problema osteomuscular mus <- copa %>% group_by(equipe) %>% count(musc) %>% mutate(prop = prop.table(n)*100) kable(mus) musa <- summary(copa$musc[copa$equipe == "curumim"]) musb <- summary(copa$musc[copa$equipe == "ceci"]) musc <- matrix(c(musa,musb), ncol=2) nome <- c("ausente", "presente") musm <- as.data.frame(cbind(nome, musc)) names(musm)[names(musm) == 'nome'] <- 'Problemas Músculo-esqueléticos' names(musm)[names(musm) == 'V2'] <- 'Curumim' names(musm)[names(musm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de transtornos da tireóide entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Problemas Músculo-esqueléticos ```{r} kable(musm) chisq.test(musc) ``` # Conjuntivite CIDs "H25" e "H26" ```{r, echo = FALSE} conjuntivite <- c("H25", "H26") copa$conju <- grepl(paste(conjuntivite, collapse = "|"), copa$CID) copa$conju <- as.factor(ifelse(copa$conju == TRUE, 1,0)) # 10 com conjuntivite conj <- copa %>% group_by(equipe) %>% count(conju) %>% mutate(prop = prop.table(n)*100) kable(conj) conja <- summary(copa$conju[copa$equipe == "curumim"]) conjb <- summary(copa$conju[copa$equipe == "ceci"]) conjc <- matrix(c(conja,conjb), ncol=2) nome <- c("ausente", "presente") conjm <- as.data.frame(cbind(nome, conjc)) names(conjm)[names(conjm) == 'nome'] <- 'Problemas oftalmológicos' names(conjm)[names(conjm) == 'V2'] <- 'Curumim' names(conjm)[names(conjm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de transtornos da tireóide entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Problemas oftalmológicos ```{r} kable(conjm) chisq.test(conjc) ``` # Genito-Urinário Todos os CIDs enre "N10" e "N99". ```{r, echo = FALSE} urinario <- c("N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9") copa$urina <- grepl(paste(urinario, collapse = "|"), copa$CID) copa$urina <- as.factor(ifelse(copa$urina == TRUE, 1,0)) # 33 com problema urin?rio uro <- copa %>% group_by(equipe) %>% count(urina) %>% mutate(prop = prop.table(n)*100) kable(uro) uroa <- summary(copa$urina[copa$equipe == "curumim"]) urob <- summary(copa$urina[copa$equipe == "ceci"]) uroc <- matrix(c(uroa,urob), ncol=2) nome <- c("ausente", "presente") urom <- as.data.frame(cbind(nome, uroc)) names(urom)[names(urom) == 'nome'] <- 'Problemas Urinários' names(urom)[names(urom) == 'V2'] <- 'Curumim' names(urom)[names(urom) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de transtornos da tireóide entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por problemas urinários ```{r} kable(urom) chisq.test(uroc) ``` # IRC Todos os CIDs entre "N17", "N18" e "N19". ```{r, echo = FALSE} renal <- c("N17", "N18", "N19") copa$IRC <- grepl(paste(renal, collapse = "|"), copa$CID) copa$IRC <- as.factor(ifelse(copa$IRC == TRUE, 1,0)) # 8 com Insufici?ncia Renal renal <- copa %>% group_by(equipe) %>% count(IRC) %>% mutate(prop = prop.table(n)*100) kable(renal) renala <- summary(copa$IRC[copa$equipe == "curumim"]) renalb <- summary(copa$IRC[copa$equipe == "ceci"]) renalc <- matrix(c(renala,renalb), ncol=2) nome <- c("ausente", "presente") renalm <- as.data.frame(cbind(nome, renalc)) names(renalm)[names(renalm) == 'nome'] <- 'Insuficiência Renal' names(renalm)[names(renalm) == 'V2'] <- 'Curumim' names(renalm)[names(renalm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de Insuficiência Renal entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Doença renal crônica. ```{r} kable(renalm) chisq.test(renalc) ``` # Neoplasias Todos os CIDs entre "C00" e "D48" ```{r, echo = FALSE} cancer <- c("C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "D0", "D1", "D2", "D3", "D41", "D42", "D43", "D44", "D45", "D46", "D47", "D48") copa$CA <- grepl(paste(cancer, collapse = "|"), copa$CID) copa$CA <- as.factor(ifelse(copa$CA == TRUE, 1,0)) # 15 pessoas com c?ncer cancer <- copa %>% group_by(equipe) %>% count(CA) %>% mutate(prop = prop.table(n)*100) kable(cancer) cancera <- summary(copa$CA[copa$equipe == "curumim"]) cancerb <- summary(copa$CA[copa$equipe == "ceci"]) cancerc <- matrix(c(cancera,cancerb), ncol=2) nome <- c("ausente", "presente") cancerm <- as.data.frame(cbind(nome, cancerc)) names(cancerm)[names(cancerm) == 'nome'] <- 'Neoplasias' names(cancerm)[names(cancerm) == 'V2'] <- 'Curumim' names(cancerm)[names(cancerm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de pessoas com Neoplasias entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Neoplasias entre as equipes. ```{r} kable(cancerm) chisq.test(cancerc) ``` # Doenças Infecto-parasitárias Todos os CIDs entre "A00" e "B99" ```{r, echo = FALSE} infecto_parasitario <- c("A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9") copa$infecto <- grepl(paste(infecto_parasitario, collapse = "|"), copa$CID) copa$infecto <- as.factor(ifelse(copa$infecto == TRUE, 1,0)) # 29 com algum problema infectoparasit?rio infec <- copa %>% group_by(equipe) %>% count(infecto) %>% mutate(prop = prop.table(n)*100) kable(infec) infeca <- summary(copa$infecto[copa$equipe == "curumim"]) infecb <- summary(copa$infecto[copa$equipe == "ceci"]) infecc <- matrix(c(infeca,infecb), ncol=2) nome <- c("ausente", "presente") infecm <- as.data.frame(cbind(nome, infecc)) names(infecm)[names(infecm) == 'nome'] <- 'Doenças Infecto-parasitárias' names(infecm)[names(infecm) == 'V2'] <- 'Curumim' names(infecm)[names(infecm) == 'V3'] <- 'Ceci' ``` ### Teste quiquadrado comparando as proporções de Doenças Infecto-parasitárias entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos por Doenças Infecto-parasitárias. ```{r} kable(infecm) chisq.test(infecc) ``` # Obesidade ```{r, echo = FALSE} obesidade <- c("E65", "E66", "E67") copa$obeso <- grepl(paste(obesidade, collapse = "|"), copa$CID) copa$obeso <- as.factor(ifelse(copa$obeso == TRUE, 1,0)) # 10 com obesidade obes <- copa %>% group_by(equipe) %>% count(obeso) %>% mutate(prop = prop.table(n)*100) kable(obes) obesa <- summary(copa$obeso[copa$equipe == "curumim"]) obesb <- summary(copa$obeso[copa$equipe == "ceci"]) obesc <- matrix(c(obesa,obesb), ncol=2) nome <- c("ausente", "presente") obesm <- as.data.frame(cbind(nome, obesc)) names(obesm)[names(obesm) == 'nome'] <- 'Obesidade' names(obesm)[names(obesm) == 'V2'] <- 'Curumim' names(obesm)[names(obesm) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de obesidade entre as equipes. Não existe diferença significativa na proporção de pacientes atendidos classificados como obesos. ```{r} kable(obesm) chisq.test(obesc) ``` # Tireóide Todos os CIDs entre "E00" e "E07". ```{r, echo = FALSE} tireoide <- c("E00", "E01", "E02", "E03", "E04", "E05", "E06", "E07") copa$tireo <- grepl(paste(tireoide, collapse = "|"), copa$CID) copa$tireo <- as.factor(ifelse(copa$tireo == TRUE, 1,0)) # 22 com problema de tire?ide tir <- copa %>% group_by(equipe) %>% count(tireo) %>% mutate(prop = prop.table(n)*100) kable(tir) tireoa <- summary(copa$tireo[copa$equipe == "curumim"]) tireob <- summary(copa$tireo[copa$equipe == "ceci"]) tireoc <- matrix(c(tireoa,tireob), ncol=2) nome <- c("ausente", "presente") tireom <- as.data.frame(cbind(nome, tireoc)) names(tireom)[names(tireom) == 'nome'] <- 'Transtornos da Tireóide' names(tireom)[names(tireom) == 'V2'] <- 'Curumim' names(tireom)[names(tireom) == 'V3'] <- 'Ceci' ``` #### Teste quiquadrado comparando as proporções de transtornos da tireóide entre as equipes. Existe uma diferença significativa na proporção de pacientes atendidos com transtornos da tireóide. ```{r} kable(tireom) chisq.test(tireoc) ``` ## Estatísticas descritivas dos dados ```{r} vars <- c("DM", "HAS", "depress", "anx", "musc", "conju", "urina", "IRC", "CA", "infecto", "obeso", "tireo") a <- as.data.frame(sapply(copa[vars], summary)) a kable(a) ``` #### Acima o sumário de todos os CIDs estudados e o número de pacientes na clínica categorizados em cada um. As linhas representam casos (1) e não-casos(0) ```{r} total <- colSums(a) a <- rbind(a, total) at <- as.data.frame(t(a)) # transpor a tabela colnames(at)[1] <- "ausente" colnames(at)[2] <- "presente" colnames(at)[3] <- "total" kable(at) at$id <- seq(1,12) at <- at[c(4,1,2)] at_percent <- round(ns_to_percents(at, denom = "row"),3) nomes <- c("Diabetes", "Hipertensão", "Depressão", "Ansiedade", "Problemas Músculo-esqueléticos", "Conjuntivite", "Problemas urinários", "Insuficiência Renal Crônica", "Câncer", "Doenças Infecto Parasitárias", "Obesidade", "Problemas da Tireóide") at_percent$morbidades <- cbind(nomes) # Unindo as duas tabelas final <- merge(at, at_percent, by = "id") # tirando fora coluna id, n?o mais necess?ria final <- final[-1] # renomeando as vari?veis names(final)[names(final) == 'ausente.x'] <- 'ausente (N)' names(final)[names(final) == 'ausente.y'] <- 'ausente (%)' names(final)[names(final) == 'presente.x'] <- 'presente (N)' names(final)[names(final) == 'presente.y'] <- 'presente (%)' final <- final[,c(5,2,1,4,3)] kable(final) ``` ```{r, echo = FALSE} copa$DM <- grepl(paste(diabetes, collapse = "|"), copa$CID) copa$DM <- as.numeric(ifelse(copa$DM == TRUE, 1,0)) # 29 diab?ticos no total copa$HAS <- grepl("I10", copa$CID) copa$HAS <- as.numeric(ifelse(copa$HAS == TRUE, 1,0)) # 101 hipertensos no total copa$depress <- grepl("F32", copa$CID) copa$depress <- as.numeric(ifelse(copa$depress == TRUE, 1,0)) # 17 com depress?o copa$anx <- grepl("F41", copa$CID) copa$anx <- as.numeric(ifelse(copa$anx == TRUE, 1,0)) # 23 com ansiedade muscular <- c("M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9") copa$musc <- grepl(paste(muscular, collapse = "|"), copa$CID) copa$musc <- as.numeric(ifelse(copa$musc == TRUE, 1,0)) # 39 com algum problema osteomuscular renal <- c("N17", "N18", "N19") copa$IRC <- grepl(paste(renal, collapse = "|"), copa$CID) copa$IRC <- as.numeric(ifelse(copa$IRC == TRUE, 1,0)) # 8 com Insufici?ncia Renal cancer <- c("C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "D0", "D1", "D2", "D3", "D41", "D42", "D43", "D44", "D45", "D46", "D47", "D48") copa$CA <- grepl(paste(cancer, collapse = "|"), copa$CID) copa$CA <- as.numeric(ifelse(copa$CA == TRUE, 1,0)) # 15 pessoas com c?ncer obesidade <- c("E65", "E66", "E67") copa$obeso <- grepl(paste(obesidade, collapse = "|"), copa$CID) copa$obeso <- as.numeric(ifelse(copa$obeso == TRUE, 1,0)) # 10 com obesidade tireoide <- c("E00", "E01", "E02", "E03", "E04", "E05", "E06", "E07") copa$tireo <- grepl(paste(tireoide, collapse = "|"), copa$CID) copa$tireo <- as.numeric(ifelse(copa$tireo == TRUE, 1,0)) # 22 com problema de tire?ide ``` #### Agora analisando Multimorbidade, tomei todos os CIDs de doenças crônicas e os somei. Pacientes que tinham duas ou mais condições crônicas anotadas foram consideradas com multimórbidas. Ao final, analisei se há diferença entre as equipes quanto ? multimorbidade. ```{r, echo = FALSE} copa$morbidades <- (copa$DM + copa$HAS + copa$depress + copa$anx + copa$musc + copa$IRC + copa$CA + copa$obeso + copa$tireo) copa$MMnum <- ifelse(copa$morbidades >= 2, 1, 0) copa$MM <- as.factor(copa$MMnum) mma <- summary(copa$MM[copa$equipe == "curumim"]) mmb <- summary(copa$MM[copa$equipe == "ceci"]) mmc <- matrix(c(mma,mmb), ncol=2) nome <- c("ausente", "presente") m <- as.data.frame(cbind(nome, mmc)) names(m)[names(m) == 'nome'] <- 'Multimorbidade' names(m)[names(m) == 'V2'] <- 'Curumim' names(m)[names(m) == 'V3'] <- 'Ceci' ``` ```{r} kable(m) chisq.test(mmc) ``` #### Teste quiquadrado comparando a proporção de multimórbidos nas duas populações. Seu resultado mostra que há diferença significativa entre os dois grupos quanto a proporção de multimórbidos. <file_sep><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title> Um exeplo para o GBEM &middot; </title> <link rel="stylesheet" href="/css/poole.css"> <link rel="stylesheet" href="/css/syntax.css"> <link rel="stylesheet" href="/css/lanyon.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700|PT+Sans:400"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/assets/apple-touch-icon-144-precomposed.png"> <link rel="shortcut icon" href="/assets/favicon.ico"> <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml"> </head> <body> <input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox"> <div class="sidebar" id="sidebar"> <div class="sidebar-item"> <p>A reserved <a href="http://jekyllrb.com" target="_blank">Jekyll</a> theme that places the utmost gravity on content with a hidden drawer. Made by <a href="https://twitter.com/mdo" target="_blank">@mdo</a>.</p> </div> <nav class="sidebar-nav"> <a class="sidebar-nav-item " href="/">Home</a> <a class="sidebar-nav-item " href="/post">Posts</a> <a class="sidebar-nav-item" href="/archive/.zip">Download</a> <a class="sidebar-nav-item" href="">GitHub project</a> <span class="sidebar-nav-item">Currently on </span> </nav> <div class="sidebar-item"> <p>&copy; 2018. All rights reserved.</p> </div> </div> <div class="wrap"> <div class="masthead"> <div class="container"> <h3 class="masthead-title"> <a href="/" title="Home"></a> <small></small> </h3> </div> </div> <div class="container content"> <div class="post"> <h1 class="post-title">Um exeplo para o GBEM</h1> <span class="post-date">Jan 1, 0001</span> <p>Este é um exemplo de apresentação de um relatório de análise de dados feito sobre um estudo realizado por duas residentes de Medicina de Família e Comunidade do município do Rio de Janeiro.</p> <p>A pergunta do trabalho era bastante interessante. Ambas fizeram a residência no CMS João Barros Barreto, que fica em Copacabana e que atende à Ladeira dos Tabajaras (área de favela com muitas criançlas e gestantes adolescentes), bem como o próprio bairro de Copacabana, cheio de idosos multimórbidos. Cada uma das residentes fez seu treinamento em equipes com perfis populacionais opostos, o que as motivou à pergunta: &ldquo;Será que tivemos um treinamento semelhante, dada as diferenças notáveis das populações&rdquo;</p> <p>Os dados foram coletados durante uma semana típica de atendimento na clínica em que todos os profissionais médicos e enfermeiros das duas equipes estavam trabalhando. Foram registrados todos as consultas realizadas pelas duas equipes e os dados de todos esses pacientes foram anotados. As informações coletadas abracavam dados socioeconômicos dos pacientes, dados de morbidade (CIDs registrados), exames laboratoriais solicitados, medicamentos prescritos e encaminhamentos solicitados para o nível secundário.</p> <p>As análises preliminares postadas aqui foram feitas unicamente sobre as morbidades registradas no prontuário.</p> <pre><code class="language-r">blogdown::new_post(&quot;Post Title&quot;, ext = '.Rmd') </code></pre> </div> </div> </div> <label for="sidebar-checkbox" class="sidebar-toggle"></label> </body> </html> <file_sep>--- title: "Um exeplo para o GBEM" date: "2018-03-080" --- Este é um exemplo de apresentação de um relatório de análise de dados feito sobre um estudo realizado por duas residentes de Medicina de Família e Comunidade do município do Rio de Janeiro. A pergunta do trabalho era bastante interessante. Ambas fizeram a residência no CMS <NAME>, que fica em Copacabana e que atende à Ladeira dos Tabajaras (área de favela com muitas criançlas e gestantes adolescentes), bem como o próprio bairro de Copacabana, cheio de idosos multimórbidos. Cada uma das residentes fez seu treinamento em equipes com perfis populacionais opostos, o que as motivou à pergunta: "Será que tivemos um treinamento semelhante, dada as diferenças notáveis das populações" Os dados foram coletados durante uma semana típica de atendimento na clínica em que todos os profissionais médicos e enfermeiros das duas equipes estavam trabalhando. Foram registrados todos as consultas realizadas pelas duas equipes e os dados de todos esses pacientes foram anotados. As informações coletadas abracavam dados socioeconômicos dos pacientes, dados de morbidade (CIDs registrados), exames laboratoriais solicitados, medicamentos prescritos e encaminhamentos solicitados para o nível secundário. As análises preliminares postadas aqui foram feitas unicamente sobre as morbidades registradas no prontuário. ```r blogdown::new_post("Post Title", ext = '.Rmd') ```
0c31dfe45de39f01617e6b21a9a270744c516b37
[ "RMarkdown", "Markdown", "HTML" ]
4
RMarkdown
Filustria/exemplo-gbem
7c3cb6bf39f617081fdd72232781f1e6add8f790
681ae701472a899fd002cd655f7d1abe1f30da34
refs/heads/master
<file_sep>language: swift osx_image: xcode11.1 install: - gem install slather script: - xcodebuild -scheme LinkedList -sdk iphonesimulator -destination 'platform=iOS Simulator,OS=13.1,name=iPhone 11' build test - slather - bash <(curl -s https://codecov.io/bash) -f ./cobertura.xml<file_sep># LinkedList [![Language: Swift](https://img.shields.io/badge/language-swift-f48041.svg?style=flat)](https://developer.apple.com/swift) [![Build Status](https://travis-ci.org/mirovodin/LinkedList.svg?branch=master)](https://travis-ci.org/mirovodin/LinkedList) [![codecov](https://codecov.io/gh/mirovodin/LinkedList/branch/master/graph/badge.svg)](https://codecov.io/gh/mirovodin/LinkedList) [![License: MIT](http://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat)](https://github.com/mirovodin/LinkedList/blob/master/LICENSE) ![Release version](https://img.shields.io/github/v/release/mirovodin/LinkedList) <file_sep>coverage_service: cobertura_xml xcodeproj: LinkedList.xcodeproj scheme: LinkedList output_directory: ./<file_sep>// // LinkedListTests.swift // // Created by d.mirovodin on 24.09.2019. // Copyright © 2019 Dmitry.Mirovodin. All rights reserved. // fileprivate final class LinkedListNode<T> { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? init(value: T) { self.value = value } } public class LinkedList<T> { private typealias Node = LinkedListNode<T> private var head: Node? private var last: Node? private(set) public var count = 0 public var isEmpty: Bool { return count == 0 } init() {} convenience init<S: Sequence>(_ elements: S) where S.Iterator.Element == T { self.init() for element in elements { append(element) } } func append(_ value: T) { let previousLast = last last = Node(value: value) last?.previous = previousLast previousLast?.next = last if isEmpty { head = last } count += 1 } func removeAll() { head = nil last = nil count = 0 } subscript(index: Int) -> T { let node = self.node(at: index) return node.value } @discardableResult func removeLast() -> T { assert(!isEmpty) return remove(node: last!) } @discardableResult func removeFirst() -> T { assert(!isEmpty) return remove(node: head!) } @discardableResult func remove(at index: Int) -> T { let node = self.node(at: index) return remove(node: node) } // MARK: - Private methods private func node(at index: Int) -> Node { assert(head != nil, "List is empty") assert(index >= 0, "index must be greater or equal to 0") if index == 0 { return head! } else { var node = head!.next for _ in 1..<index { node = node?.next if node == nil { break } } assert(node != nil, "index is out of bounds.") return node! } } @discardableResult private func remove(node: Node) -> T { let nextNode = node.next let previousNode = node.previous if node === head && node === last { head = nil last = nil } else if node === head { head = node.next } else if node === last { last = node.previous } previousNode?.next = nextNode nextNode?.previous = previousNode node.next = nil node.previous = nil count -= 1 return node.value } } extension LinkedList: Equatable where T: Equatable { public static func == (lhs: LinkedList<T>, rhs: LinkedList<T>) -> Bool { return lhs.count == rhs.count && zip(lhs, rhs).allSatisfy { (arg) -> Bool in return arg.0 == arg.1 } } } extension LinkedList: CustomStringConvertible { public var description: String { var str = "[" forEach { (value) in if str.count > 1 { str += ", " } str += "\(value)" } return str + "]" } } extension LinkedList: Collection { public typealias Index = LinkedListIndex<T> public var startIndex: Index { return LinkedListIndex<T>(node: head, tag: 0) } public var endIndex: Index { return LinkedListIndex<T>(node: last, tag: count) } public subscript(position: Index) -> T { return position.node!.value } public func index(after idx: Index) -> Index { return LinkedListIndex<T>(node: idx.node?.next, tag: idx.tag + 1) } } public struct LinkedListIndex<T>: Comparable { fileprivate let node: LinkedListNode<T>? let tag: Int public static func==<T>(lhs: LinkedListIndex<T>, rhs: LinkedListIndex<T>) -> Bool { return (lhs.tag == rhs.tag) } public static func<<T>(lhs: LinkedListIndex<T>, rhs: LinkedListIndex<T>) -> Bool { return (lhs.tag < rhs.tag) } } <file_sep>// // LinkedList.h // LinkedList // // Created by d.mirovodin on 24.09.2019. // Copyright © 2019 Dmitry.Mirovodin. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for LinkedList. FOUNDATION_EXPORT double LinkedListVersionNumber; //! Project version string for LinkedList. FOUNDATION_EXPORT const unsigned char LinkedListVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <LinkedList/PublicHeader.h> <file_sep>// // LinkedListTests.swift // LinkedListTests // // Created by d.mirovodin on 24.09.2019. // Copyright © 2019 Dmitry.Mirovodin. All rights reserved. // import XCTest @testable import LinkedList final class LinkedListTests: XCTestCase { private var list: LinkedList<Int>! override func setUp() { super.setUp() list = LinkedList<Int>([1, 2, 3, 4, 5]) } override func tearDown() { list = nil super.tearDown() } // MARK: - Tests func testEquatable() { let list2 = LinkedList([1, 2, 3, 4, 5]) XCTAssertEqual(list, list2) } func testAppend() { list.append(6) XCTAssertEqual(list, LinkedList(1..<7)) XCTAssertEqual(list.count, 6) } func testNode() { list.append(10) let lastValue = list[5] let middleValue = list[3] XCTAssertEqual(lastValue, 10) XCTAssertEqual(middleValue, 4) } func testValue() { let value = list[3] XCTAssertEqual(value, 4) } func testRemoveStart() { list.remove(at: 0) XCTAssertEqual(list, LinkedList(2..<6)) XCTAssertEqual(list.count, 4) } func testRemoveLast() { let node = list.removeLast() XCTAssertEqual(node, 5) XCTAssertEqual(list, LinkedList(1..<5)) XCTAssertEqual(list.count, 4) } func testRemoveFirst() { let node = list.removeFirst() XCTAssertEqual(node, 1) XCTAssertEqual(list, LinkedList(2..<6)) XCTAssertEqual(list.count, 4) } func testRemoveEnd() { list.remove(at: list.count - 1) XCTAssertEqual(list, LinkedList(1..<5)) XCTAssertEqual(list.count, 4) } func testRemoveMiddle() { list.remove(at: 2) let list2 = LinkedList([1, 2, 4, 5]) XCTAssertEqual(list, list2) XCTAssertEqual(list.count, 4) } func testRemoveEndFromTwoElementList() { let twoElementList = LinkedList([1, 2]) twoElementList.remove(at: 1) XCTAssertEqual(twoElementList, LinkedList([1])) } func testRemoveStartFromTwoElementList() { let twoElementList = LinkedList([1, 2]) twoElementList.remove(at: 0) XCTAssertEqual(twoElementList, LinkedList([2])) } func testRemoveFromSingleElementLsit() { let singleElementList = LinkedList([1]) singleElementList.remove(at: 0) XCTAssertEqual(singleElementList, LinkedList()) } func testRemoveAndThenAdd() { for _ in (1..<6) { list.remove(at: 0) } for i in (1..<10) { list.append(i) } XCTAssertEqual(list, LinkedList((1..<10))) } }
b71c4a00565bd271b89082e1594f810063521258
[ "Swift", "Markdown", "YAML", "Objective-C" ]
6
Swift
mirovodin/LinkedList
4d759d8391d0598b673e73cdd17c90a1bc3d870b
33bcde54b6f63171128af01ca58b560cbc1239dc
refs/heads/master
<repo_name>CauueSanttos/crawler-robot<file_sep>/src/utils/extractDate.js export default function extractDate(date) { return date.replace(/[/]/g, ''); }<file_sep>/README.md <h1 align="center"> <br> <img src="https://media.glassdoor.com/sqll/2806339/asksuite-brazil-squarelogo-1563777768189.png" alt="<NAME>" width="120"> <br> <br> <NAME> </h1> <p align="center">Robô Crawler que extrai informações de um motor de reservas.</p> <p align="center"> <a href="https://opensource.org/licenses/MIT"> <img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License MIT"> </a> </p> ## Tecnologias [//]: # (Add the features of your project here:) Este aplicativo apresenta todas as mais recentes ferramentas e práticas em desenvolvimento web! - 💹 **Node.js** — Ambiente de execução Javascript server-side. - 📉 **Express** — É um framework para criação de API's REST utilizando Node.js - 📶 **Puppeteer** — API de alto nível para controlar o Chrome ou o Chromium sobre o DevTools. - ⭕ **Yup** — Biblioteca para validar schemas. - 🌐 **Sucrase** — Uma alternativa ao Babel que permite um desenvolvimento muito rápido. - ✔ **Prettier** — Utilizado para manter um código fonte mais bonito. - 🧲 **Nodemon** — Reinicia o servidor quando detecta alterações em ambiente de desenvolvimento. - 🔷 **Eslint** — Ferramenta de análise de código estática para identificar padrões problemáticos encontrados no código. ## Iniciando o projeto 1 - Entre no caminho do projeto via powershell ou cmd utilizando **cd crawler-robot** <br /> 2 - Execute o comando **yarn** após entrar no diretório para instalar as dependências. <br /> 3 - Após instalar as dependências, execute o comando **yarn dev** para iniciar o servidor. <br /> 4 - É necessário uma ferramenta para fazer requisições à API REST como **Insomnia** ou **Postman** <br /> 5 - Url base para execução da api é: ```http://localhost:3333``` ### Executando o Robô **Descrição:** Ao informar a data de **checkin** e a data de **checkout** o robô irá extrair os dados do motor de reservas e retornar uma resposta com as opções encontradas. <br /> **Rota POST:** ```http://localhost:3333/buscar``` <br /> **Body:** <pre> { "checkin": "15/03/2020", "checkout": "18/03/2020" } </pre> **Resposta:** <br/> <pre> [ { "price": "Preço do apartamento", "name": "Nome da hospedagem", "description": "Descrição do quarto", "images": [ "Imagens do quarto", ] }, { "price": "Preço do apartamento", "name": "Nome da hospedagem", "description": "Descrição do quarto", "images": [ "Imagens do quarto", ] }, ] </pre> Caso não encontrado nenhuma hospedagem relacionada as datas passadas no corpo da requisição, essa é a resposta: <pre> { "error": "Desculpe-nos. Não existem apartamentos disponíveis para a pesquisa realizada." } </pre> Os campos **checkin** e **checkout** são obrigatórios na requisição, o **Yup** é responsável por validar o SCHEMA. Suponhamos que não foi passado o campo **checkout**, a resposta será essa: <pre> { "error": "Validation fails", "messages": [ { "name": "ValidationError", "path": "checkout", "type": "required", "errors": [ "checkout is a required field" ], "inner": [], "message": "checkout is a required field", "params": { "path": "checkout" } } ] } </pre> ## Licença Licença MIT - consulte a página [LICENÇA](https://opensource.org/licenses/MIT) para obter detalhes. <file_sep>/src/utils/scrapingData.js /* eslint-disable no-undef */ import puppeteer from 'puppeteer'; import baseUrl from './baseUrl'; export default async function scrapingData(checkin, checkout) { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(baseUrl(checkin, checkout)); const result = await page.evaluate(() => { const results = []; const table = document.querySelector('.maintable'); const rooms = table.querySelectorAll('.roomName'); rooms.forEach(room => { const roomResult = {}; /** * Find room price */ roomResult.price = room .querySelector('.sincePrice') .querySelector('h6').textContent; /** * Find room description */ const description = room.querySelector('.excerpt'); roomResult.name = description.querySelector('h5').textContent; roomResult.description = description.querySelector('p').textContent; /** * Find room images */ const thumb = room.querySelector('.thumb'); const slides = thumb.querySelectorAll('.slide'); const images = []; slides.forEach(slide => { images.push( `https://myreservations.omnibees.com${slide .querySelector('img') .getAttribute('src')}` ); }); roomResult.images = images; results.push(roomResult); }); return results; }); return result; } <file_sep>/src/utils/baseUrl.js import extractDate from './extractDate'; export default function api(checkIn, checkOut) { const checkInDate = extractDate(checkIn); const checkOutdate = extractDate(checkOut); return `https://myreservations.omnibees.com/default.aspx?q=5462&version=MyReservation&sid=fa068d9a-889d-47d9-adda-0088587755a7#/&diff=false&CheckIn=${checkInDate}&CheckOut=${checkOutdate}&Code=&group_code=&loyality_card=&NRooms=1&ad=1&ch=0&ag=-`; } <file_sep>/src/app/controllers/CrawlerController.js import scrapingData from '../../utils/scrapingData'; class CrawlerController { async store(req, res) { try { const { checkin, checkout } = req.body; const data = await scrapingData(checkin, checkout); return res.json(data); } catch (err) { return res.status(400).json({ error: 'Desculpe-nos. Não existem apartamentos disponíveis para a pesquisa realizada.', }); } } } export default new CrawlerController();
3f9543ac77b4597bacd7c59ed1fbd8f1e93d9e72
[ "Markdown", "JavaScript" ]
5
Markdown
CauueSanttos/crawler-robot
c556bc31bbfbf6a3ce0d783384b34b464032f59f
a69b2e8f86eba16f8aa7e1aca2e9413691bfe810
refs/heads/master
<repo_name>saralmarion/lo-k-.-<file_sep>/README.md # lo-k-.- lok, word watch
6d05ef19b1611e3607152df24ec5967083776c11
[ "Markdown" ]
1
Markdown
saralmarion/lo-k-.-
8a709dee3a8d0d2a18d7ea5888654853bd0efbc0
1841c5150edaaa1205e45b4683c4a7884f3c53b0
refs/heads/master
<file_sep>// // ViewController.swift // plistDemo // // Created by <NAME> on 02/01/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var tblViewUserData: UITableView! @IBOutlet var signUpbtn: UIButton! @IBOutlet var txtUsername: UITextField! @IBOutlet var txtPassword: UITextField! var keysArray = NSMutableArray() var valueArray = NSMutableArray() var plistData: [String: AnyObject] = [:] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. readPropertyList() } func getPath() -> String { let plistPath: String? = Bundle.main.path(forResource: "data", ofType: "plist")! //the path of the data let plistXML = FileManager.default.contents(atPath: plistPath!)! return plistPath! } @IBAction func signUpbtnClicked(_ sender: Any) { let plistPath = self.getPath() if FileManager.default.fileExists(atPath: plistPath) { let nationAndCapitalCitys = NSMutableDictionary(contentsOfFile: plistPath)! nationAndCapitalCitys.setValue(txtUsername.text!, forKey: txtPassword.text!) nationAndCapitalCitys.write(toFile: plistPath, atomically: true) } readPropertyList() // keysArray.removeAllObjects() // valueArray.removeAllObjects() txtUsername.text = "" txtPassword.text = "" } func readPropertyList() { var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml //Format of the Property List. //Our data let plistPath = self.getPath() //the path of the data let plistXML = FileManager.default.contents(atPath: plistPath)! if let nationAndCapitalCitys = NSMutableDictionary(contentsOfFile: plistPath) { keysArray.removeAllObjects() valueArray.removeAllObjects() for (_, element) in nationAndCapitalCitys.enumerated() { // self.textView.text = self.textView.text + "\(element.key) --> \(element.value) \n" keysArray.add(element.key) valueArray.add(element.value) } } print(plistData) tblViewUserData.reloadData() } } extension ViewController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { keysArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserDataTableViewCell", for: indexPath) as! UserDataTableViewCell cell.lblUserName.text = valueArray[indexPath.row] as? String cell.lblPassword.text = keysArray[indexPath.row] as? String // keysArray.removeAllObjects() // valueArray.removeAllObjects() // cell.lblPassword.text = plistData[txtUsername.text!] as? String return cell } }
15ebbf7ace78d1d9acc0cb6478602f15a66f1ebe
[ "Swift" ]
1
Swift
praut09/PlistSwift
0067f24db34f77470777eba63b32a95ae928f12c
8f9663501108a577782d7d821f7d19f127201a40
refs/heads/master
<file_sep>// // Review.h // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface Review : NSObject @property (nonatomic,assign) int userID; @property (nonatomic,strong) NSString *user; @property (nonatomic,strong) NSString *skin_type; @property (nonatomic,strong) NSString *review; -(id)initWithUserID:(int)u_id user:(NSString *)r_user skin_type:(NSString *)r_skin_type review:(NSString *)r_review; @end <file_sep>// // ProductSearchViewController.h // SkinScope_v2 // // Created by <NAME> on 5/9/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Product.h" #import "ZBarSDK.h" @interface ProductSearchViewController : UIViewController <UIActionSheetDelegate, ZBarReaderDelegate> @property (nonatomic,strong) IBOutlet UISearchBar *mySearchBar; @property (nonatomic,strong) IBOutlet UIButton *addBtn; @property (nonatomic,strong) IBOutlet UIButton *scanBtn; @property (nonatomic,strong) IBOutlet UILabel *resultsLabel; @property (nonatomic,strong) IBOutlet UIBarButtonItem *filterButton; @property (nonatomic,strong) IBOutlet UITableView *searchResults; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; @property (nonatomic,strong) NSArray *products; @property (nonatomic,strong) Product *product; @property (nonatomic,strong) NSString *filterRating; @property (nonatomic,strong) NSString *productUPC; -(IBAction)showFilterModal; -(IBAction)pushAddProductVC; -(IBAction)showScanner; -(void)searchForProducts; -(void)searchByUPC; @end <file_sep>// // PageViewController.h // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "ProductViewController.h" #import "Product.h" @interface PageViewController : UIViewController <UIPageViewControllerDataSource> @property (nonatomic,strong) UIPageViewController *myPageViewController; @property (nonatomic,strong) NSArray *pageTitles; @property (nonatomic,strong) NSArray *pageIDs; @property (nonatomic,strong) Product *product; @end <file_sep>// // CreateAccountViewController.h // SkinScope_v2 // // Created by <NAME> on 5/17/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Dropdown.h" @interface CreateAccountViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate> @property (nonatomic,strong) IBOutlet UITextField *firstName; @property (nonatomic,strong) IBOutlet UITextField *lastName; @property (nonatomic,strong) IBOutlet Dropdown *skinType; @property (nonatomic,strong) IBOutlet UITextField *email; @property (nonatomic,strong) IBOutlet UITextField *password; @property (nonatomic,strong) IBOutlet UITextField *passwordConfirmation; @property (nonatomic,strong) IBOutlet UIButton *submitBtn; @property (nonatomic,strong) IBOutlet UIScrollView *scrollView; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; @property (nonatomic,strong) UIToolbar *keyboardButtonView; @property (nonatomic,strong) UITextField *activeField; @property (nonatomic,strong) NSArray *skinTypeOptions; -(IBAction)doneClicked:(id)sender; -(IBAction)nextClicked:(id)sender; -(IBAction)prevClicked:(id)sender; -(IBAction)submitAccount:(id)sender; @end <file_sep>// // DropdownArrowView.m // SkinScope_v2 // // Created by <NAME> on 5/14/14. // Copyright (c) 2014 <NAME>. All rights reserved. // // Code for custom drop down from here: http://rogchap.com/2013/08/13/simple-ios-dropdown-control-using-uitextfield/ #import "DropdownArrowView.h" @implementation DropdownArrowView //create dropdown arrow +(DropdownArrowView*) default{ DropdownArrowView* view = [[DropdownArrowView alloc] initWithFrame:CGRectMake(0, 0, 43, 28)]; view.backgroundColor = [UIColor clearColor]; return view; } //draw dropdown arrow -(void)drawRect:(CGRect)rect{ //set stroke color UIColor* strokeColor = [UIColor colorWithRed:100.0/255.0 green:100.0/255.0 blue:100.0/255.0 alpha:1]; //create frame CGRect frame = self.bounds; //bezier drawing UIBezierPath* bezierPath = [UIBezierPath bezierPath]; [bezierPath moveToPoint: CGPointMake(CGRectGetMinX(frame) + 24.82, CGRectGetMinY(frame) + 8.08)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 25.98, CGRectGetMinY(frame) + 9.25)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 17.01, CGRectGetMinY(frame) + 18.22)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 17.01, CGRectGetMinY(frame) + 18.22)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 15.85, CGRectGetMinY(frame) + 19.38)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 15.85, CGRectGetMinY(frame) + 19.38)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 15.85, CGRectGetMinY(frame) + 19.38)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 14.68, CGRectGetMinY(frame) + 18.22)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 14.68, CGRectGetMinY(frame) + 18.22)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 5.71, CGRectGetMinY(frame) + 9.25)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 6.88, CGRectGetMinY(frame) + 8.08)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 15.85, CGRectGetMinY(frame) + 17.05)]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 24.82, CGRectGetMinY(frame) + 8.08)]; [bezierPath closePath]; bezierPath.miterLimit = 4; bezierPath.usesEvenOddFillRule = YES; [strokeColor setFill]; [bezierPath fill]; } @end <file_sep>// // PageViewController.m // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "PageViewController.h" #import "ProductViewController.h" #import "ReviewsViewController.h" #import "IngredientsListViewController.h" @interface PageViewController () @end @implementation PageViewController @synthesize myPageViewController, pageTitles, pageIDs, product; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //set back button text and color for navigation controller self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; //set nav bar title self.title = product.name; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //set page titles and IDs for child view controllers pageTitles = @[@"Product Overview", @"Product Reviews", @"Product Ingredients"]; pageIDs = @[@"ProductOverview", @"ProductReviews", @"ProductIngredients"]; //create page view controller myPageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"]; [myPageViewController setDataSource:self]; //setup first child view controller ProductViewController *startingViewController = (ProductViewController *)[self viewControllerAtIndex:0]; NSArray *viewControllers = @[startingViewController]; [myPageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]; //show the page view controller [self addChildViewController:myPageViewController]; [self.view addSubview:myPageViewController.view]; [myPageViewController didMoveToParentViewController:self]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Page View Controller Data Source //get view previous view controller - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { //get current page/index NSUInteger index = ((ProductViewController*) viewController).pageIndex; //if currently on first page, there is no previous page if ((index == 0) || (index == NSNotFound)) { return nil; } //get previous page index--; //return previous view controller return [self viewControllerAtIndex:index]; } //get next view controller - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { //get current page/index NSUInteger index = ((ProductViewController*) viewController).pageIndex; if (index == NSNotFound) { return nil; } //get next page/index index++; //if currently on last page, there is no next page if (index == [self.pageTitles count]) { return nil; } //return next view controller return [self viewControllerAtIndex:index]; } //create next view controller - (UIViewController *)viewControllerAtIndex:(NSUInteger)index { if (([self.pageTitles count] == 0) || (index >= [self.pageTitles count])) { return nil; } //if first page, create the product overview view controller if(index == 0){ //create view controller ProductViewController *productViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductOverview"]; //pass data productViewController.pageIndex = index; productViewController.product = product; return productViewController; } //if second page, create the product reviews view controller else if(index == 1){ //create view controller ReviewsViewController *reviewsViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductReviews"]; //pass data reviewsViewController.pageIndex = index; reviewsViewController.product = product; return reviewsViewController; } //if third page, create the product ingredients view controller else if(index == 2){ //create view controller IngredientsListViewController *ingredientsViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ProductIngredients"]; //pass data ingredientsViewController.pageIndex = index; ingredientsViewController.product = product; return ingredientsViewController; } return nil; } #pragma mark Page Indicator Functions - (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController { return [self.pageTitles count]; } - (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController { return 0; } @end <file_sep>// // AddReviewViewController.m // SkinScope_v2 // // Created by <NAME> on 5/14/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "AddReviewViewController.h" #import <RestKit/RestKit.h> #import <QuartzCore/QuartzCore.h> #import "User.h" #import "Review.h" @interface AddReviewViewController () @end @implementation AddReviewViewController @synthesize writeReviewLabel, reviewText, submitBtn, clearBtn, product, spinner; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //set nav bar title self.title = product.name; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //set fonts [writeReviewLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:18]]; [reviewText setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:14]]; submitBtn.titleLabel.font = [UIFont fontWithName:@"ProximaNova-Regular" size:16]; clearBtn.titleLabel.font = [UIFont fontWithName:@"ProximaNova-Regular" size:16]; //change appearance of text view reviewText.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1]; reviewText.layer.borderWidth = 0.5f; reviewText.layer.borderColor = [[UIColor colorWithRed:68.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1] CGColor]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark Text View Functions //clear text from text view -(IBAction)clearReviewText{ reviewText.text = @""; } //tapping outside the search bar will dimiss the keyboard -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [reviewText resignFirstResponder]; } //hide keyboard when user hits return key -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ //if return key was pressed if([text isEqualToString:@"\n"]) { [textView resignFirstResponder]; //hide the keyboard return NO; } return YES; } #pragma mark API Call Functions //attempt to add review to database -(IBAction)submitReview{ //start activity indicator [spinner startAnimating]; //create post url NSString *addReviewURL = [NSString stringWithFormat:@"/api/products/%i/reviews/create", product.productID]; //get user credentials User *sharedUser = [User sharedUser]; NSString *username = [sharedUser getUsername]; NSString *password = [sharedUser getPassword]; //setup header for authentication RKObjectManager *objectManager = [RKObjectManager sharedManager]; [objectManager.HTTPClient setAuthorizationHeaderWithUsername:username password:<PASSWORD>]; //make the call [[RKObjectManager sharedManager] postObject:nil path:addReviewURL parameters:@{@"review": reviewText.text} success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){ //stop activity indicator [spinner stopAnimating]; //clear text view reviewText.text = @""; //display success message UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your review has been submitted." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [successAlert show]; } failure:^(RKObjectRequestOperation *operation, NSError *error){ //stop activity indicator [spinner stopAnimating]; //get errors as JSON NSString *errors = [[error userInfo] objectForKey:NSLocalizedRecoverySuggestionErrorKey]; //convert JSON to dictionary NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [errors dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: nil]; //create error message NSMutableString *errorMsg = [NSMutableString string]; //handles message for server errors if([JSON objectForKey:@"error"] != nil){ [errorMsg appendFormat:@"%@", [JSON objectForKey:@"error"]]; } //handles message for validation errors else{ //loop through dictionary to build error message [errorMsg appendString:@"Your review was not submitted for the following reasons: "]; for (NSString* key in [JSON allKeys]){ [errorMsg appendFormat:@"%@ ", [[JSON objectForKey:key] objectAtIndex:0]]; } } //display error message UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:errorMsg delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [errorAlert show]; } ]; } @end <file_sep>// // AddProductViewController.m // SkinScope_v2 // // Created by <NAME> on 5/14/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "AddProductViewController.h" #import <RestKit/RestKit.h> #import "User.h" @interface AddProductViewController () @end @implementation AddProductViewController @synthesize name, brand, categoryDropdown, upc, categoryOptions, firstIngredient, addIngredientBtn, submitBtn, scrollView, activeField, previousIngredient, keyboardButtonView, contentHeight, spinner; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad{ [super viewDidLoad]; //set nav bar title self.title = @"Add a Product"; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //define category options categoryOptions = @[@"Select Category", @"Cleanser", @"Toner", @"Makeup Remover", @"Exfoliant", @"Moisturizer", @"Sunscreen", @"Serum", @"Mask", @"Eye Care", @"Lip Care", @"Body Care"]; //setup delegate and datasource for dropdown categoryDropdown.pickerDelegate = self; categoryDropdown.pickerDataSource = self; //create toolbar for keyboard keyboardButtonView = [[UIToolbar alloc] init]; keyboardButtonView.barStyle = UIBarStyleBlackTranslucent; keyboardButtonView.tintColor = [UIColor whiteColor]; [keyboardButtonView sizeToFit]; //create buttons for keyboard UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneClicked:)]; UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStyleBordered target:self action:@selector(nextClicked:)]; UIBarButtonItem *prevButton = [[UIBarButtonItem alloc] initWithTitle:@"Prev" style:UIBarButtonItemStyleBordered target:self action:@selector(prevClicked:)]; //create flex space for toolbar UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; //add toolbar to keyboard [keyboardButtonView setItems:[NSArray arrayWithObjects:prevButton, nextButton, flex, doneButton, nil]]; name.inputAccessoryView = keyboardButtonView; brand.inputAccessoryView = keyboardButtonView; categoryDropdown.inputAccessoryView = keyboardButtonView; upc.inputAccessoryView = keyboardButtonView; firstIngredient.inputAccessoryView = keyboardButtonView; //set fonts [name setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [brand setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [categoryDropdown setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [upc setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [firstIngredient setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; submitBtn.titleLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:24]; //set fonts for toolbar buttons [doneButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ProximaNova-Bold" size:16], NSFontAttributeName,nil] forState:UIControlStateNormal]; [nextButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ProximaNova-Bold" size:16], NSFontAttributeName,nil] forState:UIControlStateNormal]; [prevButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ProximaNova-Bold" size:16], NSFontAttributeName,nil] forState:UIControlStateNormal]; //change border color of text fields name.layer.borderColor=[[UIColor whiteColor]CGColor]; name.layer.borderWidth= 1.0f; brand.layer.borderColor=[[UIColor whiteColor]CGColor]; brand.layer.borderWidth= 1.0f; categoryDropdown.layer.borderColor=[[UIColor whiteColor]CGColor]; categoryDropdown.layer.borderWidth= 1.0f; upc.layer.borderColor=[[UIColor whiteColor]CGColor]; upc.layer.borderWidth= 1.0f; firstIngredient.layer.borderColor=[[UIColor whiteColor]CGColor]; firstIngredient.layer.borderWidth= 1.0f; //add padding to left side of text fields name.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); brand.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); categoryDropdown.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); upc.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); firstIngredient.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); //set content size for scroll view contentHeight = 300; [scrollView setContentSize:CGSizeMake(250, contentHeight)]; //set add ingredient button image UIImage *addImage = [UIImage imageNamed:@"add.png"]; [addIngredientBtn setImage:addImage forState:UIControlStateNormal]; //set previous ingredient field - used to dynamically add more ingredient fields previousIngredient = firstIngredient; } - (void)didReceiveMemoryWarning{ [super didReceiveMemoryWarning]; } #pragma mark Text Field Functions //handles navigating between text fields and dismissing the keyboard - (BOOL)textFieldShouldReturn:(UITextField *)textField{ UIView *view = [self.view viewWithTag:textField.tag + 1]; if(!view){ [textField resignFirstResponder]; } else{ [view becomeFirstResponder]; } return YES; } - (void)textFieldDidBeginEditing:(UITextField *)textField{ //keep track of the active text field activeField = textField; } - (void)textFieldDidEndEditing:(UITextField *)textField{ //dismiss the keyboard [textField resignFirstResponder]; //unset the active text field activeField = nil; } //prevent user from typing in the category dropdown field - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if(textField == categoryDropdown){ return NO; } return YES; } //hide keyboard when user presses the "done" button -(IBAction)doneClicked:(id)sender{ [self.view endEditing:YES]; } //move to next field when user presses the "next" button -(IBAction)nextClicked:(id)sender{ UIView *view = [self.view viewWithTag:activeField.tag + 1]; //if no more text fields, end editing if(!view){ [self.view endEditing:YES]; } //move to next text field else{ [view becomeFirstResponder]; } } //move to previous when user presses the "prev" button -(IBAction)prevClicked:(id)sender{ UIView *view = [self.view viewWithTag:activeField.tag - 1]; //if no more text fields, end editing if(view.tag == 0){ [self.view endEditing:YES]; } //move to previous text field else{ [view becomeFirstResponder]; } } //dynamically create text field for next ingredient -(IBAction)addTextField:(id)sender{ //create frame for new text field CGRect nextIngredientFrame = CGRectMake(previousIngredient.frame.origin.x, previousIngredient.frame.origin.y + 38, previousIngredient.frame.size.width, previousIngredient.frame.size.height); //init new text field UITextField *nextIngredient = [[UITextField alloc] initWithFrame:nextIngredientFrame]; //settings for new text field nextIngredient.delegate = self; nextIngredient.tag = previousIngredient.tag + 1; nextIngredient.placeholder = @"Ingredient"; nextIngredient.font = [UIFont fontWithName:@"ProximaNova-Regular" size:16]; nextIngredient.autocorrectionType = UITextAutocorrectionTypeNo; nextIngredient.keyboardType = UIKeyboardTypeDefault; nextIngredient.returnKeyType = UIReturnKeyNext; nextIngredient.backgroundColor = [UIColor whiteColor]; nextIngredient.borderStyle = UITextBorderStyleLine; nextIngredient.layer.borderColor=[[UIColor whiteColor]CGColor]; nextIngredient.layer.borderWidth= 1.0f; nextIngredient.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); //add toolbar to keyboard nextIngredient.inputAccessoryView = keyboardButtonView; //add new text field to scroll view [scrollView addSubview:nextIngredient]; //move add ingredient button down CGRect addButtonFrame = CGRectMake(addIngredientBtn.frame.origin.x, addIngredientBtn.frame.origin.y + 38, addIngredientBtn.frame.size.width, addIngredientBtn.frame.size.height); [addIngredientBtn setFrame:addButtonFrame]; //change width of previous ingredient field CGRect prevIngredientFrame = CGRectMake(previousIngredient.frame.origin.x, previousIngredient.frame.origin.y, 250, previousIngredient.frame.size.height); [previousIngredient setFrame:prevIngredientFrame]; //move submit button down CGRect submitButtonFrame = CGRectMake(submitBtn.frame.origin.x, submitBtn.frame.origin.y + 38, submitBtn.frame.size.width, submitBtn.frame.size.height); [submitBtn setFrame:submitButtonFrame]; //set previous ingredient field to new field - for the next time we want to add a new field previousIngredient = nextIngredient; //activate new text field [nextIngredient becomeFirstResponder]; //recalculate content size of scroll view contentHeight += 38; scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, contentHeight); } #pragma mark Keyboard Functions //register for keyboard notifications -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:Nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil]; } //scroll form up when keyboard is shown -(void)keyboardWasShown:(NSNotification *)notification{ //get keyboard size CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; //setup animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.25]; [UIView setAnimationBeginsFromCurrentState:YES]; //adjust the bottom content inset of scroll view UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 5, 0.0); scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; //animate [UIView commitAnimations]; } //move form back down when keyboard is hidden -(void)keyboardWasHidden:(NSNotification*)notification{ //setup animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.25]; [UIView setAnimationBeginsFromCurrentState:YES]; //adjust scroll view inset UIEdgeInsets contentInsets = UIEdgeInsetsZero; scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; //animate [UIView commitAnimations]; } #pragma mark Picker View Functions -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ categoryDropdown.text = [categoryOptions objectAtIndex:row]; } -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ return 1; } -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ return categoryOptions.count; } -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ return [categoryOptions objectAtIndex:row]; } #pragma mark API Call Functions -(IBAction)submitProduct:(id)sender{ //start activity indicator [spinner startAnimating]; //create post url NSString *addProductURL = @"/api/products/create"; //create query params NSMutableDictionary *queryParams = [[NSMutableDictionary alloc] init]; [queryParams setObject:name.text forKey:@"name"]; [queryParams setObject:brand.text forKey:@"brand"]; [queryParams setObject:categoryDropdown.text forKey:@"category"]; //add upc to params, if available if([upc.text length] > 0){ [queryParams setObject:upc.text forKey:@"upc"]; } //array to hold ingredients NSMutableArray *ingredients = [[NSMutableArray alloc] init]; //loop through uitextfields to get ingredients for (UIView *view in [scrollView subviews]) { if ([view isKindOfClass:[UITextField class]]) { UITextField *textField = (UITextField *)view; //if text field is an ingredient field... if(textField.tag >= 5 && [textField.text length] > 0){ //add to ingredients array [ingredients addObject:textField.text]; } } } //add ingredients to query params [queryParams setObject:ingredients forKey:@"ingredients"]; //get user credentials User *sharedUser = [User sharedUser]; NSString *username = [sharedUser getUsername]; NSString *password = [sharedUser getPassword]; //setup header for authentication RKObjectManager *objectManager = [RKObjectManager sharedManager]; [objectManager.HTTPClient setAuthorizationHeaderWithUsername:username password:password]; //make the call [[RKObjectManager sharedManager] postObject:nil path:addProductURL parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){ //stop activity indicator [spinner stopAnimating]; //loop through all uitextfields for (UIView *view in [scrollView subviews]) { if ([view isKindOfClass:[UITextField class]]) { //clear out all text fields UITextField *textField = (UITextField *)view; textField.text = @""; //remove extra ingredient fields if(textField.tag > 5){ [textField removeFromSuperview]; } } } //change width of original ingredient field CGRect firstIngredientFrame = CGRectMake(firstIngredient.frame.origin.x, firstIngredient.frame.origin.y, 212, firstIngredient.frame.size.height); [firstIngredient setFrame:firstIngredientFrame]; //move add ingredient button back up CGRect addButtonFrame = CGRectMake(addIngredientBtn.frame.origin.x, 185, addIngredientBtn.frame.size.width, addIngredientBtn.frame.size.height); [addIngredientBtn setFrame:addButtonFrame]; //move submit button back up CGRect submitButtonFrame = CGRectMake(submitBtn.frame.origin.x, 228, submitBtn.frame.size.width, submitBtn.frame.size.height); [submitBtn setFrame:submitButtonFrame]; //recalculate content size of scroll view contentHeight = 266; scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, contentHeight); //display success message UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your product has been submitted." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [successAlert show]; } failure:^(RKObjectRequestOperation *operation, NSError *error){ //get errors as JSON NSString *errors = [[error userInfo] objectForKey:NSLocalizedRecoverySuggestionErrorKey]; //convert JSON to dictionary NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [errors dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: nil]; //create error message NSMutableString *errorMsg = [NSMutableString string]; //handles message for server errors if([JSON objectForKey:@"error"] != nil){ [errorMsg appendFormat:@"%@", [JSON objectForKey:@"error"]]; } //handles message for validation errors else{ //loop through dictionary to build error message [errorMsg appendString:@"Your product was not submitted for the following reasons: "]; for (NSString* key in [JSON allKeys]){ [errorMsg appendFormat:@"%@ ", [[JSON objectForKey:key] objectAtIndex:0]]; } } //stop activity indicator [spinner stopAnimating]; //display error message UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:errorMsg delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [errorAlert show]; } ]; } @end <file_sep>// // IngredientViewController.m // SkinScope_v2 // // Created by <NAME> on 5/13/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "IngredientViewController.h" @interface IngredientViewController () @end @implementation IngredientViewController @synthesize ingredient, ingredientLabel, irr, irrLabel, com, comLabel, rating, ratingLabel, ratingBkg, function, functionLabel, description, descriptionLabel; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; [description sizeToFit]; } - (void)viewDidLoad { [super viewDidLoad]; //set nav bar title self.title = ingredient.name; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //change font of labels [ingredientLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:18]]; [irr setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:12]]; [irrLabel setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:12]]; [com setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:12]]; [comLabel setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:12]]; [rating setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:16]]; [ratingLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:12]]; [function setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:12]]; [functionLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:12]]; [description setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:12]]; [descriptionLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:12]]; //set text of rating rating.text = [ingredient.rating uppercaseString]; //if irritancy rating is -1, set value to unknown if(ingredient.irr == -1){ irr.text = @"?/5"; } else{ irr.text = [NSString stringWithFormat:@"%i/5", ingredient.irr]; } //if comedogenicity rating is -1, set value to unknown if(ingredient.com == -1){ com.text = @"?/5"; } else{ com.text = [NSString stringWithFormat:@"%i/5", ingredient.com]; } //if function is null set text to unknown if([ingredient.function length] == 0){ function.text = @"Unknown"; } else{ function.text = ingredient.function; } //if description is null set text to unknown if([ingredient.description length] == 0){ description.text = @"Unknown"; } else{ //set text description.text = ingredient.description; //figure out height of description label NSString *text = description.text; CGFloat lineHeight = description.font.lineHeight; CGFloat lines; //if text is less than one line, height is equal to lineHeight if(text.length / 35.0f < 1){ lines = lineHeight; } //if text is more than one line, calculate height else{ lines = (text.length / 35.0f) * lineHeight; } //resize description label description.frame = CGRectMake(description.frame.origin.x, description.frame.origin.y, description.frame.size.width, lines); [description sizeToFit]; } //set rating image bkg if([ingredient.rating isEqualToString:@"Good"]){ ratingBkg.image = [UIImage imageNamed:@"goodBkg.png"]; } else if([ingredient.rating isEqualToString:@"Average"]){ ratingBkg.image = [UIImage imageNamed:@"averageBkg.png"]; } else if([ingredient.rating isEqualToString:@"Poor"]){ ratingBkg.image = [UIImage imageNamed:@"poorBkg.png"]; } else if([ingredient.rating isEqualToString:@"Unknown"]){ ratingBkg.image = [UIImage imageNamed:@"unknownBkg.png"]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end <file_sep>// // ReviewsViewController.h // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Product.h" #import "CustomReviewCell.h" @interface ReviewsViewController : UIViewController <UIActionSheetDelegate> @property (nonatomic,strong) IBOutlet UILabel *reviewsLabel; @property (nonatomic,strong) IBOutlet UIBarButtonItem *composeButton; @property (nonatomic,strong) IBOutlet UIBarButtonItem *filterButton; @property (nonatomic,strong) IBOutlet UITableView *reviewsList; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; @property (nonatomic,assign) int pageIndex; @property (nonatomic, strong) CustomReviewCell *prototypeCell; @property (nonatomic,strong) NSString *filterSkinType; @property (nonatomic,strong) Product *product; @property (nonatomic,strong) NSArray *reviews; -(IBAction)pushAddReviewVC; -(IBAction)showFilterModal; -(void)getReviews; @end <file_sep>// // SkinScopeAppDelegate.m // SkinScope_v2 // // Created by <NAME> on 5/7/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "SkinScopeAppDelegate.h" #import <RestKit/RestKit.h> #import "Product.h" #import "Review.h" #import "Ingredient.h" @implementation SkinScopeAppDelegate @synthesize objectManager, emptyMapping, productSearchMapping, productReviewsMapping, loginDescriptor, productSearchDescriptor, productReviewsDescriptor, productIngredientsMapping, productIngredientsDescriptor, addReviewDescriptor, addProductDescriptor, createAccountDescriptor; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Initialize HTTPClient NSURL *baseURL = [NSURL URLWithString:@"http://skinscope.info"]; AFHTTPClient* client = [[AFHTTPClient alloc] initWithBaseURL:baseURL]; // Initialize RestKit objectManager = [[RKObjectManager alloc] initWithHTTPClient:client]; [self defineObjectMappings]; [self defineResponseDesciptors]; [self addDescriptors]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } #pragma mark RestKit / API Call Functions //all RestKit / API call object mappings are defined here -(void)defineObjectMappings{ //object mapping for login attempt emptyMapping = [RKObjectMapping mappingForClass:[NSObject class]]; //object mapping for product search productSearchMapping = [RKObjectMapping mappingForClass:[Product class]]; [productSearchMapping addAttributeMappingsFromDictionary:@{ @"id": @"productID", @"upc": @"upc", @"name": @"name", @"brand": @"brand", @"category": @"category", @"rating": @"rating", @"numIngredients": @"numIngredients", @"numIrritants": @"numIrritants", @"numComedogenics": @"numComedogenics", @"numReviews": @"numReviews" }]; //object mapping for product reviews productReviewsMapping = [RKObjectMapping mappingForClass:[Review class]]; [productReviewsMapping addAttributeMappingsFromDictionary:@{ @"review": @"review", @"user.id": @"userID", @"user.username": @"user", @"user.skin_type": @"skin_type" }]; //object mapping for product ingredients productIngredientsMapping = [RKObjectMapping mappingForClass:[Ingredient class]]; [productIngredientsMapping addAttributeMappingsFromDictionary:@{ @"id": @"ingredientID", @"name": @"name", @"rating": @"rating", @"function": @"function", @"benefits": @"benefits", @"negatives": @"negatives", @"com": @"com", @"irr": @"irr", @"description": @"description" }]; } //all RestKit / API call response descriptors are defined here -(void)defineResponseDesciptors{ //response descriptor for login attempt loginDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:emptyMapping method:RKRequestMethodGET pathPattern:@"/api/users/auth" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; //response descriptor for product search productSearchDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productSearchMapping method:RKRequestMethodGET pathPattern:@"/api/products" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; //response descriptor for product reviews productReviewsDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productReviewsMapping method:RKRequestMethodGET pathPattern:@"/api/products/:id/reviews" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; //response descriptor for product reviews productIngredientsDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:productIngredientsMapping method:RKRequestMethodGET pathPattern:@"/api/products/:id/ingredients" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; //response descriptor for adding a product review addReviewDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:emptyMapping method:RKRequestMethodPOST pathPattern:@"/api/products/:i/reviews/create" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; //response descriptor for adding a product addProductDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:emptyMapping method:RKRequestMethodPOST pathPattern:@"/api/products/create" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; //response descriptor for creating an account createAccountDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:emptyMapping method:RKRequestMethodPOST pathPattern:@"/api/users/create" keyPath:@"" statusCodes:[NSIndexSet indexSetWithIndex:200]]; } //add response descriptors to object manager -(void)addDescriptors{ [objectManager addResponseDescriptorsFromArray:@[loginDescriptor, productSearchDescriptor, productReviewsDescriptor, productIngredientsDescriptor, addReviewDescriptor, addProductDescriptor, createAccountDescriptor ]]; } @end <file_sep>// // Ingredient.m // SkinScope_v2 // // Created by <NAME> on 5/13/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "Ingredient.h" @implementation Ingredient @synthesize ingredientID, name, rating, function, benefits, negatives, com, irr, description; -(id)initWithIngredientID:(int)i_id name:(NSString *)i_name rating:(NSString *)i_rating function:(NSString *)i_function benefits:(NSString *)i_benefits negatives:(NSString *)i_negatives com:(int)i_com irr:(int)i_irr description:(NSString *)i_desc{ self = [super init]; // set properties if(self){ ingredientID = i_id; name = i_name; rating = i_rating; function = i_function; benefits = i_benefits; negatives = i_negatives; com = i_com; irr = i_irr; description = i_desc; } return self; } @end <file_sep>// // ProductSearchViewController.m // SkinScope_v2 // // Created by <NAME> on 5/9/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "ProductSearchViewController.h" #import <RestKit/RestKit.h> #import "Product.h" #import "ProductViewController.h" @interface ProductSearchViewController () @end @implementation ProductSearchViewController @synthesize mySearchBar, resultsLabel, addBtn, scanBtn, searchResults, products, product, filterRating, spinner, productUPC; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //set back button text and color for navigation controller self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //show the navigation bar [self.navigationController.navigationBar setHidden:NO]; //make navigation bar transparent [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; self.navigationController.navigationBar.shadowImage = [UIImage new]; self.navigationController.navigationBar.translucent = YES; //hide back button - already logged in, no need to go back [self.navigationItem setHidesBackButton:YES animated:YES]; //change appearance of search bar [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setLeftViewMode:UITextFieldViewModeNever]; [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]]; //custom clear button in search bar UIImage *imgClear = [UIImage imageNamed:@"clear.png"]; [mySearchBar setImage:imgClear forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal]; //set scan button image UIImage *scanImage = [UIImage imageNamed:@"scan.png"]; [scanBtn setImage:scanImage forState:UIControlStateNormal]; //round the corners of scan button CALayer *btnLayer = [scanBtn layer]; [btnLayer setMasksToBounds:YES]; [btnLayer setCornerRadius:3.0f]; //set add button image UIImage *addImage = [UIImage imageNamed:@"add.png"]; [addBtn setImage:addImage forState:UIControlStateNormal]; //round the corners of add button CALayer *addLayer = [addBtn layer]; [addLayer setMasksToBounds:YES]; [addLayer setCornerRadius:3.0f]; //change font of title [resultsLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:18]]; //prevent table cell left indentation [searchResults setSeparatorInset:UIEdgeInsetsZero]; //don't filter products by default filterRating = @""; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark Search Bar Functions //clear filter and placeholder text when starting a new search -(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar{ mySearchBar.text = @""; filterRating = @""; } //search submitted - make api call -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ //dismiss the keyboard [searchBar resignFirstResponder]; //search [self searchForProducts]; } //tapping outside the search bar will dimiss the keyboard -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [mySearchBar resignFirstResponder]; } #pragma mark Table View Functions -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return products.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductCell" forIndexPath:indexPath]; Product *rowProduct = [products objectAtIndex:indexPath.row]; //set table cell image based on product rating if([[rowProduct rating] isEqualToString:@"Good"]){ cell.imageView.image = [UIImage imageNamed:@"good.png"]; } else if([[rowProduct rating] isEqualToString:@"Average"]){ cell.imageView.image = [UIImage imageNamed:@"average.png"]; } else if([[rowProduct rating] isEqualToString:@"Poor"]){ cell.imageView.image = [UIImage imageNamed:@"poor.png"]; } else{ cell.imageView.image = [UIImage imageNamed:@"unknown.png"]; } //set product name cell.textLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:12]; cell.textLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; cell.textLabel.text = [rowProduct name]; //set product brand cell.detailTextLabel.font = [UIFont fontWithName:@"ProximaNova-Regular" size:10]; cell.textLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; cell.detailTextLabel.text = [rowProduct brand]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [tableView deselectRowAtIndexPath:indexPath animated:YES]; // get product product = [products objectAtIndex:indexPath.row]; //push next view controller [self pushProductVC]; } #pragma mark Search Result Functions //search for products by text -(void)searchForProducts{ //show activity indicator [spinner startAnimating]; //setup query parameters NSDictionary *queryParams; //if no rating is specified, don't filter results if([filterRating isEqualToString:@""]){ queryParams = @{@"name" : mySearchBar.text, @"brand" : mySearchBar.text}; } //filter results based on rating else{ queryParams = @{@"name" : mySearchBar.text, @"brand" : mySearchBar.text, @"rating" : filterRating}; } //make the call [[RKObjectManager sharedManager] getObjectsAtPath:@"/api/products" parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { [spinner stopAnimating]; //hide activity indicator products = mappingResult.array; //store results [searchResults reloadData]; //show the results } failure:^(RKObjectRequestOperation *operation, NSError *error) { [spinner stopAnimating]; //hide activity indicator products = [NSArray array]; //empty array [searchResults reloadData]; //empty the table view //no products found, show error message UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No products were found." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [errorAlert show]; } ]; } //search for products by UPC / Barcode -(void)searchByUPC{ //show activity indicator [spinner startAnimating]; //setup query parameters NSDictionary *queryParams = @{@"upc": productUPC}; //make the call [[RKObjectManager sharedManager] getObjectsAtPath:@"/api/products" parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { [spinner stopAnimating]; //hide activity indicator products = mappingResult.array; //store results [searchResults reloadData]; //show the results } failure:^(RKObjectRequestOperation *operation, NSError *error) { [spinner stopAnimating]; //hide activity indicator products = [NSArray array]; //empty array [searchResults reloadData]; //empty the table view //no products found, show error message UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No products were found." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [errorAlert show]; } ]; } //display action sheet modal with filter options -(IBAction)showFilterModal{ UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@" Filter by Rating" delegate:(id<UIActionSheetDelegate>)self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles: @"All Results", @"Good", @"Average", @"Poor", @"Unknown", nil]; //show action sheet [popup showInView:[UIApplication sharedApplication].keyWindow]; } //customize action sheet title and buttons - (void)willPresentActionSheet:(UIActionSheet *)actionSheet{ for (UIView *subview in actionSheet.subviews) { //customize buttons if ([subview isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)subview; //set color [button setTitleColor:[UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1] forState:UIControlStateNormal]; //set font [button.titleLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:14]]; //set alignment and padding [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; [button setContentEdgeInsets:UIEdgeInsetsMake(0.0, 25.0, 0.0, 0.0)]; [button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 10.0, 0.0, 0.0)]; //custom padding on cancel button since it does not have an image if([button.titleLabel.text isEqualToString:@"Cancel"]){ [button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)]; } //add icons to action sheet buttons if([button.titleLabel.text isEqualToString:@"All Results"]){ [button setImage:[UIImage imageNamed:@"allResults.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Good"]){ [button setImage:[UIImage imageNamed:@"good.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Average"]){ [button setImage:[UIImage imageNamed:@"average.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Poor"]){ [button setImage:[UIImage imageNamed:@"poor.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Unknown"]){ [button setImage:[UIImage imageNamed:@"unknown.png"] forState:UIControlStateNormal]; } } //customize title else if ([subview isKindOfClass:[UILabel class]]) { UILabel *label = (UILabel *)subview; //set color [label setTextColor:[UIColor colorWithRed:120.0/255.0 green:120.0/255.0 blue:120.0/255.0 alpha:1]]; //set font [label setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:14]]; //set alignment [label setTextAlignment:NSTextAlignmentLeft]; } } } //filter results - (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex { //set filter switch (buttonIndex) { //all results case 0: filterRating = @""; break; //good case 1: filterRating = @"Good"; break; //average case 2: filterRating = @"Average"; break; //poor case 3: filterRating = @"Poor"; break; //unknown case 4: filterRating = @"Unknown"; break; //default default: filterRating = @""; break; } //search for products if(![mySearchBar.text isEqualToString:@""] && ![mySearchBar.text isEqualToString:@"Search"]){ [self searchForProducts]; } } #pragma mark Segue //segue to the product search view controller -(void)pushProductVC{ [self performSegueWithIdentifier:@"pushProductVC" sender:self]; } //segue to the product search view controller -(IBAction)pushAddProductVC{ [self performSegueWithIdentifier:@"pushAddProductVC" sender:self]; } //pass product to next view controller - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"pushProductVC"]) { // Get destination view ProductViewController *productViewController = [segue destinationViewController]; // Pass the product to destination view [productViewController setProduct:product]; } } #pragma mark - Add Scanner //create scan modal view //uses ZBar iPhone SDK: http://zbar.sourceforge.net/iphone/sdkdoc/index.html -(IBAction)showScanner{ //create ZBar reader ZBarReaderViewController *reader = [ZBarReaderViewController new]; reader.readerDelegate = self; // EXAMPLE: Set UPC-A [reader.scanner setSymbology:ZBAR_UPCA config:ZBAR_CFG_ENABLE to:1]; reader.readerView.zoom = 1.0; //display barcode scanner in modal view controller [self presentViewController:reader animated:YES completion:nil]; } //get UPC from image - (void)imagePickerController:(UIImagePickerController *)reader didFinishPickingMediaWithInfo:(NSDictionary *) info{ id<NSFastEnumeration> results = [info objectForKey:ZBarReaderControllerResults]; ZBarSymbol *symbol = nil; for(symbol in results) break; if(symbol){ //set search term to UPC code productUPC = symbol.data; //search using UPC [self searchByUPC]; //dismiss the modal view controller [reader dismissViewControllerAnimated:YES completion:nil]; } } @end <file_sep>// // ProductViewController.m // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "ProductViewController.h" #import "Product.h" @interface ProductViewController () @end @implementation ProductViewController @synthesize overviewLabel, productName, brandName, rating, ratingLabel, ratingBkg, numIngredients, ingredientsLabel, numIrritants, irritantsLabel, numComedogenics, comedogenicsLabel, product; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //clear background allows background image of page view controller to show through self.view.backgroundColor = [UIColor clearColor]; //change font of labels [overviewLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:18]]; [productName setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:22]]; [brandName setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:14]]; [rating setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:16]]; [ratingLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:12]]; [numIngredients setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:16]]; [ingredientsLabel setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [numIrritants setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:16]]; [irritantsLabel setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [numComedogenics setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:16]]; [comedogenicsLabel setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; //set text of labels productName.text = product.name; brandName.text = product.brand; rating.text = [product.rating uppercaseString]; numIngredients.text = [NSString stringWithFormat:@"%i", product.numIngredients]; numIrritants.text = [NSString stringWithFormat:@"%i", product.numIrritants]; numComedogenics.text = [NSString stringWithFormat:@"%i", product.numComedogenics]; //set rating image bkg if([product.rating isEqualToString:@"Good"]){ ratingBkg.image = [UIImage imageNamed:@"goodBkg.png"]; } else if([product.rating isEqualToString:@"Average"]){ ratingBkg.image = [UIImage imageNamed:@"averageBkg.png"]; } else if([product.rating isEqualToString:@"Poor"]){ ratingBkg.image = [UIImage imageNamed:@"poorBkg.png"]; } else if([product.rating isEqualToString:@"Unknown"]){ ratingBkg.image = [UIImage imageNamed:@"unknownBkg.png"]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end <file_sep>// // main.m // SkinScope_v2 // // Created by <NAME> on 5/7/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "SkinScopeAppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([SkinScopeAppDelegate class])); } } <file_sep>// // CustomReviewCell.h // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface CustomReviewCell : UITableViewCell @property (nonatomic,strong) IBOutlet UILabel *username; @property (nonatomic,strong) IBOutlet UILabel *skinTypeLabel; @property (nonatomic,strong) IBOutlet UILabel *skinType; @property (nonatomic,strong) IBOutlet UILabel *review; @end <file_sep>// // User.m // SkinScope_v2 // // Created by <NAME> on 5/8/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "User.h" @implementation User @synthesize username, password; //init user -(id)initWithUsername:(NSString *)u_name password:(NSString *)u_pass{ self = [super init]; // set properties if(self){ username = u_name; password = <PASSWORD>; } return self; } #pragma mark Singleton Methods + (id)sharedUser{ static User *sharedUser = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedUser = [[self alloc] init]; }); return sharedUser; } -(id)init{ if (self = [super init]) { username = @"DefaultUsername"; password = @"<PASSWORD>"; } return self; } #pragma mark Getters and Setters -(void)setUsername:(NSString *)u_name{ username = u_name; } -(void)setPassword:(NSString *)u_pass{ password = <PASSWORD>; } -(NSString *)getUsername{ return username; } -(NSString *)getPassword{ return password; } @end <file_sep>// // CustomReviewCell.m // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "CustomReviewCell.h" @implementation CustomReviewCell @synthesize username, skinType, skinTypeLabel, review; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { // Initialization code } return self; } - (void)awakeFromNib { // Initialization code } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } @end <file_sep>// // MappingProvider.m // SkinScope_v2 // // Created by <NAME> on 5/9/14. // Copyright (c) 2014 <NAME>. All rights reserved. // Code organization for RestKit app - http://restkit-tutorials.com/code-organization-in-restkit-based-app/ #import <Foundation/Foundation.h> @class RKObjectMapping; @interface MappingProvider : NSObject + (RKObjectMapping *) userMapping; + (RKObjectMapping *) repositoryMapping; @end <file_sep>// // MappingProvider.h // SkinScope_v2 // // Created by <NAME> on 5/9/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface MappingProvider : NSObject @end <file_sep># Uncomment this line to define a global platform for your project platform :ios, '5.0' pod 'RestKit', '~> 0.20.0' <file_sep>// // Dropdown.h // SkinScope_v2 // // Created by <NAME> on 5/15/14. // Copyright (c) 2014 <NAME>. All rights reserved. // // Code for custom drop down from here: http://rogchap.com/2013/08/13/simple-ios-dropdown-control-using-uitextfield/ #import <UIKit/UIKit.h> @interface Dropdown : UITextField @property (nonatomic) id<UIPickerViewDelegate> pickerDelegate; @property (nonatomic) id<UIPickerViewDataSource> pickerDataSource; @end <file_sep>// // IngredientsListViewController.m // SkinScope_v2 // // Created by <NAME> on 5/13/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "IngredientsListViewController.h" #import <RestKit/RestKit.h> #import "Ingredient.h" #import "IngredientViewController.h" @interface IngredientsListViewController () @end @implementation IngredientsListViewController @synthesize ingredientsLabel, filterButton, ingredientsList, pageIndex, filterRating, product, ingredients, ingredient, spinner; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //clear background allows background image of page view controller to show through self.view.backgroundColor = [UIColor clearColor]; //change font of labels [ingredientsLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:18]]; //prevent table cell left indentation [ingredientsList setSeparatorInset:UIEdgeInsetsZero]; //don't filter ingredients by default filterRating = @""; //get ingredients [self getIngredients]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark Table View Functions -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ //if there are no reviews, display a message if(ingredients.count == 0){ return 1; } //else display the reviews else{ return ingredients.count; } } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ //if there are reviews, display them if(ingredients.count > 0){ //create cell UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IngredientCell" forIndexPath:indexPath]; //get ingredient Ingredient *rowIngredient = [ingredients objectAtIndex:indexPath.row]; //set table cell image based on ingredient rating if([[rowIngredient rating] isEqualToString:@"Good"]){ cell.imageView.image = [UIImage imageNamed:@"good.png"]; } else if([[rowIngredient rating] isEqualToString:@"Average"]){ cell.imageView.image = [UIImage imageNamed:@"average.png"]; } else if([[rowIngredient rating] isEqualToString:@"Poor"]){ cell.imageView.image = [UIImage imageNamed:@"poor.png"]; } else{ cell.imageView.image = [UIImage imageNamed:@"unknown.png"]; } //set ingredient name cell.textLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:12]; cell.textLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; cell.textLabel.text = [rowIngredient name]; return cell; } //if there are no reviews, display a message else{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoResultsCell" forIndexPath:indexPath]; //display message cell.textLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:12]; cell.textLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; cell.textLabel.text = @"No ingredients found."; return cell; } } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [tableView deselectRowAtIndexPath:indexPath animated:YES]; // get product ingredient = [ingredients objectAtIndex:indexPath.row]; //push next view controller [self pushIngredientVC]; } #pragma mark API Call Functions -(void)getIngredients{ //show activity indicator [spinner startAnimating]; //setup query url NSString *ingredientsURL = [NSString stringWithFormat:@"/api/products/%i/ingredients", product.productID]; //setup query parameters NSDictionary *queryParams; //if no skin type is specified, don't filter results if([filterRating isEqualToString:@""]){ queryParams = nil; } //filter results based on skin type else{ queryParams = @{@"rating" : filterRating}; } //make the call [[RKObjectManager sharedManager] getObjectsAtPath:ingredientsURL parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { [spinner stopAnimating]; //hide activity indicator ingredients = mappingResult.array; //store reviews [ingredientsList reloadData]; //show the reviews } failure:^(RKObjectRequestOperation *operation, NSError *error) { [spinner stopAnimating]; //hide activity indicator ingredients = [NSArray array]; //empty the array [ingredientsList reloadData]; //display a message } ]; } //display action sheet modal with filter options -(IBAction)showFilterModal{ UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@" Filter by Rating" delegate:(id<UIActionSheetDelegate>)self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles: @"All Results", @"Good", @"Average", @"Poor", @"Unknown", nil]; //show action sheet [popup showInView:[UIApplication sharedApplication].keyWindow]; } //customize action sheet title and buttons - (void)willPresentActionSheet:(UIActionSheet *)actionSheet{ for (UIView *subview in actionSheet.subviews) { //customize buttons if ([subview isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)subview; //set color [button setTitleColor:[UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1] forState:UIControlStateNormal]; //set font [button.titleLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:14]]; //set alignment and padding [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; [button setContentEdgeInsets:UIEdgeInsetsMake(0.0, 25.0, 0.0, 0.0)]; [button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 10.0, 0.0, 0.0)]; //custom padding on cancel button since it does not have an image if([button.titleLabel.text isEqualToString:@"Cancel"]){ [button setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)]; } //add icons to action sheet buttons if([button.titleLabel.text isEqualToString:@"All Results"]){ [button setImage:[UIImage imageNamed:@"allResults.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Good"]){ [button setImage:[UIImage imageNamed:@"good.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Average"]){ [button setImage:[UIImage imageNamed:@"average.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Poor"]){ [button setImage:[UIImage imageNamed:@"poor.png"] forState:UIControlStateNormal]; } else if([button.titleLabel.text isEqualToString:@"Unknown"]){ [button setImage:[UIImage imageNamed:@"unknown.png"] forState:UIControlStateNormal]; } } //customize title else if ([subview isKindOfClass:[UILabel class]]) { UILabel *label = (UILabel *)subview; //set color [label setTextColor:[UIColor colorWithRed:120.0/255.0 green:120.0/255.0 blue:120.0/255.0 alpha:1]]; //set font [label setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:14]]; //set alignment [label setTextAlignment:NSTextAlignmentLeft]; } } } //filter results - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { //set filter switch (buttonIndex) { //all ingredients case 0: filterRating = @""; break; //good case 1: filterRating = @"Good"; break; //average case 2: filterRating = @"Average"; break; //poor case 3: filterRating = @"Poor"; break; //unknown case 4: filterRating = @"Unknown"; break; //default default: filterRating = @""; break; } //filter reviews [self getIngredients]; } #pragma mark Segue -(void)pushIngredientVC{ [self performSegueWithIdentifier:@"pushIngredientVC" sender:self]; } //pass ingredient to next view controller - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"pushIngredientVC"]) { // Get destination view IngredientViewController *ingredientViewController = [segue destinationViewController]; // Pass the product to destination view [ingredientViewController setIngredient:ingredient]; } } @end <file_sep>// // Dropdown.m // SkinScope_v2 // // Created by <NAME> on 5/15/14. // Copyright (c) 2014 <NAME>. All rights reserved. // // Code for custom drop down from here: http://rogchap.com/2013/08/13/simple-ios-dropdown-control-using-uitextfield/ #import "Dropdown.h" #import "DropdownArrowView.h" @implementation Dropdown{ UIPickerView* _pickerView; } -(id)initWithCoder:(NSCoder *)aDecoder{ if(self = [super initWithCoder:aDecoder]){ //create dropdown arrow self.rightView = [DropdownArrowView default]; self.rightViewMode = UITextFieldViewModeAlways; //setup picker _pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero]; _pickerView.showsSelectionIndicator = YES; //set input to picker instead of keyboard self.inputView = _pickerView; } return self; } //prevent copy/cut/paste/select actions from showing up when user double clicks the dropdown - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(paste:) || action == @selector(cut:) || action == @selector(copy:) || action == @selector(select:) || action == @selector(selectAll:)){ return NO; } return [super canPerformAction:action withSender:sender]; } -(void)setTag:(NSInteger)tag{ [super setTag:tag]; _pickerView.tag = tag; } -(void)setPickerDelegate:(id<UIPickerViewDelegate>)pickerDelegate{ _pickerView.delegate = pickerDelegate; } -(void)setPickerDataSource:(id<UIPickerViewDataSource>)pickerDataSource{ _pickerView.dataSource = pickerDataSource; } @end <file_sep>// // Product.m // SkinScope_v2 // // Created by <NAME> on 5/8/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "Product.h" @implementation Product @synthesize productID, upc, name, brand, category, rating; -(id)initWithID:(int)p_id upc:(NSString *)p_upc name:(NSString *)p_name brand:(NSString *)p_brand category:(NSString *)p_cat rating:(NSString *)p_rating{ self = [super init]; // set properties if(self){ productID = p_id; upc = p_upc; name = p_name; brand = p_brand; category = p_cat; rating = p_rating; } return self; } @end <file_sep>// // Ingredient.h // SkinScope_v2 // // Created by <NAME> on 5/13/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface Ingredient : NSObject @property (nonatomic,assign) int ingredientID; @property (nonatomic,strong) NSString *name; @property (nonatomic,strong) NSString *rating; @property (nonatomic,strong) NSString *function; @property (nonatomic,strong) NSString *benefits; @property (nonatomic,strong) NSString *negatives; @property (nonatomic,assign) int com; @property (nonatomic,assign) int irr; @property (nonatomic,strong) NSString *description; -(id)initWithIngredientID:(int)i_id name:(NSString *)i_name rating:(NSString *)i_rating function:(NSString *)i_function benefits:(NSString *)i_benefits negatives:(NSString *)i_negatives com:(int)i_com irr:(int)i_int description:(NSString *)i_desc; @end <file_sep>// // User.h // SkinScope_v2 // // Created by <NAME> on 5/8/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface User : NSObject @property (nonatomic,strong) NSString *username; @property (nonatomic,strong) NSString *password; //init +(id)sharedUser; -(id)initWithUsername:(NSString *)u_name password:(NSString *)u_pass; //setters and getters -(void)setUsername:(NSString *)u_name; -(void)setPassword:(NSString *)u_pass; -(NSString *)getUsername; -(NSString *)getPassword; @end <file_sep>// // SkinScopeViewController.h // SkinScope_v2 // // Created by <NAME> on 5/7/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface SkinScopeViewController : UIViewController @property (nonatomic,strong) IBOutlet UILabel *titleLabel; @property (nonatomic,strong) IBOutlet UITextField *email; @property (nonatomic,strong) IBOutlet UITextField *password; @property (nonatomic,strong) IBOutlet UIButton *login; @property (nonatomic,strong) IBOutlet UIButton *createAccount; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; -(IBAction)attemptLogin:(id)sender; -(void)checkAccountInfo; -(void)pushSearchVC; -(IBAction)pushCreateAccountVC:(id)sender; @end <file_sep>// // Product.h // SkinScope_v2 // // Created by <NAME> on 5/8/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface Product : NSObject @property (nonatomic,assign) int productID; @property (nonatomic,strong) NSString *upc; @property (nonatomic,strong) NSString *name; @property (nonatomic,strong) NSString *brand; @property (nonatomic,strong) NSString *category; @property (nonatomic,strong) NSString *rating; @property (nonatomic,assign) int numIngredients; @property (nonatomic,assign) int numIrritants; @property (nonatomic,assign) int numComedogenics; @property (nonatomic,assign) int numReviews; -(id)initWithID:(int)p_id upc:(NSString *)p_upc name:(NSString *)p_name brand:(NSString *)p_brand category:(NSString *)p_cat rating:(NSString *)p_rating; @end <file_sep>// // AddReviewViewController.h // SkinScope_v2 // // Created by <NAME> on 5/14/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Product.h" @interface AddReviewViewController : UIViewController <UITextViewDelegate> @property (nonatomic,strong) IBOutlet UILabel *writeReviewLabel; @property (nonatomic,strong) IBOutlet UITextView *reviewText; @property (nonatomic,strong) IBOutlet UIButton *submitBtn; @property (nonatomic,strong) IBOutlet UIButton *clearBtn; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; @property (nonatomic,strong) Product *product; -(IBAction)clearReviewText; -(IBAction)submitReview; @end <file_sep>SkinScope iOS App v2 =========================== SkinScope is a native iOS app designed to help consumers quickly and easily research skincare products before puchasing. This app is a prototype. **[View the deck](http://www.slideshare.net/CarlaCrandall/skinscope-ios-app-process-annotated-designs)** for a full list of planned features and a preview of the UI. ### Dependencies 1. SkinScope uses [RestKit](http://restkit.org/) to handle RESTful API calls. 2. SkinScope also uses the [ZBar iPhone SDK](http://zbar.sourceforge.net/iphone/sdkdoc/).<file_sep>// // ReviewsViewController.m // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "ReviewsViewController.h" #import <RestKit/RestKit.h> #import "Review.h" #import "CustomReviewCell.h" #import "AddReviewViewController.h" @interface ReviewsViewController () @end @implementation ReviewsViewController @synthesize reviewsLabel, composeButton, filterButton, pageIndex, product, reviews, reviewsList, filterSkinType, prototypeCell, spinner; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; //clear background allows background image of page view controller to show through self.view.backgroundColor = [UIColor clearColor]; //change font of labels [reviewsLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:18]]; //prevent table cell left indentation [reviewsList setSeparatorInset:UIEdgeInsetsZero]; //don't filter reviews by default filterSkinType = @""; //get reviews for the product [self getReviews]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark Table View Functions -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ //if there are no reviews, display a message if(reviews.count == 0){ return 1; } //else display the reviews else{ return reviews.count; } } //configure review table cells - (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ if ([cell isKindOfClass:[CustomReviewCell class]]){ CustomReviewCell *reviewCell = (CustomReviewCell *)cell; Review *rowReview = [reviews objectAtIndex:indexPath.row]; //set review user reviewCell.username.font = [UIFont fontWithName:@"ProximaNova-Bold" size:14]; reviewCell.username.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; reviewCell.username.text = [rowReview user]; //set review skin type reviewCell.skinTypeLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:10]; reviewCell.skinTypeLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; reviewCell.skinType.font = [UIFont fontWithName:@"ProximaNova-Regular" size:10]; reviewCell.skinType.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; reviewCell.skinType.text = [rowReview skin_type]; //set review text reviewCell.review.font = [UIFont fontWithName:@"ProximaNova-Regular" size:12]; reviewCell.review.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; reviewCell.review.text = [rowReview review]; //figure out height of review label NSString *text = reviewCell.review.text; CGFloat lineHeight = reviewCell.review.font.lineHeight; CGFloat lines; //if text is less than one line, height is equal to lineHeight if(text.length / 35.0f < 1){ lines = lineHeight; } //if text is more than one line, calculate height else{ lines = (text.length / 35.0f) * lineHeight; } //resize review label reviewCell.review.frame = CGRectMake(reviewCell.review.frame.origin.x, reviewCell.review.frame.origin.y, 223, lines); [reviewCell.review sizeToFit]; } } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{ //if there are reviews, display them if(reviews.count > 0){ //create cell CustomReviewCell *cell = (CustomReviewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomReviewCell" forIndexPath:indexPath]; //configure cell [self configureCell:cell forRowAtIndexPath:indexPath]; return cell; } //if there are no reviews, display a message else{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoResultsCell" forIndexPath:indexPath]; //display message cell.textLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:12]; cell.textLabel.textColor = [UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1]; cell.textLabel.text = @"No reviews found."; return cell; } } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ //calculate height for reviews if(reviews.count > 0){ //create a prototype cell [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath]; //figure out height of review label UILabel *contentLabel = prototypeCell.review; NSString *text = prototypeCell.review.text; CGFloat lineHeight = contentLabel.font.lineHeight; CGFloat lines; //if text is less than one line, height is equal to lineHeight if(text.length / 35.0f < 1){ lines = lineHeight; } //if text is more than one line, calculate height else{ lines = (text.length / 35.0f) * lineHeight; } //add on height for the rest of the labels CGFloat height = lines + 70.0f; //return dynamic height return height; } //if no reviews, return default height else{ return 44; } } -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{ return UITableViewAutomaticDimension; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"User selected row"); } //getter for prototype cell - used to calculate dynamic cell height -(CustomReviewCell *)prototypeCell{ if (!prototypeCell){ prototypeCell = [self.reviewsList dequeueReusableCellWithIdentifier:@"CustomReviewCell"]; } return prototypeCell; } #pragma mark API Call Functions -(void)getReviews{ //show activity indicator [spinner startAnimating]; //setup query url NSString *reviewsURL = [NSString stringWithFormat:@"/api/products/%i/reviews", product.productID]; //setup query parameters NSDictionary *queryParams; //if no skin type is specified, don't filter results if([filterSkinType isEqualToString:@""]){ queryParams = nil; } //filter results based on skin type else{ queryParams = @{@"skin_type" : filterSkinType}; } //make the call [[RKObjectManager sharedManager] getObjectsAtPath:reviewsURL parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { [spinner stopAnimating]; //hide activity indicator reviews = mappingResult.array; //store reviews [reviewsList reloadData]; //show the reviews } failure:^(RKObjectRequestOperation *operation, NSError *error) { [spinner stopAnimating]; //hide activity indicator reviews = [NSArray array]; //empty the array [reviewsList reloadData]; //display a message } ]; } //display action sheet modal with filter options -(IBAction)showFilterModal{ UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:@" Filter by Skin Type" delegate:(id<UIActionSheetDelegate>)self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles: @"All Results", @"Normal", @"Oily", @"Dry", @"Sensitive", @"Combination", nil]; //show action sheet [popup showInView:[UIApplication sharedApplication].keyWindow]; } //customize action sheet title and buttons - (void)willPresentActionSheet:(UIActionSheet *)actionSheet{ for (UIView *subview in actionSheet.subviews) { //customize buttons if ([subview isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)subview; //set color [button setTitleColor:[UIColor colorWithRed:54.0/255.0 green:54.0/255.0 blue:54.0/255.0 alpha:1] forState:UIControlStateNormal]; //set font [button.titleLabel setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:14]]; //set alignment and padding [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; [button setContentEdgeInsets:UIEdgeInsetsMake(0.0, 25.0, 0.0, 0.0)]; } //customize title else if ([subview isKindOfClass:[UILabel class]]) { UILabel *label = (UILabel *)subview; //set color [label setTextColor:[UIColor colorWithRed:120.0/255.0 green:120.0/255.0 blue:120.0/255.0 alpha:1]]; //set font [label setFont:[UIFont fontWithName:@"ProximaNova-Bold" size:14]]; //set alignment [label setTextAlignment:NSTextAlignmentLeft]; } } } //filter results - (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex { //set filter switch (buttonIndex) { //all reviews case 0: filterSkinType = @""; break; //normal case 1: filterSkinType = @"Normal"; break; //oily case 2: filterSkinType = @"Oily"; break; //dry case 3: filterSkinType = @"Dry"; break; //sensitive case 4: filterSkinType = @"Sensitive"; break; //combination case 5: filterSkinType = @"Combination"; break; //default default: filterSkinType = @""; break; } //filter reviews [self getReviews]; } #pragma mark Segue //push the next view controller -(IBAction)pushAddReviewVC{ [self performSegueWithIdentifier:@"pushAddReviewVC" sender:self]; } //pass product to next view controller - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"pushAddReviewVC"]) { // Get destination view AddReviewViewController *addReviewViewController = [segue destinationViewController]; // Pass the product to destination view [addReviewViewController setProduct:product]; } } @end <file_sep>// // SkinScopeViewController.m // SkinScope_v2 // // Created by <NAME> on 5/7/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "SkinScopeViewController.h" #import <QuartzCore/QuartzCore.h> #import <RestKit/RestKit.h> #import "SSKeychain.h" #import "User.h" @interface SkinScopeViewController () @end @implementation SkinScopeViewController @synthesize titleLabel, email, password, login, spinner, createAccount; - (void)viewDidLoad { [super viewDidLoad]; //check to see if account info is in keychain [self checkAccountInfo]; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //hide the navigation bar [self.navigationController.navigationBar setHidden:YES]; //change font of navigation bar title [self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"Bree-Bold" size:20.0], NSFontAttributeName, nil]]; //set back button text and color for navigation controller self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; //change font of title [titleLabel setFont:[UIFont fontWithName:@"Bree-Bold" size:50]]; //change font of text fields UIFont *pn_reg = [UIFont fontWithName:@"ProximaNova-Regular" size:16]; [email setFont:pn_reg]; [password setFont:pn_reg]; //change border color of text fields email.layer.borderColor=[[UIColor whiteColor]CGColor]; email.layer.borderWidth= 1.0f; password.layer.borderColor=[[UIColor whiteColor]CGColor]; password.layer.borderWidth= 1.0f; //add padding to left side of text fields email.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); password.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); //change font of buttons login.titleLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:24]; createAccount.titleLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:14]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark Keyboard Related Functions //handles navigating between text fields and dismissing the keyboard - (BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField == self.password) { [textField resignFirstResponder]; } else if (textField == self.email) { [self.password becomeFirstResponder]; } return YES; } //slide form up when the user begins editing //prevents fields from getting stuck under the keyboard - (void)textFieldDidBeginEditing:(UITextField *)textField { //setup animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.25]; [UIView setAnimationBeginsFromCurrentState:YES]; //move form up email.frame = CGRectMake(email.frame.origin.x, (email.frame.origin.y - 100.0), email.frame.size.width, email.frame.size.height); password.frame = CGRectMake(password.frame.origin.x, (password.frame.origin.y - 100.0), password.frame.size.width, password.frame.size.height); login.frame = CGRectMake(login.frame.origin.x, (login.frame.origin.y - 100.0), login.frame.size.width, login.frame.size.height); [UIView commitAnimations]; } //slide form down when user is finished editing //prevents fields from getting stuck under the keyboard - (void)textFieldDidEndEditing:(UITextField *)textField { //setup animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.25]; [UIView setAnimationBeginsFromCurrentState:YES]; //move form down email.frame = CGRectMake(email.frame.origin.x, (email.frame.origin.y + 100.0), email.frame.size.width, email.frame.size.height); password.frame = CGRectMake(password.frame.origin.x, (password.frame.origin.y + 100.0), password.frame.size.width, password.frame.size.height); login.frame = CGRectMake(login.frame.origin.x, (login.frame.origin.y + 100.0), login.frame.size.width, login.frame.size.height); [UIView commitAnimations]; } //tapping outside the form will dimiss the keyboard - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; } #pragma mark API Call Functions //check to see if account information has been saved to keychain -(void)checkAccountInfo{ //get all accounts (if any) NSArray *accounts = [SSKeychain accountsForService:@"SkinScope.com"]; //account info exists, login automatically if([accounts count] == 1){ //get username & password from keychain NSString *username = [[accounts objectAtIndex:0] objectForKey:@"acct"]; NSString *pass = [SSKeychain passwordForService:@"SkinScope.com" account:username]; //[SSKeychain deletePasswordForService:@"SkinScope.com" account:username]; //setup user User *sharedUser = [User sharedUser]; [sharedUser setUsername:username]; [sharedUser setPassword:<PASSWORD>]; [self pushSearchVC]; } } //attempt to login using supplied credentials -(IBAction)attemptLogin:(id)sender{ //dismiss the keyboard [self.view endEditing:YES]; //show activity indicator [spinner startAnimating]; //setup header for authentication RKObjectManager *objectManager = [RKObjectManager sharedManager]; [objectManager.HTTPClient setAuthorizationHeaderWithUsername:self.email.text password:<PASSWORD>]; //make the call [[RKObjectManager sharedManager] getObjectsAtPath:@"/api/users/auth" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { [spinner stopAnimating]; //save account information to keychain [SSKeychain setPassword:<PASSWORD> forService:@"SkinScope.com" account:self.email.text]; //setup user User *sharedUser = [User sharedUser]; [sharedUser setUsername:self.email.text]; [sharedUser setPassword:<PASSWORD>]; [self pushSearchVC]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { [spinner stopAnimating]; //authentication failed, show error message UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"There was an issue with your email and password combination. Please try again." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [errorAlert show]; } ]; } #pragma mark Segue //segue to the product search view controller -(void)pushSearchVC{ [self performSegueWithIdentifier:@"pushSearchVC" sender:self]; } //segue to the create account view controller -(IBAction)pushCreateAccountVC:(id)sender{ [self performSegueWithIdentifier:@"pushCreateAccountVC" sender:self]; } @end <file_sep>// // IngredientViewController.h // SkinScope_v2 // // Created by <NAME> on 5/13/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Ingredient.h" @interface IngredientViewController : UIViewController @property (nonatomic,strong) IBOutlet UILabel *ingredientLabel; @property (nonatomic,strong) IBOutlet UILabel *irr; @property (nonatomic,strong) IBOutlet UILabel *irrLabel; @property (nonatomic,strong) IBOutlet UILabel *com; @property (nonatomic,strong) IBOutlet UILabel *comLabel; @property (nonatomic,strong) IBOutlet UILabel *rating; @property (nonatomic,strong) IBOutlet UILabel *ratingLabel; @property (nonatomic,strong) IBOutlet UIImageView *ratingBkg; @property (nonatomic,strong) IBOutlet UILabel *function; @property (nonatomic,strong) IBOutlet UILabel *functionLabel; @property (nonatomic,strong) IBOutlet UILabel *description; @property (nonatomic,strong) IBOutlet UILabel *descriptionLabel; @property (nonatomic,strong) Ingredient *ingredient; @end <file_sep>// // IngredientsListViewController.h // SkinScope_v2 // // Created by <NAME> on 5/13/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Product.h" #import "Ingredient.h" @interface IngredientsListViewController : UIViewController @property (nonatomic,strong) IBOutlet UILabel *ingredientsLabel; @property (nonatomic,strong) IBOutlet UIBarButtonItem *filterButton; @property (nonatomic,strong) IBOutlet UITableView *ingredientsList; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; @property (nonatomic,assign) int pageIndex; @property (nonatomic,strong) NSString *filterRating; @property (nonatomic,strong) Product *product; @property (nonatomic,strong) NSArray *ingredients; @property (nonatomic,strong) Ingredient *ingredient; -(IBAction)showFilterModal; -(void)getIngredients; @end <file_sep>// // DropdownArrowView.h // SkinScope_v2 // // Created by <NAME> on 5/14/14. // Copyright (c) 2014 <NAME>. All rights reserved. // // Code for custom drop down from here: http://rogchap.com/2013/08/13/simple-ios-dropdown-control-using-uitextfield/ #import <UIKit/UIKit.h> @interface DropdownArrowView : UIView <UIActionSheetDelegate> +(DropdownArrowView*) default; @end <file_sep>// // ProductViewController.h // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Product.h" @interface ProductViewController : UIViewController @property (nonatomic,strong) IBOutlet UILabel *overviewLabel; @property (nonatomic,strong) IBOutlet UILabel *productName; @property (nonatomic,strong) IBOutlet UILabel *brandName; @property (nonatomic,strong) IBOutlet UILabel *rating; @property (nonatomic,strong) IBOutlet UILabel *ratingLabel; @property (nonatomic,strong) IBOutlet UIImageView *ratingBkg; @property (nonatomic,strong) IBOutlet UILabel *numIngredients; @property (nonatomic,strong) IBOutlet UILabel *ingredientsLabel; @property (nonatomic,strong) IBOutlet UILabel *numIrritants; @property (nonatomic,strong) IBOutlet UILabel *irritantsLabel; @property (nonatomic,strong) IBOutlet UILabel *numComedogenics; @property (nonatomic,strong) IBOutlet UILabel *comedogenicsLabel; @property (nonatomic,assign) int pageIndex; @property (nonatomic,strong) Product *product; @end <file_sep>// // AddProductViewController.h // SkinScope_v2 // // Created by <NAME> on 5/14/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "Dropdown.h" @interface AddProductViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate> @property (nonatomic,strong) IBOutlet UIScrollView *scrollView; @property (nonatomic,strong) IBOutlet UITextField *name; @property (nonatomic,strong) IBOutlet UITextField *brand; @property (nonatomic,strong) IBOutlet Dropdown *categoryDropdown; @property (nonatomic,strong) IBOutlet UITextField *upc; @property (nonatomic,strong) IBOutlet UITextField *firstIngredient; @property (nonatomic,strong) IBOutlet UIButton *addIngredientBtn; @property (nonatomic,strong) IBOutlet UIButton *submitBtn; @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *spinner; @property (nonatomic,strong) UIToolbar *keyboardButtonView; @property (nonatomic,strong) UITextField *activeField; @property (nonatomic,strong) UITextField *previousIngredient; @property (nonatomic,strong) NSArray *categoryOptions; @property (nonatomic,assign) int contentHeight; -(IBAction)doneClicked:(id)sender; -(IBAction)nextClicked:(id)sender; -(IBAction)prevClicked:(id)sender; -(IBAction)addTextField:(id)sender; -(IBAction)submitProduct:(id)sender; @end <file_sep>// // Review.m // SkinScope_v2 // // Created by <NAME> on 5/12/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "Review.h" @implementation Review @synthesize userID, user, skin_type, review; -(id)initWithUserID:(int)u_id user:(NSString *)r_user skin_type:(NSString *)r_skin_type review:(NSString *)r_review{ self = [super init]; // set properties if(self){ userID = u_id; user = r_user; skin_type = r_skin_type; review = r_review; } return self; } @end <file_sep>// // SkinScopeAppDelegate.h // SkinScope_v2 // // Created by <NAME> on 5/7/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import <RestKit/RestKit.h> #import "User.h" @interface SkinScopeAppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic,strong) UIWindow *window; @property (nonatomic,strong) RKObjectManager *objectManager; //RestKit Object Mappings @property (nonatomic,strong) RKObjectMapping *emptyMapping; @property (nonatomic,strong) RKObjectMapping *productSearchMapping; @property (nonatomic,strong) RKObjectMapping *productReviewsMapping; @property (nonatomic,strong) RKObjectMapping *productIngredientsMapping; //RestKit Response Descriptors @property (nonatomic,strong) RKResponseDescriptor *loginDescriptor; @property (nonatomic,strong) RKResponseDescriptor *productSearchDescriptor; @property (nonatomic,strong) RKResponseDescriptor *productReviewsDescriptor; @property (nonatomic,strong) RKResponseDescriptor *productIngredientsDescriptor; @property (nonatomic,strong) RKResponseDescriptor *addReviewDescriptor; @property (nonatomic,strong) RKResponseDescriptor *addProductDescriptor; @property (nonatomic,strong) RKResponseDescriptor *createAccountDescriptor; -(void)defineObjectMappings; -(void)defineResponseDesciptors; -(void)addDescriptors; @end <file_sep>// // CreateAccountViewController.m // SkinScope_v2 // // Created by <NAME> on 5/17/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import "CreateAccountViewController.h" #import <RestKit/RestKit.h> #import "SSKeychain.h" #import "User.h" @interface CreateAccountViewController () @end @implementation CreateAccountViewController @synthesize firstName, lastName, skinType, email, password, passwordConfirmation, submitBtn, scrollView, spinner, keyboardButtonView, activeField, skinTypeOptions; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad{ [super viewDidLoad]; //show the navigation bar [self.navigationController.navigationBar setHidden:NO]; //make navigation bar transparent [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; self.navigationController.navigationBar.shadowImage = [UIImage new]; self.navigationController.navigationBar.translucent = YES; //set nav bar title self.title = @"Create an Account"; //set background image UIImage *background = [UIImage imageNamed: @"background.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; [self.view insertSubview: imageView atIndex:0]; //define skin type options skinTypeOptions = @[@"Select Skin Type", @"Normal", @"Oily", @"Dry", @"Sensitive", @"Combination"]; //setup delegate and datasource for dropdown skinType.pickerDelegate = self; skinType.pickerDataSource = self; //create toolbar for keyboard keyboardButtonView = [[UIToolbar alloc] init]; keyboardButtonView.barStyle = UIBarStyleBlackTranslucent; keyboardButtonView.tintColor = [UIColor whiteColor]; [keyboardButtonView sizeToFit]; //create buttons for keyboard UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneClicked:)]; UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStyleBordered target:self action:@selector(nextClicked:)]; UIBarButtonItem *prevButton = [[UIBarButtonItem alloc] initWithTitle:@"Prev" style:UIBarButtonItemStyleBordered target:self action:@selector(prevClicked:)]; //create flex space for toolbar UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; //add toolbar to keyboard [keyboardButtonView setItems:[NSArray arrayWithObjects:prevButton, nextButton, flex, doneButton, nil]]; firstName.inputAccessoryView = keyboardButtonView; lastName.inputAccessoryView = keyboardButtonView; skinType.inputAccessoryView = keyboardButtonView; email.inputAccessoryView = keyboardButtonView; password.inputAccessoryView = keyboardButtonView; passwordConfirmation.inputAccessoryView = keyboardButtonView; //set fonts [firstName setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [lastName setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [skinType setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [email setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [password setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; [passwordConfirmation setFont:[UIFont fontWithName:@"ProximaNova-Regular" size:16]]; submitBtn.titleLabel.font = [UIFont fontWithName:@"ProximaNova-Bold" size:24]; //set fonts for toolbar buttons [doneButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ProximaNova-Bold" size:16], NSFontAttributeName,nil] forState:UIControlStateNormal]; [nextButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ProximaNova-Bold" size:16], NSFontAttributeName,nil] forState:UIControlStateNormal]; [prevButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"ProximaNova-Bold" size:16], NSFontAttributeName,nil] forState:UIControlStateNormal]; //change border color of text fields firstName.layer.borderColor=[[UIColor whiteColor]CGColor]; firstName.layer.borderWidth= 1.0f; lastName.layer.borderColor=[[UIColor whiteColor]CGColor]; lastName.layer.borderWidth= 1.0f; skinType.layer.borderColor=[[UIColor whiteColor]CGColor]; skinType.layer.borderWidth= 1.0f; email.layer.borderColor=[[UIColor whiteColor]CGColor]; email.layer.borderWidth= 1.0f; password.layer.borderColor=[[UIColor whiteColor]CGColor]; password.layer.borderWidth= 1.0f; passwordConfirmation.layer.borderColor=[[UIColor whiteColor]CGColor]; passwordConfirmation.layer.borderWidth= 1.0f; //add padding to left side of text fields firstName.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); lastName.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); skinType.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); email.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); password.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); passwordConfirmation.layer.sublayerTransform = CATransform3DMakeTranslation(8, 0, 0); //set content size for scroll view //contentHeight = 300; [scrollView setContentSize:CGSizeMake(250, 303)]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark Text Field Functions //handles navigating between text fields and dismissing the keyboard - (BOOL)textFieldShouldReturn:(UITextField *)textField{ UIView *view = [self.view viewWithTag:textField.tag + 1]; if(!view){ [textField resignFirstResponder]; } else{ [view becomeFirstResponder]; } return YES; } - (void)textFieldDidBeginEditing:(UITextField *)textField{ //keep track of the active text field activeField = textField; } - (void)textFieldDidEndEditing:(UITextField *)textField{ //dismiss the keyboard [textField resignFirstResponder]; //unset the active text field activeField = nil; } //prevent user from typing in the skin type dropdown field - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if(textField == skinType){ return NO; } return YES; } //hide keyboard when user presses the "done" button -(IBAction)doneClicked:(id)sender{ [self.view endEditing:YES]; } //move to next field when user presses the "next" button -(IBAction)nextClicked:(id)sender{ UIView *view = [self.view viewWithTag:activeField.tag + 1]; //if no more text fields, end editing if(!view){ [self.view endEditing:YES]; } //move to next text field else{ [view becomeFirstResponder]; } } //move to previous when user presses the "prev" button -(IBAction)prevClicked:(id)sender{ UIView *view = [self.view viewWithTag:activeField.tag - 1]; //if no more text fields, end editing if(view.tag == 0){ [self.view endEditing:YES]; } //move to previous text field else{ [view becomeFirstResponder]; } } #pragma mark Picker View Functions -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ skinType.text = [skinTypeOptions objectAtIndex:row]; } -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ return 1; } -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ return skinTypeOptions.count; } -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ return [skinTypeOptions objectAtIndex:row]; } #pragma mark Keyboard Functions //register for keyboard notifications -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:Nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil]; } //scroll form up when keyboard is shown -(void)keyboardWasShown:(NSNotification *)notification{ //get keyboard size CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; //setup animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.25]; [UIView setAnimationBeginsFromCurrentState:YES]; //adjust the bottom content inset of scroll view UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 5, 0.0); scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; //animate [UIView commitAnimations]; } //move form back down when keyboard is hidden -(void)keyboardWasHidden:(NSNotification*)notification{ //setup animation [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.25]; [UIView setAnimationBeginsFromCurrentState:YES]; //adjust scroll view inset UIEdgeInsets contentInsets = UIEdgeInsetsZero; scrollView.contentInset = contentInsets; scrollView.scrollIndicatorInsets = contentInsets; //animate [UIView commitAnimations]; } #pragma mark API Call Functions -(IBAction)submitAccount:(id)sender{ //start activity indicator [spinner startAnimating]; //create post url NSString *createAccountURL = @"/api/users/create"; //create query params NSDictionary *queryParams = @{@"first_name": firstName.text, @"last_name": lastName.text, @"skin_type": skinType.text, @"email": email.text, @"password": <PASSWORD>, @"password_confirmation": <PASSWORD>}; //make the call [[RKObjectManager sharedManager] postObject:nil path:createAccountURL parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){ //stop activity indicator [spinner stopAnimating]; //save account information to keychain [SSKeychain setPassword:<PASSWORD> forService:@"SkinScope.com" account:email.text]; //setup user User *sharedUser = [User sharedUser]; [sharedUser setUsername:email.text]; [sharedUser setPassword:<PASSWORD>]; //loop through all uitextfields for (UIView *view in [scrollView subviews]) { if ([view isKindOfClass:[UITextField class]]) { //clear out all text fields UITextField *textField = (UITextField *)view; textField.text = @""; } } //display success message UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your account has been created. Click \"Okay\" to begin using the app." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [successAlert show]; //go to product search view controller [self pushSearchVC]; } failure:^(RKObjectRequestOperation *operation, NSError *error){ //get errors as JSON NSString *errors = [[error userInfo] objectForKey:NSLocalizedRecoverySuggestionErrorKey]; //convert JSON to dictionary NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:[errors dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil]; //create error message NSMutableString *errorMsg = [NSMutableString string]; //handles message for server errors if([JSON objectForKey:@"error"] != nil){ [errorMsg appendFormat:@"%@", [JSON objectForKey:@"error"]]; } //handles message for validation errors else{ //loop through dictionary to build error message [errorMsg appendString:@"Your account was not created for the following reasons: "]; for (NSString* key in [JSON allKeys]){ [errorMsg appendFormat:@"%@ ", [[JSON objectForKey:key] objectAtIndex:0]]; } } //stop activity indicator [spinner stopAnimating]; //display error message UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:errorMsg delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; [errorAlert show]; } ]; } #pragma mark Segue //segue to the product search view controller -(void)pushSearchVC{ [self performSegueWithIdentifier:@"pushSearchVC-B" sender:self]; } @end
7a038beb0d905a864da48773c44b83e9c9bc373f
[ "Markdown", "Ruby", "Objective-C" ]
41
Markdown
CarlaCrandall/SkinScope_iOS_App_v2
bfd7012314beb218b38be3d7ae0d8e9b2eeb9a51
5d6a0b053443324b3f0e2ec36a3c181f7b4913b6
refs/heads/master
<file_sep># Project-JustifyHtml bdkj
3eaefcd71ef768099e20eec9c1240e4c8bf54595
[ "Markdown" ]
1
Markdown
imabtiwari/Project-JustifyHtml
2383cc582186229d603c0f75d7a890404d58911c
c8c58e13d6dff822110d6739c6ee5df13f49c64c
refs/heads/master
<repo_name>FukushimaTakeshi/chrome_extensions<file_sep>/chronus_ex/js/content_script.js chrome.runtime.onMessage.addListener( function(msg, sender, sendResponse) { if (msg) { var start_list = OPERATION.document.getElementsByName('PeriodStart'); var end_list = OPERATION.document.getElementsByName('PeriodEnd'); var work_list = OPERATION.document.getElementsByName('WorkIDSelect'); var holiday_list = OPERATION.document.getElementsByName('HolidayIDSelect'); var cause_list = OPERATION.document.getElementsByName('Cause'); for (var i = 0, len = start_list.length; i < len-1; i++) { if (holiday_list[i].value == ' ') { start_list[i].value = msg.start; end_list[i].value = msg.end; work_list[i].value = msg.work; cause_list[i].value = msg.cause; } } sendResponse('input completed'); } } ); <file_sep>/career_ex/js/myscript.js document.getElementById('input').onclick = function() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, { lastName: document.getElementById('lastName').value, firstName: document.getElementById('firstName').value, lastNameKana: document.getElementById('lastNameKana').value, firstNameKana: document.getElementById('firstNameKana').value, tel: document.getElementById('tel').value, email: document.getElementById('email').value, emailConfirmation: document.getElementById('emailConfirmation').value, birthYear: document.getElementById('birthYear').value, birthMonth: document.getElementById('birthMonth').value, birthDay: document.getElementById('birthDay').value }, function(msg) { // console.log('response message:', msg); }); }); return false; } <file_sep>/chronus_ex/js/myscript.js document.getElementById('save').onclick = function() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, { start: document.getElementById('start').value, end: document.getElementById('end').value, work: document.getElementById('work').value, cause: document.getElementById('cause').value }, function(msg) { // console.log('response message:', msg); }); }); return false; } <file_sep>/career_ex/js/content_script.js chrome.runtime.onMessage.addListener( function(msg, sender, sendResponse) { if (msg) { document.getElementsByName('nmSei')[0].value = msg.lastName; document.getElementsByName('nmMei')[0].value = msg.firstName; document.getElementsByName('nmSeiKana')[0].value = msg.lastNameKana; document.getElementsByName('nmMeiKana')[0].value = msg.firstNameKana; document.getElementsByName('tel')[0].value = msg.tel; document.getElementsByName('email')[0].value = msg.email; document.getElementsByName('emailConfirm')[0].value = msg.emailConfirmation; document.getElementsByName('birthYear')[0].value = msg.birthYear; document.getElementsByName('birthMonth')[0].value = msg.birthMonth; document.getElementsByName('birthDay')[0].value = msg.birthDay; sendResponse('input completed'); } } );
6625bb3221df6f1e591f82add06680603efa7df5
[ "JavaScript" ]
4
JavaScript
FukushimaTakeshi/chrome_extensions
800e915657bc3e455660785c37b9965428d7c579
90e9c2936f6e42514c6a0dc2800477a06054f395
refs/heads/main
<file_sep>import axios from 'axios' // const baseURL = 'https://60deefccabbdd9001722d12d.mockapi.io/shop/products' // const baseURL = 'https://jsonplaceholder.typicode.com/users' const baseURL = 'https://mocki.io/v1/9cf0f7a3-2ecc-4f32-ac23-08e6ab61dbb6' const getAllProduct = () => { const res = axios.get(baseURL).then((res) => res.data) return res } const addProduct = (contactObj) => { const res = axios.post(baseURL, contactObj) return res.then((res) => res.data) } const deleteProduct = (id) => { const res = axios.delete(`${baseURL}/${id}`) return res.then((response) => response.data) } const updateProduct = (id, updatedData) => { const res = axios.put(`${baseURL}/${id}`, updatedData) return res.then((response) => response.data) } const shopSevice = { getAllProduct, addProduct, deleteProduct, updateProduct, } export default shopSevice <file_sep>import React, { useState, useEffect } from "react"; import TOP_BANNER from "../resources/Home/banner-top.svg"; import SEARCH_ICON from "../resources/Home/search-icon.svg"; import ARROW_RIGHT from "../resources/Home/arrow-right.svg"; import PLUS_ICON from "../resources/Home/add-icon.svg"; import AliceCarousel, { Classnames } from "react-alice-carousel"; import CART_ICON from "../resources/Home/cart-icon.svg"; import { Link } from "react-router-dom"; import "react-alice-carousel/lib/alice-carousel.css"; import shopService from "../service/shopService"; import "../styles/home.css"; const Home = () => { const [products, setProducts] = useState(null); const [cart, setCart] = useState([]); const handleClick = (product) => { const itemInCart = cart.concat(product); setCart(itemInCart); console.log(product); console.log(itemInCart); }; const responsive_collections = { 0: { items: 1 }, 568: { items: 2 }, 1024: { items: 3 }, }; const responsive_featured = { 0: { items: 2 }, 568: { items: 3 }, 1024: { items: 5 }, }; const collection_proucts = products && products.map((product, index = 0) => ( <div className="item" data-value={index++}> <div className="row m-2"> <div className="m-3"> <div className="card border-0 product-card text-left p-2"> <img className="" alt="product image" src={product.image} /> <div className="card-body"> <p className="text-title">{product.name}</p> <p className="text-description">{product.description}</p> <p className="text-yellow text-description"> <strong>Shop Now </strong> <img className="arrow-right" src={ARROW_RIGHT} /> </p> </div> </div> </div> </div> </div> )); const featured_products = products && products.map((product, index = 0) => ( <div className="item m-2" data-value={index++}> <div className="my-5 py-2"> <div className="card product-card-bg border-0 p-3"> <div className="card-block"> <img className="img-fluid" src={product.image} /> {/* <h4 className='card-title'>{product.name}</h4> */} <h6 className="text-title text-muted mt-2">{product.name}</h6> <p className="p-y-1">Designer</p> <p className="text-dark d-flex justify-content-between align-items-center mt-2"> <div className="text-dark"> <strong>${product.price}</strong> </div> <div onClick={() => { handleClick(product); }} className="" > <img className="arrow-right" src={PLUS_ICON} /> </div> </p> </div> </div> </div> </div> )); useEffect(() => { shopService.getAllProduct().then((products) => { setProducts(products); }); }, []); const CartStyle = { border: "1px solid #000", borderRadius: "50%", width: "3.5rem", margin: 0, top: "auto", right: 20, bottom: 20, left: "auto", position: "fixed", zIndex: "999", }; console.log("products :", products); return ( <> <section className="section-home-1"> <Link to="/cart"> <img src={CART_ICON} style={CartStyle} /> <div className="cart-count">{cart.length}</div> </Link> <div className="row m-0 top-container d-flex"> <div className="col-12 p-0"> <img src={TOP_BANNER} className="img-fluid banner" alt="banner" /> </div> <div className="input-group search-container m-4 rounded border"> <span className="input-group-text border-0"> <img src={SEARCH_ICON} className="img-fluid" alt="search" /> </span> <input type="text" className="form-control border-0" placeholder="Search Product" /> </div> </div> <div className="store-wrapper m-lg-1 p-lg-1 p-md-0 p-sm-0 p-xs-0"> <div> {products ? ( <AliceCarousel mouseTracking items={collection_proucts} responsive={responsive_collections} controlsStrategy="alternate" // autoPlay autoPlayStrategy="none" // autoPlayInterval={1000} // animationDuration={1000} animationType="fadeout" infinite disableDotsControls={true} disableButtonsControls={true} /> ) : ( <div className="d-flex justify-content-center m-5 p-4"> <img style={{ width: "3rem" }} src="https://icon-library.com/images/loading-icon-transparent-background/loading-icon-transparent-background-25.jpg" /> </div> )} </div> <div> <div className="m-4 p-0"> <div className="d-flex justify-content-between"> <div className="display-4"> <h4> <strong>featured Products</strong> </h4> </div> <div className=""> <h6>See All</h6> </div> </div> </div> </div> {products ? ( <AliceCarousel mouseTracking items={featured_products} responsive={responsive_featured} controlsStrategy="alternate" // autoPlay autoPlayControls={false} infinite={true} renderKey={false} // duration={2000} disableDotsControls={true} disableButtonsControls={true} // autoPlayInterval={2000} infinite /> ) : ( <div className="d-flex justify-content-center m-5 p-4"> <img style={{ width: "3rem" }} src="https://icon-library.com/images/loading-icon-transparent-background/loading-icon-transparent-background-25.jpg" /> </div> )} </div> <div className="container parent p-0 m-0"> <div className="row bottom-container child"> {/* {products.map((product) => ( <div className='col-12 col-lg-3 col-md-4'> <div className='card p-4'> <div className='card-block'> <h4 className='card-title'>{product.name}</h4> <img className='img-fluid' src={product.image} /> <h6 className='card-subtitle text-muted'>{product.name}</h6> <p className='card-text p-y-1'> Some quick example text to build on the card title. </p> <a href='#' className='card-link'> {product.price} </a> <a href='#' className='card-link'> <img className='arrow-right' src={PLUS_ICON} /> </a> </div> </div> </div> ))} */} </div> </div> </section> </> ); }; export default Home;
bb2dd7800303909a36f8e0b6f521c5850286c3dd
[ "JavaScript" ]
2
JavaScript
Code-Recursion/web-store
aec430d799284340de7e23495d4bccf8cd6949ae
eef3eca3403ad33a2cb5e40d47f8bd83edeeb0f3
refs/heads/master
<file_sep>using DMS.SharedKernel.Infrastructure.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace DMS.SharedKernel.Infrastructure.Data { public interface IRepository<T, TId> : IReadOnlyRepository<T, TId> where T : Entity<TId>, IAggregateRoot { void Save(T obj); void Update(T obj); void Delete(T obj); void Delete(Expression<Func<T, bool>> where); } } <file_sep>using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Security.Policy; using DMS.Books.Models.PocoModels; using DMS.SharedKernel.Infrastructure.Data; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.Books.Repositories { public class BookDbContext : BaseDbContext<BookDbContext>, IBookDbContext { public BookDbContext() { } public IDbSet<BookCategory> BookCategories { get; set; } public IDbSet<Book> Books { get; set; } public void SetModified<T, TId>(T entity) where T : Entity<TId>, IAggregateRoot { Entry(entity).State = EntityState.Modified; } public void SetAdd<T, TId>(T entity) where T : Entity<TId>, IAggregateRoot { Entry(entity).State = EntityState.Added; } public IDbSet<T> DbSet<T,TId>() where T:Entity<TId>,IAggregateRoot { return Set<T>(); } public IEnumerable<TClass> ExecuteQuery<TClass>(string query) where TClass : class, new() { return Database.SqlQuery<TClass>(query); } public void ExecuteCommand(string query, params object[] parameters) { Database.ExecuteSqlCommand(query, parameters); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // modelBuilder.Conventions.Add<PluralizingEntitySetNameConvention>(); modelBuilder.Entity<Book>() .HasRequired(m => m.BookCategory) .WithMany(t => t.Books) .HasForeignKey(m => m.BookCategoryId) .WillCascadeOnDelete(true); //base.OnModelCreating(modelBuilder); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class BookByAuthorResponse { public IEnumerable<BookSummaryView> Books { get; set; } public IEnumerable<BookCategoryView> BookCategoryViews { get; set; } public int BookCount { get; set; } public List<string> InitialCharacters { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.SharedKernel.Infrastructure.Data { public interface IReadOnlyRepository<T, TId> : IDisposable where T : Entity<TId>, IAggregateRoot { T GetById(TId id); T Get(Expression<Func<T, bool>> where); IEnumerable<T> GetAll(); IEnumerable<T> GetMany(Expression<Func<T, bool>> where); //Execute Stored Procedure IEnumerable<TClass> ExecWithStoreProcedure<TClass>(string query) where TClass:class ,new(); void ExecuteWithStoreProcedure(string query, params object[] parameters); } } <file_sep>using System.Data.Entity; using System.Security.Policy; using DMS.Books.Models.PocoModels; using DMS.SharedKernel.Infrastructure.Data; namespace DMS.Books.Repositories { public interface IBookDbContext:IDbContext { IDbSet<BookCategory> BookCategories { get; set; } IDbSet<Book> Books { get; set; } } } <file_sep>using System; namespace DMS.SharedKernel.Infrastructure.CacheStorage { public enum CacheKeys { Product } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Repositories { public class BookUnitOfWork : IBookUnitOfWork { private readonly IBookDbContext _context; public BookUnitOfWork() { _context = new BookDbContext(); } public BookUnitOfWork(IBookDbContext context) { _context = context; } public int Commit() { return _context.SaveChanges(); } public IBookDbContext Context { get { return _context; } } public void Dispose() { _context.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.DataInitializer.Models; namespace DMS.DataInitializer { public class DmsContext : DbContext { public DmsContext() : base("name=DmsContext") { } public DbSet<BookCategory> BookCategories { get; set; } public DbSet<Book> Books { get; set; } //Context Mapping protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); // Configure Id as PK modelBuilder.Entity<BookCategory>() .HasKey(e => e.Id); modelBuilder.Entity<Book>() .HasKey(e => e.Id); // Configure BookCategoryId as FK for Book modelBuilder.Entity<Book>() .HasRequired<BookCategory>(s => s.BookCategory) .WithMany(s => s.Books) .HasForeignKey(s => s.BookCategoryId) .WillCascadeOnDelete(true); base.OnModelCreating(modelBuilder); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using DMS.Books.Services.Interfaces; using DMS.Books.Services.Messaging; using DMS.Books.Services.Viewmodels; using DMS.Controllers.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace DMS.Controllers.Test { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { var facade = new Mock<IBookFacade>(); var books = new GetAllBookResponse(); facade.Setup(x => x.GetAllBooks()).Returns(books); var controller = new BookController(facade.Object); var response = (ViewResult) controller.Index(); facade.Verify(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using DMS.Books.Services.Interfaces; namespace DMS.Controllers.Controllers { public class BookController:Controller { private readonly IBookFacade _bookFacade; public BookController(IBookFacade bookFacade) { _bookFacade = bookFacade; } public ActionResult Index() { var books = _bookFacade.GetAllBooks(); return View(books); } } } <file_sep>namespace DMS.Books.Services.Messaging { public class SubjectRequest { public int Take { get; set; } public int Skip { get; set; } public string SearchString { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Viewmodels { public class BookDetailsView { public int Id { get; set; } public string BookNameBengali { get; set; } public string BookNameEnglish { get; set; } public int CategoryId { get; set; } public string CategoryNameBengali { get; set; } public string CategoryNameEnglish { get; set; } public decimal Price { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Messaging { public class BookByAuthorRequest { public int AuthorId { get; set; } public int BookSkip { get; set; } public int BookTake { get; set; } public string BookSearchString { get; set; } public string CategorySearchString { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.SharedKernel.Infrastructure.Enums { public enum Currency { Taka, Dollar, Euro } } <file_sep>namespace DMS.DataInitializer.Models { public class Book { public Book() { } public int Id { get; set; } public string TitleE { get; set; } public string TitleB { get; set; } public int BookCategoryId { get; set; } public virtual BookCategory BookCategory { get; set; } public int TotalPage { get; set; } public byte[] CoverPage { get; set; } public decimal Price { get; set; } public System.DateTime PublishedDate { get; set; } public string Description { get; set; } public int IsActive { get; set; } public int Creator { get; set; } public System.DateTime CreationDate { get; set; } public int Modifier { get; set; } public System.DateTime ModificationDate { get; set; } public string Remarks { get; set; } public string IsbnNumber { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Exceptions { public class InvalidBookException:Exception { public InvalidBookException(string message) : base(message) { } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.SharedKernel.Infrastructure.Data { public interface IDbContext: IDisposable { int SaveChanges(); void SetModified<T, TId>(T entity) where T : Entity<TId>, IAggregateRoot ; void SetAdd<T, TId>(T entity) where T : Entity<TId>, IAggregateRoot; IDbSet<T> DbSet<T, TId>() where T : Entity<TId>, IAggregateRoot; IEnumerable<TClass> ExecuteQuery<TClass>(string query) where TClass : class, new(); void ExecuteCommand(string query, params object[] parameters); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class CategoryResponse { public CategoryResponse() { Categories = new List<BookCategoryView>(); } public IEnumerable<BookCategoryView> Categories { get; set; } } } <file_sep>using System; namespace DMS.SharedKernel.Infrastructure.CookieStorage { public interface ICookieStorageService { void SaveCookie(string key, string value, DateTime expires); string RetrieveCookie(string key); } } <file_sep>using System.Linq; using DMS.Books.Models.PocoModels; using DMS.SharedKernel.Infrastructure.FakeForTests; namespace DMS.Books.Fakes { public class FakeCategoryDbSet : FakeDbSet<BookCategory, int> { public override BookCategory Find(params object[] keyValues) { var keyValue = (int)keyValues.FirstOrDefault(); return this.SingleOrDefault(p => p.Id == keyValue); } } } <file_sep>using System; namespace DMS.SharedKernel.Infrastructure.CacheStorage { public interface ICacheStorage { void Remove(string key); void Store(string key, object data); void Store(string key, object data, DateTime expireTime); T Retrieve<T>(string storageKey); void RemoveRuntime(string key); void StoreRuntime(string key, object data); void StoreRuntime(string key, object data, DateTime expireTime); T RetrieveRuntime<T>(string storageKey); } } <file_sep> namespace DMS.Books.Services.Messaging { public class DeleteBookRequest { public int Id { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Models.PocoModels; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.Books.Services.Validations { public class BookValidation { public static void BookValidationLogic(Book book) { Guard.ForNullOrEmpty(book.TitleB, "Bengali Name"); Guard.ForNullOrEmpty(book.TitleE, "English Name"); Guard.ForLessEqualZero(book.BookCategoryId,"Category"); Guard.ForLessEqualZeroDecimal(book.Price, "Price"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using DMS.Books.Fakes; using DMS.Books.Models.PocoModels; using DMS.Books.Repositories; using DMS.SharedKernel.Infrastructure.Querying; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DMS.Books.FakeTests { [TestClass] public class BookRepositoryFakeTest { //Initialization private IBookDbContext _context; private IBookRepository _bookRepository; private IBookUnitOfWork _bookUnitOfWork; private void Setup() { _context = new FakeBookContext(); _context.Books.Add(new Book { Id = 1, TitleB = "Bengali Book1", TitleE = "Englishi Book1", IsActive = 1, Price = 1, CreationDate = DateTime.Today, PublishedDate = DateTime.Today, }); _context.Books.Add(new Book { Id = 2, TitleB = "Bengali Book2", TitleE = "Englishi Book2", IsActive = 1, Price = 1, CreationDate = DateTime.Today, PublishedDate = DateTime.Today, }); _context.Books.Add(new Book { Id = 3, TitleB = "Bengali Book3", TitleE = "Englishi Book3", IsActive = 1, Price = 1, CreationDate = DateTime.Today, PublishedDate = DateTime.Today, }); _bookUnitOfWork = new BookUnitOfWork(_context); _bookRepository = new BookRepository(_bookUnitOfWork); } [TestMethod] public void GetAll_Test() { //-- Arrange Setup(); //-- Act var response = _bookRepository.GetAll(); //-- Assert Assert.IsInstanceOfType(response, typeof(IEnumerable<Book>)); var enumerable = response as Book[] ?? response.ToArray(); Assert.IsTrue(enumerable.Any()); Assert.AreEqual("Bengali Book1", enumerable.ElementAt(0).TitleB); } [TestMethod] public void GetById_Test() { Setup(); const int id = 1; var response = _bookRepository.GetById(id); Assert.IsNotNull(response); Assert.IsInstanceOfType(response, typeof(Book)); Assert.AreEqual("Bengali Book1", response.TitleB); } [TestMethod] public void Get_Test() { Setup(); var where = PredicateBuilder.Create<Book>(x => x.Id == 1); var response = _bookRepository.Get(where); Assert.IsNotNull(response); Assert.IsInstanceOfType(response, typeof(Book)); Assert.AreEqual("Bengali Book1", response.TitleB); } [TestMethod] public void GetMany_Test() { Setup(); var where = PredicateBuilder.Create<Book>(x => x.Id == 1); var response = _bookRepository.Get(where); Assert.IsNotNull(response); Assert.IsInstanceOfType(response, typeof(Book)); Assert.AreEqual("Bengali Book1", response.TitleB); } } } <file_sep>@model IEnumerable<DMS.Books.Services.Viewmodels.BookDetailsView> @{ ViewBag.Title = "Indexx"; } <h2>Indexx</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.BookNameBengali) </th> <th> @Html.DisplayNameFor(model => model.BookNameEnglish) </th> <th> @Html.DisplayNameFor(model => model.CategoryId) </th> <th> @Html.DisplayNameFor(model => model.CategoryNameBengali) </th> <th> @Html.DisplayNameFor(model => model.CategoryNameEnglish) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.BookNameBengali) </td> <td> @Html.DisplayFor(modelItem => item.BookNameEnglish) </td> <td> @Html.DisplayFor(modelItem => item.CategoryId) </td> <td> @Html.DisplayFor(modelItem => item.CategoryNameBengali) </td> <td> @Html.DisplayFor(modelItem => item.CategoryNameEnglish) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </table> <file_sep>using System; using System.Globalization; using System.IO; using System.Linq; namespace DMS.SharedKernel.Infrastructure.Domain { public class Guard { public static void ForLessEqualZero(int value, string parameterName) { if (value <= 0) { throw new ArgumentOutOfRangeException(parameterName); } } public static void ForInteger(string value, string parameterName) { int number; if (!int.TryParse(value, out number)) { throw new InvalidDataException(parameterName); } } public static void ForDecimal(string value, string parameterName) { decimal number; if (!decimal.TryParse(value, out number)) { throw new InvalidDataException(parameterName); } } public static void ForLessEqualZeroDecimal(decimal value, string parameterName) { if (value <= 0) { throw new ArgumentOutOfRangeException(parameterName); } } public static void ForPrecedesDate(DateTime value, DateTime dateToPrecede, string parameterName) { if (value >= dateToPrecede) { throw new ArgumentOutOfRangeException(parameterName); } } public static void ForNullOrEmpty(string value, string parameterName) { if (String.IsNullOrEmpty(value)) { throw new ArgumentNullException(parameterName); } } } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.Books.Models.PocoModels { [Table("Book")] public class Book:Entity<int>,IAggregateRoot { public Book() { } public string TitleE { get; set; } public string TitleB { get; set; } public int BookCategoryId { get; set; } public virtual BookCategory BookCategory { get; set; } public int TotalPage { get; set; } public byte[] CoverPage { get; set; } public decimal Price { get; set; } public DateTime PublishedDate { get; set; } public string Description { get; set; } public int IsActive { get; set; } public int Creator { get; set; } public DateTime CreationDate { get; set; } public int Modifier { get; set; } public DateTime ModificationDate { get; set; } public string Remarks { get; set; } public string IsbnNumber { get; set; } } } <file_sep>using System; using System.Data.Entity; using System.Linq; using DMS.DataInitializer; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DatabaseInitializer.Test { [TestClass] public class UnitTest1 { [TestMethod] //Create Database from here because all the fully qualified domain model has been defined //inside DMS.DataInitializer and all fully qualified dbset hsa been defined DmsContext public void CanCreateDatabase() { Database.SetInitializer(new DropCreateDatabaseAlways<DmsContext>()); using (var databaseContext = new DmsContext()) { Assert.AreEqual(0, databaseContext.Books.Count()); } } } } <file_sep>using System.Data.Entity; namespace DMS.SharedKernel.Infrastructure.Data { public class BaseDbContext<TContext> : DbContext where TContext : DbContext { static BaseDbContext() { Database.SetInitializer<TContext>(null); } protected BaseDbContext() : base("name=DmsContext") { } } } <file_sep>using System; using System.Collections.Generic; using DMS.Books.Models.PocoModels; namespace DMS.Books.Repositories { public class CategoryRepository:BaseBookRepository<BookCategory,int>,ICategoryRepository { public CategoryRepository(IBookUnitOfWork unitOfWork) : base(unitOfWork) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Messaging { public class HomePageRequest { public int TakeBook { get; set; } } } <file_sep>using System; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class CreateBookRequest { public CreateBookRequest() { Create = new CreateBookView(); } public CreateBookView Create { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Viewmodels { public class CreateBookView { public int Id { get; set; } public string TitleE { get; set; } public string TitleB { get; set; } public int BookCategoryId { get; set; } public int TotalPage { get; set; } public byte[] CoverPage { get; set; } public decimal Price { get; set; } public DateTime PublishedDate { get; set; } public string Description { get; set; } public int IsActive { get; set; } public string Remarks { get; set; } public string IsbnNumber { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using DMS.Books.Models.PocoModels; using DMS.Books.Repositories; using DMS.Books.Services.Exceptions; using DMS.Books.Services.Interfaces; using DMS.Books.Services.Messaging; using DMS.Books.Services.Viewmodels; using DMS.SharedKernel.Infrastructure.Domain; using DMS.SharedKernel.Infrastructure.Logging; namespace DMS.Books.Services.Implementations { public class BookFacade:IBookFacade { private readonly IBookRepository _bookRepository; private readonly ICategoryRepository _category; private readonly IBookUnitOfWork _bookUnitOfWork; public BookFacade(IBookRepository bookRepository, ICategoryRepository category, IBookUnitOfWork bookUnitOfWork) { _bookRepository = bookRepository; _category = category; _bookUnitOfWork = bookUnitOfWork; } private IEnumerable<BookSummaryView> GetTopRecent(int take) { return _bookRepository.GetAll().Where(x => x.IsActive == 1) .OrderByDescending(x => x.Id) .Take(take) .Select(b => new BookSummaryView { Id = b.Id, TitleBengali = b.TitleB, TitleEnglish = b.TitleE, PriceBdt = b.Price }); } private IEnumerable<BookSummaryView> GetTopDownloaded(int take) { var query = _bookRepository.GetAll().Where(x => x.IsActive == 1).Select(b => new { Id = b.Id, TitleBengali = b.TitleB, TitleEnglish = b.TitleE, PriceBdt = b.Price }); return query.OrderByDescending(x => x.PriceBdt).Take(take).Select(b => new BookSummaryView { Id = b.Id, TitleBengali = b.TitleBengali, TitleEnglish = b.TitleEnglish, PriceBdt = b.PriceBdt }); } private IEnumerable<BookSummaryView> GetTopRated(int take) { return _bookRepository.GetAll().Where(x => x.IsActive == 1).Take(take).Select(b => new BookSummaryView { Id = b.Id, TitleBengali = b.TitleB, TitleEnglish = b.TitleE, PriceBdt = b.Price }).OrderByDescending(y => y.PriceBdt); } /// <summary> /// Get books for Home page /// </summary> /// <param name="request"></param> /// <returns></returns> public HomePageResponse GetHomePageBooks(HomePageRequest request) { HomePageResponse response = new HomePageResponse(); response.TopRecent = this.GetTopRecent(request.TakeBook); response.TopDownloaded = this.GetTopDownloaded(request.TakeBook); response.TopRated = this.GetTopRated(request.TakeBook); return response; } /// <summary> /// Get All books order by published date descending /// </summary> /// <param name="request"></param> /// <returns></returns> public BookSummaryResponse GetBookSummaries(BookSummaryRequest request) { BookSummaryResponse response = new BookSummaryResponse(); response.BookSummaries = _bookRepository.GetAll().Where(x => x.IsActive == 1) .OrderByDescending(x => x.Id) .Select(b => new BookSummaryView { Id = b.Id, TitleBengali = b.TitleB, TitleEnglish = b.TitleE, PriceBdt = b.Price }); var bookSummaryViews = response.BookSummaries as BookSummaryView[] ?? response.BookSummaries.ToArray(); response.IniatialCharacters = bookSummaryViews.Select(summary => summary.TitleBengali.ToArray()[0].ToString()).ToList(); response.Count = bookSummaryViews.Count(); if (!string.IsNullOrEmpty(request.SearchString)) bookSummaryViews = bookSummaryViews.Where(x => x.TitleBengali.StartsWith(request.SearchString)).ToArray(); response.BookSummaries = bookSummaryViews.Skip(request.Skip).Take(request.Take); return response; } /// <summary> /// Get All Subjects /// </summary> /// <returns></returns> public CategoryResponse GetAllSubjects() { CategoryResponse response = new CategoryResponse { Categories = _category.GetAll() .Where(x => x.IsActive == 1) .OrderBy(y => y.NameB) .Select(b => new BookCategoryView { Id = b.Id, CategoryNameBengali = b.NameB, CategoryNameEnglish = b.NameE }) }; return response; } public GetAllBookResponse GetAllBooks() { var bookDetailsView = _bookRepository.GetAll().Select(x=>new BookDetailsView { Id = x.Id, BookNameBengali = x.TitleB, BookNameEnglish = x.TitleE, CategoryNameBengali = x.BookCategory.NameB, CategoryNameEnglish = x.BookCategory.NameE, CategoryId = x.BookCategoryId, Price = x.Price }); var response = new GetAllBookResponse {BookDetails = bookDetailsView}; return response; } public ResponseBase SaveBook(CreateBookRequest request) { var response = new ResponseBase(); try { var book = new Book { BookCategoryId = request.Create.BookCategoryId, CoverPage = request.Create.CoverPage, CreationDate = DateTime.Now, Description = request.Create.Description, IsActive = request.Create.IsActive, IsbnNumber = request.Create.IsbnNumber, Price = request.Create.Price, PublishedDate = request.Create.PublishedDate, Remarks = request.Create.Remarks, TitleB = request.Create.TitleB, TitleE = request.Create.TitleE, TotalPage = request.Create.TotalPage }; _bookRepository.Save(book); _bookUnitOfWork.Commit(); response.TransactionMessage = "Data Saved Successfully"; response.TransactionStatus = true; } catch (InvalidBookException ex) { response.TransactionMessage = "Failed To Save Data"; response.TransactionStatus = false; LoggingFactory.GetLogger().Log(ex.Message.ToString()); } return response; } public ResponseBase UpdateBook(CreateBookRequest request) { var response = new ResponseBase(); try { var book = _bookRepository.GetById(request.Create.Id); book.BookCategoryId = request.Create.BookCategoryId; book.CoverPage = request.Create.CoverPage; book.CreationDate = DateTime.Now; book.Description = request.Create.Description; book.IsActive = request.Create.IsActive; book.IsbnNumber = request.Create.IsbnNumber; book.Price = request.Create.Price; book.PublishedDate = request.Create.PublishedDate; book.Remarks = request.Create.Remarks; book.TitleB = request.Create.TitleB; book.TitleE = request.Create.TitleE; book.TotalPage = request.Create.TotalPage; _bookRepository.Update(book); _bookUnitOfWork.Commit(); response.TransactionMessage = "Data Updated Successfully"; response.TransactionStatus = true; } catch (InvalidBookException ex) { response.TransactionMessage = "Failed to Update Data"; response.TransactionStatus = false; LoggingFactory.GetLogger().Log(ex.Message.ToString()); } return response; } public ResponseBase DeleteBook(DeleteBookRequest request) { var response = new ResponseBase(); try { var book = _bookRepository.GetById(request.Id); _bookRepository.Delete(book); _bookUnitOfWork.Commit(); response.TransactionMessage = "Book deleted Successfully"; response.TransactionStatus = true; } catch (InvalidBookException ex) { response.TransactionMessage = "Book deletion failed"; response.TransactionStatus = false; LoggingFactory.GetLogger().Log(ex.Message.ToString()); } return response; } } } <file_sep>using System; using System.Security.Cryptography; namespace DMS.SharedKernel.Infrastructure.Encrypt { public class EncryptionDecryption { /// <summary> /// Encrypt The Value /// </summary> /// <param name="argument"></param> /// <returns></returns> //public static string Encrypt(string argument) { // byte[] strBytes = System.Text.Encoding.Unicode.GetBytes(argument); // string encryptString = Convert.ToBase64String(strBytes); // return encryptString; //} public static string EncryptString(string Message) { string Passphrase = <PASSWORD>"; byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the encoder TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] DataToEncrypt = UTF8.GetBytes(Message); // Step 5. Attempt to encrypt the string try { ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor(); Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Return the encrypted string as a base64 encoded string return Convert.ToBase64String(Results); } /// <summary> /// Decrypt The Value /// </summary> /// <param name="argument"></param> /// <returns></returns> //public static string Decrypt(string argument) { // byte[] strByteData = Convert.FromBase64String(argument); // string originalString = System.Text.Encoding.Unicode.GetString(strByteData); // return originalString; //} public static string DecryptString(string Message) { string Passphrase = <PASSWORD>"; byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the decoder TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] DataToDecrypt = Convert.FromBase64String(Message); // Step 5. Attempt to decrypt the string try { ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor(); Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Return the decrypted string in UTF8 format return UTF8.GetString(Results); } } } <file_sep>using System; using System.Collections.Generic; using DMS.Books.Models.PocoModels; namespace DMS.Books.Repositories { public class BookRepository:BaseBookRepository<Book,int>,IBookRepository { public BookRepository(IBookUnitOfWork unitOfWork) : base(unitOfWork) { } } } <file_sep>using DMS.Books.Models.PocoModels; using DMS.SharedKernel.Infrastructure.Data; namespace DMS.Books.Repositories { public interface ICategoryRepository : IRepository<BookCategory, int> { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class HomePageResponse { public HomePageResponse() { TopRecent = new List<BookSummaryView>(); TopDownloaded = new List<BookSummaryView>(); TopRated = new List<BookSummaryView>(); } public IEnumerable<BookSummaryView> TopRecent { get; set; } public IEnumerable<BookSummaryView> TopDownloaded { get; set; } public IEnumerable<BookSummaryView> TopRated { get; set; } } } <file_sep>using DMS.Books.Repositories; using DMS.Books.Services.Implementations; using DMS.Books.Services.Interfaces; using DMS.SharedKernel.Infrastructure.Configuration; using DMS.SharedKernel.Infrastructure.EmailService; using DMS.SharedKernel.Infrastructure.Logging; using StructureMap; using StructureMap.Configuration.DSL; namespace DMS.Web { public class Bootstrap { public static void ConfigureDependencies() { ObjectFactory.Initialize(x => { x.AddRegistry<ControllerRegistry>(); }); } public class ControllerRegistry : Registry { public ControllerRegistry() { For<IBookDbContext>().Use<BookDbContext>(); // Repositories Configure For<IBookRepository>().Use<BookRepository>(); For<ICategoryRepository>().Use<CategoryRepository>(); //Unit of Work configure For<IBookUnitOfWork>().Use<BookUnitOfWork>(); // Services configure For<IBookFacade>().Use<BookFacade>(); // Application Settings configure For<IApplicationSettings>().Use <WebConfigApplicationSettings>(); // Logger configure For<ILogger>().Use<Log4NetAdapter>(); // Email Service configure For<IEmailService>().Use<SMTPService>(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class GetAllBookResponse { public GetAllBookResponse() { BookDetails = new List<BookDetailsView>(); } public IEnumerable<BookDetailsView> BookDetails { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.SharedKernel.Infrastructure.Domain { public static class StringSplitter { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.SharedKernel.Infrastructure.Data { public interface IUnitOfWork<TDbContext>:IDisposable where TDbContext: IDbContext { int Commit(); TDbContext Context { get; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Messaging; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Interfaces { public interface IBookFacade { HomePageResponse GetHomePageBooks(HomePageRequest request); BookSummaryResponse GetBookSummaries(BookSummaryRequest request); CategoryResponse GetAllSubjects(); GetAllBookResponse GetAllBooks(); ResponseBase SaveBook(CreateBookRequest request); ResponseBase UpdateBook(CreateBookRequest request); ResponseBase DeleteBook(DeleteBookRequest request); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Viewmodels { public class BookSummaryView { public int Id { get; set; } public string TitleBengali { get; set; } public string TitleEnglish { get; set; } public decimal PriceBdt { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class BookSummaryResponse { public IEnumerable<BookSummaryView> BookSummaries { get; set; } public IEnumerable<String> IniatialCharacters { get; set; } public int Count { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using DMS.SharedKernel.Infrastructure.Data; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.Books.Repositories { public abstract class BaseBookRepository<T,TId>:IRepository<T,TId> where T:Entity<TId>, IAggregateRoot { protected readonly IBookDbContext BookDbContext; private readonly IDbSet<T> _dbSet; protected BaseBookRepository(IBookUnitOfWork unitOfWork) { //For Actual // BookDbContext = unitOfWork.Context as BookDbContext; //For Test BookDbContext = unitOfWork.Context; if (BookDbContext == null) throw new NullReferenceException("Book DbContext is null"); _dbSet = BookDbContext.DbSet<T, TId>(); } public void Save(T obj) { _dbSet.Add(obj); BookDbContext.SetAdd<T, TId>(obj); } public void Update(T obj) { _dbSet.Attach(obj); BookDbContext.SetModified<T, TId>(obj); } public void Delete(T obj) { _dbSet.Remove(obj); } public void Delete(Expression<Func<T, bool>> where) { var entities = _dbSet.Where(where); if(!entities.Any()) return; foreach (var entity in entities) { _dbSet.Remove(entity); } } public T GetById(TId id) { return _dbSet.Find(id); } public T Get(Expression<Func<T, bool>> where) { return _dbSet.Where(where).FirstOrDefault(); } public IEnumerable<T> GetAll() { return _dbSet; } public IEnumerable<T> GetMany(Expression<Func<T, bool>> where) { return _dbSet.Where(where); } public IEnumerable<TClass> ExecWithStoreProcedure<TClass>(string query) where TClass : class, new() { return BookDbContext.ExecuteQuery<TClass>(query); } public void ExecuteWithStoreProcedure(string query, params object[] parameters) { BookDbContext.ExecuteCommand(query,parameters); } public void Dispose() { BookDbContext.Dispose(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Messaging; namespace DMS.Books.Services.Interfaces { public interface ISubjectFacade { SubjectsResponse GetAllSubjects(SubjectRequest request); } } <file_sep> using System.ComponentModel.DataAnnotations.Schema; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.Books.Models.PocoModels { using System; using System.Collections.Generic; [Table("BookCategory")] public class BookCategory : Entity<int>, IAggregateRoot { public BookCategory() { this.Books = new HashSet<Book>(); } public string NameE { get; set; } public string NameB { get; set; } public int IsActive { get; set; } public int Creator { get; set; } public System.DateTime CreationDate { get; set; } public int Modifier { get; set; } public System.DateTime ModificationDate { get; set; } public string Remarks { get; set; } public virtual ICollection<Book> Books { get; set; } } } <file_sep>using System; using System.Web; namespace DMS.SharedKernel.Infrastructure.CacheStorage { public class HttpContextCacheAdapter : ICacheStorage { public void Remove(string key) { HttpContext.Current.Cache.Remove(key); } public void Store(string key, object data) { HttpContext.Current.Cache.Insert(key, data); } public void Store(string key, object data, DateTime expireTime) { HttpContext.Current.Cache.Insert(key, data, null, expireTime, TimeSpan.Zero); } public T Retrieve<T>(string key) { T itemStored = (T)HttpContext.Current.Cache.Get(key); if (itemStored == null) itemStored = default(T); return itemStored; } public void RemoveRuntime(string key) { HttpRuntime.Cache.Remove(key); } public void StoreRuntime(string key, object data) { HttpRuntime.Cache.Insert(key, data); } public void StoreRuntime(string key, object data, DateTime expireTime) { HttpRuntime.Cache.Insert(key, data, null, expireTime, TimeSpan.Zero); } public T RetrieveRuntime<T>(string key) { T itemStored = (T)HttpRuntime.Cache.Get(key); if (itemStored == null) itemStored = default(T); return itemStored; } } } <file_sep> namespace DMS.DataInitializer.Models { using System; using System.Collections.Generic; public class BookCategory { public BookCategory() { this.Books = new HashSet<Book>(); } public int Id { get; set; } public string NameE { get; set; } public string NameB { get; set; } public int IsActive { get; set; } public int Creator { get; set; } public System.DateTime CreationDate { get; set; } public int Modifier { get; set; } public System.DateTime ModificationDate { get; set; } public string Remarks { get; set; } public virtual ICollection<Book> Books { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Messaging { public class SubjectsResponse { public SubjectsResponse() { Subjects = new List<BookCategoryView>(); Initials = new List<string>(); } public IEnumerable<BookCategoryView> Subjects { get; set; } public IEnumerable<string> Initials { get; set; } public int CategoryCount { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Messaging { public class ResponseBase { public bool TransactionStatus { get; set; } public string TransactionMessage { get; set; } } } <file_sep>using DMS.Books.Models.PocoModels; using DMS.SharedKernel.Infrastructure.Data; namespace DMS.Books.Repositories { public interface IBookRepository:IRepository<Book,int> { } } <file_sep>using System; using System.Data.Entity; using DMS.Books.Models.PocoModels; using DMS.Books.Repositories; using DMS.SharedKernel.Infrastructure.Domain; namespace DMS.Books.Fakes { public class FakeBookContext:IBookDbContext { public FakeBookContext() { Books = new FakeBookDbSet(); BookCategories=new FakeCategoryDbSet(); } public IDbSet<BookCategory> BookCategories { get; set; } public IDbSet<Book> Books { get; set; } public void SetModified<T, TId>(T entity) where T : Entity<TId>, IAggregateRoot { throw new NotImplementedException(); } public void SetAdd<T, TId>(T entity) where T : Entity<TId>, IAggregateRoot { throw new NotImplementedException(); } public System.Collections.Generic.IEnumerable<TClass> ExecuteQuery<TClass>(string query) where TClass : class, new() { throw new NotImplementedException(); } public void ExecuteCommand(string query, params object[] parameters) { throw new NotImplementedException(); } public IDbSet<T> DbSet<T, TId>() where T : Entity<TId>, IAggregateRoot { return (IDbSet<T>) Books; } public int SaveChanges() { return 0; } public void Dispose() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Viewmodels { public class BookCategoryView { public int Id { get; set; } public string CategoryNameBengali { get; set; } public string CategoryNameEnglish { get; set; } } } <file_sep>namespace DMS.SharedKernel.Infrastructure.CookieStorage { public enum CookieDataKey { PurchasedBook, UserId, UserName, Email, Password } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DMS.Books.Services.Messaging { public class BookSummaryRequest { public int Take { get; set; } public int Skip { get; set; } public string SearchString { get; set; } } } <file_sep>using System; using DMS.Books.Repositories; using DMS.Books.Services.Implementations; using DMS.Books.Services.Interfaces; using DMS.Books.Services.Messaging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace DMS.Books.MockTests { [TestClass] public class BookFacadeMockTest { [TestMethod] public void Book_Save_Testing() { var context = new Mock<IBookDbContext>(); var bookUnitOfWork = new BookUnitOfWork(context.Object); var bookRepository = new Mock<IBookRepository>(); var categoryRepository = new Mock<ICategoryRepository>(); var facade = new BookFacade(bookRepository.Object, categoryRepository.Object, bookUnitOfWork); //var createRequest = new Mock<CreateBookRequest>(); //createRequest.Object.Create.Id = 0; //createRequest.Object.Create.IsActive = 1; //createRequest.Object.Create.IsbnNumber = "12345"; //createRequest.Object.Create.Price = 566; //createRequest.Object.Create.PublishedDate = DateTime.Now; //createRequest.Object.Create.Remarks = "Remarks"; //createRequest.Object.Create.TitleB = "Book Bengali"; //createRequest.Object.Create.TitleE = "Book English"; //createRequest.Object.Create.TotalPage = 150; //createRequest.Object.Create.BookCategoryId = 1; //createRequest.Object.Create.Description = "desc"; var createRequest = new CreateBookRequest { Create = { Id = 0, IsActive = 1, IsbnNumber = "12345", Price = 566, PublishedDate = DateTime.Now, Remarks = "Remarks", TitleB = "Book Bengali", TitleE = "Book English", TotalPage = 150, BookCategoryId = 1, Description = "desc" } }; facade.SaveBook(createRequest); } [TestMethod] public void Book_Update_Testing() { var facade = new Mock<IBookFacade>(); var createRequest = new CreateBookRequest { Create = { Id = 0, IsActive = 1, IsbnNumber = "12345", Price = 566, PublishedDate = DateTime.Now, Remarks = "Remarks", TitleB = "Book Bengali", TitleE = "Book English", TotalPage = 150, BookCategoryId = 1, Description = "desc" } }; var success = new ResponseBase {TransactionMessage = "Data Modified Successfully", TransactionStatus = true}; facade.Setup(x=>x.UpdateBook(createRequest)).Returns(success); } } } <file_sep>using System.Linq; using DMS.Books.Repositories; using DMS.Books.Services.Interfaces; using DMS.Books.Services.Messaging; using DMS.Books.Services.Viewmodels; namespace DMS.Books.Services.Implementations { public class SubjectFacade:ISubjectFacade { private readonly ICategoryRepository _repository; public SubjectFacade(ICategoryRepository repository) { _repository = repository; } public SubjectsResponse GetAllSubjects(SubjectRequest request) { SubjectsResponse response = new SubjectsResponse { Subjects = _repository.GetAll() .Where(x => x.IsActive == 1) .Select(b => new BookCategoryView { Id = b.Id, CategoryNameBengali = b.NameB, CategoryNameEnglish = b.NameE }) }; var bookCategoryViews = response.Subjects as BookCategoryView[] ?? response.Subjects.ToArray(); response.Initials = bookCategoryViews.Select(summary => summary.CategoryNameBengali.ToArray()[0].ToString()).ToList(); response.CategoryCount = bookCategoryViews.Count(); if (!string.IsNullOrEmpty(request.SearchString)) bookCategoryViews = bookCategoryViews.Where(x => x.CategoryNameBengali.StartsWith(request.SearchString)).ToArray(); response.Subjects = bookCategoryViews.Skip(request.Skip).Take(request.Take); return response; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using DMS.Controllers; using DMS.SharedKernel.Infrastructure.Configuration; using DMS.SharedKernel.Infrastructure.EmailService; using DMS.SharedKernel.Infrastructure.Logging; using StructureMap; namespace DMS.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Bootstrap.ConfigureDependencies(); ControllerBuilder.Current.SetControllerFactory(new StructuremapControllerFactory()); // Services.AutoMapperBootStrapper.ConfigureAutoMapper(); ApplicationSettingsFactory.InitializeApplicationSettingsFactory(ObjectFactory.GetInstance<IApplicationSettings>()); LoggingFactory.InitializeLogFactory(ObjectFactory.GetInstance<ILogger>()); EmailServiceFactory.InitializeEmailServiceFactory (ObjectFactory.GetInstance<IEmailService>()); LoggingFactory.GetLogger().Log("Application Started"); } } } <file_sep>using DMS.SharedKernel.Infrastructure.Data; namespace DMS.Books.Repositories { public interface IBookUnitOfWork:IUnitOfWork<IBookDbContext> { } }
2f83e1c3d8f6c1f967d27da6a6f2676e52ae9d89
[ "HTML+Razor", "C#" ]
61
HTML+Razor
mojamcpds/Domain-Driven-Design
5481301d1cba5f95e26675c0b8d9da68ed6b2906
c6e227f815b8ca4e01698ded99b2f7e35fbf49a7
refs/heads/master
<file_sep>class UsersController < ApplicationController # before_action:check_status def index end def create user= User.create(name:params[:name], email: params[:email], password:params[:password], password_confirmation:params[:password_confirmation]) if user.valid? session[:user_id] = user[:id] redirect_to '/show' else render json: user.errors end end def login user=User.find_by_email(params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user[:id] redirect_to '/show' else render text: "Either email or password was incorrect" end end end <file_sep>class AdminController < ApplicationController before_action :check_status def show end private def check_status if !session[:user_id] redirect_to '/' end end end
2ea8d7790edabe0756d61bb37d15c46f42a2927e
[ "Ruby" ]
2
Ruby
farrahh/login_reg
3fd9e5622bc069ed517e3d48ae710c7f354aeadf
1182e2b0dd21722526abfd9797d81c479c6c49c8
refs/heads/master
<repo_name>Somasekhar-java/Springboot-jwtSecurityService<file_sep>/config/application.properties eureka.client.serviceUrl.defaultZone = http://${registry.host:localhost}:${registry.port:8000}/eureka/ eureka.client.registerWithEureka = true eureka.client.fetchRegistry = true com.cts=Hellothese valuse form local git Properties files updated by Sunitha from GIT REPO ****123****.
7ca4bdc42ae6839ac8a1c78d933bce926cc11f7e
[ "INI" ]
1
INI
Somasekhar-java/Springboot-jwtSecurityService
66bb8b185bfc7bcea7a27c8c0fb4f41d472bc33e
def3c8b9655601f4ed74612980ea24acb9815b9e
refs/heads/master
<repo_name>VinayagamD/NavigationDemo<file_sep>/app/src/main/java/com/vinay/navigationdemo/fragments/SpecifyAmountFragment.kt package com.vinay.navigationdemo.fragments import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.navigation.NavController import androidx.navigation.Navigation import com.vinay.navigationdemo.R import com.vinay.navigationdemo.models.Money import kotlinx.android.synthetic.main.fragment_specify_amount.* import java.math.BigDecimal /** * A simple [Fragment] subclass. */ class SpecifyAmountFragment : Fragment() , View.OnClickListener{ lateinit var navController: NavController lateinit var recipientName: String override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_specify_amount, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { recipientName = it.getString("recipient", "") } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navController = Navigation.findNavController(view) send_btn.setOnClickListener(this) cancel_btn.setOnClickListener(this) val message = "Sending money to $recipientName" recipient.text = message } override fun onClick(v: View?) { v?.let { when(it.id){ R.id.send_btn -> { if(!TextUtils.isEmpty(input_amount.text.toString())){ val amount = Money(BigDecimal(input_amount.text.toString())) val bundle = bundleOf( "recipient" to recipientName, "amount" to amount ) navController.navigate(R.id.action_specifyAmountFragment_to_confirmationFragment, bundle) }else{ Toast.makeText(context, "Enter Amount", Toast.LENGTH_SHORT).show() } } R.id.cancel_btn -> activity?.onBackPressed() else -> {} } } } }
0239ad47be360348aefa04b9032d428fe463598b
[ "Kotlin" ]
1
Kotlin
VinayagamD/NavigationDemo
ab79d712c446466df792ae2dc7659e9a557760fe
db98e63f2bdbdfd661751134734d19d85ab4c5f7
refs/heads/master
<file_sep>applications: - path: . memory: 256M instances: 1 domain: mybluemix.net name: roytest1 host: roytest1 disk_quota: 1024M
42a3c357697df15c4cb15f6c13a189b1ceac5373
[ "YAML" ]
1
YAML
brybwy/roytest1-1463501850329
112fcf6a5b134105b7fbf66e7c448ed8ecc28c16
af831077fed245d0814233717fdf3f81fdaa438b
refs/heads/master
<repo_name>linhaiwei123/chatting-demo-src<file_sep>/assets/点击和文字输入层/scriptForLogin/send.js cc.Class({ extends: cc.Component, properties: { //聊天的输入框 inputBox:{ default: null, type: cc.EditBox, } }, onLoad(){ //有点多余 怪我咯 let self = this; }, //发送聊天消息 say(){ //获取输入框中的聊天消息 let message = this.inputBox.string; //如果聊天消息不为空 if(message){ //发送聊天消息给服务器 window.remote.emit('消息',message); this.inputBox.string = ''; } }, //发送完成后的提示 tips(){ this.inputBox.placeholder = '头顶的消息只会维持5秒哦' }, //恢复原来的提示 resume(){ this.inputBox.placeholder = '说点什么吧...' }, }); <file_sep>/server/server.js var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //保存用户连接 为单点聊天做准备 目前未实现 var 用户连接 = []; //保存用户信息 目前只有当前所在瓦片信息curTile和最近一次点击的位置location var 用户信息 = {}; io.on('connection', function(socket){ console.log('有用户连接'); socket.on('登录',function(data){ //重名验证 if(用户连接[data]){ //提醒重名 socket.emit('重名'); return ; } //保存用户名 socket.name = data; console.log('登录-用户名为: ' + socket.name); //保存连接 用户连接[socket.name] = socket; //通知前台进入大厅 socket.emit('进入大厅',socket.name); }); //当用户离线 socket.on('disconnect',function(){ //删除用户连接 delete 用户连接[socket.name]; //删除用户信息 delete 用户信息[socket.name]; //全局广播前台删除(不包括自己) socket.broadcast.emit('离线',socket.name); console.log('离线-用户名为: ' + socket.name); }); //当有新玩家 socket.on('玩家',function(data){ //保存新玩家的当前所在瓦片和最近一次点击位置 用户信息[socket.name] = data; //广播其他用户绘制这个新玩家 socket.broadcast.emit('玩家',{[socket.name]:data}); //发送给当前新玩家目前所有在线玩家的信息(信息包括自己) socket.emit('玩家',用户信息); }); //当玩家对地图点击 socket.on('点击',function(data){ // 用户信息[socket.name].location = data; //console.log('点击测试: ', 用户信息[socket.name].location); //更新该玩家最近的一次点击 用户信息[socket.name].location = data; //全局广播该点击 所有客户端集体绘制该玩家的移动 io.sockets.emit('点击',{playerName:socket.name,location:data}); }); //玩家移动过程中 实时更新当前瓦片所在位置, 方便后来登录的玩家绘制在线玩家 socket.on('瓦片',function(data){ //更新瓦片 用户信息[socket.name].curTile = data; }); //全局消息 socket.on('消息',function(data){ //全局广播消息(包括自己) io.sockets.emit('消息',{playerName:socket.name,message:data}); }); }); http.listen(3000, function(){ console.log('正在监听端口3000'); });<file_sep>/assets/渲染层/coordinateutil.js var CoordinateUtil = function(enterTile,enterPosition,tileSize,background){ //瓦片坐标转换成地图坐标 this.playerPosition = function(curTile){ let temp_1 = cc.pSub(curTile,enterTile); let temp_2 = cc.v2((temp_1.x + temp_1.y) * tileSize.x/2, (temp_1.x - temp_1.y) * tileSize.y/2); return cc.pAdd(enterPosition,temp_2); }, //点击的屏幕坐标转换成地图坐标 this.convertToBackground = function(location){ return cc.pSub(background.convertToNodeSpace(location),cc.pMult(cc.v2(background.width,background.height),0.5)); } } module.exports = CoordinateUtil; <file_sep>/assets/渲染层/scriptForFollow/background.js cc.Class({ extends: cc.Component, properties: { }, follow(node){ //cc.follow可以让地图跟踪某个玩家,可以用来保持某个玩家在摄像头的中央, 这是对所有客户端进行统一绘制算法的关键 this.node.runAction(cc.follow(node)); } }); <file_sep>/assets/渲染层/scriptForFollow/player.js //寻路工具 var PathUtil = require('pathutil'); cc.Class({ extends: cc.Component, properties: { //当前所在瓦片, 默认12, 42 curTile:{ default: cc.v2(12,42), type: cc.Vec2, }, //当前动画是否移动的标识, 这是分离点击逻辑和移动渲染的关键 stop:true, //移动速度控制参数 radio:1, //瓦片尺寸 默认为 64, 48 tileSize:{ default: cc.v2(64,48), type: cc.Vec2, } }, onLoad(){ //获取地图节点 this.background = this.node.parent; //获取名字标签 this.playerNameLabel = this.node.getChildByName('playerNameNode').getComponent(cc.Label); //获取对话框标签 this.messageLabel = this.node.getChildByName('message').getComponent(cc.Label); //获取寻路工具 this.pathutil = new PathUtil(this.node,this.radio,this.tileSize); }, //绘制聊天消息 say(message){ //在对话框标签绘制聊天消息 this.messageLabel.string = message; console.log(message); let self = this; //5秒后聊天消息消失 setTimeout(()=>{ self.messageLabel.string = ''; },5000); }, //让该玩家成为地图跟随的对象, 保证摄像头对该玩家进行跟踪 followed(){ //成为地图跟随的对象 this.background.getComponent('background').follow(this.node); }, //设置玩家名字 setPlayerName(playerName){ this.playerNameLabel.string = playerName; }, //设置当前瓦片 setCurTile(curTile){ this.curTile = curTile; }, //移动的点击逻辑部分 参数为点击在地图的坐标 move(location){ //获取A星路径 this.path = this.pathutil.convertToAStarPath(location,this.curTile); //如果已经停止移动, 就提醒继续新的绘制移动 if(stop){ this._move(); } }, //移动的渲染部分 _move(){ //移动标志位开启 this.stop = false; //如果已经移到了目标瓦片上 if(this.path.length == 0){ //移动标志位关闭 this.stop = true; //退出移动的递归 return; } //取出下一个瓦片 var step = this.path.shift(); //本地更新瓦片位置(有点多余了=.=怪我咯) this.curTile = cc.v2(step.x,step.y); //远程更新瓦片位置 window.remote.emit('瓦片',this.curTile); //移向该瓦片 this.node.runAction( cc.sequence( cc.moveBy( //移动速度 this.pathutil.playerSpeed(step), //移动位置(瓦片坐标转成直角坐标系坐标) this.pathutil.playerStep(step) ), //移动完继续递归所在方法取得下一个瓦片 cc.callFunc(this._move,this) ) ); } }); <file_sep>/assets/渲染层/pathutil.js var PathUtil = function(node,radio,tileSize){ //计算A星路径 this.convertToAStarPath = function(location,curTile){ var oldX = (location.x - node.x)/tileSize.x; var oldY = (location.y - node.y)/tileSize.y; var newX = Math.floor(oldX + oldY); var newY = -Math.floor(oldY - oldX); var openList = []; var closeList = []; var finalList = []; var start = { x:curTile.x, y:curTile.y, h: (Math.abs(newX) + Math.abs(newY))*10, g: 0, f: this.h + this.g, p: null, }; start.f = start.h + start.g; openList.push(start); var destination = {x:start.x+newX,y:start.y+newY}; while(openList.length !== 0){ var parent = openList.shift(); closeList.push(parent); if(parent.h === 0){break;} for(var i = -1; i<= 1; i++){ for(var j = -1; j <= 1; j++){ var rawX = parent.x + i; var rawY = parent.y + j; var neibour = { x: rawX, y: rawY, h: Math.max(Math.abs(rawX - destination.x),Math.abs(rawY - destination.y))*10, g: parent.g + ((i !== 0 && j !== 0)? 14 : 10), p: parent, } neibour.f = neibour.h + neibour.g; if(closeList.some((item)=>{return item.x == neibour.x && item.y == neibour.y;})){ continue; } openList.push(neibour); } } openList.sort((a,b)=>{return a.f - b.f}); } var des = closeList.pop(); while(des.p){ des.dx = des.x - des.p.x; des.dy = des.y - des.p.y; finalList.unshift(des); des = des.p; }; return finalList; }, //处理玩家移动速度 用以保持直线和斜线统一的移动速度 this.playerSpeed = function(step){ return radio * ((step.dx != 0) && (step.dy != 0) ? 1.4 : 1) / 10 }, //瓦片坐标转换成直角坐标 this.playerStep = function(step){ return cc.v2( (step.dx+step.dy)*tileSize.x/2 , -(step.dy-step.dx)* tileSize.y/2); } } module.exports = PathUtil;<file_sep>/assets/点击和文字输入层/scriptForLogin/remote.js cc.Class({ extends: cc.Component, properties: { }, onLoad(){ //初始化和服务器的连接 let self = this; if(cc.sys.isNative){ window.io = SocketIO; }else{ window.io = require('socket.io'); } window.remote = window.io('www.concatboss.cn:3000'); } }); <file_sep>/assets/点击和文字输入层/scriptForLogin/login.js cc.Class({ extends: cc.Component, properties: { inputBox:{ default: null, type: cc.EditBox, } }, onLoad(){ let self = this; //重名提醒 window.remote.on('重名',()=>{ //清空名字 self.inputBox.string = ''; //设置重名提醒消息 self.inputBox.placeholder = '和其他玩家重名啦'; }); //登录成功 window.remote.on('进入大厅',(playerName)=>{ //本地存储当前用户名 cc.sys.localStorage.setItem('playerName',playerName); //转场进入大厅 cc.director.loadScene('main'); }); }, //重名提醒完后恢复原先的提醒 resume(){ this.inputBox.placeholder = '请输入您的角色名'; }, //登录 login(){ //获取玩家输入的名字 let userName = this.inputBox.string; //如果名字不为空 if(userName){ //发送给服务器 window.remote.emit('登录',userName); } } });
e7824db5a6044737af10bac74e0c9d999d2f8e8c
[ "JavaScript" ]
8
JavaScript
linhaiwei123/chatting-demo-src
0404ada999fbf767718c0a704f132eb9e82ab914
1c062d2f92173aaa4430c7e5830d4ce603578c9e
refs/heads/master
<file_sep>@testset "MVHistory: Basic functions" begin _history = MVHistory() function f(i, b; muh=10) @test b == "yo" @test muh == .3 i end numbers = collect(-10:2:100) for i = numbers @test push!(_history, :myf, i, f(i + 1, "yo", muh = .3)) == i + 1 if i % 11 == 0 @test push!(_history, :myint, i, i - 1) == i - 1 @test push!(_history, :myint2, i - 1) == i - 1 end end println(_history) show(_history); println() @test_throws ArgumentError push!(_history, :myf, 200, "test") for k in keys(_history) @test k in [:myf, :myint, :myint2] end @test values(_history, :myf) == numbers .+ 1 @test_throws KeyError values(_history, :abc) @test first(_history, :myf) == (-10, -9) @test last(_history, :myf) == (100, 101) @test first(_history, :myint) == (0, -1) @test last(_history, :myint) == (88, 87) @test first(_history, :myint2) == (1, -1) @test last(_history, :myint2) == (5, 87) for (i, v) in enumerate(_history, :myf) @test in(i, numbers) @test i + 1 == v end for (i, v) in enumerate(_history, :myint) @test in(i, numbers) @test i % 11 == 0 @test i - 1 == v end @test typeof(_history[:myf]) <: History a1, a2 = get(_history, :myf) @test typeof(a1) <: Vector && typeof(a2) <: Vector @test length(a1) == length(a2) == length(numbers) == length(_history, :myf) @test a1 .+ 1 == a2 @test_throws ArgumentError push!(_history, :myf, 10, f(10, "yo", muh = .3)) @test_throws KeyError enumerate(_history, :sign) @test_throws KeyError length(_history, :sign) end @testset "MVHistory: Storing arbitrary types" begin _history = MVHistory(QHistory) for i = 1:100 @test push!(_history, :mystring, i % UInt8, string("i=", i + 1)) == string("i=", i+1) @test push!(_history, :myfloat, i % UInt8, Float32(i + 1)) == Float32(i+1) end @test typeof(_history[:mystring]) <: QHistory a1, a2 = get(_history, :mystring) @test typeof(a1) <: Vector{UInt8} @test typeof(a2) <: Vector{String} a1, a2 = get(_history, :myfloat) @test typeof(a1) <: Vector{UInt8} @test typeof(a2) <: Vector{Float32} end @testset "MVHistory: @trace" begin _history = MVHistory() n = 2 x = [0.0, 1.0] for i = 1:n xi = x[i] @test @trace(_history, i, xi, round(Int,xi)) == round(Int,xi) end @test haskey(_history, :xi) a1, a2 = get(_history, :xi) @test length(a1) == n @test length(a2) == n @test typeof(a1) <: Vector{Int} @test typeof(a2) <: Vector{Float64} @test haskey(_history, Symbol("round(Int, xi)")) a1, a2 = get(_history, Symbol("round(Int, xi)")) @test length(a1) == n @test length(a2) == n @test typeof(a1) <: Vector{Int} @test typeof(a2) <: Vector{Int} end @testset "Increment!" begin _history = MVHistory() key = :test val = 1 @test increment!(_history, key, 1, val) == val @test increment!(_history, key, 1, val) == 2val @test increment!(_history, key, 2, 4val) == 4val @test increment!(_history, key, 10, 5val) == 5val _history2 = MVHistory(QHistory) @test_throws MethodError increment!(_history2, key, 1, val) == val end <file_sep>mutable struct QHistory{I,V} <: UnivalueHistory{I} lastiter::I storage::Deque{Tuple{I,V}} function QHistory(::Type{V}, ::Type{I} = Int) where {I,V} new{I,V}(typemin(I), Deque{Tuple{I,V}}()) end end # ==================================================================== Base.length(history::QHistory) = length(history.storage) Base.enumerate(history::QHistory) = history.storage Base.first(history::QHistory) = first(history.storage) Base.last(history::QHistory) = last(history.storage) function Base.push!( history::QHistory{I,V}, iteration::I, value::V) where {I,V} lastiter = history.lastiter iteration > lastiter || throw(ArgumentError("Iterations must increase over time")) history.lastiter = iteration push!(history.storage, (iteration, value)) value end function Base.push!( history::QHistory{I,V}, value::V) where {I,V} lastiter = history.lastiter == typemin(I) ? zero(I) : history.lastiter iteration = lastiter + one(history.lastiter) history.lastiter = iteration push!(history.storage, (iteration, value)) value end function Base.get(history::QHistory{I,V}) where {I,V} l = length(history) k, v = first(history.storage) karray = Array{I}(undef, l) varray = Array{V}(undef, l) i = 1 for (k, v) in enumerate(history) karray[i] = k varray[i] = v i += 1 end karray, varray end Base.print(io::IO, history::QHistory{I,V}) where {I,V} = print(io, "$(length(history)) elements {$I,$V}") function Base.show(io::IO, history::QHistory{I,V}) where {I,V} println(io, "QHistory") println(io, " types: $I, $V") print(io, " length: $(length(history))") end <file_sep>using ValueHistories function msg(args...; newline = true) print(" --> ", args...) newline && println() end n = 100 # increase to match benchmark msg("Baseline: $n loops that accumulates a Float64") function f(n) tmp = 0. for i=1:n tmp += i * 3. end tmp end @time f(n) @time f(n) #----------------------------------------------------------- for T in [History, QHistory] msg("$(T): $n loops tracking accumulator as Float64") function g(_history,n) tmp = 0. for i=1:n tmp += i * 3. push!(_history, i, tmp) end tmp end _history = T(Float64) @time g(_history,n) _history = T(Float64) @time g(_history,n) msg("$(T): Converting result into arrays") @time x,y = get(_history) @time x,y = get(_history) end #----------------------------------------------------------- msg("MVHistory: $n loops tracking accumulator as Float64 and String") function g(_history,n) tmp = 0. for i=1:n tmp += i * 3. push!(_history, :myint, i, tmp) push!(_history, :mystr, i, string(tmp)) end tmp end _history = MVHistory(History) @time g(_history,n) _history = MVHistory(History) @time g(_history,n) msg("MVHistory: Converting result into arrays") @time x,y = get(_history, :mystr) @time x,y = get(_history, :mystr) @assert length(y) == n @assert typeof(y) <: Vector{String} <file_sep>name = "ValueHistories" uuid = "98cad3c8-aec3-5f06-8e41-884608649ab7" authors = ["JuliaML and contributors"] version = "0.5.4" [deps] DataStructures = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8" RecipesBase = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" [compat] DataStructures = "0.17, 0.18" RecipesBase = "0.2.3, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1" julia = "1" [extras] Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] test = ["Test"] <file_sep>module ValueHistories using DataStructures using RecipesBase export ValueHistory, UnivalueHistory, History, QHistory, MultivalueHistory, MVHistory, increment!, @trace include("abstract.jl") include("history.jl") include("qhistory.jl") include("mvhistory.jl") include("recipes.jl") end # module <file_sep># THIS FILE IS DEACTIVATED using Random using Plots using VisualRegressionTests # run a visual regression test comparing the output to the saved reference png function dotest(testname, func) Random.seed!(1) reffn = joinpath(refdir, "$testname.png") vtest = VisualTest(func, reffn) result = test_images(vtest) @test success(result) end # builds a testable function which saves a png to the location `fn` # use: VisualTest(@plotfunc(plot(rand(10))), "/tmp/tmp.png") macro plottest(testname, expr) esc(quote dotest(string($testname), fn -> begin $expr png(fn) end) end) end # don't let pyplot use a gui... it'll crash # note: Agg will set gui -> :none in PyPlot # - This unglyness needs to change had_mlp = haskey(ENV, "MPLBACKEND") _old_env = get(ENV, "MPLBACKEND", "") ENV["MPLBACKEND"] = "Agg" import PyPlot info("Matplotlib version: $(PyPlot.matplotlib[:__version__])") pyplot(size=(200,150), reuse=true) refdir = joinpath(dirname(@__FILE__), "refimg") @plottest "dynmv" begin history = ValueHistories.MVHistory(QHistory) for i=1:100 x = 0.1i push!(history, :a, x, sin(x)) push!(history, :wrongtype, x, "$(sin(x))") if i % 10 == 0 push!(history, :b, x, cos(x)) end end plot(history) end @plottest "dynmv_sub" begin history = ValueHistories.MVHistory() for i=1:100 x = 0.1i push!(history, :a, x, sin(x)) push!(history, :wrongtype, x, "$(sin(x))") if i % 10 == 0 push!(history, :b, x, cos(x)) end end plot(history, layout=2) end @plottest "queueuv" begin history = ValueHistories.QHistory(Int) for i = 1:100 push!(history, i, 2i) end plot(history) end @plottest "vectoruv" begin history = ValueHistories.History(Int) for i = 1:100 push!(history, i, 100-i) end plot(history) end @plottest "uv_vector" begin history1 = ValueHistories.History(Int) history2 = ValueHistories.QHistory(Int) for i = 1:100 push!(history1, i, 2i) push!(history2, i, 100-i) end plot([history1, history2], layout = 2) end if had_mlp ENV["MPLBACKEND"] = _old_env else delete!(ENV, "MPLBACKEND") end <file_sep> struct MVHistory{H<:UnivalueHistory} <: MultivalueHistory storage::Dict{Symbol, H} end function MVHistory(::Type{H} = History) where {H<:UnivalueHistory} MVHistory{H}(Dict{Symbol, H}()) end # ==================================================================== # Functions Base.length(history::MVHistory, key::Symbol) = length(history.storage[key]) Base.enumerate(history::MVHistory, key::Symbol) = enumerate(history.storage[key]) Base.first(history::MVHistory, key::Symbol) = first(history.storage[key]) Base.last(history::MVHistory, key::Symbol) = last(history.storage[key]) Base.keys(history::MVHistory) = keys(history.storage) Base.values(history::MVHistory, key::Symbol) = get(history, key)[2] function Base.push!( history::MVHistory{H}, key::Symbol, iteration::I, value::V) where {I,H<:UnivalueHistory,V} if !haskey(history.storage, key) _hist = H(V, I) push!(_hist, iteration, value) history.storage[key] = _hist else push!(history.storage[key], iteration, value) end value end function Base.push!( history::MVHistory{H}, key::Symbol, value::V) where {H<:UnivalueHistory,V} if !haskey(history.storage, key) _hist = H(V, Int) push!(_hist, value) history.storage[key] = _hist else push!(history.storage[key], value) end value end function Base.getindex(history::MVHistory, key::Symbol) history.storage[key] end Base.haskey(history::MVHistory, key::Symbol) = haskey(history.storage, key) function Base.get(history::MVHistory, key::Symbol) l = length(history, key) k, v = first(history.storage[key]) karray = Array{typeof(k)}(undef, l) varray = Array{typeof(v)}(undef, l) i = 1 for (k, v) in enumerate(history, key) karray[i] = k varray[i] = v i += 1 end karray, varray end function Base.show(io::IO, history::MVHistory{H}) where {H} print(io, "MVHistory{$H}") for (key, val) in history.storage print(io, "\n", " :$(key) => $(val)") end end using Base.Meta """ Easily add to a MVHistory object `tr`. Example: ```julia using ValueHistories, OnlineStats v = Variance(BoundedEqualWeight(30)) tr = MVHistory() for i=1:100 r = rand() fit!(v,r) μ,σ = mean(v),std(v) # add entries for :r, :μ, and :σ using their current values @trace tr i r μ σ end ``` """ macro trace(tr, i, vars...) block = Expr(:block) for v in vars push!(block.args, :(push!($(esc(tr)), $(quot(Symbol(v))), $(esc(i)), $(esc(v))))) end block end """ increment!(trace, key, iter, val) Increments the value for a given key and iteration if it exists, otherwise adds the key/iteration pair with an ordinary push. """ function increment!(trace::MVHistory{<:History}, key::Symbol, iter::Number, val) if haskey(trace, key) i = findfirst(isequal(iter), trace.storage[key].iterations) if i != nothing return trace[key].values[i] += val end end push!(trace, key, iter, val) end <file_sep># ValueHistories *Utility package for efficient tracking of optimization histories, training curves or other information of arbitrary types and at arbitrarily spaced sampling times* | **Package License** | **PkgEval (Nanosoldier)** | **Build Status** | |:------------------:|:---------------------:|:-----------------:| | [![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](LICENSE.md) | [![PkgEval][pkgeval-img]][pkgeval-url] | [![Build Status](https://travis-ci.org/JuliaML/ValueHistories.jl.svg?branch=master)](https://travis-ci.org/JuliaML/ValueHistories.jl) [![Build status](https://ci.appveyor.com/api/projects/status/8v1n9hqfnn5jslyn/branch/master?svg=true)](https://ci.appveyor.com/project/Evizero/valuehistories-jl/branch/master) [![Coverage Status](https://coveralls.io/repos/github/JuliaML/ValueHistories.jl/badge.svg?branch=master)](https://coveralls.io/github/JuliaML/ValueHistories.jl?branch=master) | [pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/V/ValueHistories.svg [pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/V/ValueHistories.html ## Installation This package is registered in `METADATA.jl` and can be installed as usual ```julia pkg> add ValueHistories ``` ## Overview We provide two basic approaches for logging information over time or iterations. The sample points do not have to be equally spaced as long as time/iteration is strictly increasing. - **Univalue histories**: Intended for tracking the evolution of a single value over time. - **Multivalue histories**: Track an arbitrary amount of values over time, each of which can be of a different type and associated with a label *Note that both approaches are typestable.* ### Univalue Histories This package provide two different concrete implementations - `QHistory`: Logs the values using a `Dequeue` - `History`: Logs the values using a `Vector` Supported operations for univalue histories: - `push!(history, iteration, value)`: Appends a value to the history - `get(history)`: Returns all available observations as two vectors. The first vector contains the iterations and the second vector contains the values. - `enumerate(history)` Returns an enumerator over the observations (as tuples) - `first(history)`: First stored observation (as tuple) - `last(history)`: Last stored observation (as tuple) - `length(history)`: Number of stored observations - `increment!(history, iteration, value)`: Similar to `push!` but increments the `value` if the `iteration` already exists. Only supported by `History`. Here is a little example code showing the basic usage: ```julia using Primes # Specify the type of value you wish to track history = QHistory(Float64) for i = 1:100 # Store some value of the specified type # Note how the sampling times are not equally spaced isprime(i) && push!(history, i, sin(.1*i)) end # Access stored values as arrays x, y = get(history) @assert typeof(x) <: Vector{Int} @assert typeof(y) <: Vector{Float64} # You can also enumerate over the observations for (x, y) in enumerate(history) @assert typeof(x) <: Int @assert typeof(y) <: Float64 end # Let's see how this prints to the REPL history ``` ``` QHistory types: Int64, Float64 length: 25 ``` For easy visualisation we also provide recipes for `Plots.jl`. Note that this is only supported for `Real` types. ```julia using Plots plot(history, legend=false) ``` ![qhistory](https://rawgithub.com/JuliaML/FileStorage/master/ValueHistories/qhistory.svg) ### Multivalue Histories Multivalue histories are more or less a dynamic collection of a number of univalue histories. Each individual univalue history is associated with a symbol `key`. If the user stores a value under a `key` that has no univalue history associated with it, then a new one is allocated and specialized for the given type. Supported operations for multivalue histories: - `push!(history, key, iteration, value)`: Appends a value to the multivalue history - `get(history, key)`: Returns all available observations as two vectors. The first vector contains the iterations and the second vector contains the values. - `enumerate(history, key)` Returns an enumerator over the observations (as tuples) - `first(history, key)`: First stored observation (as tuple) - `last(history, key)`: Last stored observation (as tuple) - `length(history, key)`: Number of stored observations - `increment!(history, key, iteration, value)`: Similar to `push!` but increments the `value` if the `key` and `iteration` combination already exists. Here is a little example code showing the basic usage: ```julia using ValueHistories, Primes history = MVHistory() for i=1:100 x = 0.1i # Store any kind of value without losing type stability # The first push! to a key defines the tracked type # push!(history, key, iter, value) push!(history, :mysin, x, sin(x)) push!(history, :mystring, i, "i=$i") # Sampling times can be arbitrarily spaced # Note how we store the sampling time as a Float32 this time isprime(i) && push!(history, :mycos, Float32(x), cos(x)) end # Access stored values as arrays x, y = get(history, :mysin) @assert length(x) == length(y) == 100 @assert typeof(x) <: Vector{Float64} @assert typeof(y) <: Vector{Float64} # Each key can be queried individually x, y = get(history, :mystring) @assert length(x) == length(y) == 100 @assert typeof(x) <: Vector{Int64} @assert typeof(y) <: Vector{String} @assert y[1] == "i=1" # You can also enumerate over the observations for (x, y) in enumerate(history, :mycos) @assert typeof(x) <: Float32 @assert typeof(y) <: Float64 end # Let's see how this prints to the REPL history ``` ``` MVHistory{ValueHistories.History{I,V}} :mysin => 100 elements {Float64,Float64} :mystring => 100 elements {Int64,String} :mycos => 25 elements {Float32,Float64} ``` For easy visualisation we also provide recipes for `Plots.jl`. Note that this is only supported for `Real` types. ```julia using Plots plot(history) ``` ![mvhistory](https://rawgithub.com/JuliaML/FileStorage/master/ValueHistories/mvhistory.svg) ## License This code is free to use under the terms of the MIT license. <file_sep>abstract type ValueHistory end abstract type UnivalueHistory{I} <: ValueHistory end abstract type MultivalueHistory <: ValueHistory end Base.push!(history::UnivalueHistory, iteration, value) = throw(ArgumentError("The specified arguments are of incompatible type")) # length(history::ValueHistory) = error() # enumerate(history::ValueHistory) = error() # get(history::ValueHistory) = error() # first(history::ValueHistory) = error() # last(history::ValueHistory) = error() <file_sep>_is_plotable_history(::UnivalueHistory) = false _is_plotable_history(::QHistory{I,V}) where {I,V<:Real} = true _is_plotable_history(::History{I,V}) where {I,V<:Real} = true _filter_plotable_histories(h::MVHistory) = filter(p -> _is_plotable_history(p.second), h.storage) @recipe function plot(h::Union{History,QHistory}) markershape --> :ellipse title --> "Value History" get(h) end @recipe function plot(h::MVHistory) filtered = _filter_plotable_histories(h) k_vec = [k for (k, v) in filtered] v_vec = [v for (k, v) in filtered] if length(v_vec) > 0 markershape --> :ellipse label --> reshape(map(string, k_vec), (1,length(k_vec))) if get(plotattributes, :layout, nothing) != nothing title --> plotattributes[:label] legend --> false else title --> "Multivalue History" end get_vec = map(get, v_vec) [x for (x, y) in get_vec], [y for (x, y) in get_vec] else throw(ArgumentError("Can't plot an empty history, nor a history with strange types")) end end @recipe function plot(hs::AbstractVector{T}) where {T<:ValueHistories.UnivalueHistory} for h in hs @series begin h end end end <file_sep>mutable struct History{I,V} <: UnivalueHistory{I} lastiter::I iterations::Vector{I} values::Vector{V} function History(::Type{V}, ::Type{I} = Int) where {I,V} new{I,V}(typemin(I), Array{I}(undef, 0), Array{V}(undef, 0)) end end Base.length(history::History) = length(history.iterations) Base.enumerate(history::History) = zip(history.iterations, history.values) Base.first(history::History) = history.iterations[1], history.values[1] Base.last(history::History) = history.iterations[end], history.values[end] Base.get(history::History) = history.iterations, history.values function Base.push!( history::History{I,V}, iteration::I, value::V) where {I,V} lastiter = history.lastiter iteration > lastiter || throw(ArgumentError("Iterations must increase over time")) history.lastiter = iteration push!(history.iterations, iteration) push!(history.values, value) value end function Base.push!( history::History{I,V}, value::V) where {I,V} lastiter = history.lastiter == typemin(I) ? zero(I) : history.lastiter iteration = lastiter + one(history.lastiter) history.lastiter = iteration push!(history.iterations, iteration) push!(history.values, value) value end Base.print(io::IO, history::History{I,V}) where {I,V} = print(io, "$(length(history)) elements {$I,$V}") function Base.show(io::IO, history::History{I,V}) where {I,V} println(io, "History") println(io, " * types: $I, $V") print(io, " * length: $(length(history))") end """ increment!(trace, iter, val) Increments the value for a given iteration if it exists, otherwise adds the iteration with an ordinary push. """ function increment!(trace::History{I,V}, iter::Number, val) where {I,V} if !isempty(trace.iterations) if trace.lastiter == iter # Check most common case to make it faster i = length(trace.iterations) else i = findfirst(isequal(iter), trace.iterations) end if i != nothing return (trace.values[i] += val) end end push!(trace, iter, val) end <file_sep>using ValueHistories using Test tests = [ "tst_history.jl" "tst_mvhistory.jl" ] perf = [ "bm_history.jl" ] for t in tests @testset "[->] $t" begin include(t) end end for p in perf @testset "[->] $p" begin include(p) end end <file_sep>for T in [History, QHistory] @testset "$(T): Basic functions" begin _history = T(Float64) @test push!(_history, 1, 10.) == Float64(10.) @test push!(_history, 2, Float64(21.)) == Float64(21.) @test_throws ArgumentError push!(_history, 1, Float64(11.)) @test_throws ArgumentError push!(_history, 2, 10) @test_throws ArgumentError push!(_history, 3, Float32(10)) _history = T(Float64) numbers = collect(1:100) push!(_history, 10, Float64(5)) for i = numbers @test push!(_history, Float64(i + 1)) == Float64(i + 1) end @test first(_history) == (10, Float64(5.)) @test last(_history) == (110, Float64(101.)) _history = T(Float64) numbers = collect(1:2:200) for i = numbers @test push!(_history, i, Float64(i + 1)) == Float64(i + 1) end println(_history) show(_history); println() @test first(_history) == (1, Float64(2.)) @test last(_history) == (199, Float64(200.)) for (i, v) in enumerate(_history) @test in(i, numbers) @test Float64(i + 1) == v end a1, a2 = get(_history) @test typeof(a1) <: Vector{Int} && typeof(a2) <: Vector{Float64} @test length(a1) == length(a2) == length(numbers) == length(_history) @test convert(Vector{Float64}, a1 .+ 1) == a2 end @testset "$(T): No explicit iteration" begin _history = T(Float64) end @testset "$(T): Storing arbitrary types" begin _history = T(String, UInt8) for i = 1:100 @test push!(_history, i % UInt8, string("i=", i + 1)) == string("i=", i+1) end show(_history); println() a1, a2 = get(_history) @test typeof(a1) <: Vector{UInt8} @test typeof(a2) <: Vector{String} end end @testset "History: increment!" begin _history = History(Float64) val = 1. @test increment!(_history, 0, val) == val @test increment!(_history, 0, val) == 2val @test increment!(_history, 2, 4val) == 4val @test increment!(_history, 10, 5val) == 5val _history2 = QHistory(Float64) @test_throws MethodError increment!(_history2, 1, val) == val end
9cc583107e0c09b8986ac10660653fa2e37c0f62
[ "Markdown", "TOML", "Julia" ]
13
Markdown
JuliaML/ValueHistories.jl
fc38f7e282c5d7291b9c35f9e3a2d75432e28f09
1ee74c05c8cc4bd2fede427b02529adcb6ed1a4e
refs/heads/master
<repo_name>nuttavadeepj/flutter_credential<file_sep>/lib/main.dart import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/services.dart'; void main() { runApp(MyApp()); } const primaryColor = Color(0xFF742092); const buttonColor = Color(0xFF73A794); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => ApplicationState(), builder: (context, _) => Consumer<ApplicationState>( builder: (ctx, auth, _) => MaterialApp( home: auth.credentials != null ? HomePage() : LoginPage()))); } } class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { var _current = 0; var _itemController = TextEditingController(); void _onChangePage(page) { setState(() { _current = page; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: primaryColor, title: Text('Sign in Form'), actions: [ IconButton( icon: Icon(Icons.logout), onPressed: () { Provider.of<ApplicationState>(context, listen: false).logout(); }) ], ), body: Text( 'You are inside the system', style: TextStyle(color: Color(0xFF742092), fontSize: 20), ), ); } } class LoginPage extends StatelessWidget { final _emailController = TextEditingController(); final _passwordController = TextEditingController(); final _formkey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: primaryColor, title: Text('Sign in Form'), ), body: Container( padding: EdgeInsets.symmetric(horizontal: 40), child: Padding( padding: const EdgeInsets.only(top: 40), child: Column( children: [ Form( key: _formkey, child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 30), child: TextFormField( controller: _emailController, autofocus: true, decoration: InputDecoration( labelText: 'Email', border: OutlineInputBorder()), validator: (value) { if (value.isEmpty) { return 'Please enter email'; } return null; }, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: TextFormField( controller: _passwordController, keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], decoration: InputDecoration( labelText: 'Password', border: OutlineInputBorder()), validator: (value) { if (value.isEmpty) { return 'Please enter password'; } return null; }, ), ), ], )), Padding( padding: const EdgeInsets.only(top: 30), child: ElevatedButton( onPressed: () { final email = _emailController.text; final password = _passwordController.text; Provider.of<ApplicationState>(context, listen: false) .login(email, password, context); }, child: Text('Sign In'), ), ), ], ), )), ); } } class ApplicationState extends ChangeNotifier { String credentials; ApplicationState() { init(); } Future<void> init() async { await Firebase.initializeApp(); FirebaseAuth.instance.userChanges().listen((user) { if (user != null) { credentials = user.email; } else { credentials = null; } notifyListeners(); }); } Future<void> logout() async { await FirebaseAuth.instance.signOut(); notifyListeners(); } Future<void> login( String email, String password, BuildContext context) async { UserInfo userInfo = UserInfo(email: email, password: password); try { var status = await FirebaseAuth.instance .fetchSignInMethodsForEmail(userInfo.email); if (!status.contains('password')) { await FirebaseAuth.instance.createUserWithEmailAndPassword( email: userInfo.email, password: <PASSWORD>); } else { try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: userInfo.email, password: userInfo.password); } on FirebaseAuthException catch (_) { showDialog( context: context, builder: (_) => AlertDialog( title: Text("Email is already used with others password"), )); } } } on FirebaseAuthException catch (_) { showDialog( context: context, builder: (_) => AlertDialog( title: Text("Email is Invalid Format"), )); } notifyListeners(); } } class UserInfo { String email; String password; UserInfo({this.email, this.password}); } <file_sep>/lib/mainauthen.dart import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_auth/firebase_auth.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => ApplicationState(), builder: (context, _) => Consumer<ApplicationState>( builder: (ctx, auth, _) => MaterialApp( home: auth.credentials != null ? SecondPage() : LoginPage()))); } } class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { final _formkey = GlobalKey<FormState>(); FocusNode myFocusNode; final _emailController = TextEditingController(); final _passwordController = TextEditingController(); final password = <PASSWORD>; @override void initState() { super.initState(); myFocusNode = FocusNode(); } @override void dispose() { myFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0xFFC858BA), title: Text( 'LOGIN', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 21), ), ), body: Column( children: [ LoginContent(), Form( key: _formkey, child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric( horizontal: 38, vertical: 30), child: TextFormField( focusNode: myFocusNode, controller: _emailController, autofocus: true, decoration: InputDecoration( labelText: 'Email', border: OutlineInputBorder()), validator: (value) { if (value.isEmpty) { return 'Please enter email'; } return null; }, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 38), child: TextFormField( controller: _passwordController, obscureText: password, decoration: InputDecoration( labelText: 'Password', border: OutlineInputBorder()), validator: (value) { if (value.isEmpty) { return 'Please enter password'; } return null; }, ), ), Padding( padding: const EdgeInsets.only(top: 30), child: ElevatedButton( onPressed: () { final email = _emailController.text; final password = _passwordController.text; Provider.of<ApplicationState>(context, listen: false) .login(email, password, context); myFocusNode.requestFocus(); if (_formkey.currentState.validate()) { ApplicationState().login(email, password, context); } }, child: Text('SUBMIT'), ), ), ], )), ], ), floatingActionButton: Padding( padding: const EdgeInsets.all(13.0), child: FloatingActionButton( backgroundColor: Color(0xFFC858BA), child: Icon(Icons.chevron_right), tooltip: 'next', onPressed: () { print(_emailController.text); print(_passwordController.text); }, ), ), ); } } class LoginContent extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: Center( child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 40), child: Text( 'PLEASE LOGIN BELOW', style: TextStyle(color: Color(0xFF742092), fontSize: 20), ), ) ], ), ), ); } } class SecondPage extends StatefulWidget { @override _SecondPageState createState() => _SecondPageState(); } class _SecondPageState extends State<SecondPage> { var _current = 0; void _onChangePage(page) { setState(() { _current = page; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0xFFC858BA), title: Text( // 'PAGE 2', _current == 0 ? "Page2" : "Page3", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 21), ), actions: [ IconButton( onPressed: () { Provider.of<ApplicationState>(context).logout(); }, icon: Icon(Icons.logout)) ], ), body: Center( child: _current == 0 ? Column( children: [Text('This is page 2')], ) : Column( children: [ Text('This is page 3'), ], ), ), bottomNavigationBar: BottomNavigationBar( currentIndex: _current, backgroundColor: Color(0xFFC858BA), selectedItemColor: Color(0xFFFFC973), items: [ BottomNavigationBarItem( icon: Icon(Icons.chevron_left), label: 'left'), BottomNavigationBarItem( icon: Icon(Icons.chevron_right), label: 'right'), ], onTap: _onChangePage, ), floatingActionButton: _current == 0 ? FloatingActionButton( onPressed: () {}, child: Icon(Icons.add), backgroundColor: Color(0xFF742092), ) : null, ); } } class ApplicationState extends ChangeNotifier { String credentials; ApplicationState() { init(); } Future<void> init() async { await Firebase.initializeApp(); FirebaseAuth.instance.userChanges().listen((user) { if (user != null) { credentials = user.email; } else { credentials = null; } notifyListeners(); }); } Future<void> logout() async { await FirebaseAuth.instance.signOut(); notifyListeners(); } Future<void> login( String email, String password, BuildContext context) async { UserInfo userInfo = UserInfo(email: email, password: password); try { var status = await FirebaseAuth.instance .fetchSignInMethodsForEmail(userInfo.email); if (!status.contains('password')) { await FirebaseAuth.instance.createUserWithEmailAndPassword( email: userInfo.email, password: userInfo.password); } else { try { await FirebaseAuth.instance.signInWithEmailAndPassword( email: userInfo.email, password: <PASSWORD>.password); } on FirebaseAuthException catch (_) { showDialog( context: context, builder: (_) => AlertDialog( title: Text("Email is already used with others password"), )); } } } on FirebaseAuthException catch (_) { showDialog( context: context, builder: (_) => AlertDialog( title: Text("Email is Invalid Format"), )); } notifyListeners(); } } class UserInfo { String email; String password; UserInfo({this.email, this.password}); }
f16f4fb6abd496cfbd296d7a61c1d73d9badcb92
[ "Dart" ]
2
Dart
nuttavadeepj/flutter_credential
c92ba6457497ef798dd73f11592e442c91db8eb2
31641f9f17faa05ae26c46734d9eb74412c6bbf8
refs/heads/master
<repo_name>TannaManohar/EE026_57<file_sep>/os.c #include<stdio.h> #include <semaphore.h> #define MAX_RESOURCES 5 // available_resources would be involved in the race condition int available_resources = MAX_RESOURCES; /* decrease available_resources by count resources return 0 if sufficient resources available, otherwise return -1 */ int decrease_count(int count) { if (available_resources < count) return -1; else { available_resources -= count; return 0; } } // increase available_resources by count int increase_count(int count) { available_resources += count; return 0; } int main(void) { sem_t semaphore; sem_init(&semaphore, 0, 1); printf("\n Job %d started\n", sem_init); sem_wait(&semaphore); printf("\n Job %d waiting\n", sem_wait); sem_post(&semaphore); }
ae87fdaee9090545d1839782e5dbf620f1a4f692
[ "C" ]
1
C
TannaManohar/EE026_57
976bf0aa22704264fd14a5fd7191aae6122b3e2b
6e364e88b51bce2f6890916bec9ec2763438227b
refs/heads/master
<repo_name>BrianErikson/gh-notify<file_sep>/src/notify.rs use notify_rust::{Notification, NotificationHint, NotificationUrgency}; use rusthub::notifications; use std::process::Command; use std::thread; use std::path::Path; const APP_NAME: &'static str = "gh-notify"; pub fn show_notification(notification: &notifications::Notification) { let subject = format!("{} - {}", notification.subject.subject_type, notification.repository.name); let body = notification.subject.title.clone(); let url = notification.subject.url.clone(); let url = url.replace("api.", "").replace("repos/", "").replace("/pulls/", "/pull/"); thread::spawn(move || { notify_action( &subject, &body, "Open in Browser", 120, |action| { match action { "default" | "clicked" => { open_link(&url); }, "__closed" => (), _ => () } } ).unwrap_or_else(|err| error!("While showing notification: {}", err)); }); } pub fn open_link(url: &str) { debug!("Opening browser link: {}", url); let _ = Command::new("sh") .arg("-c") .arg(format!("xdg-open '{}'", url)) .output() .expect("Failed to open web browser instance."); } pub fn notify_action<F>(summary: &str, body: &str, button_text: &str, timeout: i32, action: F) -> Result<(), String> where F: FnOnce(&str) { let icon = match Path::new("./icon.png").canonicalize() { Ok(path) => path.to_string_lossy().into_owned(), Err(_) => "clock".to_string() }; let handle = try!(Notification::new() .appname(APP_NAME) .summary(&summary) .icon(&icon) .body(&body) .action("default", &button_text) // IDENTIFIER, LABEL .action("clicked", &button_text) // IDENTIFIER, LABEL .hint(NotificationHint::Urgency(NotificationUrgency::Normal)) .timeout(timeout) .show().map_err(|err| err.to_string())); handle.wait_for_action(action); Ok(()) }<file_sep>/src/main.rs #[macro_use] extern crate log; extern crate rusthub; extern crate notify_rust; extern crate rustc_serialize; extern crate env_logger; mod io; mod notify; use rusthub::notifications; use rusthub::notifications::{NotificationResponse, Notifications}; use std::thread; use std::time::Duration; const TIMEOUT: i32 = 120; fn filter_unseen(notifications: &Notifications) -> Notifications { let list = match io::get_saved_notifications() { Ok(saves) => notifications.list .clone() .into_iter() .filter(|n| !saves.list.iter().any(|sn| n.updated_at == sn.updated_at && n.subject.title == sn.subject.title)) .collect(), Err(err) => { error!("{}", err); notifications.list.clone() } }; Notifications { list: list } } fn main() { // INIT env_logger::init().unwrap(); let token: String = io::retrieve_token(TIMEOUT).unwrap(); debug!("Token: {}", &token); // TODO: Check if this token is stale before using it in the main loop // MAIN LOOP loop { // Get notifications let response: NotificationResponse = notifications::get_notifications_oauth(&token).unwrap(); let unseen = filter_unseen(&response.notifications); debug!("Unseen Notifications: {} out of {}", unseen.list.len(), response.notifications.list.len()); // Display notifications for notification in &unseen.list { notify::show_notification(&notification); thread::sleep(Duration::new(0, 500000000)); // Sleep for a half-second to give notify api a chance } // Cache Previous Notifications io::write_notifications(&response.notifications) .unwrap_or_else(|err| error!("While writing notifications: {}", err)); debug!("\nPoll Interval: {}\nRate Limit: {}\nRate Limit Remaining: {}", response.poll_interval, response.rate_limit, response.rate_limit_remaining); // Sleep for requested time by GitHub let sleep_time: u64 = response.poll_interval as u64; thread::sleep(Duration::new(sleep_time, 0)); } }<file_sep>/README.md # gh-notify ![icon](http://i.imgur.com/ovNhtF4.png) Lightweight GitHub notifier built with Rust <file_sep>/src/io.rs use std::io::{Read, Write}; use std::env; use std::fs::{DirBuilder, OpenOptions, File}; use std::path::PathBuf; use std::path::Path; use rustc_serialize::{Decoder, Decodable, Encoder, Encodable}; use rustc_serialize::json; use rusthub::oauth_web; use rusthub::notifications::{Notifications}; use notify; #[derive(Debug)] struct GhNotifyConfig { token: String } impl Decodable for GhNotifyConfig { fn decode<D: Decoder>(d: &mut D) -> Result<GhNotifyConfig, D::Error> { d.read_struct("root", 1, |d| { Ok(GhNotifyConfig { token: try!(d.read_struct_field("token", 0, |d| Decodable::decode(d))) }) }) } } impl Encodable for GhNotifyConfig { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_struct("root", 1, |s| { try!(s.emit_struct_field("token", 0, |s| { s.emit_str(&self.token) })); Ok(()) }) } } fn get_notifications_path() -> PathBuf { let mut path = get_notify_path(); path.push("prev_notifications.json"); path } fn get_config_path() -> PathBuf { let mut path = get_notify_path(); path.push("config"); path } fn get_notify_path() -> PathBuf { let mut path = env::home_dir().expect("Can't find home directory!"); path.push(".gh-notify"); path } fn open_file(path: &PathBuf) -> Result<File, String> { info!("Opening {}...", path.as_path().to_string_lossy()); match path.is_file() { false => { info!("File doesn't exist. Creating directories..."); let mut dir = env::home_dir().expect("Impossible to get your home dir!"); dir.push(".gh-notify"); try!(DirBuilder::new() .recursive(true) .create(&dir).map_err(|err| err.to_string())); OpenOptions::new() .read(true) .write(true) .create(true) .open(&path).map_err(|err| err.to_string()) } true => OpenOptions::new() .read(true) .write(true) .create(true) .open(&path).map_err(|err| err.to_string()) } } fn build_new_token(timeout: i32) -> Result<String, String> { info!("Building new token..."); let client_id = "f9128<KEY>7de".to_string(); let scope = vec!("notifications".to_string()); let mut secret = String::new(); debug!("Opening secret..."); try!(File::open(&Path::new("secret")) .expect("Could not open secret") .read_to_string(&mut secret).map_err(|err| err.to_string())); let url = oauth_web::create_authentication_link(client_id.clone(), scope, true); try!(notify::notify_action( "Authorize gh-notify for GitHub Access", "gh-notify needs authorization in order to receive notifications. Click to open an authorization window.", "Open Browser", timeout, |action| { match action { "default" | "clicked" => { notify::open_link(&url); }, "__closed" => error!("the notification was closed before authentication could occur"), _ => () } } )); debug!("Capturing authorization from GitHub redirect. Blocking..."); let token = try!(match oauth_web::capture_authorization(client_id, secret, timeout as u64) { Some(token) => Ok(token), None => Err("Authorization capture either timed out or something went wrong...") }); try!(write_config(&GhNotifyConfig { token: token.clone() })); Ok(token) } fn write_config(config: &GhNotifyConfig) -> Result<(), String> { info!("Writing configuration to disk..."); let mut file = try!(OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&get_config_path()) .map_err(|err| err.to_string())); let encode: String = try!(json::encode(config).map_err(|err| err.to_string())); try!(file.write(encode.as_bytes()).map_err(|err| err.to_string())); try!(file.flush().map_err(|err| err.to_string())); debug!("Configuration saved."); Ok(()) } pub fn retrieve_token(timeout: i32) -> Result<String, String> { info!("Retrieving token..."); let mut config = try!(open_file(&get_config_path())); let mut json_str = String::new(); let token: String = match config.read_to_string(&mut json_str) { Ok(_) => { debug!("Config file read sucessfully. Parsing..."); match json::decode::<GhNotifyConfig>(&json_str) { Ok(config_struct) => config_struct.token, Err(_) => try!(build_new_token(timeout)) } }, Err(_) => try!(build_new_token(timeout)) }; Ok(token) } pub fn get_saved_notifications() -> Result<Notifications, String> { info!("Getting saved notifications..."); let mut file: File = try!(open_file(&get_notifications_path())); let mut json_str = String::new(); match file.read_to_string(&mut json_str) { Ok(_) => { info!("Notifications file read sucessfully. Parsing..."); match json::decode::<Notifications>(&json_str) { Ok(notifications) => Ok(notifications), Err(err) => Err(err.to_string()) } }, Err(err) => Err(err.to_string()) } } pub fn write_notifications(w_notifications: &Notifications) -> Result<(), String> { match json::encode(&w_notifications) { Ok(str) => { let mut write_file = try!(open_file(&get_notifications_path())); try!(write_file.set_len(0).map_err(|err| err.to_string())); // Truncate to 0 try!(write_file.write(str.as_bytes()).map_err(|err| err.to_string())); try!(write_file.flush().map_err(|err| err.to_string())); info!("Notifications written to file."); Ok(()) } Err(err) => Err(err.to_string()) } }<file_sep>/Cargo.toml [package] name = "gh-notify" version = "0.1.0" authors = ["brianerikson <<EMAIL>>"] description = "Github Notifier built with Rust" homepage = "https://github.com/BrianErikson/gh-notify" repository = "https://github.com/BrianErikson/gh-notify" readme = "README.md" keywords = [ "github" ] license = "MIT" build = "build.rs" [dependencies] rusthub = { git = "https://github.com/puritylake/rusthub.git", rev = "c91c43e89bd68d84de782e3ceb5d9f6086d1a030" } notify-rust = "3.1.1" rustc-serialize = "0.3.19" log = "0.3.6" env_logger = "0.3.3"<file_sep>/build.rs use std::env; use std::fs; fn main() { let home_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let out_dir: String; let target = env::var("OUT_DIR").unwrap(); match target { _ if target.contains("release") => out_dir = format!("{}/target/release", home_dir), _ if target.contains("debug") => out_dir = format!("{}/target/debug", home_dir), _ => panic!("Could not find target directory.") }; let in_secret_path = format!("{}/secret", home_dir); let out_secret_path = format!("{}/secret", out_dir); let in_icon_path = format!("{}/icon.png", home_dir); let out_icon_path = format!("{}/icon.png", out_dir); fs::copy(&in_secret_path, &out_secret_path).unwrap(); fs::copy(&in_icon_path, &out_icon_path).unwrap(); }
9665a1a9fc846110ead1f07f1278c1a8bf304a30
[ "Rust", "Markdown", "TOML" ]
6
Rust
BrianErikson/gh-notify
c834504d291f111e40af3ed59728b0194ce3f25a
4f7e8674e53ef822be0fb536abc6d695fb07d563
refs/heads/main
<file_sep>package us.careydevelopment.util.ip.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Service; import us.careydevelopment.util.ip.config.IpApiConfig; import us.careydevelopment.util.ip.model.CityBlocksIpv4; import us.careydevelopment.util.ip.repository.CityBlocksIpv4Repository; /** * This is a Spring-aware singleton. * * You can instantiate it from any Java application, whether it's using Spring or not. * * The whole point here is to take advantage of Spring framework benefits (repository * interface, document-to-object mapping, etc.) without burdening the application that * use this singleton with Spring dependencies. * * @author <NAME> * */ @Service public class IpService { private static IpService IP_SERVICE; @Autowired private CityBlocksIpv4Repository ipv4Repo; /** * This singleton will "Springify" this entire package if it * hasn't already done so. * * It uses AnnotationConfigApplicationContext to load the config * file that ultimately scans the entire package for Spring-specific * annotations. * * Then, it returns this object as retrieved from the application context. * * @return IpService singleton */ public static IpService getIpService() { if (IP_SERVICE == null) { ApplicationContext context = new AnnotationConfigApplicationContext(IpApiConfig.class); IP_SERVICE = context.getBean(IpService.class); } return IP_SERVICE; } /** * Saves an IPv4 IP address object. * * @param ip */ public void persistIpv4(CityBlocksIpv4 ip) { ipv4Repo.save(ip); } /** * Searches for a match based on IP address * * Will perform a Class C search if no matches on full IP address. * * @param ipAddress - full IP address * @return - list of matching GeoInfo objects */ public List<CityBlocksIpv4> findByIpAddress(String ipAddress) { List<CityBlocksIpv4> list = new ArrayList<>(); if (ipAddress != null) { list = ipv4Repo.findByIpAddress(ipAddress); if (list == null || list.size() == 0) { return findByClassC(ipAddress); } } return list; } /** * Accepts a full IP address and searches for matches based on the first three numbers. * * It's a search by Class C network, where everything before the last period is part of the same * network. * * @param ipAddress - full IP address * @return - list of matching GeoInfo objects */ public List<CityBlocksIpv4> findByClassC(String ipAddress) { List<CityBlocksIpv4> list = new ArrayList<>(); if (ipAddress != null) { int lastPeriod = ipAddress.lastIndexOf("."); if (lastPeriod > -1) { String firstThreeNumbers = ipAddress.substring(0, lastPeriod); list = ipv4Repo.findByClassC(firstThreeNumbers); } } return list; } } <file_sep>package us.careydevelopment.util.ip.util; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import us.careydevelopment.util.ip.model.CityBlocksIpv4; import us.careydevelopment.util.ip.model.GeoInfo; import us.careydevelopment.util.ip.service.IpService; /** * I use this class to update the database from time to time. * * IP Info comes from MaxMind. * * https://www.maxmind.com * * @author <NAME> */ public class IpInfoPersister { private static final String IPV4_DATA = "./GeoLite2-City-Blocks-IPv4.csv"; private static final String GEO_DATA = "./GeoLite2-City-Locations-en.csv"; private IpService service = IpService.getIpService(); public static void main(String[] args) { IpInfoPersister persister = new IpInfoPersister(); persister.go(); } private void go() { List<GeoInfo> geos = getGeoInfo(); persistIpv4Data(geos); } private List<GeoInfo> getGeoInfo() { List<GeoInfo> geos = new ArrayList<>(); Path path = Paths.get(GEO_DATA); try (Stream<String> stream = Files.lines(path)) { geos = stream.map(line -> { GeoInfo geo = getGeoInfoFromLine(line); //System.err.println(geo); return geo; }).collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } return geos; } private void persistIpv4Data(List<GeoInfo> geos) { Path path = Paths.get(IPV4_DATA); try (Stream<String> stream = Files.lines(path)) { stream .skip(3000001) //.limit(500000) .parallel() .map(line -> { CityBlocksIpv4 ip = getIpFromLine(line, geos); System.err.println("Retrieved " + ip); return ip; }) .filter(ip -> ip.getGeoInfo() != null) .forEach(ip -> { service.persistIpv4(ip); }); } catch (IOException e) { e.printStackTrace(); } } private GeoInfo getGeoInfoFromLine(String line) { GeoInfo geo = new GeoInfo(); String[] parts = line.split(","); String geoNameId = parts[0]; String localeCode = parts[1]; String continentCode = parts[2]; String continentName = stripQuotes(parts[3]); String countryIsoCode = parts[4]; String countryName = stripQuotes(parts[5]); String cityName = stripQuotes(parts[10]); String timeZone = parts[12]; String state = stripQuotes(parts[7]); String isInEuInd = parts[13]; boolean isInEu = "1".equals(isInEuInd); geo.setCityName(cityName); geo.setContinentCode(continentCode); geo.setContinentName(continentName); geo.setCountryIsoCode(countryIsoCode); geo.setCountryName(countryName); geo.setGeoNameId(geoNameId); geo.setIsInEuropeanUnion(isInEu); geo.setLocaleCode(localeCode); geo.setTimeZone(timeZone); geo.setState(state); return geo; } private CityBlocksIpv4 getIpFromLine(String line, List<GeoInfo> geos) { CityBlocksIpv4 ip = new CityBlocksIpv4(); String[] parts = line.split(","); String network = parts[0]; String ipAddress = getIpAddressFromNetwork(network); String geoNameId = parts[1]; Optional<GeoInfo> geoOpt = geos .stream() .filter(geo -> geo.getGeoNameId().equals(geoNameId)) .findFirst(); if (geoOpt.isPresent()) { ip.setGeoInfo(geoOpt.get()); ip.setNetwork(network); ip.setIpAddress(ipAddress); } return ip; } private String getIpAddressFromNetwork(String network) { String ipAddress = network; if (network != null) { int slash = network.indexOf("/"); if (slash > -1) { ipAddress = network.substring(0, slash); } } return ipAddress; } private String stripQuotes(String orig) { String updated = orig; if (orig != null) { int quote = orig.indexOf("\""); if (quote == 0) { updated = orig.substring(1, orig.length() - 1); } } return updated; } } <file_sep>package us.careydevelopment.util.ip.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; /** * Handles configuration for MongoDB. * * Properties are set in the application.properties file * * @author <NAME> * */ @Configuration @ComponentScan("us.careydevelopment.util.ip") @EnableMongoRepositories(basePackages= {"us.careydevelopment.util.ip.repository"}) public class MongoConfig extends AbstractMongoClientConfiguration { private static final Logger LOG = LoggerFactory.getLogger(MongoConfig.class); @Value("${mongo.db}") private String mongoConnection; @Value("${mongo.db.name}") private String mongoDatabaseName; @Override protected String getDatabaseName() { return mongoDatabaseName; } @Override @Bean public MongoClient mongoClient() { MongoClient client = MongoClients.create(mongoConnection); return client; } public @Bean MongoTemplate mongoTemplate() { return new MongoTemplate(mongoClient(), "ipDB"); } } <file_sep>package us.careydevelopment.util.ip.config; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * Main config class. * * Remember: this class needs to be loaded via AnnotationConfigApplicationContext. * * You can see an example of that in the {@link us.careydevelopment.util.ip.service.IpService IpService class}. * * @author <NAME> * */ @PropertySource("classpath:application.properties") @Configuration @ComponentScan("us.careydevelopment.util.ip") public class IpApiConfig { /** * Static method available if, for whatever reason, some developer wants to use this package * independent of the service. */ public static void init() { ApplicationContext context = new AnnotationConfigApplicationContext(IpApiConfig.class); } /** * Necessary to read @Value */ @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } } <file_sep>package us.careydevelopment.util.ip.model; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.springframework.data.mongodb.core.mapping.Document; /** * Forgive the awkward class name. It's borrowed from the dataset provided by * MaxMind. * * This object includes details about an IPv4 address. * * @author <NAME> * */ @Document(collection = "#{@environment.getProperty('mongo.ipv4.collection')}") public class CityBlocksIpv4 { private String ipAddress; private String network; private GeoInfo geoInfo; public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getNetwork() { return network; } public void setNetwork(String network) { this.network = network; } public GeoInfo getGeoInfo() { return geoInfo; } public void setGeoInfo(GeoInfo geoInfo) { this.geoInfo = geoInfo; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((network == null) ? 0 : network.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CityBlocksIpv4 other = (CityBlocksIpv4) obj; if (network == null) { if (other.getNetwork() != null) return false; } else if (!network.equals(other.getNetwork())) return false; return true; } public String toString() { return ReflectionToStringBuilder.toString(this); } }
2ba921e36bc27f9eef15758bdcac309601f8ead4
[ "Java" ]
5
Java
careydevelopment/ip-api
fe27d8efded152618a88184a4b18b5cbd14e1924
3f132e0176c02d55e5e7c73e506bbf6a53a3ce41
refs/heads/master
<repo_name>Ydeh22/Spiking-Neural-Network-Encoder-RTL<file_sep>/ut_SpikeDriver_SPI_RTL/mem/SPI_slv_dpRAM_256x16.v /* ---------------------------------------------------------------------------- MODULO de interface serial == SPI_slv_dpRAM_ == (CMD = 24 bits) autor: <NAME> versão: 1.1 data: 2019_04_23 -- Módulo SPI SLAVE memória DUAL-PORT RAM (port "b" carregada por SPI) O modulo endereça até (2^14)-1 pos mem, (Addx vem no SRcmd, de 16 bits) NÃO USAR o endereço Addx = 14'b00_0000_0000_0000 (reservado). O módulo usa padrão SPI de 4 fios (CPOL=1 CPHA=1 ou CPOL=0 CPHA=0) sck ==> clock da interface que vem do MESTRE que controla barramento mosi ==> dado de entrada (1 bit serial) do mestre para este escravo miso ==> dado de saída (1 bit serial) daqui p/ mestre nss ==> chip select (em NÍVEL LOW enquanto há comunicação M<=>S) OBS: o sinal sck é enviado como clk da memória no "port b" -- Funcionamento: 1. o mestre baixa=↓nss (nss=0 ativo; nss=1 final) 2. mestre coloca bit de dado (para SRcmd) 3. mestre pulsa "sck" (↓sck e ↑sck)ou(↑sck e ↓sck) - strCapture ↑sck 4. depois de 14 pulsos, SRcmd = |Add14| ... |Add0| ? | ? | 4.1 o circ copia SRcmd[13:0] p/ "Radd_b" 5. No 15o. pulso o sinal SRcmd[1] é copiado (ler=1; escrever=0) 6. se SRCmd[1]=0, (memory write) 6.1 até 15o ↑sck o circ copia MOSI e desloca SRin, 6.2 na ↓sck qdo (SZW-1), o circ gera wen_b; 6.3 prox ↑sck, copia {SRin[SZWD-2:0], mosi} p/ mem pelo port-b 6.4 prox ↓sck baixa wen_b; 6.5 O valor do Radd_b (= Add_b) é inc 2 sck após wen_b (++Radd_b) 6.5 se SRcmd[0]=1 (modo contínuo), repete de 6.1 (até que item 8 ocorra) 7. se SRCmd[1]=1, (memory read) 7.1 na do 16o. pulso ↑sck o circ lê memória (retido em Q_b) 7.2 na prox ↓sck copia Q_b p/ SRout 7.3 O valor do Radd_b (= Add_b) é inc (++Radd_b) 7.3 a cada ↓sck desloca SRout 1 bit p/ esquerda até SZW-1, 7.4 se SRcmd[0]=1, em (SZW-1), prox ↑sck, lê mem p/ Q_b e repete 7.2 8. quando ↑nss volta para reset OBS: ** alterar o módulo DPRAM (IP da Intel) "dpRAM_01" e ajustar: SZWD(A/B) = para o tamanho da palavra (8/16/32 bits) de memória SZADD(A/B) = tamanho do bus add da memória (e.g. p/ 1K, SZADD=10) Params do IP DPRAM: clk_a, clk_b, wen_a, wen_b separados, o resto default ADD0 é end inicial desse módulo de RAM; e ADDF = ADD0+((2**SZADD)-1). -----------------------------------------------------------------------------*/ module SPI_slv_dpRAM_256x16 ( input sck, mosi, nss, // inputs SPI output miso, // serial OUT (usar OR em >1 interface) input [SZADDA-1:0] Add_a, // end porta "a" input clk_a, wen_a, // clk_a e write enable de 'a' input [SZWDA-1:0] D_a, // dado entrada p/ mem p/ port 'a' output [SZWDA-1:0] Q_a // dado saída p/ mem p/ port 'a' ); // pars *passados: larg WORD mem, larg Add_bus mem, faixa ends dessa interface parameter SZWDA = 1; // larg word port_a (ex 1 bits) parameter SZADDA = 8; // larg Add_a: (ex 8 bits=256 adds) parameter SZWDB = 16; // larg word port_b (ex 16 bits) parameter SZADDB = 4; // larg Add_b: (ex 4 bits=16 adds) parameter SZCMD = 24; // tam reg de comando: SRcmd parameter ADD0 = 22'h3F_0000; // end inic RAM (ex:3F_0000...3F_FFFF) // parametros locais localparam SZADD = SZCMD-2; // tam reg end desse dispositivo SPI localparam SZCMDcnt = 5; // num bits do contador de comando localparam SZBITcnt = 6; // num bits do contador de BITs localparam ADDF=ADD0+((2**SZADDB)-1);// end final desse bloco de RAM // p/ zerar SRdata E SRcmd - independente do comprimento em bits deles localparam [SZWDB-1:0] RESSR = {{(SZWDB-1){1'b0}}, 1'b0}; localparam [SZCMD-1:0] RESCMD = {{(SZCMD-1){1'b0}}, 1'b0}; localparam [SZCMDcnt-1:0] REScntCMD = {{(SZCMDcnt-1){1'b0}}, 1'b0}; localparam [SZCMDcnt-1:0] LOCKcntCMD = {{(SZCMDcnt-1){1'b1}}, 1'b1}; localparam [SZBITcnt-1:0] REScntBIT = {{(SZBITcnt-1){1'b0}}, 1'b0}; localparam [SZBITcnt-1:0] LOCKcntBIT = {{(SZBITcnt-1){1'b1}}, 1'b1}; localparam [SZADDB-1:0] RESADDB = {{(SZADDB-1){1'b0}}, 1'b0}; localparam [SZADDB-1:0] RESADDSPI = {{(SZADD-1){1'b0}}, 1'b0}; // esses registradores tem a ver com a interface serial de config reg [SZWDB-1:0] SRin, SRout; // shiftReg entrada e saída reg [SZCMD-1:0] SRcmd; // ShiftReg in comando reg [SZADD-1:0] RaddSPI; // reg com end do disp SPI reg [SZADDB-1:0] Radd_b; // reg end mem port-b (via SPI) reg [SZCMDcnt-1:0] CntCMD; // conta bits de COMANDO reg [SZBITcnt-1:0] CntBIT; // conta bits de DADOS reg nxtWD; // flag new WD na ↓sck reg fWRDok; // flag chegou word wire mCS; // mem ChipSelect dessa DPRAM // lógica combinacional deste módulo assign miso = mCS ? SRout[SZWDB-1]: 1'b0; assign mCS = ((RaddSPI>=ADD0) && (RaddSPI<=ADDF))? 'b1: 'b0; // SUBIDA de sck: controla contadores de bits CMD ou DATA always @(posedge sck or posedge nss) begin if(nss=='b1) // ... em reset begin SRcmd <= RESCMD; // zera o registrador de COMANDO SRin <= RESSR; // zera o reg desloc de entrada RESSR CntCMD <= REScntCMD; // zera contador de bits COMANDO CntBIT <= REScntBIT; // zera contador de bits DADOS nxtWD <= 'b0; // indicador prox palavra fWRDok <= 'b0; // não chegou comando... end else if (CntCMD < LOCKcntCMD) begin case (CntCMD) (SZCMD-1): begin CntCMD <= CntCMD + 'b1; // inc contador de bits SRcmd <= SRcmd << 1; // desloca SRcmd[0] <= mosi; // copia MOSI CntBIT <= REScntBIT; // zera contador de bits DADOS end SZCMD: begin nxtWD <= 'b0; // indicador prox palavra SRin <= SRin << 1; // e deslocar dados SRin[0] <= mosi; // entrada MOSI gravada em SRin[0] CntCMD <= LOCKcntCMD; // trava contador de bits COMANDO CntBIT <= CntBIT + 'b1; // continua contar bits end default: begin CntCMD <= CntCMD + 'b1; // inc contador de bits SRcmd <= SRcmd << 1; // desloca SRcmd[0] <= mosi; // copia MOSI end endcase end else if(CntBIT < LOCKcntBIT) begin case (CntBIT) (SZWDB-1): begin // tem que gravar na RAM fWRDok <= 'b1; // liga fWRDok (chegou ao menos 1 WRD) SRin <= SRin << 1; // e deslocar dados SRin[0] <= mosi; // entrada MOSI gravada em SRin[0] nxtWD <= 'b1; // indica nxt WORD p/ if (SRcmd[0]=='b1) // e flag SRcmd[0]=1 (continuar operação) CntBIT <= REScntBIT; // volta CntBIT para zero else CntBIT <= LOCKcntBIT; // se não, carrega CntBIT com 3F end default: begin nxtWD <= 'b0; // indica que não é next word CntBIT <= CntBIT + 'b1; // continua contar bits SRin <= SRin << 1; // e deslocar dados SRin[0] <= mosi; // entrada MOSI gravada em SRin[0] end endcase end end // DESCIDA de sck: controla se carrega e qdo desloca o SRout always @(negedge sck or posedge nss) begin if(nss=='b1) // ... em reset begin SRout <= RESSR; // zera o reg desloc de saída RESSR end else if (CntCMD<LOCKcntCMD) // se ainda recebe CMD begin if (CntCMD == SZCMD) // se contadora bits cmd = SZCMD begin SRout <= Q_b; // copia o valor da mem Q_b p/ SRout end end else // se não recebe mais bits de CMD begin if (nxtWD=='b1) // se flag next word=1 begin SRout <= Q_b; // copia o valor da mem Q_b p/ SRout end else // se nxt word =0, desloca SRout begin SRout <= SRout << 1; // deslocar dados end end end // DESCIDA de sck: controla quando grava WRD na RAM always @(negedge sck or posedge nss) begin if(nss=='b1) // ... em reset begin wen_b <= 'b0; // começa wen_b com zero end else if(CntBIT<LOCKcntBIT) // se recebe palavras... begin case (CntBIT) (SZWDB-1): begin wen_b <= mCS & ~SRcmd[1];// gera write enable end default: begin wen_b <= 'b0; // volta wen_b p/ zero end endcase end end // DESCIDA: controla o gerador de ENDEREÇO LOCAL (Radd_b) de memória always @(negedge sck or posedge nss) begin if(nss == 'b1) // ... em reset begin Radd_b <= RESADDB; // inicializa Radd_b com zero RaddSPI <= RESADDSPI; // inicializa RaddSPI com zero end else if (CntCMD == (SZCMD-2)) // se vieram SZCMD-2 bits cmd begin RaddSPI <= SRcmd[SZCMD-3:0]; // carrega RaddSPI c/ bits do SRcmd Radd_b <= SRcmd[SZADDB-1:0]; // carrega Radd_b c/ end ini da mem end else if (CntBIT == 2) // no 2o. bit do CntBIT begin if (SRcmd[1] || fWRDok) // é LER mem ou chegou nova word? begin Radd_b <= Radd_b + 'b1; // inc add Radd_b (loop 0xFF-->0x00) end end end // --- para instanciar o IP de Dual-port RAM --- wire [SZWDB-1:0] D_b, Q_b; // Data in B e data out B reg wen_b; // write ena port b - daqui, do SPI assign D_b = {SRin[SZWDB-2:0],mosi}; // concatena dado que vai p/ memoria dpRAM_256x16 // inst IP DRPRAM (On Chip Memory) DP_U01 ( .address_a ( Add_a ), // add_a gerado p/ circ ext ao mod SPI .address_b ( Radd_b ), // Radd_b gerado aqui, pela SPI .clock_a ( clk_a ), // clock_a p/ uso do circ externo .clock_b ( sck ), // clock_b é o próprio SCK .data_a ( D_a ), // data_a do circ ext p/ gravar na RAM .data_b ( D_b ), // data_b vem do SPI (aqui SRin) .wren_a ( wen_a ), // vem do circ externo p/ gravar na RAM .wren_b ( wen_b ), // gerado aqui, após cada WRD do SPI .q_a ( Q_a ), // lido da RAM vai p/ circ ext - s/ uso .q_b ( Q_b )); // lido da RAM p/ SPI (sai em SRout) endmodule /* Como instanciar este bloco passando parâmetros: SPI_slv_dpRAM_256x16 # // mód SPI_slv_dpRAM_ (params) ( .SZWDA ( SZWDA ), // larg word port-a (1...1024 bits) .SZADDA ( SZADDA ), // larg bus Address mem port-a .SZWDB ( SZWDB ), // larg word port-b:SPI (32,16,8 bits) .SZADDB ( SZADDB ), // larg bus Address SPI port-b .SZCMD ( SZCMD ), // tamanho do reg. de comando "SRcmd" .ADD0 ( ADD0 ) // end inicial da memória ) xS_U1 // nome do componente/instancia ( .sck ( lsck ), // ligar local sck no "sck" do SPI .mosi ( lmosi ), // ligar local mosi no "mosi" do SPI .nss ( lnss ), // ligar local nss no "nss" do SPI .miso ( lmiso ), // ligar local miso no "miso" do SPI .Add_a ( LAdd_a ), // bus address da port a .clk_a ( lclk_a ), // clk da memória na port a .wen_a ( lwen_a ), // write enable da mem na port a .D_a ( LD_a ), // dado p/ a mem via port a .Q_a ( LQ_a ) // dado vindo da memória via port a ); Atenção ao atribuir endereços! Este módulo tem até 22 bits de endereçamento */ <file_sep>/ut_SpikeDriver_SPI_RTL/SpikeDriver_SPI.v /* ---------------------------------------------------------------------------- MODULO "Driver Codificador de Spike Train" == SpikeDriver_SPI == autor: <NAME> versão: 1.1 data: 2019_05_01 (SPI com 24 bits de comando) -- Este módulo recebe NÚMEROS por meio de porta serial, e converte em SPIKES. o circuito gera spikes para até 256 neurônios pulsantes (nrds) com código: (a)"rate coding": taxa de disparo proporcional ao valor enviado (0=silente) (b)"phase coding": tempo de retardo com relação a 1 nrd base dentre 16 grupos (c)"popularion coding": disparo ± em torno de um limiar dentre 16 grupos. ENTRADAS: - via mod "SPI_slv_dpRAM" escreve-se a DPRAM#1, um circ. externo escreve até 256 valores de 16 bits pela "port-b", cada Word(16) tem: tipoNrd=5bits | ValIN=11bits | tipoNrd: • 00000=nrd "rate code" (RC): valIN é delay p/ freqs (1 Hz ... ~666 Hz) valIN = int((2000-freq*2)/freq); onde "freq" é a frequência desejada. • 01bbbb=nrd "phase coding" (PH) e bbbb tem o indx da LUT c/ nrd que faz sync (valIN = delay com relação ao nrd indexado na LUT da base do grupo bbb) • 10bbbb=nrd "pop code" (PP), bbbb=indx do grupo na LUT c/ val limiar PPR:if(ValIN<(limiar<<2)){disparo=ValIN}else{zero} ValLIM = int( ((2000-freq*2)/freq)<<2 ). O valor é multiplicado p/ 4. ValIN: 11 bits que controlam delay ou limiar p/ disparo. - via "SPI_slv_dpRAM" escreve-se na DPRAM#2 (64W x 8bits) (a) escreve-se 16 vars 8 bits (add 0x00 até 0x0F), forma LUT com 16 indxs de nrds cujos disparos são usados para "phase coding"; ex: se nrd 7 é ref, depois que nrd 7 dispara, nrd X conta delay valIN(X)ms; se nrd 7 dispara em alta freq (delay menor que valIN(X), nrd X não dispara. (b) escreve-se 16 vars 8 bits (add 0x10 até 0x1F), com uma LUT C/ vals de limiares (delaysX4) p/ 16 grupos de nrds codificados em 'population code' ex: ValLIM=250, quaQuer delay menor que (250x4) gera freq saída, ou seja, se valIN < 1000 começa a disparar. F=1/T; 1/(999)ms => acima de ~1 Hz. ex: ValLIM=1, quaQuer delay menor que (1x4) gera saída = F=1/(3ms)=333Hz (c) escreve-se 32 indxs de nrds (add 0x20 até 0x3F), que terão as saídas ligadas diretamente aos fios em paralelo de saída Firin_Out (FiredOut). - via "SPI_slv_dpRAM" lê-se de uma DPRAM#3 (32W x 8bits = 256 bits). O LSB do end 0x00 da DPRAM3 tem 1 bit(=1) se nrd #0 disparou; (=0) se não, O MSB do end 0x1F da DPRAM3 tem 1 bit(=1) se nrd #255 disparou; (=0) se não, - TODOS os "Adds" das DPRAMs devem estar entre 0x0300 até 0x3FFF (maior). SAÍDA: 32 fios geram saída em paralelo de até 32 nrds, chamada FiredOut. Os indxs dos nrds que disparam está nos ends (add 0x20 até 0x3F) da DPRAM2. O módulo (SLAVE) usa SPI de 4 fios (CPOL=0 CPHA=0 OU 1,1) p/ enviar resultados sck ==> clock da interface que vem do MESTRE que controla barramento mosi ==> dado de entrada (1 bit serial) do mestre para este escravo miso ==> dado de saída (1 bit serial) daqui p/ mestre nss ==> chip select (em NÍVEL LOW enquanto há comunicação M<=>S) OBS: o sinal sck é enviado como clk da memória no "port b" -- Módulo SPI SLAVE memória DUAL-PORT RAM (port "b" carregada por SPI) O modulo endereça até (2^22)-1 pos mem, (Addx vem no SRcmd, de 24 bits) NÃO USAR Addx = 22'b00_0000_0000_0000_0000_0000 (reservado). O módulo usa padrão SPI de 4 fios (CPOL=1 CPHA=1 ou CPOL=0 CPHA=0) sck ==> clock da interface que vem do MESTRE que controla barramento mosi ==> dado de entrada (1 bit serial) do mestre para este escravo miso ==> dado de saída (1 bit serial) daqui p/ mestre nss ==> chip select (em NÍVEL LOW enquanto há comunicação M<=>S) OBS: o sinal sck é enviado como clk da memória no "port b" -- Funcionamento: 1. o mestre baixa=↓nss (nss=0 ativo; nss=1 final) 2. mestre coloca bit de dado (para SRcmd) 3. mestre pulsa "sck" (↓sck e ↑sck)ou(↑sck e ↓sck) - strCapture ↑sck 4. depois de 22 pulsos, SRcmd = |Add22| ... |Add0| ? | ? | 4.1 o circ copia SRcmd[21:0] p/ "Radd_b" 5. No 23o. pulso o sinal SRcmd[1] é copiado (ler=1; escrever=0) 6. se SRCmd[1]=0, (memory write) 6.1 até 23o ↑sck o circ copia MOSI e desloca SRin, 6.2 na ↓sck qdo (SZW-1), o circ gera wen_b; 6.3 prox ↑sck, copia {SRin[SZWD-2:0], mosi} p/ mem pelo port-b 6.4 prox ↓sck baixa wen_b; 6.5 O valor do Radd_b (= Add_b) é inc 2 sck após wen_b (++Radd_b) 6.5 se SRcmd[0]=1 (modo contínuo), repete de 6.1 (até que item 8 ocorra) 7. se SRCmd[1]=1, (memory read) 7.1 na ↑do 16o. ↑sck o circ lê memória (retém em Q_b) 7.2 na prox ↓sck copia Q_b p/ SRout 7.3 O valor do Radd_b (= Add_b) é inc (++Radd_b) 7.3 a cada ↓sck desloca SRout 1 bit p/ esquerda até SZW-1, 7.4 se SRcmd[0]=1, em (SZW-1), prox ↑sck, lê mem p/ Q_b e repete 7.2 8. quando ↑nss volta para reset obs1: ** este módulo grava PORT_B da memória via dados que vem do SPI. OBS2: ** alterar o módulo DPRAM (IP da Intel) "dpRAM_01" e ajustar: SZWD(A/B) = para o tamanho da palavra (8/16/32 bits) de memória SZADD(A/B) = tamanho do bus add da memória (e.g. p/ 1K, SZADDA=10) Params do IP DPRAM: clk_a, clk_b, wen_a, wen_b separados, o resto default ADD0 é end inicial desse módulo de RAM; e ADDF = ADD0+((2**SZADDB)-1). -----------------------------------------------------------------------------*/ module SpikeDriver_SPI // este modulo 256 nrds ( input clk10M, clk2K, nreset, // ↑clk_10_MHz, ↑clk_2_KHz e ↓reset input lsck, lmosi, lnss, // input do SPI output lmiso, // saída SPI output reg [SZPFIRED-1:0] FiredOut, // saída Parallel Firing OUt output [31:0] TestPoint, // test points 7 bits output [7:0] LED, output reg trg ); // ** para testes !!! reg [7:0] estado; assign TestPoint = {WQ_4a,2'b0,AddLST,estado}; assign LED[0] = rd_3a; //assign TestPoint = {WQ_4a,WQ_1a}; // parametros desse módulo no sistema parameter SZCMD = 24; // ** SPI: comando com 24 bits !!! parameter ADD0 = 22'h20_3800; // end ini da DPRAM#1 no sistema parameter ADD1 = 22'h20_3900; // end da DPRAM#2 no sistema parameter ADD2 = 22'h20_3940; // end da DPRAM#3 no sistema // parametros internos do módulo localparam SZWD1=16; // tam WRD da DPRAM#1 ports a/b localparam SZADD1 = 8; // tam do BUS de end da DPRAM#1 localparam SZWD2=SZADD1; // tam WRD da DPRAM#2 (idx p/ #1) localparam SZADD2 = 6; // tam do BUS de end da DPRAM#2 localparam SZWD3A = 1; // larg word port-a (1...1024 bits) localparam SZADD3A = 8; // larg bus Add mem port-a (256 bits) localparam SZWD3B = 16; // larg word port-b:SPI (32,16,8 bits) localparam SZADD3B = 4; // larg bus add mem port-b (16 wrds) localparam SZPFIRED=32; // tam saídas paralelas FiredOut // constantes para zerar ou setar regs internamente localparam [SZWD1-6:0] ZEROWD1 = {{(SZWD1-6){1'b0}},1'b0}; // 11 bits localparam [SZWD1-1:0] FIREDSTT1 = {4'b1100,{(SZWD1-8){1'b0}},4'b0001}; localparam [SZWD1-1:0] FIREDSTT2 = {4'b1100,{(SZWD1-8){1'b0}},4'b0010}; localparam [SZWD1-1:0] FIREDSTT3 = {4'b1100,{(SZWD1-8){1'b0}},4'b0100}; localparam [SZWD1-1:0] FIREDSTT4 = {4'b1100,{(SZWD1-8){1'b0}},4'b1000}; localparam [SZADD1-1:0] RESADDN = {{(SZADD1-1){1'b0}},1'b0}; localparam [SZADD1-1:0] ULTADDN = {{(SZADD1-1){1'b1}},1'b1}; localparam [SZADD3A-1:0] RESADDFRD = {{(SZADD3A-1){1'b0}},1'b0}; localparam [SZADD3A-1:0] ULTADDFRD = {{(SZADD3A-1){1'b1}},1'b1}; localparam [SZADD2-1:0] RESADDLST = {{(SZADD2-1){1'b0}}, 1'b0}; localparam [SZADD2-1:0] FIRADDLST = {1'b1,{(SZADD2-2){1'b0}},1'b0}; localparam [SZADD2-1:0] ULTADDLST = {{(SZADD2-1){1'b1}},1'b1}; // regs, flags e fios do sistema reg [SZWD1-1:0] RD_4a; // reg rasc guarda Resultado 1o. mod reg [SZWD1-1:0] Rasc; // reg rasc p/ PH e PP coding reg [SZADD1-1:0] AddN; // Add do nrd under test reg [SZADD2-1:0] AddLST; // add da mem dpRAM#2 reg [SZADD2-1:0] Radd_2a; // add rasc da mem dpRAM#2 reg [(2**SZWD2)-1:0] Rfired; // reg 255 bits c/ disparos (*t-1) reg wen_3a; // hab gravar port_a mem#3 (ctrl FSM) reg wen_4a; // hab gravar port_a mem#4 (ctrl FSM) // sel ADD (mux): p/ Add_2a (0=Q_1a, 1=AddLST); p/ Add_3a(0=AddN, 1=Q_2a) reg selmxAdd_2a; // selmux Add_2a control na FSM reg selmxAdd_3a; // selmux Add_3a control na FSM // lógica para geração do sinal de saída lmiso wire lmiso1, lmiso2, lmiso3; assign lmiso = lmiso1 | lmiso2 | lmiso3; // ** para testes reg [15:0] val_16; // ↑↑ FSM principal - controle de todo o processo reg [6:0] stt; // vetor p/ controlar estado da máq parameter SRES=0, CPMM_01=1, CPMM_02=2, CPMM_03=3, CPMM_04=4, CPMM_05=5, LOOP_INI=6, TEST_FIRED=7, AFT_FIRE_TST=8, LOOP_PH1=9, LOOP_PH2=10, LOOP_PP1=11, LOOP_PP2=12, LOOP_FIM=13, FOUT_01=14, FOUT_02=15, FOUT_03=16, FOUT_04=17, FOUT_SAI=18, CPFIR_01=19, CPFIR_02=20, CPFIR_03=21, CPFIR_04=22, CPFIR_SAI=23, WAIT_LOW=24, WAIT_HIGH=25, S1X=26, S2X=27, S3X=28, S4X=29, S5X=30, S6X=31, S4Y=32; always @(posedge clk10M or negedge nreset) // ↑clk10M ou ↓nreset begin if (nreset=='b0) // se nreset = '0' begin stt <= SRES; trg <= 'b0; end else begin case(stt) SRES: //SRES: sai do reset... begin stt <= S1X; //stt<=S1; // vai p/ S1 iniciar varredura AddN end // ** para testes - preencher as mems #1 e #2 internamente S1X: // ini begin stt <= S2X; end S2X: // ↑clk10M, grava #4 : muda val_16 begin if (AddN == ULTADDN) // se gravou no último AddN begin stt <= S3X; // vai para S3X (preencheu tudo) end else // se AddN < 0xFF (último AddN) begin stt <= S2X; // volta p/ estado S2X end end S3X: begin stt <= S4X; end S4X: // ini begin if (AddN == ULTADDN) // se gravou no último AddN begin stt <= S5X; // vai para S5 (preencheu tudo) end else // se AddN < 0xFF (último AddN) begin stt <= S4X; // volta p/ estado S4X end end S5X: begin stt <= S6X; // volta p/ estado S5X end S6X: // ↑clk10M, muda val D2 e Add#2 begin if (Radd_2a == 6'b11_1111) // se gravou no último AddN begin stt <= CPMM_01; //nxtEV: CPMM_01' end else begin stt <= S6X; // vai para S6X end end // ** para testes - preencher as mems #1 e #2 internamente // preencher a memória #4 copiando valores iniciais da mem #1 p/ mem #4 CPMM_01: // CPMM_01: ↑clk10M, leu Q1 begin // nxtEV: CPMM_02' (copy D4<=Q1) stt <= CPMM_02; // prox stt CPMM_02 end CPMM_02: // ↑clk10M, salvou D4 begin // nxtEV: CPMM_03' (++AddN, WE4=0) stt <= CPMM_03; // prx CPMM_03 end CPMM_03: // ↑clk10M, leu Q1 begin // nxtEV: CPMM_04' (copy D4<=Q1) stt <= CPMM_04; // prx CPMM_04 end CPMM_04: // ↑clk10M, salvou D4 begin // nxtEV: CPMM_03' ou CPMM_05' if (AddN == ULTADDN) // se salvou no último AddN begin // nxtEV: CPMM_05' (AddN=0, WE4=0) stt <= CPMM_05; // vai para CPMM_05 (preencheu mem) end else // se AddN<0xFF (< último AddN) begin // nxtEV: CPMM_03' (++AddN, WE4=0) stt <= CPMM_03; // volta p/ estado CPMM_03 end end CPMM_05: // ↑clk10M, fim da cópia da mem begin // nxtEV: LOOP_INI' stt <= S4Y; // prox stt end S4Y: // ini begin trg <= 'b1; if (AddN == ULTADDN) // se gravou no último AddN begin stt <= LOOP_INI; // vai para LOOP_INI (verificou) end else // se AddN < 0xFF (último AddN) begin stt <= S4Y; // volta p/ estado S4X end end // mem #4 preenchida - pode iniciar operação LOOP_INI: // ↑clk10M, lêu Q4[AddN] e Q1[AddN] begin // nxtEV: TEST_FIRED' stt <= TEST_FIRED; // prox stt end // equivale à função CPMM_04 acima (salvar e teste ultimo AddN TEST_FIRED: // ↑clk10M, salvar D4 e D3 begin if (AddN == ULTADDN) // se salvou o último AddN begin // nxtEV: LOOP_FIM' stt <= LOOP_FIM; // vai para CPMM_05 (fim loop) end else // se AddN<0xFF (< último AddN) begin case (WQ_4a[SZWD1-1:SZWD1-2]) // testa 2 MSB de Q4 // tipo fire-rate coding: Q4 p/ ver se disparou (2'b00): begin stt<=AFT_FIRE_TST; // volta p/ AFT_FIRE_TST end // tipo phase-coding: testa Q4 p/ firing ou vai p/ teste de fase (2'b01): // PH: gerar codigo "phase coding" begin if (WQ_4a[10:0]==ZEROWD1)// WQ_4a[10:0] = zero? fired! begin stt <= AFT_FIRE_TST; // volta p/ AFT_FIRE_TST end else // se não zero, testa phase begin // nxtEV: LOOP_PH1' (ajst ler Fired) stt <= LOOP_PH1; // cont Phase-Coding em LOOP_PH1 end end // tipo population-coding: lê (Q_2a<<2) p/ comparar com Q4_a (2'b10): // PP: gerar cod "population coding" begin // nxtEV: LOOP_PP1' (ajst Radd_2a) stt <= LOOP_PP1; // cont Phase-Coding em LOOP_PP' end // todos os tipos passam por estes estágios pós-disparo (2'b11): // ↑clk10M, estágios do disparado begin stt <= AFT_FIRE_TST; // cont Phase-Coding em S7 end endcase end end // depois do teste fired, grava novo RD_4a na mem #4 e "fired" em rd_3a AFT_FIRE_TST: // (AFT_FIRE_TST)↓ WE4=0, ++AddN begin stt <= TEST_FIRED; // prox stt end // caso especial 1: Phase code (se Rfired[Q2]=1 na iteração anterior) LOOP_PH1: // ↑clk10M, lê Q_2a[Radd_2a] (são 8bits) begin // nxtEV: LOOP_PH2' ajst p/ ler Rfired stt <= LOOP_PH2; // prox stt end LOOP_PH2: // ↑clk10M, faz nada begin // nxtEV: AFT_FIRE_TST' (volta loop) stt <= AFT_FIRE_TST; // prox stt AFT_FIRE_TST end // caso especial 2: Population code (testa se WQ_4a <= (Q_2a << 2)) LOOP_PP1: // ↑clk10M, lê Q_2a[Radd_2a] begin // nxtEV: LOOP_PP2' (testa disp) stt <= LOOP_PP2; // vai para estado LOOP_PP2 end LOOP_PP2: // ↑clk10M, muda stt apenas begin // nxtEV: AFT_FIRE_TST' (volta loop) stt <= AFT_FIRE_TST; // vai para estado AFT_FIRE_TST end LOOP_FIM: // ↑clk10M, vai p/ begin //nxtEV: FIRE_OUT1' ajst add mem #3 stt <= FOUT_01; // prox stt end // varredura da lista (32 elementos em Q2) p/ set do FiredOut[AddLST] FOUT_01: // FOUT_01: ↑clk10M, leu Q2 begin // nxtEV: FOUT_02' (copy D4<=Q1) stt <= FOUT_02; // prox stt FOUT_02 end FOUT_02: // ↑clk10M, ler Q3 begin // nxtEV: FOUT_03' (salva, ++Add) stt <= FOUT_03; // prx FOUT_03 end FOUT_03: // ↑clk10M, leu Q3[Q2] begin // nxtEV: FOUT_04' stt <= FOUT_04; // prx FOUT_04 end FOUT_04: // ↑clk10M, salvou D4 begin // nxtEV: FOUT_03' ou FOUT_SAI' if (AddLST == ULTADDLST) // se salvou no último ULTADDLST begin // nxtEV: FOUT_SAI' stt <= FOUT_SAI; // vai para FOUT_05 (preencheu mem) end else // se AddN<0xFF (< último AddN) begin // nxtEV: FOUT_03' (++AddN, WE4=0) stt <= FOUT_03; // volta p/ estado FOUT_03 end end FOUT_SAI: begin stt <= CPFIR_01; // prx CPFIR_01 end // loop copiar estado disparos em Rfired CPFIR_01: // CPFIR_01: ↑clk10M, leu Q3[0] begin // nxtEV: CPFIR_02' (Rfired<=Q3) stt <= CPFIR_02; // prox stt CPFIR_02 end CPFIR_02: // ↑clk10M, salvou Rfired begin // nxtEV: CPFIR_03' (++AddN) stt <= CPFIR_03; // prx CPFIR_03 end CPFIR_03: // ↑clk10M, leu Q3 begin // nxtEV: CPFIR_04' (Rfired<=Q3) stt <= CPFIR_04; // prx CPFIR_04 end CPFIR_04: // ↑clk10M, salvou D4 begin // nxtEV: CPFIR_03' ou CPFIR_05' if (AddN == ULTADDN) // se salvou no último AddN begin // nxtEV: CPFIR_05' (AddN=0, WE4=0) stt <= CPFIR_SAI; // vai para CPFIR_SAI (preencheu mem) end else // se AddN<0xFF (< último AddN) begin // nxtEV: CPFIR_03' (++AddN, WE4=0) stt <= CPFIR_03; // volta p/ estado CPFIR_03 end end CPFIR_SAI: // ↑clk10M, fim da cópia Rfired begin stt <= WAIT_LOW; // prox stt end // terminou varredura Fireout[k], espera nova subida de ↑clk2K... WAIT_LOW: //se clk2K='1' espera descer begin if (clk2K=='b1) begin stt<=WAIT_LOW; end else begin stt<=WAIT_HIGH; end end WAIT_HIGH: //clk2K está em '0' e sobe begin if (clk2K=='b0) // se clk2K == zero, repete S16 begin stt<=WAIT_HIGH; end else // ↑clk2K, recomeçar LOOP begin // nxtEV: LOOP_INI' stt <= LOOP_INI; // repete ciclo a partir de S4 end // p/ S4 reiniciar varredura AddN end endcase end end // -- final da FSM // ↓↓ FSM: responde na descida do clodk 10MHz always @(negedge clk10M or negedge nreset) // ↓clk10M ou ↓nreset begin if (nreset=='b0) // se nreset = '0' begin AddN <= RESADDN; // reset do indx de nrd wen_1a <= 'b0; // reset wen_1a val_16 <= 16'd8; RD_1a <= 16'd7; wen_4a <= 'b0; // reset wen_4a wen_3a <= 'b0; // reset wen_3a selmxAdd_2a <= 'b0; // ctrl mux sel Add_2a selmxAdd_3a <= 'b0; // ctrl mux sel Add_3a end else begin case(stt) SRES: //SRES: sai do reset... begin end // ** para testes - preencher as mems #1 e #2 internamente S1X: // ini begin wen_1a <= 'b1; // para escrever em wen_1a end S2X: // ↑clk10M, grava #4 : muda val_16 begin RD_1a <= val_16; if (val_16 == 12) val_16 <= 16'd7; else val_16 <= val_16 + 'b1; AddN <= AddN + 'b1; // inc AddN end S3X: begin wen_1a <= 'b0; // parar de escrever em wen_1a AddN <= RESADDN; // restart AddN end S4X: // ini begin AddN <= AddN + 'b1; // inc AddN end S5X: // ↑clk10M, grava #2 [32...] : muda val_16 begin Radd_2a <= 6'b000000; RD_2a <= 8'd2; // input Da DPRAM#2 wen_2a <= 'b1; // para escrever em wen_4a end S6X: // ↑clk10M, muda val D2 e Add#2 begin Radd_2a <= Radd_2a + 'b1; // inc Radd_2a if (Radd_2a < 6'b100000) // se gravou no último AddN begin RD_2a <= 8'b0; end else begin RD_2a <= RD_2a + 'b1; end end // ** para testes - preencher as mems #1 e #2 internamente // preencher a memória #4 copiando valores iniciais da mem #1 CPMM_01: //(CPMM_01')↓clk10M: inicia AddN=0 begin // nxtEV: ↑CPMM_01 wen_2a <= 'b0; // parar de escrever em wen_2a AddN <= RESADDN; // restart AddN p/ zero end CPMM_02: //(CPMM_02')↓ leu Q1[0]: D4<=Q1, WE4=1 begin // nxtEV: ↑CPMM_02 (salvar D4) wen_4a <= 'b1; // hab memWR #4 RD_4a <= WQ_1a; // D4[0] <= Q1[0] end CPMM_03: // (CPMM_03') ↓clk10M, WE4=0, ++AddN begin // nxtEV: ↑CPMM_03 wen_4a <= 'b0; // desabilita memWR #4 AddN <= AddN + 'b1; // inc AddN end CPMM_04: // (CPMM_04')↓ leu Q1[0]: D4<=Q1, WE4=1 begin // nxtEV: ↑CPMM_04 (save D4, test AddN) wen_4a <= 'b1; // hab memWR #4 RD_4a <= WQ_1a; // RD_4a copia WQ_1a da mem #1 end CPMM_05: // (CPMM_05')↓ fim da cópia begin // nxtEV: ↑CPMM_05 (vai p/ LOOP_INI) wen_4a <= 'b0; // desabilita memWR #4 AddN <= RESADDN; // restart AddN p/ zero end S4Y: // ini begin AddN <= AddN + 'b1; // inc AddN end // mem #4 preenchida - pode iniciar operação LOOP_INI: // (LOOP_INI')↓: muda muxes begin // nxtEV: ↑LOOP_INI (ler Q1 e Q4) estado <= 8'b0000_0001; AddN <= RESADDN; // restart AddN p/ zero selmxAdd_2a <= 'b0; // ctrl mux sel Add_2a selmxAdd_3a <= 'b0; // ctrl mux sel Add_3a end TEST_FIRED: // (TEST_FIRED)↓: leu Q1[0] e Q4[0] begin // nxtEV: ↑TEST_FIRED (save M#3 M#4) case (WQ_4a[SZWD1-1:SZWD1-2]) // testa 2 MSB da var contd do nrd // tipo fire-rate coding: testa Q4 p/ ver se disparou (2'b00): begin estado <= 8'b0001_0000; wen_4a <= 'b1; // hab memWR #4 (salvar novo RD_4a) wen_3a <= 'b1; // hab memWR #3 (salvar "fired") if (WQ_4a[10:0]==ZEROWD1) // WQ_4a[10:0] = zero? fired! begin rd_3a<='b1; // dispara o nrd RD_4a<=FIREDSTT1; // disparo está no estágio 1 end else // se não zero, só decrementa begin rd_3a<='b0; // não dispara o nrd RD_4a<=WQ_4a-'b1; // dec 1 de WQ_4a end end // tipo phase-coding: testa Q4 p/ firing ou vai p/ teste de fase (2'b01): // PH: gerar codigo "phase coding" begin estado <= 8'b0001_0001; if (WQ_4a[10:0]==ZEROWD1) // WQ_4a[10:0] = zero? fired! begin // nxtEV: wen_4a <= 'b1; // hab memWR #4 (salvar novo RD_4a) wen_3a <= 'b1; // hab memWR #3 (salvar "fired") rd_3a<='b1; // dispara o nrd RD_4a<=FIREDSTT1; // disparo está no estágio 1 end else // se não zero, testa phase em S6 begin // nxtEV: LOOP_PH1' (ajst ler Q2) rd_3a <= 'b0; // NÃO dispara o nrd end end // tipo population-coding: lê (Q_2a<<2) p/ comparar com Q4_a (2'b10): // PP: gerar cod "population coding" begin estado <= 8'b0001_0010; Rasc<=WQ_4a; // salva valor de WQ_4a p/ comparar end // todos os tipos passam por estes estágios pós-disparo (2'b11): // ↑clk10M, estágios do disparado begin estado <= 8'b0001_0011; wen_4a <= 'b1; // hab memWR #4 (salvar novo RD_4a) wen_3a <= 'b1; // hab memWR #3 (salvar "fired") case (WQ_4a) // testar estado de Q4[AddN] FIREDSTT1: // 1o. clk10M depois do disparo begin rd_3a<='b1; // dispara o nrd RD_4a<=FIREDSTT2; // disparou e está no estágio 2 end FIREDSTT2: // 2o. clk10M depois do disparo begin rd_3a<='b0; // dispara o nrd ? RD_4a<=FIREDSTT3; // está no estágio 3 end FIREDSTT3: // 3o. clk10M depois do disparo begin rd_3a<='b0; // dispara o nrd ? RD_4a<=FIREDSTT4; // está no estágio 4 end FIREDSTT4: // 4o. clk10M depois do disparo begin rd_3a<='b0; // dispara o nrd RD_4a<=WQ_1a; // copia dado de Q1[AddN] => D4[AddN] end default: // 5o. clk10M depois do disparo begin RD_4a<=WQ_1a; // copia dado de Q1[AddN] => D4[AddN] end endcase end endcase end // equivale em função ao CPMM_03 AFT_FIRE_TST: // (AFT_FIRE_TST)↓ WE4=0, ++AddN begin // nxtEV: AFT_FIRE_TST estado <= 8'b0010_0000; wen_4a <= 'b0; // ↓desab memWR #4 wen_3a <= 'b0; // ↓desab memWR #3 (rd_3a) rd_3a <= 'b0; // sem disparo o nrd RD_4a <= 16'd0; // disparo está no estágio 1 AddN <= AddN + 'b1; // inc AddN end // caso especial 1: Phase code (se Rfired[Q2]=1 na iteração anterior) LOOP_PH1: // (LOOP_PH1') ajst Add p/ ler Q2 begin // nxtEV: ↑LOOP_PH1 (lê Q2) Radd_2a<={2'b00,WQ_1a[SZWD1-3:SZWD1-6]};//add_2a:0x00..0F end LOOP_PH2: // (LOOP_PH2') c/ RFired[Q2], calc D3 e D4 begin // nxtEV: ↑LOOP_PH3 (faz nada ) wen_4a <= 'b1; // hab memWR #4 (salvar novo RD_4a) wen_3a <= 'b1; // hab memWR #3 (salvar "fired") if (Rfired[WQ_2a] == 'b1) // se Rfired[Q2], nrd base =1 em *t-1 begin // assim, reseta o nrd p/ Q_1a[AddN] RD_4a <= FIREDSTT4; // coloca o nrd no estágio FIREDSTT4 end else // este nrd não disp, nem o nrd base begin // assim, apenas decrementa este nrd RD_4a <= WQ_4a - 'b1; // decrementa 1 unidade end end // caso especial 2: Population code (testa se WQ_4a <= (Q_2a << 2)) LOOP_PP1: // (LOOP_PP1') ajst Add p/ ler #2 begin // nxtEV: ↑LOOP_PP1 (lê Q2) Radd_2a<={2'b01,WQ_1a[SZWD1-3:SZWD1-6]}; //add_2a:0x10..0x1F end LOOP_PP2: // (LOOP_PP2') tem Q2, calc D3 e D4 begin // nxtEV: ↑LOOP_PP2 (faz nada) wen_4a <= 'b1; // hab memWR #4 (salvar novo RD_4a) wen_3a <= 'b1; // hab memWR #3 (salvar "fired") if (Rasc <= (WQ_2a << 2)) // se Rasc (WQ_4a) <= Q_2a<<2 (limiar) begin rd_3a <= 'b1; // dispara o nrd RD_4a <= FIREDSTT1; // disparou e está no estágio 1 end else // não está no limiar, decrementa begin rd_3a <= 'b0; // NÃO dispara o nrd RD_4a <= WQ_4a - 'b1; // decrementa 1 unidade end end LOOP_FIM: // (LOOP_FIM') lê idxnrd Q2[AddLST] begin estado <= 8'b0011_0000; wen_4a <= 'b0; // ↓desab memWR #4 wen_3a <= 'b0; // ↓desab memWR #3 (rd_3a) AddN <= RESADDN; // restart AddN p/ zero end // varredura da lista (32 elementos em Q2) p/ set do FiredOut[AddLST] FOUT_01: //(FOUT_01')↓clk10M: inicia AddN=0 begin // nxtEV: ↑FOUT_01 (ler Q2[0]) AddLST <= FIRADDLST; // 1o. end lista fired (addLST=0) selmxAdd_2a <= 'b1; // sel Add_2a p/ AddLST selmxAdd_3a <= 'b1; // sel Add_3a p/ WQ_2a end FOUT_02: //(FOUT_02')↓ leu Q2[AddLST] begin // nxtEV: ↑FOUT_02 (ler Q3[Q2]) // faz nada end FOUT_03: // (FOUT_03')↓:leu Q3[], salva, ++Add begin // nxtEV: ↑FOUT_03 (ler Q2[AddLST]) FiredOut[AddLST-6'd32]<=wQ_3a; // salva bit wQ_3a em FiredOut[AddLST] AddLST<=AddLST+'b1; // inc indx da lista (p/ ler Q2) end FOUT_04: // (FOUT_04')↓ leu Q2[AddLST] begin // nxtEV: ↑FOUT_04 (ler Q3[Q2]) // faz nada end FOUT_SAI: begin FiredOut[AddLST-6'd32]<=wQ_3a; // salva wQ_3a[MSB] em FiredOut[MSB] selmxAdd_2a <= 'b0; // sel Add_2a p/ Radd_2a selmxAdd_3a <= 'b0; // sel Add_3a p/ AddN end // loop copiar estado disparos em Rfired CPFIR_01: //(CPFIR_01')↓clk10M: inicia AddN=0 begin // nxtEV: ↑CPFIR__01 (ler Q3[0]) AddN <= RESADDN; // restart AddN p/ zero end CPFIR_02: //(CPFIR_02')↓ leu Q3[0] begin // nxtEV: ↑CPFIR__02 Rfired[AddN] <= wQ_3a; // salva WQ_3a[0] em Rfired end CPFIR_03: // (CPFIR_03') ↓clk10M ++AddN begin // nxtEV: ↑CPFIR__03 (ler Q3[AddN]) AddN <= AddN + 'b1; // inc AddN end CPFIR_04: // (CPFIR_04')↓ leu Q3[AddN] begin // nxtEV: ↑CPFIR_04 testa AddN Rfired[AddN] <= wQ_3a; // salva WQ_3a[0] em Rfired end CPFIR_SAI: // (CPFIR_SAI')↓ fim da cópia begin // nxtEV: ↑CPFIR__05 (vai p/ LOOP_INI) AddN <= RESADDN; // restart AddN p/ zero wen_4a <= 'b0; // reset wen_4a wen_3a <= 'b0; // reset wen_3a selmxAdd_2a <= 'b0; // reset mux sel Add_2a p/ Radd_2a selmxAdd_3a <= 'b0; // reset mux sel Add_3a p/ AddN end // terminou varredura Fireout[k], espera nova subida de ↑clk2K... endcase end end // -- final da FSM // DPRAM#1: mestre escreve tipo/vals que controlam a conversão/geração spikes // wire wen_1a; // wen locais p/ port_a DPRAM#1 reg wen_1a; // assign wen_1a = 'b0; // nunca escreve pela port_a wire [SZWD1-1:0] WQ_1a; // saída Qb DPRAM#1 reg [SZWD1-1:0] RD_1a; // saída Qb DPRAM#1 // wire [SZWD1-1:0] WD_1a; // saída Qb DPRAM#1 SPI_slv_dpRAM_256x16 # // mód SPI_slv_dpRAM_256x16 (params) ( .SZWDA ( SZWD1 ), // larg word port-a (1...1024 bits) .SZADDA ( SZADD1 ), // larg bus Address mem port-a .SZWDB ( SZWD1 ), // larg word port-b:SPI (32,16,8 bits) .SZADDB ( SZADD1 ), // larg bus Address SPI port-b .SZCMD ( SZCMD ), // tamanho do reg. de comando "SRcmd" .ADD0 ( ADD0 ) // end inicial da memória ) slv_U1 // nome do componente/instancia ( .sck ( lsck ), // ligar local sck no "sck" do SPI .mosi ( lmosi ), // ligar local mosi no "mosi" do SPI .nss ( lnss ), // ligar local nss no "nss" do SPI .miso ( lmiso1 ), // ligar local miso no "miso" do SPI .Add_a ( AddN ), // bus_Add port_a #1 (=AddN) .clk_a ( clk10M ), // clk mem#1 port_a (FSM) .wen_a ( wen_1a ), // Write_Enable mem#1 port_a (=0) .D_a ( RD_1a ), // dado p/ mem #1 port_a (sem uso) .Q_a ( WQ_1a ) // dado vem da mem #1 port_a ); // DPRAM#2 (LUT): 16 idx "PH", 16 lim "PP"<<2, 32 idxs nrds "fired" paralelo // wire wen_2a; // wen locais p/ port_a DPRAM#2 reg wen_2a; // wen locais p/ port_a DPRAM#2 // assign wen_2a = 'b0; // nunca escreve pela port a wire [SZADD2-1:0] Add_2a; // endereço port 'a' da DPRAM#2 assign Add_2a = selmxAdd_2a? AddLST: Radd_2a; // mux sel Add_2a // wire [SZWD2-1:0] WD_2a; // input Da DPRAM#2 reg [SZWD2-1:0] RD_2a; // input Da DPRAM#2 wire [SZWD2-1:0] WQ_2a; // saída Qb DPRAM#2 SPI_slv_dpRAM_64x8 # // mód SPI_slv_dpRAM_64x8 (params) ( .SZWDA ( SZWD2 ), // larg word port-a (1...1024 bits) .SZADDA ( SZADD2 ), // larg bus Address mem port-a .SZWDB ( SZWD2 ), // larg word port-b:SPI (32,16,8 bits) .SZADDB ( SZADD2 ), // larg bus Address SPI port-b .SZCMD ( SZCMD ), // tamanho do reg. de comando "SRcmd" .ADD0 ( ADD1 ) // end inicial da memória ) slv_U2 // nome do componente/instancia ( .sck ( lsck ), // ligar local sck no "sck" do SPI .mosi ( lmosi ), // ligar local mosi no "mosi" do SPI .nss ( lnss ), // ligar local nss no "nss" do SPI .miso ( lmiso2 ), // ligar local miso no "miso" do SPI .Add_a ( Add_2a ), // bus_Add port_a #2 (=after mux) .clk_a ( clk10M ), // clk mem#2 port_a (FSM) .wen_a ( wen_2a ), // Write_Enable mem#2 port_a (=0) .D_a ( RD_2a ), // dado p/ mem #2 port_a (sem uso) .Q_a ( WQ_2a ) // dado vem da mem #2 port_a ); // DPRAM#3 (mem FIRED) =1 nos nrds que dispararam agora! reg rd_3a; // ff-d fired =1 qdo nrd disparou; wire [SZADD1-1:0] Add_3a; // Add da port_a mem 3 (fired) assign Add_3a = selmxAdd_3a? WQ_2a: AddN; // mux quem endereça Add_3a wire wQ_3a; // fio conectado ao bit Qa, não usado SPI_slv_dpRAM_256x1_16x16 # // mód SPI_slv_dpRAM_64x8 (params) ( .SZWDA ( SZWD3A ), // larg word port-a (1...1024 bits) .SZADDA ( SZADD3A ), // larg bus Address mem port-a .SZWDB ( SZWD3B ), // larg word port-b:SPI (32,16,8 bits) .SZADDB ( SZADD3B ), // larg bus Address SPI port-b .SZCMD ( SZCMD ), // tamanho do reg. de comando "SRcmd" .ADD0 ( ADD2 ) // end inicial da memória ) slv_U3 // nome do componente/instancia ( .sck ( lsck ), // ligar local sck no "sck" do SPI .mosi ( lmosi ), // ligar local mosi no "mosi" do SPI .nss ( lnss ), // ligar local nss no "nss" do SPI .miso ( lmiso3 ), // ligar local miso no "miso" do SPI .Add_a ( Add_3a ), // bus_Add port_a #3 (=after mux) .clk_a ( clk10M ), // clk mem#3 port_a (FSM) .wen_a ( wen_3a ), // Write_Enable mem#3 port_a (FSM) .D_a ( rd_3a ), // dado p/ a mem via port a .Q_a ( wQ_3a ) // dado vem da mem #3 port_a ); // DPRAM#4 (contadores e controle maq de estados) wire wen_4b; // wen locais p/ port_b DPRAM#4 assign wen_4b = 'b0; // nunca escreve pela port b wire [SZADD1-1:0] Add_4b; // ends port B da DPRAM#4 (sem uso) // wire clk_4b; // clks da DPRAM#4 (sem uso) // assign clk_4b = 'b0; // clk sempre =0 wire [SZWD1-1:0] WD_4b; // entrada Db DPRAM#4 wire [SZWD1-1:0] WQ_4a, WQ_4b; // saídas Qa e Qb DPRAM#4 dpRAM_256x16 DP_U04 // inst IP DRPRAM (On Chip Memory) ( .address_a ( AddN ), // bus_Add port_a #4 (=AddN) .address_b ( Add_4b ), // Add_4b (sem uso) .clock_a ( clk10M ), // clk mem#4 port_a (FSM) .clock_b ( clk10M ), // clock_b (sem uso = 0) .data_a ( RD_4a ), // data4_a (inc conts e FIREDSTT_) .data_b ( WD_4b ), // data4_b (sem uso) .wren_a ( wen_4a ), // Write_Enable mem#4 port_a (FSM) .wren_b ( wen_4b ), // Write_Enable mem#4 port_b (=0) .q_a ( WQ_4a ), // WQ_4a (sai contadores e FIREDSTT_) .q_b ( WQ_4b ) // WQ_4b (sem uso) ); endmodule /* -------------------------------------------------------------------------- ... Como instanciar este módulo ... SpikeDriver_SPI // este modulo com 256 nrds SpkDrv_U1 // nome do componente/instance ( .clk10M ( clk_10M ), // clock 10MHz do PLL .clk2K ( clk_2K ), // clock 2KHz preciso (do PLL) .nreset ( n_reset), // ↓reset ativo na descida p/ "0" .lsck ( l_sck ), // clk vem do mestre SPI .lmosi ( l_mosi ), // dado in "mosi" vem do mestre SPI .lnss ( l_nss ), // sel ativo em "0" vem do mestre SPI .lmiso ( l_miso ), // saída p/ SPI "miso". Passa p/ OR .FiredOut ( l_FiredWire ) // fios saída 32 canais FiredOut ); OBS: este módulo deve ter os endereços das RAMs ajustados antes de sintetizar os endereços são de 22 bits: 00_0001 até 22'h3F_FFFF ( ~4 MBytes ) NÃO usar o endereço 0x00_0000 porque é reservado do sistema/Avalon ----------------------------------------------------------------------------*/<file_sep>/ut_SpikeDriver_SPI_RTL/ut_SpikeDriver_SPI.v // ------------------ modulo interface SpikeDriver --------------------------// // // apenas faz a interface com o módulo SpikeDriver_SPI // autor <NAME> data: 2019_03_06 // // //---------------------------------------------------------------------------// module ut_SpikeDriver_SPI ( input CLK_50, nreset, // clk e reset do sistema input lsck, lmosi, lnss, // input do SPI config memorias output lmiso, // saída SPI config memorias output [SZPFIRED-1:0] FOut, // saída Parallel Firing OUt output drck, dsck, dsdo, output [31:0] TestPoint, output [7:0] LED ); parameter SZPFIRED = 32; // tam do vetor saída paralela FiredOut parameter ANODECOMM =1; // display anodo comum wire [7:0] dec_point; // vetor ponto decimal assign dec_point = 8'b0; // dp inicia zerado // fios para reset e clk wire rst; assign rst = ~nreset; // reset para pll wire clk_150M, clk_100M, clk_10M, clk_400K, clk_2K; reg clk_1K; always @(posedge CLK_50) // divisor p/ gerar 1 KHz begin clk_1K <= ~clk_1K; // divide clk_2k p/ gerar 1 KHz end wire trg; // instancia o módulo SpikeDriver_SPI SpikeDriver_SPI // este modulo com 256 nrds SpkDrv_U1 // nome do componente/instance ( .clk10M ( clk_10M ), // clock 10MHz do PLL .clk2K ( clk_2K ), // clock 2KHz preciso (do PLL) .nreset ( nreset), // ↓reset ativo na descida p/ "0" .lsck ( lsck ), // clk vem do mestre SPI .lmosi ( lmosi ), // dado in "mosi" vem do mestre SPI .lnss ( lnss ), // sel ativo em "0" vem do mestre SPI .lmiso ( lmiso ), // saída p/ SPI "miso". Passa p/ OR .FiredOut ( FOut ), // fios saída 32 canais FiredOut .TestPoint ( TestPoint ), .LED ( LED), .trg ( trg ) ); snand_pll // instancia PLL no circuito pll_U1 // nome do comp ( .refclk ( CLK_50 ), // refclk = CLK_50 MHz da placa .rst ( rst ), // reset.reset .outclk_0 ( clk_150M ), // outclk 150 MHz .outclk_1 ( clk_100M ), // outclk 100 MHz p/ stp .outclk_2 ( clk_10M ), // outclk 10 MHz .outclk_4 ( clk_400K ), // clk 400 KHz .outclk_7 ( clk_2K ) // outclk 2 KHz p/ timer SpikeDriver ); endmodule
09b1cea6bdf455b1a8afb366e6fa6ffb4df8bb44
[ "Verilog" ]
3
Verilog
Ydeh22/Spiking-Neural-Network-Encoder-RTL
92c563be35976e3de39c5fd47d8d33da1a21bb57
9ec0f013c7783275a7fe443fba1d9ed180cc9354
refs/heads/master
<file_sep> var express = require('express'), bodyParser = require('body-parser'), restful = require('node-restful'), config = require('config'), path = require('path'), fs = require('fs'), mongoose = restful.mongoose; var app = express(); app.use( bodyParser.json() ); app.use( express.static(path.join(__dirname, 'public')) ); mongoose.connect( config.get('db.conn') ); mongoose.connection.on('error', console.log); fs.readdirSync(__dirname + '/schemas').forEach(function (file) { if (~file.indexOf('.js')) require(__dirname + '/schemas/' + file); }); fs.readdirSync(__dirname + '/routers').forEach(function (file) { if (~file.indexOf('.js')) require(__dirname + '/routers/' + file)(app); }); var port = process.env.PORT || 3000; app.listen( port ); console.log('Server running at port ' + port); <file_sep>var restful = require('node-restful'), mongoose = restful.mongoose; var ProductSchema = mongoose.Schema({ name: String, price: Number }); module.exports = ProductSchema; <file_sep>nodejs-api-template =================== An archetype of a Node JS API server. Use it as a template project when you want to start a new project.
87760ef33a4020d8fc9bdb85afa1e4fe3549c178
[ "Markdown", "JavaScript" ]
3
Markdown
guumaster/nodejs-api-template
0b60e76587284af69c1241f333f36cc46b6a9570
9a8d7aa6c838ca91587979f02aef8b919f0e5966
refs/heads/master
<repo_name>PDE26jjk/dx11Test<file_sep>/1/hillTess.cpp #include "hillTess.h" HillTess::HillTess(Graphics* gpx) : PDEeffect("HillTess.cso",gpx) { LoadFx(); SetTopoLayout(); } void HillTess::Draw() { Bind(); mTech->GetDesc(&techDesc); pContext->OMSetRenderTargets(1u, mGfx->GetpMainTarget(), mGfx->GetDepthStencilView()); // 渲染方式 pContext->RSSetState(mWIREFRAME.Get()); static float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f }; pContext->OMSetBlendState(mBlendStateTransparency.Get(), blendFactors, 0xffffffff); /****************************更新坐标并绘制**************************/ XMMATRIX ViewProjM = XMLoadFloat4x4(&mGfx->GetMainCamera().ViewProj); XMMATRIX world = XMMatrixIdentity(); XMMATRIX worldViewProj = world * ViewProjM; mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); mfxWorld->SetMatrix(reinterpret_cast<float*>(&world)); HR(mfxEyePosW->SetRawValue(&mGfx->GetMainCamera().GetPosition(), 0, sizeof(XMFLOAT3))); for (UINT p = 0; p < techDesc.Passes; ++p) { mTech->GetPassByIndex(p)->Apply(0, pContext.Get()); pContext->Draw(4, 0u); } /****************************更新坐标并绘制完**************************/ pContext->RSSetState(0); } void HillTess::LoadFx() { mTech= mFX->GetTechniqueByName("Tess"); mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix(); mfxWorld = mFX->GetVariableByName("gWorld")->AsMatrix(); mfxEyePosW = mFX->GetVariableByName("gEyePosW")->AsVector(); D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(XMFLOAT3) * 4; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; XMFLOAT3 vertices[4] = { XMFLOAT3(-10.0f, 0.0f, +10.0f), XMFLOAT3(+10.0f, 0.0f, +10.0f), XMFLOAT3(+10.0f, 0.0f, -10.0f), XMFLOAT3(-10.0f, 0.0f, -10.0f), }; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = vertices; HR(pDevice->CreateBuffer(&vbd, &vinitData, &mVB)); mVBstride = sizeof(XMFLOAT3); mVBoffset = 0; } void HillTess::SetTopoLayout() { mTopoLayout = TopoLayout(TopoLayoutType::HillTessP); } <file_sep>/1/Shape.cpp #include "Shape.h" #include <algorithm> #include "BasicEffect.h" PDEshape::PDEshape(MeshData& meshData) : meshData(meshData), blendType(BlendType::None), mEffect(BasicEffect::get_instance()) { init(); } void PDEshape::init() { XMStoreFloat4x4(&W, XMMatrixIdentity()); XMStoreFloat4x4(&TexW, XMMatrixIdentity()); initMat(); } void PDEshape::Move(float x, float y, float z) { XMStoreFloat4x4(&W,XMLoadFloat4x4(&W) * XMMatrixTranslation(x, y, z)); } void PDEshape::Scale(float x, float y, float z) { XMStoreFloat4x4(&W, XMLoadFloat4x4(&W) * XMMatrixScaling(x, y, z)); } void PDEshape::Rotate(XMVECTOR A, float angle) { XMStoreFloat4x4(&W, XMLoadFloat4x4(&W) * XMMatrixRotationAxis(A, angle)); } void PDEshape::MoveTex(float u, float v) { XMStoreFloat4x4(&TexW, XMLoadFloat4x4(&TexW) * XMMatrixTranslation(u, v, 1.0f)); } void PDEshape::ScaleTex(float x, float y) { XMStoreFloat4x4(&TexW, XMLoadFloat4x4(&TexW) * XMMatrixScaling(x, y, 1.0f)); } void PDEshape::RotateTex(XMVECTOR A, float angle) { XMStoreFloat4x4(&TexW, XMLoadFloat4x4(&TexW) * XMMatrixRotationAxis(A, angle)); } void PDEshape::ResetTex() { XMStoreFloat4x4(&TexW, XMMatrixIdentity()); } void PDEshape::SetMatOpaque(float opaque) { opaque = std::clamp(opaque, 0.0f, 1.0f); this->Mat.Diffuse.w = opaque; } XMMATRIX PDEshape::InverseTranspose(CXMMATRIX M) { XMMATRIX A = M; A.r[3] = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f); XMVECTOR det = XMMatrixDeterminant(A); return XMMatrixTranspose(XMMatrixInverse(&det, A)); } void PDEshape::initMat() { Mat.Ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); Mat.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); Mat.Specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 16.0f); Mat.Reflect = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); } <file_sep>/1/basic.hlsl #include "basic.hlsli" Texture2D gBillboardMap; // 阴影光源 float4 gShadowL; float2 GetReflectUV(float3 PosL) { float4 PosH; PosH = mul(float4(PosL, 1.0f), gReflectWorldViewProj); float4 PosD = PosH / PosH.a; float u = (PosD.x + 1.0f) / +2.0f; float v = (PosD.y - 1.0f) / -2.0f; float2 rUV = float2(u, v); return rUV; } struct BillboardVSIn { float3 PosL : POSITION; float2 Size : SIZE; }; struct BillboardVSOut { float3 PosW : POSITION; float2 Size : SIZE; }; BillboardVSOut BillboardVS(BillboardVSIn vin) { lastTime = time; BillboardVSOut vout; vout.PosW = vin.PosL; vout.Size = vin.Size; return vout; } float2 gTexC[4] = { float2(0.0f, 1.0f), float2(0.0f, 0.0f), float2(1.0f, 1.0f), float2(1.0f, 0.0f) }; [maxvertexcount(4)] void BillboardGS(point BillboardVSOut gin[1], inout TriangleStream<VertexOut> output) { /*float4 PosH : SV_POSITION; float3 PosW : POSITION; float3 NormalW : NORMAL; float2 Tex : TEXCOORD;*/ BillboardVSOut bpoint = gin[0]; float3 up = float3(0.0f, 1.0f, 0.0f); float3 look = gEyePosW - bpoint.PosW; look.y = 0.0f; look = normalize(look); float3 right = cross(up, look); float halfWidth = bpoint.Size.x / 2.0f; float Height = bpoint.Size.y ; float4 v[4]; v[0] = float4(bpoint.PosW + halfWidth * right, 1.0f); v[1] = float4(bpoint.PosW + halfWidth * right + Height * up, 1.0f); v[2] = float4(bpoint.PosW - halfWidth * right, 1.0f); v[3] = float4(bpoint.PosW - halfWidth * right + Height * up, 1.0f); VertexOut gout; [unroll] for (int i = 0; i < 4; ++i) { gout.PosH = mul(v[i], gWorldViewProj); gout.PosW = v[i].xyz; gout.NormalW = look; gout.Tex = gTexC[i]; //gout.PrimID = primID; output.Append(gout); } } VertexOut ShadowVS(VertexIn vin) { lastTime = time; VertexOut vout; //Wave(vin.PosL.x, vin.PosL.z, vin.PosL.y, vin.NormalL); // 计算阴影矩阵 float4 shadowPlane = float4(0.0f, 1.0f, 0.0f, 0.0f); float4x4 S = MatrixShadow(shadowPlane, gShadowL); vout.PosW = 0.0f; vout.NormalW = float3(0.0f, 1.0f, 0.0f); //vout.PosH = mul(float4(vin.PosL, 1.0f), mul(S,gWorldViewProj)); vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj); // Output vertex attributes for interpolation across triangle. vout.Tex = 0.0f; //vout.Tex = vin.Tex; return vout; } VertexOut RefVS(VertexIn vin) { lastTime = time; VertexOut vout; //Wave(vin.PosL.x, vin.PosL.z, vin.PosL.y, vin.NormalL); vout.PosW = mul(float4(vin.PosL, 1.0f), gWorld).xyz; vout.NormalW = mul(vin.NormalL, (float3x3)gWorldInvTranspose); vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj); // Output vertex attributes for interpolation across triangle. vout.Tex = GetReflectUV(vin.PosL); //vout.Tex = vin.Tex; return vout; } float4 BillboardPS(VertexOut pin, uniform bool gUseTexure, uniform bool gUseFog = true) : SV_Target { // Default to multiplicative identity. float4 texColor = float4(1, 1, 1, 1); if (gUseTexure) { // Sample texture. texColor = gBillboardMap.Sample(samAnisotropic, pin.Tex); } //clip(texColor.a - 0.05f); float4 litColor = texColor; // Start with a sum of zero. float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 spec = float4(0.0f, 0.0f, 0.0f, 0.0f); litPixel(pin, ambient, diffuse, spec); litColor = texColor * (ambient + diffuse) + spec; float distToEye = distance(gEyePosW, pin.PosW); if (gUseFog) { float fogLerp = saturate((distToEye - gFogStart) / gFogRange); // Blend the fog color and the lit color. use alpha as amount litColor = lerp(litColor, gFogColor, fogLerp * gFogColor.a); } // Common to take alpha from diffuse material. litColor.a = texColor.a * gMaterial.Diffuse.a; //return litColor; //return float4(gMaterial.Diffuse.r, gMaterial.Diffuse.g, gMaterial.Diffuse.b,1.0f ); return float4(texColor.r, texColor.g, texColor.b, texColor.a); //return float4(litColor.r, litColor.g, litColor.b,1.0f ); //return float4(ambient.r, ambient.g, ambient.b,1.0f ); } float4 RefPS(VertexOut pin, uniform bool gUseTexure, uniform bool gUseFog = true) : SV_Target { // Default to multiplicative identity. float4 texColor = float4(0, 0, 0, 0); // Sample texture. int NumberOfSamples; // 纹理坐标转化 float w,h,u,v; gReflectMap.GetDimensions(w, h, NumberOfSamples); u = lerp(0.0f, w, pin.Tex.x); v = lerp(0.0f, h, pin.Tex.y); for (int i = 0; i < NumberOfSamples; ++i) { texColor+= gReflectMap.sample[i][float2(u,v)]; } texColor /= NumberOfSamples; // Start with a sum of zero. float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 spec = float4(0.0f, 0.0f, 0.0f, 0.0f); // Sum the light contribution from each light source. litPixel(pin,ambient, diffuse, spec); // light float4 litColor = texColor; litColor = texColor * (ambient + diffuse) + spec; float distToEye = distance(gEyePosW, pin.PosW); if (gUseFog) { float fogLerp = saturate((distToEye - gFogStart) / gFogRange); // Blend the fog color and the lit color. use alpha as amount litColor = lerp(litColor, gFogColor, fogLerp * gFogColor.a); } // Common to take alpha from diffuse material. litColor.a = texColor.a * gMaterial.Diffuse.a; return litColor; //return float4(gMaterial.Diffuse.r, gMaterial.Diffuse.g, gMaterial.Diffuse.b,1.0f ); //return float4(texColor.r, texColor.g, texColor.b,1.0f ); //return float4(litColor.r, litColor.g, litColor.b,1.0f ); //return float4(ambient.r, ambient.g, ambient.b,1.0f ); } float4 ShadowPS(VertexOut pin, uniform bool gUseTexure, uniform bool gUseFog = true) : SV_Target { // Start with a sum of zero. float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 spec = float4(0.0f, 0.0f, 0.0f, 0.0f); litPixel(pin,ambient, diffuse, spec); float4 litColor = ambient + diffuse + spec; litColor.rgb = 0.00f; float distToEye = distance(gEyePosW, pin.PosW); if (gUseFog) { float fogLerp = saturate((distToEye - gFogStart) / gFogRange); // Blend the fog color and the lit color. use alpha as amount //litColor = lerp(litColor, gFogColor, fogLerp * gFogColor.a); } // Common to take alpha from diffuse material. //litColor.xyz = 0.00f; litColor.a = gMaterial.Diffuse.a; //return litColor; //return float4(gMaterial.Diffuse.r, gMaterial.Diffuse.g, gMaterial.Diffuse.b,1.0f ); //return float4(texColor.r, texColor.g, texColor.b,1.0f ); //return float4(litColor.r, litColor.g, litColor.b,0.7f ); //return float4(ambient.r, ambient.g, ambient.b,1.0f ); return float4(0.0f, 0.0f, 0.0f,0.30f ); } [maxvertexcount(9)] void someGS(triangle VertexOut input[3], inout TriangleStream<VertexOut> output) { //float4 PosH : SV_POSITION; //float3 PosW : POSITION; //float3 NormalW : NORMAL; //float2 Tex : TEXCOORD; VertexOut vertexes[6]; [unroll] for (unsigned int i = 0; i < 3; ++i) { vertexes[i] = input[i]; vertexes[i + 3].PosH = (input[i].PosH + input[(i + 1) % 3].PosH) / 2.0f; vertexes[i + 3].PosW = (input[i].PosW + input[(i + 1) % 3].PosW) / 2.0f; vertexes[i + 3].NormalW = (input[i].NormalW + input[(i + 1) % 3].NormalW) / 2.0f; vertexes[i + 3].Tex = (input[i].Tex + input[(i + 1) % 3].Tex) / 2.0f; } [unroll] for (i = 0; i < 3; ++i) { output.Append(vertexes[i]); output.Append(vertexes[i+3]); output.Append(vertexes[(i+5)%3+3]); output.RestartStrip(); } } [maxvertexcount(3)] void someGS2(triangle VertexOut input[3], inout TriangleStream<VertexOut> output) { //float4 PosH : SV_POSITION; //float3 PosW : POSITION; //float3 NormalW : NORMAL; //float2 Tex : TEXCOORD; float3 NormalFaceW = 0; [unroll] for (int i = 0; i < 3; ++i) { NormalFaceW+=input[i].NormalW; } NormalFaceW /= 3.0f; float littleTime = pow(2.71828f,time * 10.0f); [unroll] for (i = 0; i < 3; ++i) { input[i].PosW += NormalFaceW * littleTime; input[i].PosH = mul(float4(input[i].PosW,1.0f), gViewProj); output.Append(input[i]); } } technique11 Texture { pass P0 { SetVertexShader(CompileShader(vs_5_0, VS())); SetGeometryShader(NULL); //SetGeometryShader(CompileShader(gs_5_0, someGS2())); SetPixelShader(CompileShader(ps_5_0, PS(true))); } } technique11 Reflect { pass P0 { SetVertexShader(CompileShader(vs_5_0, RefVS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, RefPS(true))); } } technique11 ReflectNoMSAA { pass P0 { SetVertexShader(CompileShader(vs_5_0, RefVS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, PS(true))); } } technique11 NOTexture { pass P0 { SetVertexShader(CompileShader(vs_5_0, VS())); //SetGeometryShader(NULL); SetGeometryShader(CompileShader(gs_5_0, someGS2())); SetPixelShader(CompileShader(ps_5_0, PS(false))); } } technique11 NOFog { pass P0 { SetVertexShader(CompileShader(vs_5_0, VS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, PS(true,false))); } } technique11 Shadow { pass P0 { SetVertexShader(CompileShader(vs_5_0, ShadowVS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, ShadowPS(true, false))); } } technique11 Billboard { pass P0 { SetVertexShader(CompileShader(vs_5_0, BillboardVS())); SetGeometryShader(CompileShader(gs_5_0, BillboardGS())); SetPixelShader(CompileShader(ps_5_0, BillboardPS(true, false))); } } <file_sep>/1/addCS.cpp #include "addCS.h" void addCS::Draw() { } void addCS::LoadFx() { } void addCS::SetTopoLayout() { } <file_sep>/1/WinMain.cpp #include "window.h" #include "App.h" #include <sstream> //LRESULT CALLBACK WinProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam){ // // switch (msg) { // case WM_CLOSE: // PostQuitMessage(69); // break; // case WM_KEYDOWN: // if (wParam == 'F') // SetWindowText(hWnd, "eeeeeeeee"); // break; // case WM_KEYUP: // if (wParam == 'F') // SetWindowText(hWnd, "aaaaaaaaaaa"); // break; // case WM_CHAR: { // static std::string title; // title.push_back((char)wParam); // SetWindowText(hWnd, title.c_str()); // } // break; // case WM_LBUTTONDOWN: // const POINTS pt = MAKEPOINTS(lParam); // std::ostringstream oss; // oss << "(" << pt.x << "," << pt.y << ")"; // SetWindowText(hWnd, oss.str().c_str()); // break; // } // // return DefWindowProc(hWnd, msg, wParam, lParam); //} int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { return App{}.Go(); }<file_sep>/1/Camera.cpp #include "Camera.h" using namespace DirectX; Camera::Camera() { XMVECTOR pos = XMVectorZero(); XMVECTOR dir = XMVectorSet(0.0f,0.0f,1.0f,0.0f); float AspectRatio = 1.33333333f; new(this) Camera(pos, dir, AspectRatio); } Camera::Camera(const XMVECTOR& pos, const XMVECTOR& dir, float AspectRatio) : FovAngleY(0.25f * XM_PI), NearZ(0.01f), FarZ(10000.0f), AspectRatio(AspectRatio) { XMStoreFloat4(&up,Coordinate::Y); XMStoreFloat4(&this->pos, pos); XMStoreFloat4(&this->dir, dir); SetAspectRatio(AspectRatio); SetCamera(pos, dir); } void Camera::SetCamera(const XMVECTOR& pos, const XMVECTOR& dir) { XMFLOAT4 position; XMStoreFloat4(&position, pos); // 计算视矩阵 float x = position.x; float z = position.z; float y = position.y; this->pos = XMFLOAT4(x, y, z,1.0f); XMStoreFloat4(&this->dir, dir); UpdateViewMatrix(); } void Camera::MoveCamera(const XMVECTOR& offset) { XMVECTOR pos = XMLoadFloat4(&this->pos); pos += offset; pos.m128_f32[3] = 1.0f; XMStoreFloat4(&this->pos, pos); UpdateViewMatrix(); } void Camera::RotateCamera(const XMVECTOR& A, float angle) { XMVECTOR dir = XMLoadFloat4(&this->dir); dir = XMVector3Transform(dir, XMMatrixRotationAxis(A, angle)); float dirY = XMVectorGetY(dir); if (dirY > 0.99f || dirY < -0.99f) return; XMStoreFloat4(&this->dir, dir); UpdateViewMatrix(); } void Camera::SetAspectRatio(const float& AspectRatio) { this->AspectRatio = AspectRatio; // 计算投影矩阵 XMMATRIX PM = XMMatrixPerspectiveFovLH(FovAngleY, AspectRatio, NearZ, FarZ); XMStoreFloat4x4(&P, PM); } void Camera::UpdateViewMatrix() { XMVECTOR pos = XMLoadFloat4(&this->pos); XMVECTOR dir = XMLoadFloat4(&this->dir); XMVECTOR up = XMLoadFloat4(&this->up); XMMATRIX VM = XMMatrixLookToLH(pos, dir, up); XMStoreFloat4x4(&V, VM); XMMATRIX PM = XMLoadFloat4x4(&P); XMMATRIX ViewProjM = VM * PM; XMStoreFloat4x4(&ViewProj, ViewProjM); } <file_sep>/1/GeometryGenerator.cpp #include "GeometryGenerator.h" #include <algorithm> using namespace DirectX; void GeometryGenerator::CreateGrid(float width, float depth, UINT m, UINT n, MeshData& meshData) { UINT vertexCount = m * n; UINT faceCount = (m - 1) * (n - 1) * 2; // // Create the vertices. // float halfWidth = 0.5f * width; float halfDepth = 0.5f * depth; float dx = width / (n - 1); float dz = depth / (m - 1); float du = 1.0f / (n - 1); float dv = 1.0f / (m - 1); meshData.Vertices.resize(vertexCount); for (UINT i = 0; i < m; ++i) { float z = halfDepth - i * dz; for (UINT j = 0; j < n; ++j) { float x = -halfWidth + j * dx; meshData.Vertices[i * n + j].Position = XMFLOAT3(x, 0.0f, z); // Ignore for now, used for lighting. meshData.Vertices[i * n + j].Normal = XMFLOAT3(0.0f, 1.0f, 0.0f); meshData.Vertices[i * n + j].TangentU = XMFLOAT3(1.0f, 0.0f, 0.0f); // Ignore for now, used for texturing. meshData.Vertices[i * n + j].TexC.y = j * du; meshData.Vertices[i * n + j].TexC.x = i * dv; } } meshData.Indices.resize(faceCount * 3); // 3 indices per face // Iterate over each quad and compute indices. LinkGrid(m, n, 0, meshData); } void GeometryGenerator::GreateRevolvingSolid(std::vector<XMFLOAT2> line, UINT slice, MeshData& meshData) { slice = std::max(3u, slice); UINT pointCount = line.size(); meshData.Vertices.resize(pointCount * slice + 2); UINT topV = pointCount * slice; UINT bottomV = pointCount * slice + 1; meshData.Vertices[topV].Position = XMFLOAT3(0.0f, line[0].y, 0.0f); meshData.Vertices[bottomV].Position = XMFLOAT3(0.0f, line[pointCount-1].y, 0.0f); float dRad = -2 * XM_PI / slice; for (UINT i = 0; i < slice; ++i) { for (UINT j = 0; j < pointCount; ++j) { meshData.Vertices[i * pointCount+j].Position = XMFLOAT3(line[j].x * cosf(i * dRad), line[j].y, line[j].x * sinf(i * dRad)); } } UINT indicesCount = 3 * slice * 2 + slice * (pointCount - 1) * 6; meshData.Indices.resize(indicesCount); // 连接网格 UINT k = LinkGrid(slice, pointCount, 0, meshData); // 封边 for (UINT i = 0; i < pointCount - 1; ++i) { meshData.Indices[k] = i; meshData.Indices[k + 1] = slice * pointCount - pointCount + i; meshData.Indices[k + 2] = slice * pointCount - pointCount + 1 + i; meshData.Indices[k + 3] = i; meshData.Indices[k + 4] = slice * pointCount - pointCount + 1 + i; meshData.Indices[k + 5] = i + 1; k += 6; // next quad } // 封上口 for (UINT i = 0; i < slice - 1; ++i) { meshData.Indices[k] = topV; meshData.Indices[k + 1] = pointCount * i; meshData.Indices[k + 2] = pointCount * (i + 1); k += 3; // next quad } meshData.Indices[k] = topV; meshData.Indices[k + 1] = pointCount * (slice - 1); meshData.Indices[k + 2] = 0; k += 3; // next quad // 封下口 for (UINT i = 1; i < slice; ++i) { meshData.Indices[k] = bottomV; meshData.Indices[k + 2] = pointCount * i - 1; meshData.Indices[k + 1] = pointCount * (i + 1) -1; k += 3; // next quad } meshData.Indices[k] = bottomV; meshData.Indices[k + 2] = pointCount * slice - 1; meshData.Indices[k + 1] = pointCount - 1; CreateNormal(meshData); } void GeometryGenerator::CreateCylinder(float bottomRadius, float topRadius, float height, UINT sliceCount, UINT stackCount, MeshData& meshData) { stackCount = std::max(1u, stackCount); float radiusStep = (topRadius - bottomRadius) / stackCount; float stackHeight = height / stackCount; std::vector<XMFLOAT2> line(stackCount +1 ); for (UINT i = 0; i < stackCount+1; ++i) { line[i] = XMFLOAT2(topRadius - i * radiusStep, height - i * stackHeight); } GreateRevolvingSolid(line, sliceCount, meshData); } void GeometryGenerator::CreateNormal(MeshData& meshData) { UINT numTriangles = meshData.Indices.size() / 3; UINT numVertices = meshData.Vertices.size(); std::vector<XMVECTOR> normals(numVertices); // Input: // 1. An array of vertices (mVertices). Each vertex has a // position component (pos) and a normal component (normal). // 2. An array of indices (mIndices). // For each triangle in the mesh: for (UINT i = 0; i < numTriangles; ++i) { // indices of the ith triangle UINT i0 = meshData.Indices[i * 3 + 0]; UINT i1 = meshData.Indices[i * 3 + 1]; UINT i2 = meshData.Indices[i * 3 + 2]; // vertices of ith triangle Vertex v0 = meshData.Vertices[i0]; Vertex v1 = meshData.Vertices[i1]; Vertex v2 = meshData.Vertices[i2]; // compute face normal XMVECTOR e0 = XMLoadFloat3(&v1.Position) - XMLoadFloat3(&v0.Position); XMVECTOR e1 = XMLoadFloat3(&v2.Position) - XMLoadFloat3(&v0.Position); XMVECTOR faceNormal = XMVector3Cross(e0, e1); // This triangle shares the following three vertices, // so add this face normal into the average of these // vertex normals. normals[i0] += faceNormal; normals[i1] += faceNormal; normals[i2] += faceNormal; } //For each vertex v, we have summed the face normals of all // the triangles that share v, so now we just need to normalize. for (UINT i = 0; i < numVertices; ++i) XMStoreFloat3(&meshData.Vertices[i].Normal,XMVector3Normalize(normals[i])); } float AngleFromXY(float x, float y) { float theta = 0.0f; // Quadrant I or IV if (x >= 0.0f) { // If x = 0, then atanf(y/x) = +pi/2 if y > 0 // atanf(y/x) = -pi/2 if y < 0 theta = atanf(y / x); // in [-pi/2, +pi/2] if (theta < 0.0f) theta += 2.0f * XM_PI; // in [0, 2*pi). } // Quadrant II or III else theta = atanf(y / x) + XM_PI; // in [0, 2*pi). return theta; } void GeometryGenerator::CreateGeosphere(float radius, UINT numSubdivisions, MeshData& meshData) { // Put a cap on the number of subdivisions. numSubdivisions = std::min(numSubdivisions, 5u); // Approximate a sphere by tessellating an icosahedron. const float X = 0.525731f; const float Z = 0.850651f; XMFLOAT3 pos[12] = { XMFLOAT3(-X, 0.0f, Z), XMFLOAT3(X, 0.0f, Z), XMFLOAT3(-X, 0.0f, -Z), XMFLOAT3(X, 0.0f, -Z), XMFLOAT3(0.0f, Z, X), XMFLOAT3(0.0f, Z, -X), XMFLOAT3(0.0f, -Z, X), XMFLOAT3(0.0f, -Z, -X), XMFLOAT3(Z, X, 0.0f), XMFLOAT3(-Z, X, 0.0f), XMFLOAT3(Z, -X, 0.0f), XMFLOAT3(-Z, -X, 0.0f) }; DWORD k[60] = { 1,4,0, 4,9,0, 4,5,9, 8,5,4, 1,8,4, 1,10,8, 10,3,8, 8,3,5, 3,2,5, 3,7,2, 3,10,7, 10,6,7, 6,11,7, 6,0,11, 6,1,0, 10,1,6, 11,0,9, 2,11,9, 5,2,9, 11,2,7 }; meshData.Vertices.resize(12); meshData.Indices.resize(60); for (size_t i = 0; i < 12; ++i) meshData.Vertices[i].Position = pos[i]; for (size_t i = 0; i < 60; ++i) meshData.Indices[i] = k[i]; for (size_t i = 0; i < numSubdivisions; ++i) Subdivide(meshData);// Project vertices onto sphere and scale. for (size_t i = 0; i < meshData.Vertices.size(); ++i) { // Project onto unit sphere. XMVECTOR n = XMVector3Normalize(XMLoadFloat3( &meshData.Vertices[i].Position)); // Project onto sphere. XMVECTOR p = radius * n; XMStoreFloat3(&meshData.Vertices[i].Position, p); XMStoreFloat3(&meshData.Vertices[i].Normal, n); // Derive texture coordinates from spherical coordinates. float theta = AngleFromXY( meshData.Vertices[i].Position.x, meshData.Vertices[i].Position.z); float phi = acosf(meshData.Vertices[i].Position.y / radius); meshData.Vertices[i].TexC.x = theta / XM_2PI; meshData.Vertices[i].TexC.y = phi / XM_PI; // Partial derivative of P with respect to theta meshData.Vertices[i].TangentU.x = -radius * sinf(phi) * sinf(theta); meshData.Vertices[i].TangentU.y = 0.0f; meshData.Vertices[i].TangentU.z = +radius * sinf(phi) * cosf(theta); XMVECTOR T = XMLoadFloat3(&meshData.Vertices[i].TangentU); XMStoreFloat3(&meshData.Vertices[i].TangentU, XMVector3Normalize(T)); } } void GeometryGenerator::Subdivide(MeshData& meshData) { // Save a copy of the input geometry. MeshData inputCopy = meshData; meshData.Vertices.resize(0); meshData.Indices.resize(0); // v1 // * // / \ // / \ // m0*-----*m1 // / \ / \ // / \ / \ // *-----*-----* // v0 m2 v2 UINT numTris = inputCopy.Indices.size() / 3; for (UINT i = 0; i < numTris; ++i) { Vertex v0 = inputCopy.Vertices[inputCopy.Indices[i * 3 + 0]]; Vertex v1 = inputCopy.Vertices[inputCopy.Indices[i * 3 + 1]]; Vertex v2 = inputCopy.Vertices[inputCopy.Indices[i * 3 + 2]]; // // Generate the midpoints. // Vertex m0, m1, m2; // For subdivision, we just care about the position component. We derive the other // vertex components in CreateGeosphere. m0.Position = XMFLOAT3( 0.5f * (v0.Position.x + v1.Position.x), 0.5f * (v0.Position.y + v1.Position.y), 0.5f * (v0.Position.z + v1.Position.z)); m1.Position = XMFLOAT3( 0.5f * (v1.Position.x + v2.Position.x), 0.5f * (v1.Position.y + v2.Position.y), 0.5f * (v1.Position.z + v2.Position.z)); m2.Position = XMFLOAT3( 0.5f * (v0.Position.x + v2.Position.x), 0.5f * (v0.Position.y + v2.Position.y), 0.5f * (v0.Position.z + v2.Position.z)); // // Add new geometry. // meshData.Vertices.push_back(v0); // 0 meshData.Vertices.push_back(v1); // 1 meshData.Vertices.push_back(v2); // 2 meshData.Vertices.push_back(m0); // 3 meshData.Vertices.push_back(m1); // 4 meshData.Vertices.push_back(m2); // 5 meshData.Indices.push_back(i * 6 + 0); meshData.Indices.push_back(i * 6 + 3); meshData.Indices.push_back(i * 6 + 5); meshData.Indices.push_back(i * 6 + 3); meshData.Indices.push_back(i * 6 + 4); meshData.Indices.push_back(i * 6 + 5); meshData.Indices.push_back(i * 6 + 5); meshData.Indices.push_back(i * 6 + 4); meshData.Indices.push_back(i * 6 + 2); meshData.Indices.push_back(i * 6 + 3); meshData.Indices.push_back(i * 6 + 1); meshData.Indices.push_back(i * 6 + 4); } } void GeometryGenerator::CreateBox(float width, float height, float depth, MeshData& meshData) { // // Create the vertices. // Vertex v[24]; float w2 = 0.5f * width; float h2 = 0.5f * height; float d2 = 0.5f * depth; // Fill in the front face vertex data. v[0] = Vertex(-w2, -h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); v[1] = Vertex(-w2, +h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); v[2] = Vertex(+w2, +h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); v[3] = Vertex(+w2, -h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); // Fill in the back face vertex data. v[4] = Vertex(-w2, -h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); v[5] = Vertex(+w2, -h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); v[6] = Vertex(+w2, +h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); v[7] = Vertex(-w2, +h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); // Fill in the top face vertex data. v[8] = Vertex(-w2, +h2, -d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); v[9] = Vertex(-w2, +h2, +d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); v[10] = Vertex(+w2, +h2, +d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); v[11] = Vertex(+w2, +h2, -d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); // Fill in the bottom face vertex data. v[12] = Vertex(-w2, -h2, -d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); v[13] = Vertex(+w2, -h2, -d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); v[14] = Vertex(+w2, -h2, +d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); v[15] = Vertex(-w2, -h2, +d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); // Fill in the left face vertex data. v[16] = Vertex(-w2, -h2, +d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[17] = Vertex(-w2, +h2, +d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); v[18] = Vertex(-w2, +h2, -d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[19] = Vertex(-w2, -h2, -d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); // Fill in the right face vertex data. v[20] = Vertex(+w2, -h2, -d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); v[21] = Vertex(+w2, +h2, -d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); v[22] = Vertex(+w2, +h2, +d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); v[23] = Vertex(+w2, -h2, +d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); meshData.Vertices.assign(&v[0], &v[24]); // // Create the indices. // UINT i[36]; // Fill in the front face index data i[0] = 0; i[1] = 1; i[2] = 2; i[3] = 0; i[4] = 2; i[5] = 3; // Fill in the back face index data i[6] = 4; i[7] = 5; i[8] = 6; i[9] = 4; i[10] = 6; i[11] = 7; // Fill in the top face index data i[12] = 8; i[13] = 9; i[14] = 10; i[15] = 8; i[16] = 10; i[17] = 11; // Fill in the bottom face index data i[18] = 12; i[19] = 13; i[20] = 14; i[21] = 12; i[22] = 14; i[23] = 15; // Fill in the left face index data i[24] = 16; i[25] = 17; i[26] = 18; i[27] = 16; i[28] = 18; i[29] = 19; // Fill in the right face index data i[30] = 20; i[31] = 21; i[32] = 22; i[33] = 20; i[34] = 22; i[35] = 23; meshData.Indices.assign(&i[0], &i[36]); } UINT GeometryGenerator::LinkGrid(UINT m, UINT n, UINT startInd, MeshData& meshData) { UINT k = startInd; for (UINT i = 0; i < m - 1; ++i) { for (UINT j = 0; j < n - 1; ++j) { meshData.Indices[k] = i * n + j; meshData.Indices[k + 1] = i * n + j + 1; meshData.Indices[k + 2] = (i + 1) * n + j; meshData.Indices[k + 3] = (i + 1) * n + j; meshData.Indices[k + 4] = i * n + j + 1; meshData.Indices[k + 5] = (i + 1) * n + j + 1; k += 6; // next quad } } return k; } <file_sep>/1/TopoLayout.cpp #include "TopoLayout.h" TopoLayout::TopoLayout(TopoLayoutType type) :type(type) { } ID3D11InputLayout* TopoLayout::GetLayout(ID3D11Device* pDevice,ID3DX11EffectTechnique* tech) { D3D11_INPUT_ELEMENT_DESC* vertexDesc = nullptr; UINT numEle = 0u;// ¼¸¸öÓïÒå switch (type) { case TopoLayoutType::BillbordPS:{ topo = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; static D3D11_INPUT_ELEMENT_DESC vdBillbord[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "SIZE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12,D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; vertexDesc = vdBillbord; numEle = 2; break; } case TopoLayoutType::TrianglePNT: { topo = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; static D3D11_INPUT_ELEMENT_DESC vdTriangle[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12,D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24,D3D11_INPUT_PER_VERTEX_DATA, 0 } }; numEle = 3; vertexDesc = vdTriangle; break; } case TopoLayoutType::HillTessP: { topo = D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST; static D3D11_INPUT_ELEMENT_DESC vdHillTess[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; numEle = 1; vertexDesc = vdHillTess; break; } default: return nullptr; } // Create the input layout D3DX11_PASS_DESC passDesc; tech->GetPassByIndex(0)->GetDesc(&passDesc); HR(pDevice->CreateInputLayout(vertexDesc, numEle, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, mInputLayout.GetAddressOf())); return mInputLayout.Get(); } <file_sep>/1/Graphics.cpp #include "Graphics.h" #include "Shape.h" #include "GeometryGenerator.h" #include "DDSTextureLoader11.h" #include "ScreenGrab11.h" #include "TopoLayout.h" #include "Effect.h" Graphics::Graphics(HWND hWnd, UINT width,UINT height, bool enable4xMsaa) : mWinWidth(width), mWinHeight(height), mBGColor(0.0f, 1.0f, 0.0f, 1.0f), gfxTimer(), mEnable4xMsaa(enable4xMsaa), cameraIsChange(true), mMainCamera(Camera()) //mBasicEffect(this) { //mEnable4xMsaa = false; //以下方法开不了抗锯齿 //DXGI_SWAP_CHAIN_DESC sd; //sd.BufferDesc.Width = 0; //sd.BufferDesc.Height = 0; //sd.BufferDesc.RefreshRate.Numerator = 60; //sd.BufferDesc.RefreshRate.Denominator = 1; //sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; //sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; //// //sd.SampleDesc.Count = 1; //sd.SampleDesc.Quality = 0; //sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; //sd.BufferCount = 1; // 双缓冲 //sd.OutputWindow = hWnd; //sd.Windowed = true; //sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; //sd.Flags = 0; //HR(D3D11CreateDeviceAndSwapChain( // nullptr, // D3D_DRIVER_TYPE_HARDWARE, // nullptr, // 0, // nullptr, // 0, // D3D11_SDK_VERSION, // &sd, // &pSwap, // &pDevice, // nullptr, // &pContext //)); // 初始化设备、上下文、交换链 #pragma region device,context,swapchain UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; HR(D3D11CreateDevice( 0,// default adapter D3D_DRIVER_TYPE_HARDWARE, 0,// no software device createDeviceFlags, 0, 0,// default feature level array D3D11_SDK_VERSION, &pDevice, &featureLevel, &pContext)); if (featureLevel != D3D_FEATURE_LEVEL_11_0) { MessageBoxA(0, "Direct3D Feature Level 11 unsupported.", 0, 0); return; } // HR:书作者提供来方便判断hr是否成功的宏 HR(pDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality)); assert(m4xMsaaQuality > 0); DXGI_SWAP_CHAIN_DESC sd; sd.BufferDesc.Width = 0; sd.BufferDesc.Height = 0; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; // Use 4X MSAA? if (mEnable4xMsaa) { sd.SampleDesc.Count = 4; // m4xMsaaQuality is returned via CheckMultisampleQualityLevels(). sd.SampleDesc.Quality = m4xMsaaQuality - 1; } //No MSAA else { sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; } sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = hWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_SEQUENTIAL; sd.Flags = 0; wrl::ComPtr<IDXGIDevice> dxgiDevice = 0; HR(pDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice)); wrl::ComPtr<IDXGIAdapter> dxgiAdapter = 0; HR(dxgiDevice->GetParent(__uuidof(IDXGIAdapter),(void**) & dxgiAdapter)); // Finally got the IDXGIFactory interface. IDXGIFactory* dxgiFactory = 0; HR(dxgiAdapter->GetParent(__uuidof(IDXGIFactory),(void**) & dxgiFactory)); // Now, create the swap chain. HR(dxgiFactory->CreateSwapChain(pDevice.Get(), &sd, &pSwap)); #pragma endregion //mBasicEffect.init(); //BasicEffect mBasicEffect(this); /****************************创建深度模板视图**************************/ D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = mWinWidth; depthStencilDesc.Height = mWinHeight; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; // Use 4X MSAA? --must match swap chain MSAA values. if (mEnable4xMsaa) { depthStencilDesc.SampleDesc.Count = 4; depthStencilDesc.SampleDesc.Quality = m4xMsaaQuality - 1; }//No MSAA else { depthStencilDesc.SampleDesc.Count = 1; depthStencilDesc.SampleDesc.Quality = 0; } depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; HR(pDevice->CreateTexture2D(&depthStencilDesc, // Description of texture to create. 0,// 填充数据,由于是深度纹理,为0 &mDepthStencilBuffer)); // Return pointer to depth/stencil buffer. HR(pDevice->CreateDepthStencilView( mDepthStencilBuffer.Get(), // Resource we want to create a view to. 0,// D3D11_DEPTH_STENCIL_VIEW_DESC,0表示使用纹理的数据类型(不是typeless) mDepthStencilView.GetAddressOf())); // Return depth/stencil view /****************************创建深度模板视图完**************************/ /****************************定义主渲染目标视图***********************/ Microsoft::WRL::ComPtr<ID3D11Resource> pBackBuffer; //ID3D11Resource* pBackBuffer = pSwap->GetBuffer(0, __uuidof(ID3D11Resource), &pBackBuffer); pDevice->CreateRenderTargetView( pBackBuffer.Get(), nullptr, &pMainTarget ); pContext->OMSetRenderTargets(1u, pMainTarget.GetAddressOf(), mDepthStencilView.Get()); /*****************************定义主渲染目标视图完***********************/ //pContext->OMSetRenderTargets(1u, pTarget.GetAddressOf(),nullptr); /****************************定义主视口**************************/ mMainViewPort.TopLeftX = 0.0f; mMainViewPort.TopLeftY = 0.0f; mMainViewPort.Width = float(mWinWidth); mMainViewPort.Height = float(mWinHeight); mMainViewPort.MinDepth = 0.0f; mMainViewPort.MaxDepth = 1.0f; pContext->RSSetViewports(1, &mMainViewPort); /****************************定义主视口完**************************/ //D3D11_RECT rects = { 100, 100, 400, 400 }; //pContext->RSSetScissorRects(1, &rects); } Graphics::~Graphics() { //if (mDirLights.size() > 0) { // for (int i = 0; i < mDirLights.size(); ++i) { // if (&mDirLights[i] != nullptr) // delete &mDirLights[i]; // } //} } void Graphics::SetCamera(Camera camera) { this->mMainCamera = camera; cameraIsChange = true; } void Graphics::UpdateCamera() { cameraIsChange = true; } void Graphics::EndFrame() { if (cameraIsChange) { cameraIsChange = false; } pSwap->Present(1u, 0u); } void Graphics::DrawFrame() { // 更新资源 //mTech->GetDesc(&techDesc); ClearBuffer(pMainTarget.Get()); for (auto e : effects) { e->Draw(); } } void Graphics::ClearBuffer(ID3D11RenderTargetView* target) { XMFLOAT4 cc(0.0f, 0.0f, 1.0f, 0.5f); pContext->ClearRenderTargetView(target, reinterpret_cast<float*>(&mBGColor)); pContext->ClearDepthStencilView(mDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); } #pragma region 测试代码 #pragma endregion <file_sep>/1/Wave.hlsl #include "basic.hlsli" //ÁúÊép384 // //VERSION 2: Using SampleLevel and texture coordinates. // cbuffer cbUpdateSettings { float gWaveConstants[3]; float2 gDisplacementMapTexelSize = float2(1.0f, 1.0f); float gGridSpatialStep = 5.0f; }; SamplerState samPoint { Filter = MIN_MAG_MIP_POINT; AddressU = CLAMP; AddressV = CLAMP; }; SamplerState samDisplacement { Filter = ANISOTROPIC; MaxAnisotropy = 4; AddressU = BORDER; AddressV = BORDER; }; Texture2D gPrevSolInput; Texture2D gCurrSolInput; RWTexture2D<float> gNextSolOutput; #define RAND_MAX 0x7fff //Î±Ëæ»úÊýËã·¨ https://blog.csdn.net/pizi0475/article/details/48518665 #define cMult 0.0001002707309736288 #define aSubtract 0.2727272727272727 float randGrieu(float4 t) { float a = t.x + t.z * cMult + aSubtract - floor(t.x); a *= a; float b = t.y + a; b -= floor(b); float c = t.z + b; c -= floor(c); float d = c; a += c * cMult + aSubtract - floor(a); a *= a; b += a; b -= floor(b); c += b; c -= floor(c); return (a+b+c+d)/4.0f; } [numthreads(16, 16, 1)] void WaveCS(int3 dispatchThreadID : SV_DispatchThreadID) { // Equivalently using SampleLevel() instead of operator []. int x = dispatchThreadID.x; int y = dispatchThreadID.y; float2 c = float2(x, y) / 512.0f; float2 t = float2(x, y - 1) / 512.0f; float2 b = float2(x, y + 1) / 512.0f; float2 l = float2(x - 1, y) / 512.0f; float2 r = float2(x + 1, y) / 512.0f; //gNextSolOutput[int2(x, y)] = // gWaveConstants[0] * gPrevSolInput.SampleLevel(samPoint, c, 0.0f).r + // gWaveConstants[1] * gCurrSolInput.SampleLevel(samPoint, c, 0.0f).r + // gWaveConstants[2] * ( // gCurrSolInput.SampleLevel(samPoint, b, 0.0f).r + // gCurrSolInput.SampleLevel(samPoint, t, 0.0f).r + // gCurrSolInput.SampleLevel(samPoint, r, 0.0f).r + // gCurrSolInput.SampleLevel(samPoint, l, 0.0f).r); //gNextSolOutput[int2(x, y)] = 0.5f; // ÈÅÂÒ /*if (time - t_base > 0.025f) return;*/ //if (time - t_base < 0.25f) { //float now = time; //GroupMemoryBarrierWithGroupSync(); float t_base = 500.0f; if (time - t_base > 0.0f) { t_base += 500.0f; float magnitude = frac(randGrieu(float4(time - t_base,c,lastTime - x - y))); float q = abs(frac(randGrieu(float4(time,t,lastTime - y)))); float w = abs(frac(randGrieu(float4(time,b,lastTime - x)))); //float magnitude = 0.5f; x = 511 * q; y = 511 * w; float halfMag = 0.5f * magnitude; //Disturb the ijth vertex height and its neighbors. gNextSolOutput[int2(x,y)] = magnitude; gNextSolOutput[int2(x, y+1)] = halfMag; gNextSolOutput[int2(x, y-1)] = halfMag; gNextSolOutput[int2(x+1, y)] = halfMag; gNextSolOutput[int2(x-1, y)] = halfMag; } } VertexOut WaveVS(VertexIn vin) { VertexOut vout; Texture2D gDisplacementMap = gCurrSolInput; // Sample the displacement map using non-transformed // [0,1]^2 tex-coords. vin.PosL.y = gDisplacementMap.SampleLevel( samDisplacement, vin.Tex, 0.0f).r; // Estimate normal using finite difference. float du = gDisplacementMapTexelSize.x; float dv = gDisplacementMapTexelSize.y; float l = gDisplacementMap.SampleLevel( samDisplacement, vin.Tex - float2(du, 0.0f), 0.0f).r; float r = gDisplacementMap.SampleLevel( samDisplacement, vin.Tex + float2(du, 0.0f), 0.0f).r; float t = gDisplacementMap.SampleLevel( samDisplacement, vin.Tex - float2(0.0f, dv), 0.0f).r; float b = gDisplacementMap.SampleLevel( samDisplacement, vin.Tex + float2(0.0f, dv), 0.0f).r; vin.NormalL = normalize(float3(-r + l, 2.0f * gGridSpatialStep, b - t)); // Transform to world space space. vout.PosW = mul(float4(vin.PosL, 1.0f), gWorld).xyz; vout.NormalW = mul(vin.NormalL, (float3x3)gWorldInvTranspose); // Transform to homogeneous clip space. vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj); // Output vertex attributes for interpolation across triangle. vout.Tex = mul(float4(vin.Tex, 0.0f, 1.0f), gTexTransform).xy; return vout; } technique11 WaveTex { pass P0 { SetVertexShader(NULL); SetGeometryShader(NULL); SetComputeShader(CompileShader(cs_5_0, WaveCS())); } }; technique11 DrawWave { pass P0 { SetVertexShader(CompileShader(vs_5_0, WaveVS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, PS(true, false))); } };<file_sep>/1/basic.hlsli #include "light.hlsli" cbuffer cbPerFrame { float3 gEyePosW; float gFogStart; float gFogRange; float4 gFogColor; }; cbuffer cbPerObject { float time; float4x4 gWorld; float4x4 gWorldInvTranspose; float4x4 gWorldViewProj; float4x4 gViewProj; float4x4 gReflectWorldViewProj; float4x4 gTexTransform; Material gMaterial; } // 纹理 Texture2D gDiffuseMap; Texture2DMS <float4, 4> gReflectMap; struct VertexIn { float3 PosL : POSITION; float3 NormalL : NORMAL; float2 Tex : TEXCOORD; }; struct VertexOut { float4 PosH : SV_POSITION; float3 PosW : POSITION; float3 NormalW : NORMAL; float2 Tex : TEXCOORD; }; // 记录时间 static float lastTime; static const float dt = 0.5f; // 采样器设置 SamplerState samAnisotropic { Filter = ANISOTROPIC; MaxAnisotropy = 4; AddressU = BORDER; AddressV = BORDER; }; // 计算灯光组 void litPixel(VertexOut pin, inout float4 ambient, inout float4 diffuse, inout float4 spec) { // Interpolating normal can unnormalize it, so normalize it. pin.NormalW = normalize(pin.NormalW); float3 toEyeW = normalize(gEyePosW - pin.PosW); // Sum the light contribution from each light source. float4 A, D, S; for (int i = 0; i < num_DL; ++i) { ComputeDirectionalLight(gMaterial, DLs[i], pin.NormalW, toEyeW, A, D, S); ambient += A; diffuse += D; spec += S; } for (int j = 0; j < num_PL; ++j) { ComputePointLight(gMaterial, PLs[j], pin.PosW, pin.NormalW, toEyeW, A, D, S); ambient += A; diffuse += D; spec += S; } for (int k = 0; k < num_SL; ++k) { ComputeSpotLight(gMaterial, SLs[k], pin.PosW, pin.NormalW, toEyeW, A, D, S); ambient += A; diffuse += D; spec += S; } } VertexOut VS(VertexIn vin) { lastTime = time; VertexOut vout; //Wave(vin.PosL.x, vin.PosL.z, vin.PosL.y, vin.NormalL); vout.PosW = mul(float4(vin.PosL, 1.0f), gWorld).xyz; vout.NormalW = mul(vin.NormalL, (float3x3)gWorldInvTranspose); vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj); // Output vertex attributes for interpolation across triangle. vout.Tex = mul(float4(vin.Tex, 0.0f, 1.0f), gTexTransform).xy; //vout.Tex = vin.Tex; return vout; } float4 PS(VertexOut pin, uniform bool gUseTexure, uniform bool gUseFog = true) : SV_Target { // Default to multiplicative identity. float4 texColor = float4(1, 1, 1, 1); if (gUseTexure) { // Sample texture. texColor = gDiffuseMap.Sample(samAnisotropic, pin.Tex); } //clip(texColor.a - 0.05f); float4 litColor = texColor; // Start with a sum of zero. float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 spec = float4(0.0f, 0.0f, 0.0f, 0.0f); litPixel(pin, ambient, diffuse, spec); litColor = texColor * (ambient + diffuse) + spec; float distToEye = distance(gEyePosW, pin.PosW); if (gUseFog) { float fogLerp = saturate((distToEye - gFogStart) / gFogRange); // Blend the fog color and the lit color. use alpha as amount litColor = lerp(litColor, gFogColor, fogLerp * gFogColor.a); } // Common to take alpha from diffuse material. litColor.a = texColor.a * gMaterial.Diffuse.a; return litColor; //return float4(gMaterial.Diffuse.r, gMaterial.Diffuse.g, gMaterial.Diffuse.b,1.0f ); //return float4(texColor.r, texColor.g, texColor.b, texColor.a); //return float4(litColor.r, litColor.g, litColor.b,1.0f ); //return float4(ambient.r, ambient.g, ambient.b,1.0f ); } <file_sep>/1/effect.cpp #include "BasicEffect.h" PDEeffect::PDEeffect(const char *FXfilename, Graphics* gfx) : mGfx(gfx) { pDevice = wrl::ComPtr<ID3D11Device>(mGfx->GetDevice()); pContext = wrl::ComPtr<ID3D11DeviceContext>(mGfx->GetDeviceContext()); wrl::ComPtr<ID3DBlob> compiledShader; HR(D3DReadFileToBlob(CA2W(FXfilename), &compiledShader)); HR(D3DX11CreateEffectFromMemory( compiledShader->GetBufferPointer(), compiledShader->GetBufferSize(), 0, pDevice.Get(), &mFX)); CreateState(); } void PDEeffect::Bind() { // 绑定到管道 pContext->IASetVertexBuffers(0, 1, mVB.GetAddressOf(), &mVBstride, &mVBoffset); if(mIB) pContext->IASetIndexBuffer(mIB.Get(), DXGI_FORMAT_R32_UINT, 0); if (mTopoLayout.GetType() != TopoLayoutType::UnDefine) { pContext->IASetInputLayout(mTopoLayout.GetLayout(pDevice.Get(), mTech.Get())); pContext->IASetPrimitiveTopology(mTopoLayout.GetTopo()); } } wrl::ComPtr<ID3D11RasterizerState> PDEeffect::mWIREFRAME = nullptr; wrl::ComPtr<ID3D11RasterizerState> PDEeffect::mSOLID = nullptr; wrl::ComPtr<ID3D11RasterizerState> PDEeffect::mBACK = nullptr; wrl::ComPtr<ID3D11BlendState> PDEeffect::mBlendStateSRC = nullptr; wrl::ComPtr<ID3D11BlendState> PDEeffect::mBlendStateAdd = nullptr; wrl::ComPtr<ID3D11BlendState> PDEeffect::mBlendStateSubtract = nullptr; wrl::ComPtr<ID3D11BlendState> PDEeffect::mBlendStateMultiply = nullptr; wrl::ComPtr<ID3D11BlendState> PDEeffect::mBlendStateTransparency = nullptr; wrl::ComPtr<ID3D11DepthStencilState> PDEeffect::mNoDoubleBlendDSS = nullptr; bool PDEeffect::mIsLoadState = false; void PDEeffect::CreateState() { if (!mIsLoadState) { CreateAllBlendState(); CreateAllDepthStencilState(); CreateAllRasterizerState(); mIsLoadState = true; } } inline void PDEeffect::CreateAllRasterizerState() { /****************************创建栅格化设定**************************/ // 线框渲染 D3D11_RASTERIZER_DESC rsDesc; ZeroMemory(&rsDesc, sizeof(D3D11_RASTERIZER_DESC)); rsDesc.FillMode = D3D11_FILL_WIREFRAME; rsDesc.CullMode = D3D11_CULL_NONE; rsDesc.FrontCounterClockwise = false; rsDesc.DepthClipEnable = true; //rsDesc.ScissorEnable = true; HR(pDevice->CreateRasterizerState(&rsDesc, &mWIREFRAME)); // 体渲染 rsDesc.FillMode = D3D11_FILL_SOLID; rsDesc.CullMode = D3D11_CULL_BACK; rsDesc.FrontCounterClockwise = false; rsDesc.DepthClipEnable = true; //rsDesc.ScissorEnable = true; HR(pDevice->CreateRasterizerState(&rsDesc, &mSOLID)); rsDesc.CullMode = D3D11_CULL_NONE; HR(pDevice->CreateRasterizerState(&rsDesc, &mBACK)); /****************************创建栅格化设定完**************************/ } inline void PDEeffect::CreateAllBlendState() { D3D11_BLEND_DESC blendDesc = { 0 }; blendDesc.AlphaToCoverageEnable = false; blendDesc.IndependentBlendEnable = false; blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL ; HR(pDevice->CreateBlendState(&blendDesc, mBlendStateSRC.GetAddressOf())); blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; HR(pDevice->CreateBlendState(&blendDesc, mBlendStateAdd.GetAddressOf())); blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_SUBTRACT; HR(pDevice->CreateBlendState(&blendDesc, mBlendStateSubtract.GetAddressOf())); blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_SRC_COLOR; HR(pDevice->CreateBlendState(&blendDesc, mBlendStateMultiply.GetAddressOf())); blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; HR(pDevice->CreateBlendState(&blendDesc, mBlendStateTransparency.GetAddressOf())); } inline void PDEeffect::CreateAllDepthStencilState() { //p348 D3D11_DEPTH_STENCIL_DESC noDoubleBlendDesc; noDoubleBlendDesc.DepthEnable = true; noDoubleBlendDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; noDoubleBlendDesc.DepthFunc = D3D11_COMPARISON_LESS; noDoubleBlendDesc.StencilEnable = true; noDoubleBlendDesc.StencilReadMask = 0xff; noDoubleBlendDesc.StencilWriteMask = 0xff; noDoubleBlendDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_INCR; noDoubleBlendDesc.FrontFace.StencilFunc = D3D11_COMPARISON_EQUAL; // We are not rendering backfacing polygons, so these settings do not matter. noDoubleBlendDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; noDoubleBlendDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_INCR; noDoubleBlendDesc.BackFace.StencilFunc = D3D11_COMPARISON_EQUAL; HR(pDevice->CreateDepthStencilState(&noDoubleBlendDesc, mNoDoubleBlendDSS.GetAddressOf())); } PDEeffect::PDEeffect() :mTopoLayout() { } <file_sep>/1/WaveFX.cpp #include "WaveFX.h" #include "GeometryGenerator.h" #include "DirectXTex.h" WaveFX::WaveFX(BasicEffect* be) : PDEeffect("Wave.cso",be->GetGfx()), mBe(be) { LoadFx(); SetTopoLayout(); } WaveFX::~WaveFX() { if (mWave != nullptr) { delete mWave; mWave = nullptr; } } #include "ScreenGrab11.h" void WaveFX::Draw() { mTechWaveTex->GetDesc(&techDesc); float now = mGfx->GetRanderTime() * 1000.0f; mFX->GetVariableByName("time")->AsScalar()->SetFloat(now); // 按照 012 120 201 的顺序绑定3张纹理,以达成循环利用 // P C N // 0 1 2 // 1 2 0 // 2 0 1 static UINT texCount = 0; for (UINT p = 0; p < techDesc.Passes; ++p) { HR(mfxPrevSolInput->SetResource(mSRVs[texCount].Get())); HR(mfxCurrSolInput->SetResource(mSRVs[(texCount+1u)%3].Get())); HR(mfxNextSolOutput->SetUnorderedAccessView(mUAVs[(texCount + 2u) % 3].Get())); HR(mTechWaveTex->GetPassByIndex(p)->Apply(0, mGfx->GetDeviceContext())); UINT numGroupsX = (UINT)ceilf(mTexW / 16.0f); UINT numGroupsY = (UINT)ceilf(mTexH / 16.0f); mGfx->GetDeviceContext()->Dispatch(numGroupsX, numGroupsY, 1); } ++texCount; if (texCount > 2) texCount = 0; // Unbind the input texture from the CS for good housekeeping. ID3D11ShaderResourceView* nullSRV[1] = { 0 }; mGfx->GetDeviceContext()->CSSetShaderResources(0, 1, nullSRV); // Unbind output from compute shader (we are going to use // this output as an input in the next pass), and a resource // cannot be both an output and input at the same time. ID3D11UnorderedAccessView* nullUAV[1] = { 0 }; mGfx->GetDeviceContext()->CSSetUnorderedAccessViews(0, 1, nullUAV, 0); ID3D11Resource* tex; mSRVs[0]->GetResource(&tex); SaveDDSTextureToFile(mGfx->GetDeviceContext(), tex, L"wa1.dds"); mSRVs[1]->GetResource(&tex); SaveDDSTextureToFile(mGfx->GetDeviceContext(), tex, L"wa2.dds"); mSRVs[2]->GetResource(&tex); SaveDDSTextureToFile(mGfx->GetDeviceContext(), tex, L"wa3.dds"); ; } void WaveFX::LoadFx() { mTech = mFX->GetTechniqueByName("DrawWave"); mTechWaveTex = mFX->GetTechniqueByName("WaveTex"); mfxWaveConstants = mFX->GetVariableByName("gWaveConstants")->AsScalar(); mfxPrevSolInput = mFX->GetVariableByName("gPrevSolInput")->AsShaderResource(); mfxCurrSolInput = mFX->GetVariableByName("gCurrSolInput")->AsShaderResource(); mfxNextSolOutput = mFX->GetVariableByName("gNextSolOutput")->AsUnorderedAccessView(); mTexW = 512; mTexH = 512; //DXGI_FORMAT format = DXGI_FORMAT_A8_UNORM; DXGI_FORMAT format = DXGI_FORMAT_R16_FLOAT; D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; uavDesc.Format = format; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = 0; for (int i = 0; i < 3; ++i) { ScratchImage limage; limage.Initialize2D(format, mTexW, mTexH, 1, 1); wrl::ComPtr<ID3D11Texture2D> WaveTexture; CreateTextureEx(mGfx->GetDevice(), limage.GetImages(), limage.GetImageCount(), limage.GetMetadata(), D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS, 0, 0, false, (ID3D11Resource**)WaveTexture.GetAddressOf()); wrl::ComPtr<ID3D11ShaderResourceView> SRV; HR(pDevice->CreateShaderResourceView(WaveTexture.Get(), &srvDesc, SRV.GetAddressOf())); wrl::ComPtr<ID3D11UnorderedAccessView> UAV; HR(pDevice->CreateUnorderedAccessView(WaveTexture.Get(), &uavDesc, UAV.GetAddressOf())); mSRVs.push_back(SRV); mUAVs.push_back(UAV); } //DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; //LoadFromDDSFile(CA2W("source.dds"), DDS_FLAGS_NONE, nullptr, image); float WaveConstants[3] = { mK1,mK2, mK3 }; HR(mfxWaveConstants->SetFloatArray(WaveConstants, 0, 3)); } void WaveFX::SetTopoLayout() { /*mTopoLayout = TopoLayout(TopoLayoutType::TrianglePNT);*/ } void WaveFX::Init(float Widht, float Height, float dx, float dt, float speed, float damping) { GeometryGenerator geo; float dG = 5.0f; UINT m = (UINT)ceilf(Widht / dG); UINT n = (UINT)ceilf(Height / dG); MeshData md; geo.CreateGrid(Widht, Height, m, n, md); //mTimeStep = dt; //mSpatialStep = dx; float d = damping * dt + 2.0f; float e = (speed * speed) * (dt * dt) / (dx * dx); mK1 = (damping * dt - 2.0f) / d; mK2 = (4.0f - 8.0f * e) / d; mK3 = (2.0f * e) / d; mWave = new PDEshape(md); mWave->SetShadow(false); mWave->SetBlendType(BlendType::None); mBe->AddShape(mWave); } <file_sep>/1/box.h #pragma once #include "h.h" // 定义一个只有颜色和位置的顶点信息 using namespace DirectX; struct Vertex { XMFLOAT3 Pos; XMFLOAT3 Color; }; // 继承书上给的D3DApp类 class Box : { public: Box(); ~Box(); private: void BuildGeometryBuffers(); void BuildFX(); void BuildVertexLayout(); private: ID3D11Buffer* mBoxVB; ID3D11Buffer* mBoxIB; ID3DX11Effect* mFX; ID3DX11EffectTechnique* mTech; ID3DX11EffectMatrixVariable* mfxWorldViewProj; ID3D11InputLayout* mInputLayout; XMFLOAT4X4 mWorld; XMFLOAT4X4 mView; XMFLOAT4X4 mProj; // 摄像机球坐标(左手坐标,theta从x起沿xz面,phi从y起。) float mTheta; float mPhi; float mRadius; POINT mLastMousePos; }; <file_sep>/1/BasicEffect.h #ifndef BASICEFFECT #define BASICEFFECT #include "h.h" #include "effect.h" #include "light.h" #include "Graphics.h" #include "TopoLayout.h" #include "ReflectivePlane.h" namespace wrl = Microsoft::WRL; class ReflectivePlane; class PDEshape; class PDEeffect { friend class Graphics; public: PDEeffect(const char* FXfilename, Graphics* mGfx); PDEeffect(PDEeffect&) = delete; PDEeffect& operator=(PDEeffect&) = delete; ID3DX11EffectTechnique* Tech() { return mTech.Get(); } virtual void Draw() = 0; void Bind(); void CreateState(); void CreateAllRasterizerState(); void CreateAllBlendState(); void CreateAllDepthStencilState(); ID3DX11EffectTechnique* GetDrawTech() { return this->mTech.Get(); } ID3DX11Effect* GetFX(){ return mFX.Get(); } Graphics* GetGfx(){ return mGfx; } protected: virtual void LoadFx()=0; virtual void SetTopoLayout() = 0; TopoLayout mTopoLayout; PDEeffect(); wrl::ComPtr<ID3D11Device> pDevice; wrl::ComPtr<ID3D11DeviceContext> pContext; Graphics* mGfx; wrl::ComPtr<ID3DX11Effect> mFX; wrl::ComPtr<ID3DX11EffectTechnique> mTech; D3DX11_TECHNIQUE_DESC techDesc; // 顶点缓冲 wrl::ComPtr<ID3D11Buffer> mVB; // 索引缓冲 wrl::ComPtr<ID3D11Buffer> mIB; UINT mVBstride; // 顶点缓冲步长 UINT mVBoffset; // 顶点缓冲偏移 // 两种栅格化方式:体渲染和线框渲染和开启背面 static wrl::ComPtr<ID3D11RasterizerState> mWIREFRAME; static wrl::ComPtr<ID3D11RasterizerState> mSOLID; static wrl::ComPtr<ID3D11RasterizerState> mBACK; // 混合设定 static wrl::ComPtr<ID3D11BlendState> mBlendStateSRC; static wrl::ComPtr<ID3D11BlendState> mBlendStateAdd; static wrl::ComPtr<ID3D11BlendState> mBlendStateSubtract; static wrl::ComPtr<ID3D11BlendState> mBlendStateMultiply; static wrl::ComPtr<ID3D11BlendState> mBlendStateTransparency; // 深度模板设定 static wrl::ComPtr<ID3D11DepthStencilState> mNoDoubleBlendDSS; static bool mIsLoadState; }; // 单例模式 class BasicEffect : public PDEeffect { public: static BasicEffect* get_instance(Graphics* gfx) { if (this_ptr == nullptr) { this_ptr = new BasicEffect(gfx); } return this_ptr; } static BasicEffect* get_instance() { return this_ptr; } ~BasicEffect() { if (this_ptr != nullptr) { delete this_ptr; this_ptr = nullptr; } } void init(); BasicEffect() = delete; // 通过 PDEeffect 继承 virtual void Draw() override; void DrawShapes(ID3D11RenderTargetView* renderTarget, Camera& camera); void DrawMirrors(ID3D11RenderTargetView* target, Camera& camera); std::vector<UINT>& SortShapes(Camera& camera) const; void AddShape(PDEshape* pShape); void AddShapes(std::vector<PDEshape*> pShape); bool AddLight(Light light); struct Vertex { XMFLOAT3 Pos; XMFLOAT3 Normal; XMFLOAT2 Tex; }; std::vector<PDEshape*>& GetShapes() { return pShapes; } protected: virtual void LoadFx() override; virtual void SetTopoLayout() override; private: void LoadMirrors(const std::vector<ReflectivePlane*>& mirrors); void LoadShapes(); BasicEffect(Graphics* gfx); // 单例指针 static BasicEffect* this_ptr; //基础图形 std::vector<PDEshape*> pShapes; bool mIsLoadShapes; /***************技术**********************/ wrl::ComPtr<ID3DX11EffectTechnique> mTechTexture; wrl::ComPtr<ID3DX11EffectTechnique> mTechNoTexture; wrl::ComPtr<ID3DX11EffectTechnique> mTechReflect; wrl::ComPtr<ID3DX11EffectTechnique> mTechReflectNoMSAA; wrl::ComPtr<ID3DX11EffectTechnique> mTechShadow; /*************常量缓冲************************/ wrl::ComPtr<ID3DX11EffectMatrixVariable> mfxWorldViewProj; wrl::ComPtr<ID3DX11EffectMatrixVariable> mfxViewProj; wrl::ComPtr<ID3DX11EffectMatrixVariable> mfxReflectWorldViewProj; wrl::ComPtr<ID3DX11EffectMatrixVariable> mfxWorld; wrl::ComPtr<ID3DX11EffectMatrixVariable> mfxWorldInvTranspose; wrl::ComPtr<ID3DX11EffectVectorVariable> mfxEyePosW; // 实时渲染时间 wrl::ComPtr<ID3DX11EffectScalarVariable> mfxTime; // 材质 wrl::ComPtr<ID3DX11EffectVariable> mfxMaterial; wrl::ComPtr<ID3DX11EffectVariable> mfxDirLights; wrl::ComPtr<ID3DX11EffectVariable> mfxPointLights; wrl::ComPtr<ID3DX11EffectVariable> mfxSpotLights; wrl::ComPtr<ID3DX11EffectScalarVariable> mfxNum_DL; wrl::ComPtr<ID3DX11EffectScalarVariable> mfxNum_PL; wrl::ComPtr<ID3DX11EffectScalarVariable> mfxNum_SL; // 纹理 wrl::ComPtr<ID3DX11EffectShaderResourceVariable> mfxDiffuseMap; wrl::ComPtr<ID3DX11EffectShaderResourceVariable> mfxReflectMap; wrl::ComPtr<ID3DX11EffectMatrixVariable> mfxTexTransform; // 阴影 wrl::ComPtr<ID3DX11EffectVectorVariable> mfxShadowL;; /*************常量缓冲完************************/ // 图形相关 std::vector<Vertex> mVertices; std::vector<UINT> mIndexes; std::vector<UINT> mIndexCounts; std::vector<UINT> mVertexCounts; std::vector<bool> mHasTex; // 镜子 std::vector<ReflectivePlane*> mirrors; // 灯光与材质 bool lightIsChange; std::vector<DirectionalLight> mDirLights; std::vector<PointLight> mPointLights; std::vector<SpotLight> mSpotLights; UINT num_DL; UINT num_PL; UINT num_SL; }; #endif // !BASICEFFECT <file_sep>/1/light.hlsl #include "light.hlsli" cbuffer cbPerFrame { //DirectionalLight gDirLight; //PointLight gPointLight; //SpotLight gSpotLight; float3 gEyePosW; }; cbuffer cbPerObject { float time; float4x4 gWorld; float4x4 gWorldInvTranspose; float4x4 gWorldViewProj; Material gMaterial; } // 记录时间 static float lastTime; static const float dt = 0.5f; struct VertexIn { float3 PosL : POSITION; float3 NormalL : NORMAL; }; struct VertexOut { float3 PosW : POSITION; float4 PosH : SV_POSITION; float3 NormalW : NORMAL; }; // 根据时间模拟波浪 void Wave( float x, float z, out float y, out float3 n ) { y = 0.1f * (z * sin(0.2f * x + time / 1.0f) + x * cos(0.2f * z + time / 1.0f)); // Transform to world space. // 计算法线 n = float3( 0.02 * z * cos(0.2 * x + time / 1.0f) + 0.1 * cos(0.2f * z + time / 1.0f), 1.0f, 0.1 * sin(0.2 * x + time / 1.0f) + 0.02 * x * sin(0.2f * z + time / 1.0f) ); n /= length(n); } VertexOut WaveVS(VertexIn vin) { lastTime = time; VertexOut vout; //Wave(vin.PosL.x, vin.PosL.z, vin.PosL.y, vin.NormalL); vout.PosW = mul(float4(vin.PosL, 1.0f), gWorld).xyz; vout.NormalW = mul(vin.NormalL, (float3x3)gWorldInvTranspose); vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj); // Just pass vertex color into the pixel shader. return vout; } float4 LightPS(VertexOut pin) : SV_Target { // Interpolating normal can unnormalize it, so normalize it. pin.NormalW = normalize(pin.NormalW); float3 toEyeW = normalize(gEyePosW - pin.PosW); // Start with a sum of zero. float4 ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); float4 spec = float4(0.0f, 0.0f, 0.0f, 0.0f); // Sum the light contribution from each light source. float4 A, D, S; for (int i = 0; i < num_DL; ++i) { ComputeDirectionalLight(gMaterial, DLs[i],pin.NormalW, toEyeW, A, D, S); ambient += A; diffuse += D; spec += S; } for (int j = 0; j < num_PL; ++j) { ComputePointLight(gMaterial, PLs[j],pin.PosW, pin.NormalW, toEyeW, A, D, S); ambient += A; diffuse += D; spec += S; } for (int k = 0; k < num_SL; ++k) { ComputeSpotLight(gMaterial, SLs[k], pin.PosW, pin.NormalW, toEyeW, A, D, S); ambient += A; diffuse += D; spec += S; } float4 litColor = clamp(ambient + diffuse + spec,0.0f,1.0f); // Common to take alpha from diffuse material. litColor.a = gMaterial.Diffuse.a; return litColor; //return float4(0.0f, 0.0f, 0.0f, 1.0f); } float4 PS(VertexOut pin) : SV_Target{ return float4(0.0f, 0.0f, 0.0f, 1.0f); } RasterizerState WireframeRS { FillMode = Wireframe; CullMode = Back; FrontCounterClockwise = false; // Default values used for any properties we do not set. }; technique11 LightOnWaweTech { pass P0 { SetVertexShader(CompileShader(vs_5_0, WaveVS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, LightPS())); } /*pass P1 { SetVertexShader(CompileShader(vs_5_0, WaveVS())); SetGeometryShader(NULL); SetPixelShader(CompileShader(ps_5_0, PS())); SetRasterizerState(WireframeRS); }*/ }<file_sep>/1/window.h #pragma once #include "h.h" #include "keyboard.h" #include "mouse.h" #include <optional> #include "Graphics.h" #include <memory> class Window { private: class WindowClass { public: static const char* GetName() noexcept; static HINSTANCE GetInstance() noexcept; private: WindowClass() noexcept; ~WindowClass(); WindowClass(const WindowClass&) = delete; WindowClass& operator= (const WindowClass&) = delete; static constexpr const char* wndClassName = "kawaiiWindow"; static WindowClass wndClass; HINSTANCE hInst; }; public: static int wins;//窗口数量,如果只有一个窗口则没啥卵用,所有框框被关了才退出程序。待扩展 Window(int width,int height,const char* name) noexcept; ~Window(); Window(const Window&) = delete; Window& operator= (const Window&) = delete; void SetTitle(const char* title); static std::optional<int> ProcessMessages(); Graphics& Gfx(); private: static LRESULT CALLBACK HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; public: Keyboard kbd;// 键盘输入 Mouse mouse;// 鼠标输入 private: int width; int height; HWND hWnd; std::unique_ptr<Graphics> pGfx;// 智能唯一指针指向图形 };<file_sep>/1/BillBoardEffect.cpp #include "BillBoardEffect.h" #include "DDSTextureLoader11.h" #include "ScreenGrab11.h" Billboard::Billboard(BasicEffect* be) { this->mFX = be->GetFX(); this->mGfx = be->GetGfx(); this->pContext = mGfx->GetDeviceContext(); this->pDevice = mGfx->GetDevice(); SetTopoLayout(); LoadFx(); } void Billboard::Draw() { Bind(); mTech = mTechBillboard; mTech->GetDesc(&techDesc); UINT allVertex = 4; //InitBillboard(allVertex); pContext->OMSetRenderTargets(1u, mGfx->GetpMainTarget(), mGfx->GetDepthStencilView()); // 渲染方式 pContext->RSSetState(mSOLID.Get()); static float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f }; pContext->OMSetBlendState(mBlendStateTransparency.Get(), blendFactors, 0xffffffff); /****************************更新坐标并绘制**************************/ XMMATRIX ViewProjM = XMLoadFloat4x4(&mGfx->GetMainCamera().ViewProj); XMMATRIX world = XMMatrixIdentity(); XMMATRIX worldViewProj = world * ViewProjM; mfxWorldInvTranspose->SetMatrix(reinterpret_cast<float*>(&PDEshape::InverseTranspose(world))); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); for (UINT p = 0; p < techDesc.Passes; ++p) { mTech->GetPassByIndex(p)->Apply(0, pContext.Get()); pContext->Draw(allVertex,0u); } /****************************更新坐标并绘制完**************************/ pContext->RSSetState(0); } void Billboard::LoadFx() { mTech = mTechBillboard = mFX->GetTechniqueByName("Billboard"); mfxBillBoardMap = mFX->GetVariableByName("gBillboardMap")->AsShaderResource(); mfxWorldInvTranspose = mFX->GetVariableByName("gWorldInvTranspose")->AsMatrix(); mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix(); UINT allVertex = 4; float w = 100.0f; float h = 100.0f; BillboardVertex vs[] = { { { 2000.0f,0.0f,0.0f },{ w,h } }, { { 0.0f,0.0f,0.0f },{ w,h } }, { { -500.0f,0.0f,500.0f },{ w,h } }, { { 1000.0f,0.0f,1000.0f },{ w,h } }, }; D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(BillboardVertex) * allVertex; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; vbd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &vs[0]; HR(pDevice->CreateBuffer(&vbd, &vinitData, &mVB)); mVBstride = sizeof(BillboardVertex); mVBoffset = 0u; ID3D11Resource* res; ID3D11ShaderResourceView* pSRV; //DDS_ALPHA_MODE alpha = DDS_ALPHA_MODE::DDS_ALPHA_MODE_STRAIGHT; HR(CreateDDSTextureFromFile(pDevice.Get(), L"misuhara.dds", &res, &pSRV, 0u)); HR(mfxBillBoardMap->SetResource(pSRV)); res->Release(); pSRV->Release(); } void Billboard::SetTopoLayout() { mTopoLayout = TopoLayout(TopoLayoutType::BillbordPS); } <file_sep>/1/h.h #pragma once #define NOMINMAX #include <windows.h> #include "atlbase.h" #include "atlstr.h" #include <directxmath.h> #include "d3dx11effect.h" #include <wrl/client.h> #include <vector> #include <d3dcompiler.h> #pragma comment(lib,"d3d11.lib") #pragma comment(lib,"Effects11d.lib") #pragma comment(lib,"D3DCompiler.lib") #define DEBUG HRESULT WINAPI DXTraceW(_In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox); #if defined(DEBUG) | defined(_DEBUG) #ifndef HR #define HR(x) \ { \ HRESULT hr = (x); \ if(FAILED(hr)) \ { \ DXTraceW(__FILEW__, (DWORD)__LINE__, hr, L#x, true); \ } \ } #endif #else #ifndef HR #define HR(x) (x) #endif #endif namespace Colors { using namespace DirectX; XMGLOBALCONST XMVECTORF32 White = { 1.0f, 1.0f, 1.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Black = { 0.0f, 0.0f, 0.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Red = { 1.0f, 0.0f, 0.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Green = { 0.0f, 1.0f, 0.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Blue = { 0.0f, 0.0f, 1.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Yellow = { 1.0f, 1.0f, 0.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Cyan = { 0.0f, 1.0f, 1.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Magenta = { 1.0f, 0.0f, 1.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Silver = { 0.75f, 0.75f, 0.75f, 1.0f }; XMGLOBALCONST XMVECTORF32 LightSteelBlue = { 0.69f, 0.77f, 0.87f, 1.0f }; } namespace Colors2 { using namespace DirectX; XMGLOBALCONST XMFLOAT4 White = { 1.0f, 1.0f, 1.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Black = { 0.0f, 0.0f, 0.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Red = { 1.0f, 0.0f, 0.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Green = { 0.0f, 1.0f, 0.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Blue = { 0.0f, 0.0f, 1.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Yellow = { 1.0f, 1.0f, 0.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Cyan = { 0.0f, 1.0f, 1.0f, 1.0f }; XMGLOBALCONST XMFLOAT4 Magenta = { 1.0f, 0.0f, 1.0f, 1.0f }; XMGLOBALCONST XMVECTORF32 Silver = { 0.75f, 0.75f, 0.75f, 1.0f }; XMGLOBALCONST XMVECTORF32 LightSteelBlue = { 0.69f, 0.77f, 0.87f, 1.0f }; } namespace Coordinate { using namespace DirectX; XMGLOBALCONST XMVECTORF32 X = { 1.0f, 0.0f, 0.0f, 0.0f }; XMGLOBALCONST XMVECTORF32 Y = { 0.0f, 1.0f, 0.0f, 0.0f }; XMGLOBALCONST XMVECTORF32 Z = { 0.0f, 0.0f, 1.0f, 0.0f }; }<file_sep>/1/FogEffect.h #pragma once #include "effect.h" #include "BasicEffect.h" class FogEffect :public PDEeffect { public: FogEffect(BasicEffect* be); // 通过 PDEeffect 继承 virtual void Draw() override; virtual void LoadFx() override; virtual void SetTopoLayout() override; void SetFog(float fogStart, float fogRange, XMFLOAT4 fogColor); private: //基础效果 BasicEffect* mBasicEffect; //雾 float mFogStart; float mFogRange; XMFLOAT4 mFogColor; bool mFogIsChange; // 雾效果 wrl::ComPtr<ID3DX11EffectScalarVariable> mfxFogStart; wrl::ComPtr<ID3DX11EffectScalarVariable> mfxFogRange; wrl::ComPtr<ID3DX11EffectVectorVariable> mfxFogColor; // 技术 wrl::ComPtr<ID3DX11EffectTechnique> mTechNoFog; };<file_sep>/1/TopoLayout.h #pragma once #include "h.h" #include <wrl/client.h> #include <d3d11.h> #include "d3dx11effect.h" namespace wrl = Microsoft::WRL; using namespace DirectX; enum TopoLayoutType { TrianglePNT,// 三角形 位置法线贴图 BillbordPS,// 告示板 位置(地面中心) 长宽 HillTessP, UnDefine }; class TopoLayout { public: TopoLayout():type(TopoLayoutType::UnDefine) {}; TopoLayout(TopoLayoutType type); ID3D11InputLayout* GetLayout(ID3D11Device* pDevice, ID3DX11EffectTechnique* tech); D3D_PRIMITIVE_TOPOLOGY& GetTopo() { return topo; }; TopoLayoutType GetType() { return type; } private: wrl::ComPtr<ID3D11InputLayout> mInputLayout; TopoLayoutType type; D3D_PRIMITIVE_TOPOLOGY topo; };<file_sep>/1/Shape.h #pragma once #include "h.h" #include "vertex.h" #include "light.h" //#include "BasicEffect.h" namespace wrl = Microsoft::WRL; class BasicEffect; class PDEeffect; enum class BlendType { None, Add, Subtract, Multiply, Transparency, }; class PDEshape { friend class Graphics; friend class GeometryGenerator; friend class BasicEffect; public: struct MeshData { std::vector<Vertex> Vertices; std::vector<UINT> Indices; }; public: PDEshape(MeshData& meshData); PDEshape(const PDEshape& sold) = default; PDEshape& operator=(const PDEshape& sold) = default; void Move(float x,float y,float z); void Scale(float x,float y,float z); void Rotate(XMVECTOR A,float angle); void SetShadow(bool HasShadow) { this->HasShadow = HasShadow; } void MoveTex(float u, float v); void ScaleTex(float x, float y); void RotateTex(XMVECTOR A, float angle); void ResetTex(); void SetMaterial(Material Mat) { this->Mat = Mat; } void SetBlendType(BlendType blendType) { this->blendType = blendType; } void SetMatOpaque(float opaque); void SetTexture(LPCTSTR file) { this->Texture = file; } void SetTextureView(ID3D11ShaderResourceView* pSRV) { this->ShaderResourceView = wrl::ComPtr<ID3D11ShaderResourceView>(pSRV); } PDEeffect* GetEffect() { return mEffect; } virtual void init(); static XMMATRIX InverseTranspose(CXMMATRIX M); protected: PDEshape() = default; // 点数据 MeshData meshData; wrl::ComPtr<ID3D11ShaderResourceView> ShaderResourceView; // 初始化为全反射,SpecPower=16 void initMat(); // 全局矩阵 XMFLOAT4X4 W; // 贴图转换矩阵 XMFLOAT4X4 TexW; // 材质 Material Mat; // 混合选项 BlendType blendType; // 贴图文件 LPCTSTR Texture = nullptr; // 是否有阴影 bool HasShadow = true; // 特殊效果 PDEeffect* mEffect; };<file_sep>/1/light.hlsli struct DirectionalLight { float4 Ambient; float4 Diffuse; float4 Specular; float3 Direction; float pad; }; struct PointLight { float4 Ambient; float4 Diffuse; float4 Specular; float3 Position; float Range; float3 Att; float pad; }; struct SpotLight { float4 Ambient; float4 Diffuse; float4 Specular; float3 Position; float Range; float3 Direction; float Spot; float3 Att; float pad; }; struct Material { float4 Ambient; float4 Diffuse; float4 Specular; // w = SpecPower float4 Reflect; }; // µÆ¹âÊýÁ¿ int num_DL; int num_PL; int num_SL; DirectionalLight DLs[10]; PointLight PLs[10]; SpotLight SLs[10]; void ComputeDirectionalLight(Material mat, DirectionalLight L, float3 normal, float3 toEye, out float4 ambient, out float4 diffuse, out float4 spec) { // Initialize outputs. ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); spec = float4(0.0f, 0.0f, 0.0f, 0.0f); // The light vector aims opposite the direction the light rays travel. float3 lightVec = -L.Direction; // Add ambient term. ambient = mat.Ambient * L.Ambient; // Add diffuse and specular term, provided the surface is in // the line of site of the light. float diffuseFactor = dot(lightVec, normal); // Flatten to avoid dynamic branching. [flatten] if (diffuseFactor > 0.0f) { float3 v = reflect(-lightVec, normal); float specFactor = pow(max(dot(v, toEye), 0.0f), mat.Specular.w); diffuse = diffuseFactor * mat.Diffuse * L.Diffuse; spec = specFactor * mat.Specular * L.Specular; } } void ComputePointLight(Material mat, PointLight L, float3 pos, float3 normal, float3 toEye, out float4 ambient, out float4 diffuse, out float4 spec) { // Initialize outputs. ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); spec = float4(0.0f, 0.0f, 0.0f, 0.0f); // The vector from the surface to the light. float3 lightVec = L.Position - pos; // The distance from surface to light. float d = length(lightVec); // Range test. if (d > L.Range) return; // Normalize the light vector. lightVec /= d; // Ambient term. ambient = mat.Ambient * L.Ambient; // Add diffuse and specular term, provided the surface is in // the line of site of the light. float diffuseFactor = dot(lightVec, normal); // Flatten to avoid dynamic branching. [flatten] if (diffuseFactor > 0.0f) { float3 v = reflect(-lightVec, normal); float specFactor = pow(max(dot(v, toEye), 0.0f), mat.Specular.w); diffuse = diffuseFactor * mat.Diffuse * L.Diffuse; spec = specFactor * mat.Specular * L.Specular; } //Attenuate float att = 1.0f / dot(L.Att, float3(1.0f, d, d * d)); diffuse *= att; spec *= att; } void ComputeSpotLight(Material mat, SpotLight L, float3 pos, float3 normal, float3 toEye, out float4 ambient, out float4 diffuse, out float4 spec) { // Initialize outputs. ambient = float4(0.0f, 0.0f, 0.0f, 0.0f); diffuse = float4(0.0f, 0.0f, 0.0f, 0.0f); spec = float4(0.0f, 0.0f, 0.0f, 0.0f); // The vector from the surface to the light. float3 lightVec = L.Position - pos; // The distance from surface to light. float d = length(lightVec); // Range test. if (d > L.Range) return; // Normalize the light vector. lightVec /= d; // Ambient term. ambient = mat.Ambient * L.Ambient; // Add diffuse and specular term, provided the surface is in // the line of site of the light. float diffuseFactor = dot(lightVec, normal); // Flatten to avoid dynamic branching. [flatten] if (diffuseFactor > 0.0f) { float3 v = reflect(-lightVec, normal); float specFactor = pow(max(dot(v, toEye), 0.0f), mat.Specular.w); diffuse = diffuseFactor * mat.Diffuse * L.Diffuse; spec = specFactor * mat.Specular * L.Specular; } // Scale by spotlight factor and attenuate. float spot = pow(max(dot(-lightVec, L.Direction), 0.0f), L.Spot); // Scale by spotlight factor and attenuate. float att = spot / dot(L.Att, float3(1.0f, d, d * d)); ambient *= spot; diffuse *= att; spec *= att; } float4x4 MatrixShadow(float4 P,float4 L) { L = -L; float3 n = P.xyz; float d = P.w; float nL = dot(n, L.xyz); return float4x4( nL+d*L.w-L.x*n.x, -L.x*n.x, -L.z*n.x, -L.w*n.x, -L.x*n.y, nL+d*L.w-L.y*n.y, -L.z*n.y, -L.w*n.y, -L.x*n.z, -L.y*n.z, nL+d*L.w-L.z*n.z, -L.w*n.z, -L.x*d, -L.y*d, -L.z*d, nL ); }<file_sep>/1/BlurTexFx.cpp #include "BlurTexFx.h" #include "ScreenGrab11.h" BlurTexFx::BlurTexFx(Graphics* gfx) :PDEeffect("BlurTex.cso",gfx), blurCount(1) { LoadFx(); } // 龙书p401 void BlurTexFx::BlurInPlace(ID3D11DeviceContext* dc, ID3D11ShaderResourceView* inputSRV, ID3D11UnorderedAccessView* inputUAV, int blurCount) { { // // Run the compute shader to blur the offscreen texture. // for (int i = 0; i < blurCount; ++i) { // HORIZONTAL blur pass. mHorzBlurTech->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { SetInputMap(inputSRV); SetOutputMap(mBlurredOutputTexUAV.Get()); mHorzBlurTech->GetPassByIndex(p)->Apply(0, dc); // How many groups do we need to dispatch to cover a // row of pixels, where each group covers 256 pixels // (the 256 is defined in the ComputeShader). UINT numGroupsX = (UINT)ceilf(mWidth / 256.0f); dc->Dispatch(numGroupsX, mHeight, 1); } // Unbind the input texture from the CS for good housekeeping. ID3D11ShaderResourceView* nullSRV[1] = { 0 }; dc->CSSetShaderResources(0, 1, nullSRV); // Unbind output from compute shader (we are going to use // this output as an input in the next pass), and a resource // cannot be both an output and input at the same time. ID3D11UnorderedAccessView* nullUAV[1] = { 0 }; dc->CSSetUnorderedAccessViews(0, 1, nullUAV, 0); // VERTICAL blur pass. mVertBlurTech->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { SetInputMap(mBlurredOutputTexSRV.Get()); SetOutputMap(inputUAV); mVertBlurTech->GetPassByIndex(p)->Apply(0, dc); // How many groups do we need to dispatch to cover a // column of pixels, where each group covers 256 pixels // (the 256 is defined in the ComputeShader). UINT numGroupsY = (UINT)ceilf(mHeight / 256.0f); dc->Dispatch(mWidth, numGroupsY, 1); } dc->CSSetShaderResources(0, 1, nullSRV); dc->CSSetUnorderedAccessViews(0, 1, nullUAV, 0); } // Disable compute shader. dc->CSSetShader(0, 0, 0); } } void BlurTexFx::SetInputMap(ID3D11ShaderResourceView* inputMap) { mfxInput->SetResource(inputMap); ID3D11Texture2D* res; D3D11_TEXTURE2D_DESC Desc; inputMap->GetResource((ID3D11Resource**)&res); res->GetDesc(&Desc); if (mHeight != Desc.Height || mWidth != Desc.Width || mFormat != Desc.Format) { mHeight = Desc.Height; mWidth = Desc.Width; mFormat = Desc.Format; //更新尺寸,更新资源视图 CreateCacheView(); } } void BlurTexFx::SetOutputMap(ID3D11UnorderedAccessView* OutputMap) { mfxOutput->SetUnorderedAccessView(OutputMap); } void BlurTexFx::LoadFx() { mfxInput = mFX->GetVariableByName("gInput")->AsShaderResource(); mfxOutput = mFX->GetVariableByName("gOutput")->AsUnorderedAccessView(); mHorzBlurTech = mFX->GetTechniqueByName("HorzBlur"); mVertBlurTech = mFX->GetTechniqueByName("VertBlur"); } void BlurTexFx::Draw() { } void BlurTexFx::SetTopoLayout() { } void BlurTexFx::CreateCacheView() { D3D11_TEXTURE2D_DESC blurredTexDesc; blurredTexDesc.Width = mWidth; blurredTexDesc.Height = mHeight; blurredTexDesc.MipLevels = 1; blurredTexDesc.ArraySize = 1; blurredTexDesc.Format = mFormat; blurredTexDesc.SampleDesc.Count = 1; blurredTexDesc.SampleDesc.Quality = 0; blurredTexDesc.Usage = D3D11_USAGE_DEFAULT; blurredTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; blurredTexDesc.CPUAccessFlags = 0; blurredTexDesc.MiscFlags = 0; ID3D11Texture2D* blurredTex = 0; HR(pDevice->CreateTexture2D(&blurredTexDesc, 0, &blurredTex)); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = mFormat; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; HR(pDevice->CreateShaderResourceView(blurredTex, &srvDesc, mBlurredOutputTexSRV.GetAddressOf())); D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc; uavDesc.Format = mFormat; uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = 0; HR(pDevice->CreateUnorderedAccessView(blurredTex, &uavDesc, mBlurredOutputTexUAV.GetAddressOf())); // Views save a reference to the texture so we can release our reference. blurredTex->Release(); } <file_sep>/1/blurTeX.hlsl #define N 256 float gWeights[11] = { 0.05f, 0.05f, 0.1f, 0.1f, 0.1f, 0.2f, 0.1f, 0.1f, 0.1f, 0.05f, 0.05f}; static const int gBlurRadius = 5; Texture2D gInput; RWTexture2D<float4> gOutput; // 边缘镜像的缓存数组[R ...3 2 1 | 0 1 2 3 4 ..N-3 N-2 N-1| N-2 N-3...N-R] groupshared float4 gShared[N + 2 * gBlurRadius]; [numthreads(N,1,1)] void HorzBlurCS(int3 dtID : SV_DispatchThreadID, int3 gtID : SV_GroupThreadID) { // 最左边界的取样,取镜像 if (gtID.x <= gBlurRadius) { if(dtID.x <= gBlurRadius) gShared[gBlurRadius - dtID.x] = gInput[int2(dtID.x,dtID.y)]; //gShared[gBlurRadius - dtID.x] = float4(0.0f, 0.0f, 0.0f, 0.0f); else gShared[gtID.x] = gInput[int2(dtID.x- gBlurRadius,dtID.y)]; //gShared[gtID.x] = float4(0.0f, 0.0f, 0.0f, 0.0f); } // 最右边界的取样,同上 if (gtID.x >= N-1-gBlurRadius) { if (dtID.x >= int(gInput.Length.x) - 1 -gBlurRadius) gShared[2*(N-1) + gBlurRadius - dtID.x] = gInput[int2(dtID.x, dtID.y)]; else gShared[gtID.x+2*gBlurRadius] = gInput[int2(dtID.x + gBlurRadius, dtID.y)]; //gShared[gtID.x+2*gBlurRadius] = float4(0.0f, 0.0f, 0.0f, 0.0f); } // 中间缓冲区采样 gShared[gtID.x + gBlurRadius] = gInput[min(dtID.xy, gInput.Length.xy - 1)]; // 等待同步 GroupMemoryBarrierWithGroupSync(); float4 blurColor = float4(0.0f, 0.0f, 0.0f, 0.0f); [unroll] for (int i = -gBlurRadius; i <= gBlurRadius; ++i) { blurColor += gShared[gtID.x+gBlurRadius + i]* gWeights[gBlurRadius + i]; } gOutput[int2(dtID.x, dtID.y)] = blurColor; } [numthreads(1, N, 1)] void VertBlurCS(int3 dtID : SV_DispatchThreadID, int3 gtID : SV_GroupThreadID) { // 最上边界的取样,取镜像 if (gtID.y <= gBlurRadius) { if (dtID.y <= gBlurRadius) gShared[gBlurRadius - dtID.y] = gInput[int2(dtID.x, dtID.y)]; else gShared[gtID.y] = gInput[int2(dtID.x, dtID.y - gBlurRadius)]; } // 最下边界的取样,同上 if (gtID.y >= N -1 - gBlurRadius) { if (dtID.y >= int(gInput.Length.y) - 1 - gBlurRadius) gShared[2 * (N - 1) + gBlurRadius - dtID.y] = gInput[int2(dtID.x, dtID.y)]; else gShared[gtID.y + 2 * gBlurRadius] = gInput[int2(dtID.x, dtID.y + gBlurRadius)]; } // 中间缓冲区采样 gShared[gtID.y + gBlurRadius] = gInput[min(dtID.xy, gInput.Length.xy - 1)]; // 等待同步 GroupMemoryBarrierWithGroupSync(); float4 blurColor = float4(0, 0, 0, 0); [unroll] for (int i = -gBlurRadius; i <= gBlurRadius; ++i) { blurColor += gShared[gtID.y + gBlurRadius + i] * gWeights[gBlurRadius + i]; } gOutput[int2(dtID.x, dtID.y)] = blurColor; } technique11 HorzBlur { pass P0 { SetVertexShader(NULL); SetPixelShader(NULL); SetComputeShader(CompileShader(cs_5_0, HorzBlurCS())); } } technique11 VertBlur { pass P0 { SetVertexShader(NULL); SetPixelShader(NULL); SetComputeShader(CompileShader(cs_5_0, VertBlurCS())); } }<file_sep>/1/App.cpp #include "App.h" #include "GeometryGenerator.h" #include "vertex.h" #include "shape.h" #include "ReflectivePlane.h" #include "Camera.h" #include "light.h" #include <sstream> #include <iomanip> #include <algorithm> #include "BasicEffect.h" #include "FogEffect.h" #include "BillBoardEffect.h" #include "BlurTexFx.h" #include "WaveFX.h" #include "hillTess.h" App::App() : wnd(800,600,"App?!") {} int App::Go() { // 基础效果 BasicEffect* pbe = BasicEffect::get_instance(&wnd.Gfx()); // 雾效果 FogEffect Fog(pbe); Billboard billBoard(pbe); HillTess hillTess(&wnd.Gfx()); wnd.Gfx().AddEffect(pbe); //wnd.Gfx().AddEffect(&hillTess); wnd.Gfx().AddEffect(&Fog); //wnd.Gfx().AddEffect(&billBoard); WaveFX Wave(pbe); Wave.Init(200.0f, 200.0f,5.0f,5.0f,10.0f,10.0f); wnd.Gfx().AddEffect(&Wave); Fog.SetFog(0.0f, 1000.0f, XMFLOAT4(1.0f, 1.0f, 1.0f, 0.1f)); ReflectivePlane mirror1( XMFLOAT3(0.0f, 100.0f, 100.0f), XMFLOAT3(0.0f, 0.0f, -1.0f), 2000.0f, 200.0f ); using MeshData = PDEshape::MeshData; GeometryGenerator geo; PDEshape::MeshData md; geo.CreateGrid(300.0f,300.0f,1000,1000, md); PDEshape grid(md); grid.Scale(5, 0, 5); grid.SetShadow(false); geo.CreateGeosphere(20.0f, 5, md); PDEshape sphere(md); sphere.SetBlendType(BlendType::Transparency); sphere.Move(20.0f, 20.0f, 00.0f); sphere.Scale(6.0f, 4.50f, 9.0f); sphere.SetShadow(false); PDEshape sphere2(sphere); sphere2.Scale(2.0f, .50f, 3.0f); sphere2.Move(100.0f, 0.0f, 0.0f); geo.CreateCylinder(20.0f, 10.0f, 20.0f, 50, 0, md); PDEshape cylinder(md); geo.CreateBox(50.0f, 50.0f, 50.0f, md); PDEshape box(md); box.Scale(2, 2, 2); box.Move(0.0f, 50.0f, 0.0f); box.SetTexture("misuhara.dds"); box.SetBlendType(BlendType::Transparency); PDEshape box2 = box; //box.ScaleTex(0.05f, 1.0/6.0f); //box2.SetTexture("WoodCrate01.dds"); box2.SetTexture("WoodCrate02.dds"); box2.SetMatOpaque(0.5f); //box2.SetBlendType(BlendType::Transparency); PDEshape box3 = box2; box2.Move(-10.0f, 0.0f, 50.0f); box2.Scale(2.0f, 2.0f, 2.0f); box3.Move(-200.0f, 0.0f, -100.0f); box3.SetTexture("misuhara.dds"); Material wavesMat; //mWavesMat.Ambient = XMFLOAT4(0.137f, 0.42f, 0.556f, 1.0f); wavesMat.Ambient = XMFLOAT4(0.99f, 0.99f, 0.99f, 1.0f); wavesMat.Diffuse = XMFLOAT4(0.137f, 0.42f, 0.556f, 1.0f); wavesMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 96.0f); wavesMat.Reflect = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f); Material ballMat; //mWavesMat.Ambient = XMFLOAT4(0.137f, 0.42f, 0.556f, 1.0f); ballMat.Ambient = XMFLOAT4(0.0f, 0.99f, 0.99f, 1.0f); ballMat.Diffuse = XMFLOAT4(0.5f, 0.8f, 0.556f, 0.8f); ballMat.Specular = XMFLOAT4(0.8f, 0.8f, 0.8f, 96.0f); ballMat.Reflect = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f); grid.SetMaterial(wavesMat); sphere.SetMaterial(ballMat); sphere2.SetMaterial(ballMat); cylinder.SetMaterial(ballMat); std::vector<PDEshape*> shapes = {}; shapes.push_back(&box2); //shapes.push_back(&sphere); //shapes.push_back(&mirror1); pbe->AddShapes(shapes); Light DirLight(LightType::DirectionalLight); DirLight.Ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); DirLight.Diffuse = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); DirLight.Specular = XMFLOAT4(0.2f, 0.8f, 0.4f, 1.0f); DirLight.Direction = XMFLOAT3(0.57735f, -0.57735f, 0.57735f); pbe->AddLight(DirLight); Light DirLight2(LightType::DirectionalLight); DirLight2.Ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); DirLight2.Diffuse = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); DirLight2.Specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); DirLight2.Direction = XMFLOAT3(-0.57735f, 0.57735f, 0.57735f); pbe->AddLight(DirLight2); //be.AddLight(DirLight); Light SpotLight(LightType::SpotLight); SpotLight.Ambient = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f); SpotLight.Diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); SpotLight.Specular = XMFLOAT4(0.1f, 0.1f, 0.1f, 1.0f); SpotLight.Att = XMFLOAT3(0.0f, 0.003f, 0.0f); SpotLight.Spot = 30.0f; SpotLight.Range = 100000.0f; SpotLight.Position =XMFLOAT3(0.0f, 100.0f, 0.0f); SpotLight.Direction =XMFLOAT3(0.57735f, -0.57735f, 0.57735f); Light SpotLight2 = SpotLight; SpotLight2.Spot = 1.0f; SpotLight2.Range = 100000.0f; SpotLight2.Position = XMFLOAT3(200.0f, 500.0f, 0.0f); XMFLOAT3 to = XMFLOAT3(0.0f, 00.0f, 0.0f); //SpotLight2.Direction = XMFLOAT3(-0.57735f, -0.57735f, 0.57735f); XMStoreFloat3(&SpotLight2.Direction, XMVector3Normalize(XMLoadFloat3(&to) - XMLoadFloat3(&SpotLight2.Position))); //be.AddLight(SpotLight); pbe->AddLight(SpotLight2); // 设置主摄像机 XMVECTOR pos = XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f); XMVECTOR dir = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); wnd.Gfx().GetMainCamera().SetCamera(pos,dir); // 给背景刷上天依色 wnd.Gfx().SetBackgroundColor(XMFLOAT4(102 / 255.0f, 204 / 255.0f, 1.0f,1.0f)); while (true) { if (const auto ecode = Window::ProcessMessages()) { return *ecode; } else { DoFrame(); //Sleep(10); } } } void App::DoFrame() { static int x = 0; static int y = 0; static int tex_num = 0; static float speed = 10.0f; static Camera *pCamera = &wnd.Gfx().GetMainCamera(); static Mouse *pMouse = &wnd.mouse; static Keyboard *pKbd = &wnd.kbd; static Graphics *pGfx = &wnd.Gfx(); const float t = timer.Mark(); //static float mTheta = 1.5f * XM_PI; //static float mPhi = 0.25f * XM_PI; //static float mRadius = 100.0f; // 计时标题 std::ostringstream oss; oss << std::setprecision(5)<< std::fixed<< t*1000 << "(ms) fps:" << std::setprecision(0) << std::fixed << 1.0f/t; oss << " "<< "position" << "(" << std::setprecision(3) << std::fixed << pCamera->GetPosition().m128_f32[0] << "," << pCamera->GetPosition().m128_f32[1] << "," << pCamera->GetPosition().m128_f32[2] << ")"; oss << " "<< "direction" << "(" << pCamera->GetDirection().m128_f32[0] << "," << pCamera->GetDirection().m128_f32[1] << "," << pCamera->GetDirection().m128_f32[2] << ")"; wnd.SetTitle(oss.str().c_str()); //wnd.Gfx().ClearBuffer(); //#66ccff const float c = sin(timer.Peek()*3) / 2.0f + 0.5f; // 相机方向局部x坐标 XMVECTOR cameraLx = XMVector3Cross(Coordinate::Y, pCamera->GetDirection()); // 处理鼠标 const auto mouseEvent = wnd.mouse.Read(); using mouseType = Mouse::Event::Type; if ((mouseType)mouseEvent.GetType() == mouseType::Move) { float dx = 0.005f * static_cast<float>(x - pMouse->GetPosX()); float dy = 0.005f * static_cast<float>(y - pMouse->GetPosY()); x = pMouse->GetPosX(); y = pMouse->GetPosY(); if (pMouse->LeftIsPressed()) { // 更新鼠标位置和偏移 //更新摄像机 pCamera->RotateCamera(cameraLx, -dy); pCamera->RotateCamera(Coordinate::Y, -dx); pGfx->UpdateCamera(); } } // 处理键盘 XMVECTOR cameraOffset = XMVectorZero(); if (pMouse->LeftIsPressed()) { if (pKbd->KeyIsPressed('W') && !pKbd->KeyIsPressed('S')) { cameraOffset += pCamera->GetDirection() * speed; } else if (pKbd->KeyIsPressed('S') && !pKbd->KeyIsPressed('W')) { cameraOffset -= pCamera->GetDirection() * speed; } if (pKbd->KeyIsPressed('D') && !pKbd->KeyIsPressed('A')) { cameraOffset += cameraLx * speed; } else if (pKbd->KeyIsPressed('A') && !pKbd->KeyIsPressed('D')) { cameraOffset -= cameraLx * speed; } if (pKbd->KeyIsPressed('Q')) { cameraOffset -= Coordinate::Y * speed; } if (pKbd->KeyIsPressed('E')) { cameraOffset += Coordinate::Y * speed; } if (XMVector3NotEqual(cameraOffset, XMVectorZero())) { pCamera->MoveCamera(cameraOffset); pGfx->UpdateCamera(); } } //wnd.Gfx().DrawBox(); //wnd.Gfx().DrawCylinder(); pGfx->DrawFrame(); //wnd.Gfx().DrawHills(); //wnd.Gfx().ClearBuf03fer(c, c, 1.0f); //++tex_num; //static float du = 0.05f; //static float dv = 1.0f/6.0f; /*火焰*/ //wnd.Gfx().Shapes()[3].MoveTex(du, 0.0f); //if (tex_num % 20 == 0) { // wnd.Gfx().Shapes()[3].MoveTex(0.0f, 1.0f*dv); //} //if (tex_num % 120 == 0) { // wnd.Gfx().Shapes()[3].ResetTex(); // wnd.Gfx().Shapes()[3].ScaleTex(0.05f, 1.0 / 6.0f); //} /*火焰完*/ pGfx->EndFrame(); } <file_sep>/1/ReflectivePlane.h #pragma once #include "Shape.h" #include "Camera.h" class ReflectivePlane :public PDEshape { friend class Graphics; friend class BasicEffect; friend class GeometryGenerator; public: ReflectivePlane(XMFLOAT3 Position, XMFLOAT3 Direction,float width, float depth); void SetReflectView(ID3D11RenderTargetView* RTview, ID3D11ShaderResourceView* SRview); void SetCamera(const XMVECTOR& pos, const XMVECTOR& target); protected: virtual void init(); private: Camera cameraReflect; XMMATRIX refWVP; XMFLOAT3 Position; XMFLOAT3 Direction; wrl::ComPtr<ID3D11RenderTargetView> RenderTargetView; };<file_sep>/1/window.cpp #include "window.h" Window::WindowClass Window::WindowClass::wndClass; int Window::wins = 0; Window::WindowClass::WindowClass() noexcept(RegisterClassEx) : // If this parameter is NULL, GetModuleHandle returns a handle // to the file used to create the calling process (.exe file). hInst(GetModuleHandle(nullptr)) { WNDCLASSEXA wc = { 0 }; wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = HandleMsgSetup; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = GetInstance(); wc.hIcon = nullptr; wc.hCursor = nullptr; wc.hbrBackground = nullptr; wc.lpszMenuName = nullptr; wc.lpszClassName = GetName(); wc.hIconSm = nullptr; RegisterClassExA(&wc); } Window::WindowClass::~WindowClass() { UnregisterClassA(GetName(), GetInstance()); } const char* Window::WindowClass::GetName() noexcept { return wndClassName; } HINSTANCE Window::WindowClass::GetInstance() noexcept { return wndClass.hInst; } #include<iostream> Window::Window(int width, int height, const char* name) noexcept : width(width), height(height) { RECT wr; wr.left = 100; wr.right = wr.left + width; wr.top = 100; wr.bottom = wr.top + height; AdjustWindowRect(&wr, WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU, FALSE); hWnd = CreateWindowA( WindowClass::GetName(), name, WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, nullptr, nullptr, WindowClass::GetInstance(), this ); ShowWindow(hWnd, SW_SHOWDEFAULT); pGfx = std::make_unique<Graphics>(hWnd, UINT(width), UINT(height),true); pGfx -> SetAspectRatio(float(width) / float(height)); } Window::~Window() { DestroyWindow(hWnd); } void Window::SetTitle(const char* title) { if(hWnd) SetWindowTextA(hWnd, title); } std::optional<int> Window::ProcessMessages() { MSG msg; while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { return msg.wParam; } TranslateMessage(&msg); DispatchMessage(&msg); } return {}; } Graphics& Window::Gfx() { return *pGfx; } LRESULT WINAPI Window::HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_NCCREATE) { wins += 1; const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*>(lParam); Window* const pWnd = static_cast<Window*> (pCreate->lpCreateParams); SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd)); SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&Window::HandleMsgThunk)); return pWnd->HandleMsg(hWnd, msg, wParam, lParam); } return DefWindowProc(hWnd, msg, wParam, lParam); } LRESULT WINAPI Window::HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { Window* const pWnd = reinterpret_cast<Window*> (GetWindowLongPtr(hWnd, GWLP_USERDATA)); return pWnd->HandleMsg(hWnd, msg, wParam, lParam); } LRESULT Window::HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept { static POINTS pt; switch (msg) { case WM_CLOSE: wins -= 1; if(wins <= 0) PostQuitMessage(0); break; case WM_KILLFOCUS: kbd.ClearState(); break; case WM_SYSKEYDOWN: case WM_KEYDOWN: // 只有第一次按下时0x40000000为1,其余为0,记录键盘按下 if (!(lParam & 0x40000000) || kbd.AutorepeatIsEnable()) { kbd.OnKeyPressed(static_cast<unsigned char>(wParam)); } break; case WM_SYSKEYUP: case WM_KEYUP: kbd.OnKeyReleased(static_cast<unsigned char>(wParam)); break; case WM_CHAR: kbd.OnChar(static_cast<char>(wParam)); break; case WM_MOUSEMOVE: pt = MAKEPOINTS(lParam); if (pt.x >= 0 && pt.x < width && pt.y >= 0 && pt.y < height) { mouse.OnMouseMove(pt.x, pt.y); if (!mouse.IsInWindow()) { SetCapture(hWnd); mouse.OnMouseEnter(); } } else { if (wParam & (MK_LBUTTON | MK_RBUTTON)) { mouse.OnMouseMove(pt.x, pt.y); } else { ReleaseCapture(); mouse.OnMouseLeave(); } } break; case WM_LBUTTONDOWN: pt = MAKEPOINTS(lParam); mouse.OnLeftPressed(pt.x, pt.y); break; case WM_RBUTTONDOWN: pt = MAKEPOINTS(lParam); mouse.OnRightPressed(pt.x, pt.y); break; case WM_LBUTTONUP: pt = MAKEPOINTS(lParam); mouse.OnLeftReleased(pt.x, pt.y); break; case WM_RBUTTONUP: pt = MAKEPOINTS(lParam); mouse.OnRightReleased(pt.x, pt.y); break; case WM_MOUSEWHEEL: pt = MAKEPOINTS(lParam); const int delta= GET_WHEEL_DELTA_WPARAM(wParam); mouse.OnWheelDelta(pt.x, pt.y, delta); break; } return DefWindowProc(hWnd, msg, wParam, lParam); }<file_sep>/1/BlurTexFx.h #pragma once #include "BasicEffect.h" class BlurTexFx : public PDEeffect { public: BlurTexFx(Graphics* mGfx); void SetBlurCount(const UINT count) { this->blurCount = count; } void BlurInPlace(ID3D11DeviceContext* dc, ID3D11ShaderResourceView* inputSRV, ID3D11UnorderedAccessView* inputUAV, int blurCount); void SetInputMap(ID3D11ShaderResourceView* inputMap); void SetOutputMap(ID3D11UnorderedAccessView* OutputMap); private: // 通过 PDEeffect 继承 virtual void Draw() override; virtual void LoadFx() override; virtual void SetTopoLayout() override; void CreateCacheView(); // 技术 wrl::ComPtr<ID3DX11EffectTechnique> mHorzBlurTech; wrl::ComPtr<ID3DX11EffectTechnique> mVertBlurTech; // 纹理 wrl::ComPtr<ID3DX11EffectShaderResourceVariable> mfxInput; wrl::ComPtr<ID3DX11EffectUnorderedAccessViewVariable> mfxOutput; // UINT blurCount; UINT mWidth; UINT mHeight; DXGI_FORMAT mFormat; wrl::ComPtr<ID3D11ShaderResourceView> mBlurredOutputTexSRV; wrl::ComPtr<ID3D11UnorderedAccessView> mBlurredOutputTexUAV; }; <file_sep>/1/addCS.hlsl #include "light.hlsli" Texture2D gInputA; Texture2D gInputB; RWTexture2D<float4> gOutput; [numthreads(16, 16, 1)] void addCS( uint3 dispatchThreadID : SV_DispatchThreadID ) { gOutput[dispatchThreadID.xy] = gInputA[dispatchThreadID.xy] + gInputB[dispatchThreadID.xy]; } technique11 add { pass P0 { SetVertexShader(NULL); SetGeometryShader(NULL); SetComputeShader(CompileShader(cs_5_0, addCS())); } } <file_sep>/1/BasicEffect.cpp #include "BasicEffect.h" #include "DDSTextureLoader11.h" #include <algorithm> BasicEffect* BasicEffect::this_ptr = nullptr; BasicEffect::BasicEffect(Graphics* gfx) : num_DL(0), num_PL(0), num_SL(0), lightIsChange(false), mIsLoadShapes(false), PDEeffect("basic.cso",gfx) { LoadFx(); SetTopoLayout(); } void BasicEffect::init() { } void BasicEffect::LoadFx() { mTechTexture = mFX->GetTechniqueByName("Texture"); mTech = mTechNoTexture = mFX->GetTechniqueByName("NOTexture"); mTechReflect = mFX->GetTechniqueByName("Reflect"); mTechReflectNoMSAA = mFX->GetTechniqueByName("ReflectNoMSAA"); mTechShadow = mFX->GetTechniqueByName("Shadow"); mfxWorldViewProj = mFX->GetVariableByName("gWorldViewProj")->AsMatrix(); mfxViewProj = mFX->GetVariableByName("gViewProj")->AsMatrix(); mfxReflectWorldViewProj = mFX->GetVariableByName("gReflectWorldViewProj")->AsMatrix(); mfxTime = mFX->GetVariableByName("time")->AsScalar(); mfxWorld = mFX->GetVariableByName("gWorld")->AsMatrix(); mfxWorldInvTranspose = mFX->GetVariableByName("gWorldInvTranspose")->AsMatrix(); mfxEyePosW = mFX->GetVariableByName("gEyePosW")->AsVector(); mfxMaterial = mFX->GetVariableByName("gMaterial"); mfxDiffuseMap = mFX->GetVariableByName("gDiffuseMap")->AsShaderResource(); mfxReflectMap = mFX->GetVariableByName("gReflectMap")->AsShaderResource(); mfxTexTransform = mFX->GetVariableByName("gTexTransform")->AsMatrix(); mfxShadowL = mFX->GetVariableByName("gShadowL")->AsVector(); mfxDirLights = mFX->GetVariableByName("DLs"); mfxPointLights = mFX->GetVariableByName("PLs"); mfxSpotLights = mFX->GetVariableByName("SLs"); mfxNum_DL = mFX->GetVariableByName("num_DL")->AsScalar(); mfxNum_PL = mFX->GetVariableByName("num_PL")->AsScalar(); mfxNum_SL = mFX->GetVariableByName("num_SL")->AsScalar(); } void BasicEffect::SetTopoLayout() { /****************************定义拓扑、布局**************************/ //mTech = mTechBillboard; mTopoLayout = TopoLayout(TopoLayoutType::TrianglePNT); /****************************定义拓扑、布局完**************************/ } void BasicEffect::Draw() { // 更新图形 if (!mIsLoadShapes) { LoadShapes(); } // 绑定设定到管线 Bind(); // 更新资源 //mTech->GetDesc(&techDesc); float now = mGfx->GetRanderTime()*1000.0f; mfxTime->SetFloat(now); if (lightIsChange) { if (num_DL > 0) mfxDirLights->SetRawValue(&mDirLights[0], 0, sizeof(mDirLights[0]) * num_DL); if (num_PL > 0) mfxPointLights->SetRawValue(&mPointLights[0], 0, sizeof(mPointLights[0]) * num_PL); if (num_SL > 0) mfxSpotLights->SetRawValue(&mSpotLights[0], 0, sizeof(mSpotLights[0]) * num_SL); mfxNum_DL->SetInt(num_DL); mfxNum_PL->SetInt(num_PL); mfxNum_SL->SetInt(num_SL); lightIsChange = false; } //if (mFogIsChange) { // mfxFogStart->SetFloat(mFogStart); // mfxFogRange->SetFloat(mFogRange); // mfxFogColor->SetRawValue(&mFogColor, 0, sizeof(mFogColor)); // mFogIsChange = false; //} mfxEyePosW->SetRawValue(&mGfx->GetMainCamera().GetPosition(), 0, sizeof(XMFLOAT3)); for (UINT i = 0; i < mirrors.size(); ++i) { XMVECTOR refPos = XMVector3Reflect(mGfx->GetMainCamera().GetPosition(), XMLoadFloat3(&mirrors[i]->Direction)); XMVECTOR refDir = XMVector3Reflect(mGfx->GetMainCamera().GetDirection(), XMLoadFloat3(&mirrors[i]->Direction)); mirrors[i]->SetCamera(refPos, refPos + refDir); // 将物体绘制到镜子上 DrawShapes(mirrors[i]->RenderTargetView.Get(), mirrors[i]->cameraReflect); // /*ID3D11Resource* TexBuffer; mirrors[i]->RenderTargetView->GetResource(&TexBuffer);*/ //mirrors[i]->ShaderResourceView.Get()->GetResource(&TexBuffer); mGfx->ClearBuffer(*mGfx->GetpMainTarget()); //SaveDDSTextureToFile(pContext.Get(), TexBuffer, L"some.dds"); //TexBuffer->Release(); } //pContext->RSSetViewports(1, &mGfx->GetMainViewPort()); //mGfx->GetDeviceContext()->OMSetRenderTargets(1u, mGfx->GetpMainTarget(), mGfx->GetDepthStencilView()); DrawMirrors(*mGfx->GetpMainTarget(), mGfx->GetMainCamera()); DrawShapes(*mGfx->GetpMainTarget(), mGfx->GetMainCamera()); //drawBillboard(); for (auto m : mirrors) mGfx->ClearBuffer(m->RenderTargetView.Get()); } #include <DirectXTexP.h> #include <DirectXTex.h> #include "BlurTexFx.h" #include "ScreenGrab11.h" void BasicEffect::LoadShapes() { // 保存图形 //this->pShapes.insert(pShapes.end(), Shapes.begin(), Shapes.end()); if (pShapes.size() < 1u) return; /***************计算顶点、索引间隔***********************/ UINT shapesCounts = pShapes.size(); mIndexCounts = std::vector<UINT>(shapesCounts); mVertexCounts = std::vector<UINT>(shapesCounts); mIndexCounts[0] = mVertexCounts[0] = 0; UINT allIndex = 0u; UINT allVertex = 0u; for (UINT i = 0; i < shapesCounts - 1; ++i) { mIndexCounts[i + 1u] = pShapes[i]->meshData.Indices.size() + mIndexCounts[i]; mVertexCounts[i + 1u] = pShapes[i]->meshData.Vertices.size() + mVertexCounts[i]; allIndex += pShapes[i]->meshData.Indices.size(); allVertex += pShapes[i]->meshData.Vertices.size(); } allIndex += pShapes[shapesCounts - 1u]->meshData.Indices.size(); allVertex += pShapes[shapesCounts - 1u]->meshData.Vertices.size(); /***************计算顶点、索引间隔完***********************/ /***************填充顶点、索引数组、创建纹理视图***********************/ std::vector<ReflectivePlane*> mirrors; mVertices = std::vector<Vertex>(); mIndexes = std::vector<UINT>(); mHasTex = std::vector<bool>(shapesCounts); for (UINT i = 0; i < shapesCounts; ++i) { for (UINT j = 0; j < pShapes[i]->meshData.Indices.size(); ++j) mIndexes.push_back(pShapes[i]->meshData.Indices[j]); for (UINT j = 0; j < pShapes[i]->meshData.Vertices.size(); ++j) { Vertex v; XMFLOAT3 p = pShapes[i]->meshData.Vertices[j].Position; v.Pos = p; v.Normal = pShapes[i]->meshData.Vertices[j].Normal; v.Tex = pShapes[i]->meshData.Vertices[j].TexC; mVertices.push_back(v); } // 加载纹理到视图 if (pShapes[i]->Texture) { ID3D11Resource* res; ID3D11ShaderResourceView* pSRV; //DDS_ALPHA_MODE alpha = DDS_ALPHA_MODE::DDS_ALPHA_MODE_STRAIGHT; HR(CreateDDSTextureFromFileEx(pDevice.Get(),pContext.Get(), CA2W(pShapes[i]->Texture),0u, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, true, &res, &pSRV, 0u)); pShapes[i]->SetTextureView(pSRV); mHasTex[i] = true; res->Release(); pSRV->Release(); /*blurredTex->Release(); mBlurredOutputTexUAV->Release(); mBlurredOutputTexSRV->Release();*/ } // 如果有镜子要提出来 ReflectivePlane* mirror = nullptr; mirror = dynamic_cast<ReflectivePlane*>(pShapes[i]); if (mirror != nullptr) { mirrors.push_back(mirror); mHasTex[i] = true; } } // 加载镜子 LoadMirrors(mirrors); /***************填充顶点、索引数组完***********************/ /***************定义顶点、索引、相应缓冲并绑定***********************/ // 创建不变顶点缓冲 D3D11_BUFFER_DESC vbd; vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(Vertex) * allVertex; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; vbd.MiscFlags = 0; vbd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA vinitData; vinitData.pSysMem = &mVertices[0]; HR(pDevice->CreateBuffer(&vbd, &vinitData, &mVB)); // Create the index buffer D3D11_BUFFER_DESC ibd; ibd.Usage = D3D11_USAGE_IMMUTABLE; ibd.ByteWidth = sizeof(UINT) * allIndex; ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; ibd.MiscFlags = 0; ibd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA iinitData; iinitData.pSysMem = &mIndexes[0]; HR(pDevice->CreateBuffer(&ibd, &iinitData, &mIB)); mVBstride = sizeof(Vertex); mVBoffset = 0; /***************定义顶点、索引、相应缓冲并绑定完***********************/ mIsLoadShapes = true; } void BasicEffect::AddShape(PDEshape* pShape) { this->pShapes.push_back(pShape); mIsLoadShapes = false; } void BasicEffect::AddShapes(std::vector<PDEshape*> shapes) { if (shapes.size() > 0) this->pShapes.insert(this->pShapes.end(), shapes.begin(), shapes.end()); else return; mIsLoadShapes = false; } inline void BasicEffect::LoadMirrors(const std::vector<ReflectivePlane*>& Mirrors) { if (!Mirrors.size()) return; this->mirrors = Mirrors; D3D11_TEXTURE2D_DESC mirrorsDesc; mirrorsDesc.Width = mGfx->GetWinWidth(); mirrorsDesc.Height = mGfx->GetWinHeight(); mirrorsDesc.MipLevels = 1; mirrorsDesc.ArraySize = 1; mirrorsDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc; // Use 4X MSAA? if (mGfx->IsUse4xMsaa()) { mirrorsDesc.SampleDesc.Count = 4; // m4xMsaaQuality is returned via CheckMultisampleQualityLevels(). mirrorsDesc.SampleDesc.Quality = mGfx->Get4xMsaaQuality() - 1; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS; } //No MSAA else { mirrorsDesc.SampleDesc.Count = 1; mirrorsDesc.SampleDesc.Quality = 0; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; shaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; } mirrorsDesc.Usage = D3D11_USAGE_DEFAULT; mirrorsDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; mirrorsDesc.CPUAccessFlags = 0; mirrorsDesc.MiscFlags = 0; renderTargetViewDesc.Format = mirrorsDesc.Format; renderTargetViewDesc.Texture2D.MipSlice = 0; shaderResourceViewDesc.Format = mirrorsDesc.Format; shaderResourceViewDesc.Texture2D.MostDetailedMip = 0; shaderResourceViewDesc.Texture2D.MipLevels = 1; for (UINT i = 0; i < mirrors.size(); ++i) { wrl::ComPtr<ID3D11Texture2D> mirrorBuffer; wrl::ComPtr<ID3D11RenderTargetView> mirrorRTView; wrl::ComPtr<ID3D11ShaderResourceView> mirrorSRView; pDevice->CreateTexture2D(&mirrorsDesc, nullptr, mirrorBuffer.GetAddressOf()); HR(pDevice->CreateRenderTargetView( mirrorBuffer.Get(), &renderTargetViewDesc, &mirrorRTView )); HR(pDevice->CreateShaderResourceView( mirrorBuffer.Get(), &shaderResourceViewDesc, &mirrorSRView )); mirrors[i]->SetReflectView(mirrorRTView.Get(), mirrorSRView.Get()); } } bool BasicEffect::AddLight(Light light) { lightIsChange = true; if (light.getType() == LightType::DirectionalLight && mDirLights.size() <= num_DL) { mDirLights.push_back(*static_cast<DirectionalLight*>(light.getLight())); num_DL += 1; return true; } else if (light.getType() == LightType::PointLight && mPointLights.size() <= num_PL) { mPointLights.push_back(*static_cast<PointLight*>(light.getLight())); num_PL += 1; return true; } else if (light.getType() == LightType::SpotLight && mSpotLights.size() <= num_SL) { mSpotLights.push_back(*static_cast<SpotLight*>(light.getLight())); num_SL += 1; return true; } return false; } void BasicEffect::DrawShapes(ID3D11RenderTargetView* renderTarget, Camera& camera) { pContext->OMSetRenderTargets(1u, &renderTarget, mGfx->GetDepthStencilView()); // 渲染方式 pContext->RSSetState(mSOLID.Get()); //pContext->RSSetState(mWIREFRAME.Get()); // 计算渲染顺序 std::vector<UINT> drawOrder = SortShapes(camera); // 摄像机的VP矩阵 XMMATRIX ViewProjM = XMLoadFloat4x4(&camera.ViewProj); mfxViewProj->SetMatrix(reinterpret_cast<float*>(&ViewProjM)); /*********************绘制阴影************************************************************/ XMMATRIX shadowOffsetY = XMMatrixTranslation(0.0f, 0.01f, 0.0f); for (UINT& i : drawOrder) { if (!pShapes[i]->HasShadow) continue; /****************************更新坐标并绘制**************************/ XMMATRIX ViewProjM = XMLoadFloat4x4(&camera.ViewProj); HR(mfxMaterial->SetRawValue(&pShapes[i]->Mat, 0, sizeof(pShapes[i]->Mat))); for (DirectionalLight l : mDirLights) { XMVECTOR L = XMVectorSet(l.Direction.x, l.Direction.y, l.Direction.z, 0.0f); mfxShadowL->SetFloatVector(reinterpret_cast<float*>(&L)); XMVECTOR shadowPlane = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); // xz plane XMMATRIX S = XMMatrixShadow(shadowPlane, -L); XMMATRIX world = XMLoadFloat4x4(&pShapes[i]->W) * S * shadowOffsetY; XMMATRIX worldViewProj = world * ViewProjM; mfxWorldInvTranspose->SetMatrix(reinterpret_cast<float*>(&PDEshape::InverseTranspose(world))); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); static float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f }; pContext->OMSetBlendState(mBlendStateTransparency.Get(), blendFactors, 0xffffffff); mTech = mTechShadow; pContext->OMSetDepthStencilState(mNoDoubleBlendDSS.Get(), 0); for (UINT p = 0; p < techDesc.Passes; ++p) { mTech->GetPassByIndex(p)->Apply(0, pContext.Get()); pContext->DrawIndexed(pShapes[i]->meshData.Indices.size(), mIndexCounts[i], mVertexCounts[i]); } /****************************更新坐标并绘制完**************************/ pContext->RSSetState(0); } } pContext->OMSetDepthStencilState(0, 0); //pContext->ClearDepthStencilView(mDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); /*********************绘制阴影完***********************************************************************/ // Set land material (material varies per object). for (UINT& i : drawOrder) { if (dynamic_cast<ReflectivePlane*> (pShapes[i])) continue; //for (UINT i = 0; i < 2; ++i) { /****************************更新坐标并绘制**************************/ XMMATRIX world = XMLoadFloat4x4(&pShapes[i]->W); XMMATRIX worldViewProj = world * ViewProjM; mfxWorld->SetMatrix(reinterpret_cast<float*>(&world)); mfxWorldInvTranspose->SetMatrix(reinterpret_cast<float*>(&PDEshape::InverseTranspose(world))); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); mfxMaterial->SetRawValue(&pShapes[i]->Mat, 0, sizeof(pShapes[i]->Mat)); static float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f }; switch (pShapes[i]->blendType) { case BlendType::None: pContext->OMSetBlendState(nullptr, blendFactors, 0xffffffff); break; case BlendType::Add: pContext->OMSetBlendState(mBlendStateAdd.Get(), blendFactors, 0xffffffff); break; case BlendType::Subtract: pContext->OMSetBlendState(mBlendStateSubtract.Get(), blendFactors, 0xffffffff); break; case BlendType::Multiply: pContext->OMSetBlendState(mBlendStateMultiply.Get(), blendFactors, 0xffffffff); break; case BlendType::Transparency: pContext->RSSetState(mBACK.Get()); pContext->OMSetBlendState(mBlendStateTransparency.Get(), blendFactors, 0xffffffff); break; } // 加载贴图 if (mHasTex[i]) { if (pShapes[i]->ShaderResourceView) { mTech = mTechTexture; HR(mfxDiffuseMap->SetResource(pShapes[i]->ShaderResourceView.Get())); //ID3D11Resource* TexBuffer; //pShapes[i]->ShaderResourceView.Get()->GetResource(&TexBuffer); //D3D11_TEXTURE2D_DESC texDesc; //static_cast<ID3D11Texture2D*>(TexBuffer)->GetDesc(&texDesc); ////mirrors[i]->ShaderResourceView = pMainResourceOut; //std::ostringstream oss; //oss << "some" << i << ".dds"; //SaveDDSTextureToFile(pContext.Get(), TexBuffer, CA2W(oss.str().c_str())); mfxTexTransform->SetMatrix(reinterpret_cast<float*>(&pShapes[i]->TexW)); } } else { mTech = mTechNoTexture; } pShapes[i]->GetEffect()->GetDrawTech()->GetDesc(&techDesc); for (UINT p = 0; p < techDesc.Passes; ++p) { mTech->GetPassByIndex(p)->Apply(0, pContext.Get()); pContext->DrawIndexed(pShapes[i]->meshData.Indices.size(), mIndexCounts[i], mVertexCounts[i]); } /****************************更新坐标并绘制完**************************/ pContext->RSSetState(0); } } inline void BasicEffect::DrawMirrors(ID3D11RenderTargetView* target, Camera& camera) { pContext->OMSetRenderTargets(1u, &target, mGfx->GetDepthStencilView()); // 渲染方式 pContext->RSSetState(mSOLID.Get()); //pContext->RSSetState(mWIREFRAME.Get()); std::vector<PDEshape*>& mirrors = pShapes; // Set land material (material varies per object). for (UINT i = 0; i < mirrors.size(); ++i) { if (!dynamic_cast<ReflectivePlane*> (mirrors[i])) continue; /****************************更新坐标并绘制**************************/ XMMATRIX ViewProjM = XMLoadFloat4x4(&camera.ViewProj); XMMATRIX world = XMLoadFloat4x4(&mirrors[i]->W); XMMATRIX worldViewProj = world * ViewProjM; mfxWorld->SetMatrix(reinterpret_cast<float*>(&world)); mfxWorldInvTranspose->SetMatrix(reinterpret_cast<float*>(&PDEshape::InverseTranspose(world))); mfxWorldViewProj->SetMatrix(reinterpret_cast<float*>(&worldViewProj)); mfxReflectWorldViewProj->SetMatrix(reinterpret_cast<float*>(&dynamic_cast<ReflectivePlane*>(mirrors[i])->refWVP)); mfxMaterial->SetRawValue(&mirrors[i]->Mat, 0, sizeof(mirrors[i]->Mat)); static float blendFactors[] = { 0.0f, 0.0f, 0.0f, 0.0f }; //pContext->RSSetState(mBACK.Get()); pContext->OMSetBlendState(mBlendStateTransparency.Get(), blendFactors, 0xffffffff); if (mGfx->IsUse4xMsaa()) { mTech = mTechReflect; HR(mfxReflectMap->SetResource(mirrors[i]->ShaderResourceView.Get())); } else { mTech = mTechReflectNoMSAA; HR(mfxDiffuseMap->SetResource(mirrors[i]->ShaderResourceView.Get())); } mfxTexTransform->SetMatrix(reinterpret_cast<float*>(&mirrors[i]->TexW)); for (UINT p = 0; p < techDesc.Passes; ++p) { mTech->GetPassByIndex(p)->Apply(0, pContext.Get()); pContext->DrawIndexed(mirrors[i]->meshData.Indices.size(), mIndexCounts[i], mVertexCounts[i]); } /****************************更新坐标并绘制完**************************/ pContext->RSSetState(0); } } std::vector<UINT>& BasicEffect::SortShapes(Camera& camera) const { static bool isGroup = false; static XMVECTOR targeToPos = camera.GetDirection(); static std::vector<UINT> order(pShapes.size()); if (!pShapes.size()) return order; static UINT TPstart = 0; // 透明开始索引 if (!isGroup) { for (UINT i = 0; i < pShapes.size(); ++i) { order[i] = i; } for (UINT i = 0; i < pShapes.size() - 1; ++i) { if (pShapes[order[i]]->blendType == BlendType::None) continue; //if (pShapes[order[i]]->blendType == BlendType::Transparency && order[i] < pShapes.size()-1) { if (order[i] < pShapes.size() - 1) { UINT j = i + 1; while (pShapes[order[j]]->blendType != BlendType::None) { ++j; if (j >= order.size()) goto out; } std::swap(order[j], order[i]); TPstart = i + 1; } } out: isGroup = true; } // 定义按到摄像机距离比大小函数,根据向量与标量夹角为锐角时,向量头距离标量尾更远,反则反是 // 只是将全局矩阵的w(局部坐标原点)当做图形的位置,较为粗略,适用条件是 // 1,图形顺序和其局部坐标原点顺序一致, // 2, 同一个图形的像素在视点到投影面上的路径上是连续的,即图形间无重叠和穿插 auto sortByDistanceToCamera = [=](UINT& a, UINT& b)->bool { XMVECTOR AB = (XMLoadFloat4x4(&pShapes[a]->W) - XMLoadFloat4x4(&pShapes[b]->W)).r[3]; return XMVectorGetX(XMVector3Dot(AB, targeToPos)) > 0u; }; // 透明图形按到摄像机距离排序 std::sort(order.begin() + TPstart, order.end(), sortByDistanceToCamera); if (TPstart > 2) sort(order.begin() + TPstart - 1, order.begin(), sortByDistanceToCamera); return order; }<file_sep>/1/FogEffect.cpp #include "FogEffect.h" FogEffect::FogEffect(BasicEffect* be) : mFogIsChange(true), mFogStart(0.0f), mFogRange(1000.0f), mFogColor(0.0f, 0.0f, 0.0f, 1.0f) { mBasicEffect = be; this->mFX = be->GetFX(); LoadFx(); } void FogEffect::Draw() { if (mFogIsChange) { mfxFogStart->SetFloat(mFogStart); mfxFogRange->SetFloat(mFogRange); mfxFogColor->SetRawValue(&mFogColor, 0, sizeof(mFogColor)); mFogIsChange = false; } } void FogEffect::LoadFx() { mTechNoFog = mFX->GetTechniqueByName("NOFog"); mfxFogStart = mFX->GetVariableByName("gFogStart")->AsScalar(); mfxFogRange = mFX->GetVariableByName("gFogRange")->AsScalar(); mfxFogColor = mFX->GetVariableByName("gFogColor")->AsVector(); } void FogEffect::SetTopoLayout() { } void FogEffect::SetFog(float fogStart, float fogRange, XMFLOAT4 fogColor) { mFogIsChange = true; mFogStart = fogStart; mFogRange = fogRange; mFogColor = fogColor; } <file_sep>/1/effect.h #ifndef EFFECT #define EFFECT #include "h.h" #include "BasicEffect.h" namespace wrl = Microsoft::WRL; #endif<file_sep>/1/light.h #pragma once #include "h.h" using namespace DirectX; struct DirectionalLight { // ma,md,ms DirectionalLight() { ZeroMemory(this, sizeof(this)); } XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; XMFLOAT3 Direction; float Pad; // Pad the last float so we can // array of lights if we wanted. }; struct PointLight { PointLight() { ZeroMemory(this, sizeof(this)); } XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; // Packed into 4D vector: (Position, Range) XMFLOAT3 Position; float Range; // Packed into 4D vector: (A0, A1, A2, Pad) XMFLOAT3 Att; float Pad; // Pad the last float so we can set an // array of lights if we wanted. }; struct SpotLight { SpotLight() { ZeroMemory(this, sizeof(this)); } XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular;// Packed into 4D vector: (Position, Range) XMFLOAT3 Position; float Range; // Packed into 4D vector: (Direction,Spot) XMFLOAT3 Direction; float Spot; // Packed into 4D vector: (Att, Pad) XMFLOAT3 Att; float Pad; // Pad the last float so we can set an // array of lights if we wanted. }; enum class LightType { DirectionalLight, PointLight, SpotLight, OtherLight }; class Light { public: Light(LightType type) : type(type) { Ambient = {0.0f,0.0f, 0.0f, 1.0f}; Diffuse = { 0.0f,0.0f, 0.0f, 1.0f }; Specular = { 0.0f,0.0f, 0.0f, 1.0f }; Position = { 0.0f,0.0f, 0.0f}; Range = 1000.0f; Direction = { 0.0f,0.0f, 0.0f }; Spot = 96.0f; Att = { 0.0f,0.0f, 1.0f }; light = nullptr; } ~Light() { if (light != nullptr) { delete light; } } void* getLight() { Free(); if (type == LightType::DirectionalLight) { DirectionalLight* dl = new DirectionalLight(); dl->Ambient = Ambient; dl->Diffuse = Diffuse; dl->Specular = Specular; dl->Direction = Direction; light = dl; } else if (type == LightType::PointLight) { PointLight* pl = new PointLight(); pl->Ambient = Ambient; pl->Diffuse = Diffuse; pl->Specular = Specular; pl->Position = Position; pl->Range = Range; pl->Att = Att; light = pl; } else if (type == LightType::SpotLight) { SpotLight* sl = new SpotLight(); sl->Ambient = Ambient; sl->Diffuse = Diffuse; sl->Specular = Specular; sl->Position = Position; sl->Range = Range; sl->Direction = Direction; sl->Spot = Spot; sl->Att = Att; light = sl; } return light; } LightType getType() { return type; } void ChangeType(LightType type) { this->type = type; }; XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; XMFLOAT3 Position; float Range; XMFLOAT3 Direction; float Spot; XMFLOAT3 Att; private: void Free() { if (light != nullptr) { delete light; } } LightType type; void* light; }; struct Material { Material() { ZeroMemory(this, sizeof(this)); } XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; // w = SpecPower XMFLOAT4 Reflect; };<file_sep>/1/Camera.h #pragma once #include "h.h" using namespace DirectX; class Camera { public: Camera(); Camera(const XMVECTOR& pos, const XMVECTOR& dir, float AspectRatio); void SetCamera(const XMVECTOR& pos,const XMVECTOR& dir); void MoveCamera(const XMVECTOR& offset); void RotateCamera(const XMVECTOR& A, float angle); void SetAspectRatio(const float& AspectRatio); public: // 投影、视矩阵、投影视矩阵 XMFLOAT4X4 P; XMFLOAT4X4 V; XMFLOAT4X4 ViewProj; XMVECTOR const GetDirection() { return XMLoadFloat4(&dir); } XMVECTOR const GetPosition() { return XMLoadFloat4(&pos); } private: XMFLOAT4 pos; XMFLOAT4 dir; void UpdateViewMatrix(); XMFLOAT4 up; float AspectRatio; float FovAngleY; float NearZ; float FarZ; };<file_sep>/1/ReflectivePlane.cpp #include "ReflectivePlane.h" #include "GeometryGenerator.h" using namespace DirectX; ReflectivePlane::ReflectivePlane(XMFLOAT3 Position, XMFLOAT3 Direction, float width, float depth) : cameraReflect(), Position(Position) { HasShadow = false; SetBlendType(BlendType::Transparency); MeshData meshData; GeometryGenerator().CreateGrid(-width, depth,100u,100u,meshData); XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); this->meshData = meshData; this->init(); XMVECTOR dir = XMLoadFloat3(&Direction); XMStoreFloat3(&this->Direction,XMVector3Normalize(dir)); XMVECTOR pos = XMLoadFloat3(&Position); // 设置到指定位置 XMVECTOR cross = XMVector3Cross(dir,up ); Rotate(cross, XMVectorGetX(XMVector3AngleBetweenVectors(dir, up))); Move(Position.x, Position.y, Position.z); //cameraRefect.SetCamera(pos, pos + dir); } void ReflectivePlane::SetReflectView(ID3D11RenderTargetView* RTview, ID3D11ShaderResourceView* SRview) { this->RenderTargetView = wrl::ComPtr<ID3D11RenderTargetView>(RTview); this->ShaderResourceView = wrl::ComPtr<ID3D11ShaderResourceView>(SRview); } void ReflectivePlane::SetCamera(const XMVECTOR& pos, const XMVECTOR& target) { cameraReflect.SetCamera(pos, target); XMMATRIX w = XMLoadFloat4x4(&W); refWVP = w * XMLoadFloat4x4(&cameraReflect.ViewProj); for (auto &v : meshData.Vertices) { //XMVECTOR pos = XMVectorSet(v.Position.x, v.Position.y, v.Position.z, 1.0f); //XMVECTOR posW = XMVector4Transform(pos,w); XMVECTOR sss = XMVector4Transform( XMLoadFloat3(&v.Position) , refWVP); sss/= XMVectorGetW(sss); int i = 1; ++i; v.TexC.x = sss.m128_f32[0]; v.TexC.y = sss.m128_f32[1]; } } void ReflectivePlane::init() { this->PDEshape::init(); } <file_sep>/1/vertex.h #pragma once #include "h.h" using namespace DirectX; struct Vertex { Vertex() = default; Vertex(const XMFLOAT3& p, const XMFLOAT3& n, const XMFLOAT3& t, const XMFLOAT2& uv) : Position(p), Normal(n), TangentU(t), TexC(uv) {} Vertex( float px, float py, float pz, float nx, float ny, float nz, float tx, float ty, float tz, float u, float v) : Position(px, py, pz), Normal(nx, ny, nz), TangentU(tx, ty, tz), TexC(u, v) {} XMFLOAT3 Position; XMFLOAT3 Normal; XMFLOAT3 TangentU; XMFLOAT2 TexC; };<file_sep>/1/GeometryGenerator.h #pragma once #include "h.h" #include "Shape.h" #include "vertex.h" #include <vector> #include <algorithm> using MeshData = PDEshape::MeshData; class GeometryGenerator { public: GeometryGenerator() = default; GeometryGenerator(const GeometryGenerator&) = delete; GeometryGenerator& operator=(const GeometryGenerator&) = delete; ~GeometryGenerator() = default; public: void CreateGrid(float width, float depth,UINT m, UINT n, MeshData& meshData); void GreateRevolvingSolid(std::vector<XMFLOAT2> line, UINT slice, MeshData& meshData); void CreateCylinder(float bottomRadius, float topRadius, float height, UINT sliceCount, UINT stackCount, MeshData& meshData); void CreateNormal(MeshData& meshData); void CreateGeosphere(float radius, UINT numSubdivisions, MeshData& meshData); void Subdivide(MeshData& meshData); void CreateBox(float width, float height, float depth, MeshData& meshData); private: UINT LinkGrid(UINT m, UINT n, UINT startInd, MeshData& meshData); };<file_sep>/1/Graphics.h #ifndef GRAPHICS #define GRAPHICS #include "h.h" #include <d3d11.h> #include <d3dcompiler.h> #include <memory> #include "timer.h" #include "light.h" #include "Camera.h" #include "ReflectivePlane.h" #include "BasicEffect.h" class PDEeffect; //class BasicEffect {} namespace wrl = Microsoft::WRL; class Graphics { public: Graphics(HWND hWnd, UINT width, UINT height, bool enable4xMsaa); void LoadFx(); Graphics(const Graphics&) = delete; Graphics& operator=(const Graphics&) = delete; ~Graphics(); void AddEffect(PDEeffect* ef) { effects.push_back(ef); } void SetAspectRatio(float AspectRatio) { this->AspectRatio = AspectRatio; mMainCamera.SetAspectRatio(AspectRatio); } void SetBackgroundColor(XMFLOAT4 color) { this->mBGColor = color; } void SetCamera(Camera camera); void UpdateCamera(); void EndFrame(); //void DrawBox(); //void DrawShapes(ID3D11RenderTargetView* target, Camera& camera); //void DrawMirrors(ID3D11RenderTargetView* target, Camera& camera); void DrawFrame(); void ClearBuffer(ID3D11RenderTargetView* target); //std::vector<PDEshape*>& Shapes() { return pShapes; } public: bool IsUse4xMsaa() { return mEnable4xMsaa; } UINT Get4xMsaaQuality() { return m4xMsaaQuality; } UINT GetWinWidth() { return mWinWidth; } UINT GetWinHeight() { return mWinHeight; } ID3D11Device* GetDevice() { return pDevice.Get(); } ID3D11DeviceContext* GetDeviceContext() { return pContext.Get(); } Camera& GetMainCamera() { return mMainCamera; } ID3D11DepthStencilView* GetDepthStencilView() { return mDepthStencilView.Get(); } D3D11_VIEWPORT& GetMainViewPort() { return mMainViewPort; } ID3D11RenderTargetView** GetpMainTarget() { return pMainTarget.GetAddressOf(); }; float GetRanderTime() {return gfxTimer.Peek();} private: //std::vector<UINT>& SortShapes(Camera& camera) const; private: UINT mWinWidth; UINT mWinHeight; XMFLOAT4 mBGColor; bool mEnable4xMsaa; UINT m4xMsaaQuality; // 主视口 D3D11_VIEWPORT mMainViewPort; wrl::ComPtr<ID3D11Device> pDevice = nullptr; wrl::ComPtr<IDXGISwapChain> pSwap = nullptr; wrl::ComPtr<ID3D11DeviceContext> pContext = nullptr; wrl::ComPtr<ID3D11RenderTargetView> pMainTarget = nullptr; float AspectRatio = 1.333333f; // 摄像机 Camera mMainCamera; bool cameraIsChange; std::vector<PDEeffect*> effects; wrl::ComPtr<ID3D11Texture2D> mDepthStencilBuffer; wrl::ComPtr<ID3D11DepthStencilView> mDepthStencilView; // 计时器 Timer gfxTimer; #pragma region 测试代码 public: void InitBillboard(const UINT& allVertex); void drawBillboard(); #pragma endregion }; #endif // !GRAPHICS
18cdb2c316110108aa8d25f111a4c0a3dcd05713
[ "C++", "HLSL" ]
39
C++
PDE26jjk/dx11Test
772ca91e6c092aa4f0ffe8791b97db47e5488fa8
99ea8fdbe19396644a47540e5efcb6e2463dfaae
refs/heads/master
<file_sep>\chapter{Instructions for use} \label{sec:manual} \section{The measurement operation} Using of the Transistor-Tester is simple. Anyway some hints are required. In most cases are wires with alligator clips connected to the test ports with plugs. Also sockets for transistors can be connected. In either case you can connect parts with three pins to the three test ports in any order. If your part has only two pins, you can connect this pins to any two of the tree test ports. Normally the polarity of part is irrelevant, you can also connect pins of electrolytical capacitors in any order. The measurement of capacity is normally done in a way, that the minus pole is at the test port with the lower number. But, because the measurment voltage is only between 0.3 V and at most 1.3 V, the polarity doesn\'t matter. When the part is connected, you should not touch it during the measurement. You should put it down to a nonconducting pad if it is not placed in a socket. You should also not touch to the isolation of wires connected with the test ports. Otherwise the measurement results can be affected. Then you should press the start button. After displaying a start message, the measurement result should appear after two seconds. If capacitors are measured, the time to result can be longer corresponding to the capacity. How the transistor-tester continues, depends on the configuration of the software. \begin{description} \item[Single measurement mode] If the tester is configured for single measurement mode (POWER\_OFF option), the tester shut off automatical after displaying the result for 28 seconds for a longer lifetime of battery. During the display time a next measurement can be started by pressing the start button. After the shut off a next measurement can be started too of course. The next measurement can be done with the same or another part. If you have not installed the electronic for automatic shut down, your last measurement result will be displayed until you start the next measurement. \item[Endless measurement mode] A special case is the configuration without automatical shut off. For this case the POWER\_OFF option is not set in the Makefile. This configuration is normally only used without the transistors for the shut off function. A external off switch is necessary for this case. The tester will repeat measurements until power is switched off. \item[Multi measurement mode] In this mode the tester will shut down not after the first measurement but after a configurable series of measurements. For this condition a number (e.g.~5) is assigned to the POWER\_OFF option. In the standard case the tester will shut down after five measurements without found part. If any part is identified by test, the tester is shut down after double of five (ten) measurements. A single measurement with unknown part after a series of measurement of known parts will reset the counter of known measuerements to zero. Also a single measurement of known part will reset the counter of unknown measurements to zero. This behavior can result in a nearly endless series of measurements without pressing the start button, if parts are disconnected and connected in periodical manner. In this mode there is a special feature for the display period. If the start button is pressed only short for switching on the tester, the result of measurement ist only shown for 5 seconds. Buf if you press and hold the start button until the first message is shown, the further measurement results are shown for 28 seconds. The next measurement can started earlier by pressing the start button during the displaying of result. \end{description} \section{Optional menu functions for the ATmega328} If the menu function is selected, the tester start a selection menu after a long key press (\textgreater 500ms) for additional functions. This function is also available for other processors with at least 32K flash memory. The selectable functions are shown in row two of a 2-line display or as marked function in row 3 of a 4-line display. The previous and next function is also shown in row 2 and 4 of the display in this case. After a longer wait time without any interaction the program leave the menu and returns to the normal transistor tester function. With a short key press the next selection can be shown. A longer key press starts the shown or marked function. After showing the last function ''switch off'', the first function will be shown next. If your tester has also the rotary pulse encoder installed, you can call the menu with the additional functions also with a fast rotation of the encoder during the result of a previous test is shown. The menu functions can be selected with slow rotation of the encoder in every direction. Starting of the selected menu function can only be done with a key press. Within a selected function parameters can be selected with slow rotation of the encoder. A fast rotarion of the encoder will return to the selection menu. \begin{description} \item[frequency] The additional function ''frequency'' (frequency measurement) uses the ATmega Pin PD4, which is also connected to the LCD. First the frequency is allways measured by counting. If the measured frequency is below \(25~kHz\), additionally the mean period of the input signal is measured and with this value the frequency is computed with a resolution of up to \(0.001~Hz\). By selecting the POWER\_OFF option in the Makefile, the period of frequency measurement is limited to 8~minutes. The frequency measurement will be finished with a key press and the selectable functions are shown again.\\ \item[f-Generator] With the additional function ''f-Generator'' (frequency generator) the selectable frequencies can be switched with key presses. After selecting the last choise of frequencies, the generator is switched back to the first frequency next (cyclical choise). If the POWER\_OFF option is selected in the Makefile, the key must be pressed longer, because a short key press (\textless~0.2~s) only reset the time limit of 4~minutes. The elapsed time is shown with a point for every 30 seconds in row 1 of the display. With periodical short key press you can prevent the time out of the frequency generation. With a long key press (\textgreater~0.8~s) you will stop the frequency generator and return to the function menu.\\ \item[10-bit PWM] The additional function ''10-bit PWM'' (Pulse Width Modulation) generates a fixed frequency with selectable puls width at the pin TP2. With a short key press (\textless~0.5~s) the pulse width is increased by \(1~\%\), with a longer key press the pulse width is increased by \(10~\%\). If \(99~\%\) is overstepped, \(100~\%\) is subtracted from the result. If the POWER\_OFF option is selected in the Makefile, the frequency generation is finished after 8~minutes without any key press. The frequency generation can also be finished with a very long key press (\textgreater~1.3~s).\\ \item[C+ESR@TP1:3] The additional function ''C+ESR@TP1:3'' selects a stand-alone capacity measurement with ESR (Equivalent Series Resistance) measurement at the test pins TP1 and TP3. Capacities from \(2~\mu F\) up to \(50~mF\) can be measured. Because the measurement voltage is only about \(300~mV\), in most cases the capacitor can be measured ''in circuit'' without previous disassembling. If the POWER\_OFF option is selected in the Makefile, the count of measurements is limited to 250, but can be started immediately again. The series of measurements can be finished with a long key press.\\ \item[Resistor meter] With the \mbox{1 \electricR 3} symbol the tester changes to a resistor meter at TP1 and TP3 . This operation mode will be marked with a {\bf[R]} at the right side of the first display line. Because the ESR measurement is not used in this operation mode, the resolution of the measurement result for resistors below \(10~\Omega\) is only \(0.1~\Omega\). If the resistor measurement function is configured with the additional inductance measurement, a \mbox{1 \electricR \electricL 3} symbol is shown at this menu. Then the resistor meter function includes the measurement of inductance for resistors below \(2100~\Omega\). At the right side of the first display line a {\bf[RL]} is shown. For resistors below \(10~\Omega\) the ESR measurement is used, if no inductance is find out. For this reason the resolution for resistors below \(10~\Omega\) is increased to \(0.01~\Omega\). With this operation mode the measurement is repeated without any key press. With a key press the tester finish this operation mode and returns to the menu. The same resistor meter function is started automatically, if a single resistor is connected between TP1 and TP3 and the start key was pressed in the normal tester function. In this case the tester returns from the special mode opration to the normal tester function with a key press. \item[Capacitor meter] With the \mbox{1 \electricC 3} symbol the tester changes to a capacitor meter function at TP1 and TP3. This operation mode will be marked with a {\bf[C]} at the right side of the first display line. With this operation mode capacitors from \(1~pF\) up to \[100~mF\] can be measured. In this operation mode the measurement is repeated without key press. With a key press the tester finish this operation mode and returns to the menu. In the same way as with resistors, the tester changes automatically to the capacitor meter function, if a capacitor between TP1 and TP3 is measured with the normal tester function. After a automatically start of the capacitor meter function the tester returns with a key press to the normal tester function. \item[rotary encoder] With the function ''rotary encoder'' a rotary encoder can be checked. The three pins of the rotary encoder must be connected in any order to the three probes of the transistor tester before the start of the function. After starting the function the rotary knob must be turned not too fast. If the test is finished successfully, the connection of the encoder switches is shown symbolic in display row 2. The tester finds out the common contact of the two switches and shows, if the indexed position has both contacts in open state ('o') or in closed state ('C'). A rotary encoder with open switches at the indexed positions is shows in row 2 for two seconds as ''1-/-2-/-3 o''. This type of encoder has the same count of indexed positions as count of pulses for every turn. Of course the pin number of the right common contact is shown in the middle instead of '2'. If also the closed switches state is detected at the indexed positions, the row 2 of the display is also shown as ''1---2---3 C'' for two seconds. I don't know any rotary encoder, which have the switches always closed at any indexed position. The interim state of the switches between the indexed positions is also shown in row 2 for a short time (\(\textless~0.5s\)) without the characters 'o' or 'C'. If you will use the rotary encoder for handling the tester, you should set the Makefile option WITH\_ROTARY\_SWITCH=2 for encoders with only the open state ('o') and set the option WITH\_ROTARY\_SWITCH=1 for encoders with the open ('o') and closed ('C') state at the indexed positions.\\ \item[Selftest] With the menu function ''Selftest'' a full selftest with calibration is done. With that call all the test functions T1 to T7 (if not inhibited with the NO\_TEST\_T1\_T7 option) and also the calibration with external capacitor is done every time.\\ \item[Voltage] The additional function ''Voltage'' (Voltage measurement) is only possible, if the serial output is deselected or the ATmega has at least 32 pins (PLCC) and one of the additional pins ADC6 or ADC7 is used for the measurement. Because a 10:1 voltage divides is connected to PC3 (or ADC6/7), the maximum external voltage can be 50V. A installed DC-DC converter for zener diode measurement can be switched on by pressing the key. Thus connected zener diodes can be measured also. By selecting the POWER\_OFF option in the Makefile and without key pressing, the period of voltage measurement is limited to 4~minutes. The measurement can also be finished with a extra long key press (\textgreater~4~seconds). \item[Contrast] This function is available for display controllers, which can adjust the contrast level with software. The value can be decreased by a very short key press or left turn with the rotary encoder. A longer key press (\textgreater 0.4s) or a right turn of the rotary encoder will increase the value. The function will be finished and the selected value will be saved nonvolatile in the EEprom memory by a very long key press (\textgreater 1.3s). \item[Show data] The function ,,Show Data'' shows besides the version number of the software the data of the calibration. These are the zero resistance (R0) of the pin combination 1:3, 2:3 and 1:2 . In addition the resistance of the port outputs to the 5V side (RiHi) and to the 0V side (RiLo) are shown. The zero capacity values (C0) are also shown with all pin combinations (1:3, 2:3, 1:2 and 3:1, 3:2 2:1). Next the correction values for the comparator (REF\_C) and for the reference voltage (REF\_R) are also shown. With graphical displays the used icons for parts and the font set is also shown. Every page is shown for 15 seconds, but you can select the next page by a key press or a right turn of the rotary encoder. With a left turn of the rotary encoder you can repeat the output of the last page or return to the previous page. \item[Switch off] With the additional function ''Switch off'' the tester can be switched off immediately.\\ \item[Transistor] Of course you can also select the function ''Transistor'' (Transistor tester) to return to a normal Transistor tester measurement. \end{description} With the selected POWER\_OFF option in the Makefile, all additional functions are limited in time without interaction to prevent a discharged battery. \section{Selftest and Calibration} If the software is configured with the selftest function, the selftest can be prepared by connecting all three test ports together and pushing of the start button. To begin the self test, the start butten must be pressed again within 2 seconds, or else the tester will continue with a normal measurement. If the self test is started, all of the documented tests in the Selftest chapter \ref{sec:selftest} will be done. If the tester is configured with the menu function (option WITH\_MENU), the full selftest with the tests T1 to T7 are only done with the ''Selftest'' function, which is selectable as menu function. In addition the calibration with the external capacitor is done with every call from function menu, otherwise this part of calibration is only done first time. Thus the calibration with the automatically started selftest (shorted probes) can be done faster. The repetition of the tests T1 to T7 can be avoided, if the start button is hold pressed. So you can skip uninteresting tests fast and you can watch interresting tests by releasing the start button. The test 4 will finish only automatically if you separate the test ports (release connection). If the function AUTO\_CAL is selected in the Makefile, the zero offset for the capacity measurement will be calibrated with the selftest. It is important for the calibration task, that the connection between the three test ports is relased during test number 4. You should not touch to any of the test ports or connected cables when calibration (after test 6) is done. But the equipment should be the same, which is used for further measurements. Otherwise the zero offset for capacity measurement is not detected correctly. The resistance values of port outputs are determined at the beginning of every measurement with this option. A capacitor with any capacity between \(100~nF\) and \(20~\mu F\) connected to pin~1 and pin~3 is required for the last task of calibration. To indicate that, the message \mbox{1 \electricC 3 \textgreater 100nF} is shown in row 1 of the display. You should connect the capacitor not before the message C0= or this text is shown. With this capacitor the offset voltage of the analog comparator will be compensated for better measurement of capacity values. Additionally the gain for ADC measurements using the internal reference voltage will be adjusted too with the same capacitor for better resistor measurement results with the AUTOSCALE\_ADC option. If the menu option is selected for the tester and the selftest is not started as menu function, the calibration with the external capacitor is only done for the first time calibration. The calibration with the external capacitor can be repeated with a selftest call as menu selection. The zero offset for the ESR measurement will be preset with the option ESR\_ZERO in the Makefile. With every self test the ESR zero values for all three pin combinations are determined. The solution for the ESR measurement is also used to get the values of resistors below \(10~\Omega\) with a resolution of \(0.01~\Omega\). \section{special using hints} Normally the Tester shows the battery voltage with every start. If the voltage fall below a limit, a warning is shown behind the battery voltage. If you use a rechargeable 9V battery, you should replace the battery as soon as possible or you should recharge. If you use a tester with attached 2.5V precision reference, the measured supply voltage will be shown in display row two for 1 second with ''VCC=x.xxV''. It can not repeat often enough, that capacitors should be discharged before measuring. Otherwise the Tester can be damaged before the start button is pressed. If you try to measure components in assembled condition, the equipment should be allways disconnected from power source. Furthermore you should be shure, that no residual voltage reside in the equipment. Every electronical equipment has capacitors inside! If you try to measure little resistor values, you should keep the resistance of plug connectors and cables in mind. The quality and condition of plug connectors are important, also the resistance of cables used for measurement. The same is in force for the ESR measurement of capacitors. With poor connection cable a ESR value of \(0.02 \Omega\) can grow to \(0.61 \Omega\). If possible, you should connect the cables with the test clips steady to the tester (soldered). Then you must not recalibrate the tester for measuring of capacitors with low capacity values, if you measure with or without the plugged test cables. For the calibration of the zero resistance there is normaly a difference, if you connect the three pins together directly at a socket or if you connect together the test clips at the end of cables. Only in the last case the resistance of cables and clips is included in the calibration. If you are in doubt, you should calibrate your tester with jumpers directly at the socket and then measure the resistance of shorten clips with the tester. You should not expect very good accuracy of measurement results, especially the ESR measurement and the results of inductance measurement are not very exact. You can find the results of my test series in chapter \ref{sec:measurement} at page~\pageref{sec:measurement}. \section{Compoments with problems} You should keep in mind by interpreting the measurement results, that the circuit of the TransistorTester is designed for small signal semiconductors. In normal measurement condition the measurement current can only reach about 6 mA. Power semiconductors often make trouble by reason of residual current with the identification an the measurement of junction capacity value. The Tester often can not deliver enough ignition current or holding current for power Thyristors or Triacs. So a Thyristor can be detected as NPN transistor or diode. Also it is possible, that a Thyristor or Triac is detected as unknown. Another problem is the identification of semiconductors with integrated resistors. So the base - emitter diode of a BU508D transistor can not be detected by reason of the parallel connected internal \(42~\Omega\) resistor. Therefore the transistor function can not be tested also. Problem with detection is also given with power Darlington transistors. We can find often internal base - emitter resistors, which make it difficult to identify the component with the undersized measurement current. \section{Measurement of PNP and NPN transistors} For normal measurement the three pins of the transistor will be connectet in any order to the measurement inputs of the TransistorTester. After pushing the start button, the Tester shows in row 1 the type (NPN or PNP), a possible integrated protecting diode of the Collector - Emitter path and the sequence of pins. The diode symbol is shown with correct polarity. Row 2 shows the current amplification factor \(B\) or \(hFE\) and the current, by which the amplification factor is measured. If the common emitter circuit is used for the hFE determinatation, the collector current \(Ic\) is output. If the common collector circuit is used for measuring of the amplification factor, the emitter current \(Ie\) is shown. Further parameters are shown for displays with two lines in sequence, one after the the other in line 2. For displays with more lines further parameters are shown directly until the last line is allready used. When the last line is allready used before, the next parameter is shown also in the last line after a time delay automatically or earlier after a key press. If more parameters are present than allready shown, a + character is shown at the end of the last line. The next shown parameter is anyway the Base - Emitter threshold voltage. If any collector cutoff current is measurable, the collector current without base current \(I_CE0\) and the collector current with base connected to the emitter \(I_CES\) is also shown. If a protecting diode is mounted, the flux voltage \(Uf\) is also shown as last parameter. With the common Emitter circuit the tester has only two alternative to select the base current: \begin{enumerate} \item The \(680~\Omega\) resistor results to a base current of about 6.1mA. This is too high for low level transistors with high amplification factor, because the base is saturated. Because the collector current is also measured with a \(680~\Omega\) resistor, the collector current can not reach the with the amplification factor higher value. The software version of Markus F. has measured the Base - Emitter threshold voltage in this ciruit (Uf=...).\\ \item The \(470~k\Omega\) resistor results to a base current of only \(9.2~\mu A\) . This is very low for a power transistor with low current amplification factor. The software version of Markus F. has identified the current amplification factor with this circuit (hFE=...).\\ \end{enumerate} The software of the Tester figure out the current amplification factor additionally with the common Collector circuit. The higher value of both measurement methodes is reported. The common collector circuit has the advantage, that the base current is reduced by negative current feedback corresponding to the amplification factor. In most cases a better measurement current can be reached with this methode for power transistors with the \(680~\Omega\) resistor and for Darlington Transistors with \(470~k\Omega\) resistor. The reported Base - Emitter threshold voltage Uf is now measured with the same current used for determination of the current amplification factor. However, if you want to know the Base - Emitter threshold voltage with a measurement current of about 6mA, you have to disconnect the Collector and to start a new measurement. With this connection, the Base - Emitter threshold voltage at 6 mA is reported. The capacity value in reverse direction of the diode is also reported. Of course you can also analyse the base - collector diode. With Germanium transistors often a Collector cutoff current \(I_{CE0}\) with currentless base or a Collector residual current \(I_{CES}\) with base hold to the emitter level is measured. Only for ATmega328 processors the Collector cutoff current is shown in this case at the row 2 of the LCD for 5 seconds or until the next keypress before showing the current amplification factor. With cooling the cutoff current can be reduced significant for Germanium transistors. \section{Measurement of JFET and D-MOS transistors} Because the structure of JFET type is symmetrical, the Source and Drain of this transistores can not be differed. Normally one of the parameter of this transistor is the current of the transistor with the Gate at the same level as Source. This current is often higher than the current, which can be reached with the measurement circuit of the TransistorTester with the \(680~\Omega\) resistor. For this reason the \(680~\Omega\) resistor is connected to the Source. Thus the Gate get with the growing of current a negative bias voltage. The Tester reports the Source current of this circuit and additionally the bias voltage of the Gate. So various models can be differed. The D-MOS transistors (depletion type) are measured with the same methode. \section{Measurement of E-MOS transistors} You should know for enhancement MOS transistors (P-E-MOS or N-E-MOS), that the measurement of the gate threshold voltage (Vth) is more difficult with little gate capacity values. You can get a better voltage value, if you connect a capacitor with a value of some nF parallel to the gate /source. The gate threshold voltage will be find out with a drain current of about 3.5mA for a P-E-MOS and about 4mA for a N-E-MOS. The RDS or better R\textsubscript{DSon} is measured with a gate - source voltage of nearly \(5~V\), which is probably not the lowest value. <file_sep>#include "Transistortester.h" /* ShowData shows the Software version number and */ /* the calibration data at the 2-line or 4-line LCD */ #ifdef WITH_MENU void ShowData(void) { #ifdef WITH_ROTARY_SWITCH show_page_1: #endif lcd_clear(); lcd_MEM2_string(VERSION_str); // "Version x.xxk" lcd_line2(); lcd_MEM2_string(R0_str); // "R0=" DisplayValue(eeprom_read_byte(&EE_ESR_ZEROtab[2]),-2,' ',3); DisplayValue(eeprom_read_byte(&EE_ESR_ZEROtab[3]),-2,' ',3); DisplayValue(eeprom_read_byte(&EE_ESR_ZEROtab[1]),-2,LCD_CHAR_OMEGA,3); #if (LCD_LINES > 3) lcd_line3(); #else wait_for_key_ms(MIDDLE_WAIT_TIME); #ifdef WITH_ROTARY_SWITCH if (rotary.incre > FAST_ROTATION) return; // fast rotation ends the function if (rotary.count < 0) goto show_page_1; show_page_2: #endif lcd_clear(); #endif /* output line 3 */ lcd_MEM_string(RIHI); // "RiHi=" DisplayValue(RRpinPL,-1,LCD_CHAR_OMEGA,3); #if (LCD_LINES > 3) lcd_line4(); #else lcd_line2(); #endif /* output line 4 */ lcd_MEM_string(RILO); // "RiLo=" DisplayValue(RRpinMI,-1,LCD_CHAR_OMEGA,3); wait_for_key_ms(MIDDLE_WAIT_TIME); #ifdef WITH_ROTARY_SWITCH if (rotary.incre > FAST_ROTATION) return; // fast rotation ends the function #if (LCD_LINES > 3) if (rotary.count < 0) goto show_page_1; #else if (rotary.count < -1) goto show_page_1; if (rotary.count < 0) goto show_page_2; #endif show_page_3: #endif lcd_clear(); lcd_MEM_string(C0_str); //output "C0 " DisplayValue(eeprom_read_byte(&c_zero_tab[5]),0,' ',3); //output cap0 1:3 DisplayValue(eeprom_read_byte(&c_zero_tab[6]),0,' ',3); //output cap0 2:3 DisplayValue(eeprom_read_byte(&c_zero_tab[2]),-12,'F',3); //output cap0 1:2 lcd_line2(); lcd_spaces(3); DisplayValue(eeprom_read_byte(&c_zero_tab[1]),0,' ',3); //output cap0 3:1 DisplayValue(eeprom_read_byte(&c_zero_tab[4]),0,' ',3); //output cap0 3:2 DisplayValue(eeprom_read_byte(&c_zero_tab[0]),-12,'F',3); //output cap0 2:1 #if (LCD_LINES > 3) lcd_line3(); #else wait_for_key_ms(MIDDLE_WAIT_TIME); #ifdef WITH_ROTARY_SWITCH if (rotary.incre > FAST_ROTATION) return; // fast rotation ends the function if (rotary.count < -2) goto show_page_1; if (rotary.count < -1) goto show_page_2; if (rotary.count < 0) goto show_page_3; show_page_4: #endif lcd_clear(); #endif /* output line 7 */ lcd_MEM2_string(REF_C_str); // "REF_C=" i2lcd((int16_t)eeprom_read_word((uint16_t *)(&ref_offset))); #if (LCD_LINES > 3) lcd_line4(); #else lcd_line2(); #endif /* output line 8 */ lcd_MEM2_string(REF_R_str); // "REF_R=" i2lcd((int8_t)eeprom_read_byte((uint8_t *)(&RefDiff))); wait_for_key_ms(MIDDLE_WAIT_TIME); #ifdef WITH_ROTARY_SWITCH if (rotary.incre > FAST_ROTATION) return; // fast rotation ends the function #if (LCD_LINES > 3) if (rotary.count < -1) goto show_page_1; if (rotary.count < 0) goto show_page_3; #else if (rotary.count < -3) goto show_page_1; if (rotary.count < -2) goto show_page_2; if (rotary.count < -1) goto show_page_3; if (rotary.count < 0) goto show_page_4; #endif #endif #ifdef WITH_GRAPHICS ShowIcons(); // show all Icons #endif } #endif <file_sep> %\newpage \chapter{Список текущих дел и новые идеи} \label{sec:todo} \begin{enumerate} \item Добавлять и улучшать документацию. \item Подумать о том, как можно замерить реальное внутреннее выходное сопротивление порта B (переключение резистора порта) вместо принятия, что порты одинаковы. \item Может ли разрядка конденсаторов стать быстрее, если отрицательный вывод дополнительно подключить через резистор \(680~\Omega\) к VCC (+)? \item Проверить, может ли Тестер использовать представление значений с плавающей запятой. Риск перегрузки ниже. Нет желания одновременно использовать умножение и деление, чтобы получить умножение с плавающей запятой. Но я не знаю, каким объемом должна быть Flash память, необходимая для библиотеки. \item Написать Руководство пользователя для того, чтобы конфигурировать Тестер опциями Makefile и описать методику построения. \item Если ток удержания тиристора не может быть достигнут с резистором \(680~\Omega\) он безопасен для подключения катода непосредственно к GND и анода непосредственно к VCC на очень короткое время? Ток может достигнуть больше, чем \(100~mA\). Порт будет поврежден? Что с электропитанием (стабилизатор напряжения)? \item Проверять порт после самопроверки! \item Предупреждающее сообщение, если измеренное опорное напряжение не соответствует модели ATmega и VCC. \item Подумать о Тестере второго поколения с «большим» ATmega, который включает дифференциальный АЦП-порт, больше Flash памяти? Нет таких ATxmega, у которых есть напряжение питания \(5~V\), возможна только линия ATmega. \item Идея нового проекта: версия USB без LCD-дисплея, питание от USB, обмен с PC по USB. \item Управление шириной импульса с фиксированной частотой на ТР2. \item Калибровка частоты кварцевого генератора c точностью 1 PPS от приемника GPS или точная настройка с помощью подстроечных конденсаторов? \item Выбор раздельного измерения ESR. Возможность измерения "в цепи"? \item Выбор раздельного измерения 2-контактных ЭРЭ для более быстрого определения (резисторы и конденсаторы). \item Поддержка дисплея 20x4 символов. \end{enumerate} <file_sep>#if defined(MAIN_C) unsigned long ResistorVal[3]; // Values of resistor 0:1, 0:2, 1:2 uint8_t ResistorList[3]; // list of the found resistor Numbers uint8_t ResistorChecked[3]; // 2, if resistor is checked in both directions uint8_t ResistorsFound; //Number of found resistors #if FLASHEND > 0x1fff unsigned long inductor_lx; // inductance 10uH or 100uH int8_t inductor_lpre; // prefix for inductance #endif #else /* no main */ extern unsigned long ResistorVal[3]; // Values of resistor 0:1, 0:2, 1:2 extern uint8_t ResistorList[3]; // list of the found resistor Numbers extern uint8_t ResistorChecked[3]; // 2, if resistor is checked in both directions extern uint8_t ResistorsFound; //Number of found resistors #if FLASHEND > 0x1fff unsigned long inductor_lx; // inductance 10uH or 100uH int8_t inductor_lpre; // prefix for inductance #endif #endif <file_sep>// new code by <NAME> #include <avr/io.h> #include <stdlib.h> #include "Transistortester.h" #if FLASHEND > 0x3fff //================================================================= // selection of different functions /* ****************************************************************** */ /* show_Resis13 measures the resistance of a part connected to TP1 and TP3 */ /* if RMETER_WITH_L is configured, inductance is also measured */ /* ****************************************************************** */ void show_Resis13(void) { uint8_t key_pressed; message_key_released(RESIS_13_str); // "1-|=|-3 .." lcd_set_cursor(0,LCD_LINE_LENGTH-RLMETER_len); lcd_MEM2_string(RLMETER_13_str); // "[RL]" at the end of line 1 #ifdef POWER_OFF uint8_t times; for (times=0;times<250;times++) #else while (1) /* wait endless without the POWER_OFF option */ #endif { init_parts(); // set all parts to nothing found // PartFound = PART_NONE; // ResistorsFound = 0; // ResistorChecked[1] = 0; GetResistance(TP3, TP1); GetResistance(TP1, TP3); lcd_line2(); // clear old Resistance value if (ResistorsFound != 0) { #ifdef RMETER_WITH_L ReadInductance(); // measure inductance, possible only with R<2.1k RvalOut(1); // show Resistance, probably ESR if (inductor_lpre != 0) { // resistor has also inductance lcd_MEM_string(Lis_str); // "L=" DisplayValue(inductor_lx,inductor_lpre,'H',3); // output inductance lcd_set_cursor(0,5); lcd_MEM_string(Inductor_str); // -ww- lcd_testpin(TP3); } else { lcd_spaces(12); // clear old L= lcd_set_cursor(0,5); lcd_testpin(TP3); lcd_spaces(4); // clear ww-3 } #else /* without Inductance measurement, only show resistance */ inductor_lpre = -1; // prevent ESR measurement because Inductance is not tested RvalOut(1); // show Resistance, no ESR #endif } else { /* no resistor found */ lcd_data('?'); // too big lcd_spaces(19); #ifdef RMETER_WITH_L lcd_set_cursor(0,5); lcd_testpin(TP3); lcd_spaces(4); // clear ww-3 #endif } #if defined(POWER_OFF) && defined(BAT_CHECK) Bat_update(times); #endif key_pressed = wait_for_key_ms(1000); #ifdef WITH_ROTARY_SWITCH if ((key_pressed != 0) || (rotary.incre > 3)) break; #else if (key_pressed != 0) break; #endif #ifdef POWER_OFF if (DC_Pwr_mode == 1) times = 0; // no time limit with DC_Pwr_mode #endif } /* end for times */ lcd_clear(); } /* end show_Resis13() */ /* ****************************************************************** */ /* show_Cap13 measures the capacity of a part connected to TP1 and TP3 */ /* ****************************************************************** */ #if (LCD_LINES > 2) #define SCREEN_TIME 1000 #else #define SCREEN_TIME 2000 /* line 2 is multi use, wait longer to read */ #endif void show_Cap13(void) { uint8_t key_pressed; message_key_released(CAP_13_str); // 1-||-3 at the beginning of line 1 lcd_set_cursor(0,LCD_LINE_LENGTH-3); lcd_MEM2_string(CMETER_13_str); // "[C]" at the end of line 1 #ifdef POWER_OFF uint8_t times; for (times=0;times<250;times++) #else while (1) /* wait endless without the POWER_OFF option */ #endif { init_parts(); // set all parts to nothing found // PartFound = PART_NONE; // NumOfDiodes = 0; // cap.cval_max = 0; // clear cval_max for update of vloss // cap.cpre_max = -12; // set to pF unit cap.v_loss = 0; // clear vloss for low capacity values (<25pF)! ReadCapacity(TP3, TP1); lcd_line2(); // overwrite old Capacity value if (cap.cpre < 0) { // a cap is detected lcd_spaces(8); // clear Capacity value lcd_line2(); // overwrite old Capacity value DisplayValue(cap.cval,cap.cpre,'F',4); // display capacity PartFound = PART_CAPACITOR; // GetESR should check the Capacity value cap.esr = GetESR(TP3,TP1); if ( cap.esr < 65530) { // ESR is measured lcd_set_cursor(1 * PAGES_PER_LINE, 8); // position behind the capacity lcd_MEM_string(&ESR_str[1]); // show also "ESR=" DisplayValue(cap.esr,-2,LCD_CHAR_OMEGA,2); // and ESR value lcd_spaces(2); // clear old remainder of last ESR message lcd_set_cursor(0,4); lcd_MEM2_string(Resistor_str); // "-[=]- .." lcd_testpin(TP3); // add the TP3 } else { // no ESR known lcd_set_cursor(1 * PAGES_PER_LINE, 8); // position behind the capacity lcd_spaces(10); // clear ESR text and value lcd_set_cursor(0,4); // clear ESR resistor lcd_testpin(TP3); // write the TP3 lcd_spaces(5); // overwrite ESR resistor symbol } GetVloss(); // get Voltage loss of capacitor #if (LCD_LINES > 2) lcd_line3(); if (cap.v_loss != 0) { lcd_MEM_string(&VLOSS_str[1]); // "Vloss=" DisplayValue(cap.v_loss,-1,'%',2); lcd_spaces(4); } else { lcd_clear_line(); } #else if (cap.v_loss != 0) { key_pressed = wait_for_key_ms(SCREEN_TIME); #ifdef WITH_ROTARY_SWITCH // if ((key_pressed != 0) || (rotary.incre > 3)) break; #else // if (key_pressed != 0) break; #endif lcd_clear_line2(); lcd_MEM_string(&VLOSS_str[1]); // "Vloss=" DisplayValue(cap.v_loss,-1,'%',2); } #endif } else { /* no cap detected */ lcd_data('?'); lcd_spaces(18); // clear rest of line 2 #if (LCD_LINES > 2) lcd_line3(); lcd_clear_line(); // clear old Vloss= message #endif } #if defined(POWER_OFF) && defined(BAT_CHECK) Bat_update(times); #endif key_pressed = wait_for_key_ms(SCREEN_TIME); #ifdef WITH_ROTARY_SWITCH if ((key_pressed != 0) || (rotary.incre > 3)) break; #else if (key_pressed != 0) break; #endif #ifdef POWER_OFF if (DC_Pwr_mode == 1) times = 0; // no time limit with DC_Pwr_mode #endif } /* end for times */ lcd_clear(); } /* end show_Cap13() */ #endif #if defined(POWER_OFF) && defined(BAT_CHECK) // monitor Battery in line 4 or line2, if a two line display void Bat_update(uint8_t tt) { if((tt % 16) == 0) { #if (LCD_LINES > 3) lcd_line4(); Battery_check(); #else wait_about1s(); lcd_clear_line2(); Battery_check(); wait_about2s(); #endif } }; /* end Bat_update() */ #endif
8ae1135126177e38e60b612b79188421dd9be7bb
[ "TeX", "C" ]
5
TeX
timofonic/transistortester
43bd011ea0f57fd4fcf79b579e67362575e28bed
78a5bc7f2acbfc79713d17efd5fac01998d1e338
refs/heads/master
<file_sep>from flask import Flask, abort, render_template, request, redirect, url_for app = Flask(__name__) @app.route("/") def geekout(): our_title = 'Geek Out' return render_template('geekout.html', title=our_title) if __name__ == "__main__": app.run(host='0.0.0.0', debug='true')
5b2c11da5f242068070ff2ff717337ea57e8b0d0
[ "Python" ]
1
Python
danlerche/geekout
e5a3846173f48f393cf956d8373d35b3f9e3d218
25c02991271a90de6d75b156eda186f919ab85a5
refs/heads/main
<repo_name>thought2/fp-ts-number-instances<file_sep>/README.md # fp-ts-number-instances [API Docs](https://no-day.github.io/fp-ts-number-instances) Not fully law abiding `Semiring`, `Ring` and `Field` instances for the `number` type. See [this page](https://gcanti.github.io/fp-ts/modules/Semiring.ts.html) for an explanation.
4b2fe174ac5a22a59ef9fa0eabe0506ec954765c
[ "Markdown" ]
1
Markdown
thought2/fp-ts-number-instances
c2fc8ff150427b1601db283d2e966a8f95c48e04
2d5589f0d55d827bf6dbd7a7d10809672fcee3c2
refs/heads/master
<file_sep># Secret Santa ![Master](https://github.com/Sillhouette/secret_santa/workflows/Master/badge.svg) ![Develop](https://github.com/Sillhouette/secret_santa/workflows/Develop/badge.svg) ![Coverage](https://github.com/Sillhouette/secret_santa/blob/master/assets/coverage/coverage_badge_total.svg?raw=true) A small secret santa cli app used to choose recipients of secret santa gifts in a group of people ## Requirements - Ruby >= 2.6.6 ## Installation ### Github #### Install: - (ssh) Run `git clone <EMAIL>:Sillhouette/secret_santa.git && cd secret_santa` - (http) Run `git clone https://github.com/Sillhouette/secret_santa.git && cd secret_santa` Setup the commit message template ``` $ git config commit.template .git-templates/pull-request-template.md ``` ### Run: - Use `ruby bin/run.rb` to execute the app ### Tests: - Use `bundle exec rspec` to run the tests - Tests include a code coverage check ### Development - Clone repo - Run `bundle install` to install dependencies - Run `git config commit.template .git-templates/pull_request_template.md` to install commit message template ### Contributing - Fork the repo (`https://github.com/Sillhouette/secret_santa/fork`) - Run `git config commit.template .git-templates/pull_request_template.md` to install commit message template - Create your feature branch (`git checkout -b my-new-feature`) - Add changes (`git add file_name`) - Commit your changes (`git commit`) - Please follow the commit message template - Push to the branch (`git push origin my-new-feature`) - Create a new Pull Request This project has been licensed under the [MIT open source license](https://github.com/Sillhouette/secret_santa/blob/master/LICENSE.md). <file_sep>source "https://rubygems.org" gem "require_all", "~> 3.0" gem 'pry', group: :development gem "rspec", "~> 3.10", group: :development gem 'simplecov', require: false, group: :test gem 'simplecov-console', group: :test gem 'simplecov-small-badge', :require => false, git: "https://github.com/MarcGrimme/simplecov-small-badge.git" <file_sep>require 'secret_santa' describe SecretSanta do before(:each) do @secret_santa = SecretSanta.new(cli: generate_cli) Person.clear end describe '#create_participants' do it 'can create a single participant with no spouse' do name = "Hannah" spouse = nil participant_data = [[name, spouse]] num_people = 1 @secret_santa.create_participants(participant_data) participant = Person.find_by_name(name: name) result = Person.all.length expect(result).to eq num_people expect(participant.name).to eq name expect(participant.spouse).to be nil end it 'can create a single participant with a spouse' do name = "Garth" spouse = 'Jessica' participant_data = [[name, spouse]] num_people = 2 @secret_santa.create_participants(participant_data) participant = Person.find_by_name(name: name) result = Person.all.length expect(result).to eq num_people expect(participant.name).to eq name expect(participant.spouse.name).to be spouse end it 'can create a multiple participants with and without spouses' do participant_1 = ["Garth", "Jessica"] participant_2 = ["Hannah", nil] participant_3 = ["Dan", "Mickie"] participant_data = [participant_1, participant_2, participant_3] num_people = 5 @secret_santa.create_participants(participant_data) first_participant = Person.find_by_name(name: participant_1[0]) second_participant = Person.find_by_name(name: participant_2[0]) third_participant = Person.find_by_name(name: participant_3[0]) result = Person.all.length expect(result).to eq num_people expect(first_participant.name).to eq participant_1[0] expect(first_participant.spouse.name).to be participant_1[1] expect(first_participant.spouse.spouse.name).to be participant_1[0] expect(second_participant.name).to eq participant_2[0] expect(second_participant.spouse).to be nil expect(third_participant.name).to eq participant_3[0] expect(third_participant.spouse.name).to be participant_3[1] expect(third_participant.spouse.spouse.name).to be participant_3[0] end end describe '#unmatched' do it 'returns an array containing an unmatched participant' do first_person = Person.create(name: 'Hannah') second_person = Person.create(name: 'Garth') first_person.match = second_person result = @secret_santa.unmatched expect(result).to include first_person expect(result).not_to include second_person end it 'returns an array of all unmatched participants' do first_person = Person.create(name: 'Hannah') second_person = Person.create(name: 'Garth') third_person = Person.create(name: 'Dan', spouse: 'Mickie') fourth_person = Person.find_by_name(name: 'Mickie') first_person.match = second_person result = @secret_santa.unmatched expect(result).to include first_person expect(result).to include third_person expect(result).to include fourth_person expect(result).not_to include second_person end it 'does not affect size of Person.all array' do first_person = Person.create(name: 'Hannah') second_person = Person.create(name: 'Garth') expected = 2 first_person.match = second_person @secret_santa.unmatched result = Person.all.length expect(result).to eq expected end end describe '#match_participant' do it 'matches two participants together' do participant = Person.create(name: "Hannah") match = Person.create(name: 'Garth') @secret_santa.match_participant(participant) expect(participant.match).to eq match end it 'will not match spouses together' do participant = Person.create(name: 'Garth', spouse: 'Jessica') match = Person.create(name: "Hannah") @secret_santa.match_participant(participant) expect(participant.match).to eq match end it 'will not match spouses together if they are the only participants' do participant = Person.create(name: 'Garth', spouse: 'Jessica') spouse = Person.find_by_name(name: 'Jessica') @secret_santa.match_participant(participant) expect(participant.match).not_to eq spouse end it 'will not match spouses together if they are the only participants not already matched (pt 1)' do participant = Person.create(name: 'Garth', spouse: 'Jessica') participant_2 = Person.create(name: 'Hannah') spouse = Person.find_by_name(name: 'Jessica') participant_2.match = participant spouse.match = participant_2 @secret_santa.match_participant(participant) expect(participant.match).not_to eq spouse end it 'will not match spouses together if they are the only participants not already matched (pt 2)' do participant = Person.create(name: 'Garth', spouse: 'Jessica') participant_2 = Person.create(name: 'Hannah') participant_3 = Person.create(name: 'Dan') spouse = Person.find_by_name(name: 'Jessica') participant_2.match = participant_3 participant_3.match = participant_2 @secret_santa.match_participant(participant) expect(participant.match).not_to eq spouse end it 'gracefully handles one match left with only choice being spouse' do participant = Person.create(name: 'Whitney', spouse: 'Allen') participant_2 = Person.create(name: 'Hannah') participant_3 = Person.create(name: 'Garth') spouse = Person.find_by_name(name: 'Allen') participant_2.match = participant_3 participant_3.match = participant spouse.match = participant_2 @secret_santa.match_participant(participant) expect(participant.match).not_to eq spouse end end describe '#match_participants' do it 'sucessfully matches everyone' do Person.create(name: "Dan", spouse: "Mickie") Person.create(name: "Garth", spouse: "Jessica") Person.create(name: "Whitney", spouse: "Allen") Person.create(name: "Hannah") @secret_santa.match_participants expect(@secret_santa.unmatched.length).to eq 0 end end describe '#start' do it 'Runs the game' do inputs = [ "Hannah", "no", "Garth", "yes", "Jessica", "Dan", "yes", "Mickie", "Whitney", "yes", "Allen", "end", "yes" ] cli = generate_cli(*inputs) @secret_santa.cli = cli expected = 0 @secret_santa.start result = @secret_santa.unmatched.length Person.all.each do |person| expect(person.match).to_not eq person.spouse end expect(result).to eq expected end end end<file_sep>class Person attr_accessor :name, :match attr_reader :spouse @@all = [] def initialize(name:, spouse: nil) @name = name self.spouse = spouse @match = nil end def save @@all << self end def spouse=(spouse) if spouse.is_a?(String) @spouse = Person.find_or_create(name: spouse) @spouse.spouse = self else @spouse = spouse end end def self.all @@all end def self.clear @@all = [] end def self.find_by_name(name:) @@all.find { |person| person.name == name } end def self.create(name:, spouse: nil) person = self.new(name: name, spouse: spouse) person.save person end def self.find_or_create(name:) self.find_by_name(name: name) || self.create(name: name) end end<file_sep>class Cli attr_accessor :input, :output WELCOME = "Welcome to Secret Santa\n" PARTICIPANT_LIST = "\nParticipant list:" MATCH_LIST = "\nMatch list: " STOP = "end" PARTICIPANT_PROMPT = "\nPlease enter a participant's name: " EXIT_INSTRUCTION = "(Type \"#{STOP}\" to stop)" INVALID_INPUT = "\nThat response was invalid, try again." SPOUSE_NAME_PROMPT = "\nWhat is their name?" CONFIRM_PARTICIPANTS = "\nIs this all of the participants?" YES_NO = { yes: "yes", no: "no"} def initialize(input: $stdin, output: $stdout) @input = input @output = output end def welcome output.puts WELCOME end def prompt_user(prompt) output.puts prompt input.gets.strip end def print_participants output.puts PARTICIPANT_LIST output.puts Person.all.map(&:name) end def print_matches output.puts MATCH_LIST Person.all.each do |person| output.puts "#{person.name} - #{person.match.name}" if person.match end end def exit?(response) response == STOP end def validate_yes_no_response(response) YES_NO.values.include?(response) end def get_participant prompt_user(PARTICIPANT_PROMPT + EXIT_INSTRUCTION) end def get_spouse prompt_user(SPOUSE_NAME_PROMPT) end def has_spouse?(participant) spouse_prompt = "\nDoes #{participant} have a spouse?" response = prompt_user(spouse_prompt) if check_valid_response(response, YES_NO.values) return response == YES_NO[:yes] else has_spouse?(participant) end end def check_valid_response(response, valid_responses) if !valid_responses.include?(response) output.puts INVALID_INPUT return false end true end def get_participant_data participants = [] spouse = nil participant = get_participant until exit?(participant) if has_spouse?(participant) spouse = get_spouse end participants.push([participant, spouse]) spouse = nil participant = get_participant end participants end def confirm_participants response = prompt_user(CONFIRM_PARTICIPANTS) if check_valid_response(response, YES_NO.values) return response == YES_NO[:yes] end confirm_participants end end<file_sep>module Helpers def generate_cli(*inputs) input = StringIO.new(inputs.join("\n") + "\n") output = StringIO.new Cli.new(input: input, output: output) end end <file_sep>require 'person' describe Person do before(:each) do Person.clear end describe '#initialize' do it 'requires a name' do expect { Person.new() }.to raise_error ArgumentError end it 'creates a new person with a name' do name = 'Hannah' person = Person.new(name: name) expect(person.name).to eq name end it 'creates a new person with a name and spouse' do name = 'Garth' spouse = 'Jessica' person = Person.new(name: name, spouse: spouse) expect(person.name).to eq name expect(person.spouse.name).to eq spouse expect(person.spouse.spouse).to eq person end end describe '#save' do it 'saves a person to the @@all array' do person = Person.new(name: 'Dan') person.save result = Person.all.first expect(result).to eq person end end describe '#spouse=' do describe 'when given a name' do it 'creates a new person with that name' do person = Person.new(name: 'Garth') spouse = 'Jessica' person.spouse = spouse result = person.spouse expect(result).to be_a Person expect(result.name).to eq spouse end it 'sets the other person\'s spouse to itself' do person = Person.new(name: 'Garth') spouse = 'Jessica' person.spouse = spouse result = person.spouse expect(result.spouse).to be person end end end describe '.clear' do describe 'when a person is created' do it 'clears the @@all array' do Person.new(name: 'Hannah') Person.clear result = Person.all expect(result).to eq [] end end describe 'when multiple people are created' do it 'clears the @@all array' do Person.new(name: 'Hannah') Person.new(name: 'Garth') Person.new(name: 'Dan') Person.clear result = Person.all expect(result).to eq [] end end end describe '.all' do describe 'when a person is created' do it 'returns an array with only that person' do person = Person.create(name: 'Hannah') result = Person.all expect(result).to eq [person] end end describe 'when multiple people are created' do it 'returns an array with all of those people' do person_1 = Person.create(name: 'Hannah') person_2 = Person.create(name: 'Garth') person_3 = Person.create(name: 'Dan') result = Person.all expect(result).to eq [person_1, person_2, person_3] end end end describe '.find_by_name' do describe 'when given the name of a person that exists' do it 'returns that person' do person_1 = Person.create(name: 'Garth') person_2 = Person.create(name: 'Hannah') result = Person.find_by_name(name: 'Hannah') expect(result).to eq person_2 end end end describe '.create' do describe 'when given the name of a person' do it 'creates the person and saves them' do person = Person.create(name: 'Garth') result = Person.all.first expect(result).to eq person expect(Person.all.length).to eq 1 end end describe 'when multiple people are created' do it 'creates and saves all of them' do person_1 = Person.create(name: 'Garth') person_2 = Person.create(name: 'Dan') person_3 = Person.create(name: 'Hannah') result = Person.all expect(result).to eq [person_1, person_2, person_3] expect(Person.all.length).to eq 3 end end end describe '.find_or_create' do describe 'when given the name of a person that doesnt exist' do it 'creates that person' do name = 'Garth' result = Person.find_or_create(name: name) expect(result.name).to eq name end end describe 'when given the name of a person that exists' do it 'returns that person' do name = 'Garth' person = Person.create(name: name) result = Person.find_or_create(name: name) expect(result).to eq person end it 'doesnt duplicate that person' do name = 'Garth' person = Person.create(name: name) result = Person.find_or_create(name: name) expect(Person.all.length).to eq 1 end end end end<file_sep># <type>: <subject> # ticket: <comma separated ticket IDs> # Short bulleted explanation for why this change is being made # README # Type can be # feat (new feature) # fix (bug fix) # perf: (performance improvement) # refactor (refactoring production code) # style (formatting, missing semi colons, etc; no code change) # docs (changes to documentation) # test (adding or refactoring tests; no production code change) # build (changes to build) # chore (changes to config; no production code change) # -------------------- # Remember to # Use the imperative mood in the subject line # Do not end the subject line with a period # Do not use blank lines # Use the body to explain what and why vs. how # Use "-" for bullet point comments in body # --------------------<file_sep>require 'cli' describe Cli do before(:each) do Person.clear end describe '#welcome' do it 'prints the welcome message' do cli = generate_cli prompt = Cli::WELCOME expect(cli.output).to receive(:puts).with(prompt) cli.welcome end end describe '#prompt_user' do it 'prints the prompt' do cli = generate_cli("Hannah") prompt = "Do something: " expect(cli.output).to receive(:puts).with(prompt) cli.prompt_user(prompt) end it 'returns the user\'s input' do name = "Hannah" cli = generate_cli(name) prompt = "Do something: " result = cli.prompt_user(prompt) expect(result).to eq name end end describe '#print_participants' do it 'prints the list title and an empty array if no participants' do cli = generate_cli expect(cli.output).to receive(:puts).with(Cli::PARTICIPANT_LIST) expect(cli.output).to receive(:puts).with([]) cli.print_participants end it 'prints one participant in the list' do cli = generate_cli name = "Garth" Person.create(name: name) expect(cli.output).to receive(:puts).with(Cli::PARTICIPANT_LIST) expect(cli.output).to receive(:puts).with([name]) cli.print_participants end it 'prints multiple participants in the list' do cli = generate_cli names = ["Garth", "Jessica", "Hannah"] names.each {|name| Person.create(name: name) } expect(cli.output).to receive(:puts).with(Cli::PARTICIPANT_LIST) expect(cli.output).to receive(:puts).with(names) cli.print_participants end end describe '#print_matches' do it 'prints only the matches title if no people exist' do cli = generate_cli expect(cli.output).to receive(:puts).with(Cli::MATCH_LIST) cli.print_matches end it 'prints one participant and their match' do cli = generate_cli name = "Garth" match_name = "Dan" expected = "#{name} - #{match_name}" participant = Person.create(name: name) match = Person.create(name: match_name) participant.match = match expect(cli.output).to receive(:puts).with(Cli::MATCH_LIST) expect(cli.output).to receive(:puts).with(expected) cli.print_matches end it 'prints two participants and their matches' do cli = generate_cli names = ["Garth", "Dan"] names.each do |name| Person.create(name: name) end expected_1 = "#{names[0]} - #{names[1]}" expected_2 = "#{names[1]} - #{names[0]}" Person.all.first.match = Person.all[1] Person.all[1].match = Person.all.first expect(cli.output).to receive(:puts).with(Cli::MATCH_LIST) expect(cli.output).to receive(:puts).with(expected_1) expect(cli.output).to receive(:puts).with(expected_2) cli.print_matches end it 'prints complicated matches' do cli = generate_cli names = ["Garth", "Dan", "Hannah"] names.each do |name| Person.create(name: name) end expected_1 = "#{names[0]} - #{names[2]}" expected_2 = "#{names[1]} - #{names[0]}" expected_3 = "#{names[2]} - #{names[1]}" Person.all.first.match = Person.all[2] Person.all[1].match = Person.all.first Person.all[2].match = Person.all[1] expect(cli.output).to receive(:puts).with(Cli::MATCH_LIST) expect(cli.output).to receive(:puts).with(expected_1) expect(cli.output).to receive(:puts).with(expected_2) expect(cli.output).to receive(:puts).with(expected_3) cli.print_matches end end describe '#exit?' do it 'returns true if the response equals Cli::STOP' do cli = generate_cli response = Cli::STOP expected = true result = cli.exit?(response) expect(result).to eq expected end it 'returns false if the response does not equal Cli::STOP' do cli = generate_cli response = "Hannah" expected = false result = cli.exit?(response) expect(result).to eq expected end end describe '#validate_yes_no_response' do it 'returns true if the response is yes' do cli = generate_cli response = "yes" expected = true result = cli.validate_yes_no_response(response) expect(result).to eq expected end it 'returns true if the response is no' do cli = generate_cli response = "no" expected = true result = cli.validate_yes_no_response(response) expect(result).to eq expected end it 'returns true if the response is neither yes nor no' do cli = generate_cli response = "nonsense" expected = false result = cli.validate_yes_no_response(response) expect(result).to eq expected end end describe '#get_participant' do it 'prints Cli::PARTICIPANT_PROMPT and Cli::EXIT_INSTRUCTIONS' do cli = generate_cli prompt = Cli::PARTICIPANT_PROMPT + Cli::EXIT_INSTRUCTION expect(cli.output).to receive(:puts).with(prompt) cli.get_participant end it 'returns the string passed to input' do name = "Garth" cli = generate_cli(name) result = cli.get_participant expect(result).to eq(name) end end describe '#get_spouse' do it 'prints Cli::SPOUSE_PROMPT' do cli = generate_cli prompt = Cli::SPOUSE_NAME_PROMPT expect(cli.output).to receive(:puts).with(prompt) cli.get_spouse end it 'returns the string passed to input' do name = "Garth" cli = generate_cli(name) result = cli.get_spouse expect(result).to eq(name) end end describe '#has_spouse?' do it 'asks if the participant has a spouse' do response = Cli::YES_NO[:yes] cli = generate_cli(response) name = "Dan" prompt = "\nDoes #{name} have a spouse?" expect(cli.output).to receive(:puts).with(prompt) cli.has_spouse?(name) end it 'asks until it receives a proper response' do responses = ['gibberish', Cli::YES_NO[:no]] cli = generate_cli(*responses) name = "Dan" prompt = "\nDoes #{name} have a spouse?" expect(cli.output).to receive(:puts).twice.with(prompt) expect(cli.output).to receive(:puts).with(Cli::INVALID_INPUT) cli.has_spouse?(name) end it 'returns true if passed Cli::YES_NO[:yes] as the response' do response = Cli::YES_NO[:yes] expected = true cli = generate_cli(response) name = "Dan" result = cli.has_spouse?(name) expect(result).to eq expected end it 'returns false if passed Cli::YES_NO[:no] as the response' do response = Cli::YES_NO[:no] expected = false cli = generate_cli(response) name = "Hannah" result = cli.has_spouse?(name) expect(result).to eq expected end it 'asks until it receives a valid response' do responses = ['gibberish', 'hello', 'invalid', Cli::YES_NO[:no]] expected = false cli = generate_cli(*responses) name = "Hannah" prompt = "\nDoes #{name} have a spouse?" expect(cli.output).to receive(:puts).exactly(4).times.with(prompt) expect(cli.output).to receive(:puts).exactly(3).times.with(Cli::INVALID_INPUT) result = cli.has_spouse?(name) expect(result).to eq expected end end describe '#check_valid_response' do it 'outputs Cli::INVALID_INPUT if the response is not valid' do cli = generate_cli valid_responses = ["hello", "upsell", "nah"] response = "no" expected = false expect(cli.output).to receive(:puts).with(Cli::INVALID_INPUT) cli.check_valid_response(response, valid_responses) end it 'returns false if the response is not valid' do cli = generate_cli valid_responses = ["hello", "upsell", "nah"] response = "no" expected = false result = cli.check_valid_response(response, valid_responses) expect(result).to eq expected end it 'returns true if the response is valid' do cli = generate_cli valid_responses = ["hello", "upsell", "nah"] response = "nah" expected = true result = cli.check_valid_response(response, valid_responses) expect(result).to eq expected end end describe '#get_participant_data' do it 'returns an array of participant\'s data' do responses = ['Garth', Cli::YES_NO[:yes], 'Jessica', 'Hannah', Cli::YES_NO[:no], Cli::STOP] expected = [['Garth', 'Jessica'], ['Hannah', nil]] cli = generate_cli(*responses) result = cli.get_participant_data expect(result).to eq expected end end describe 'confirm_participants' do it 'returns true if passed Cli::YES_NO[:yes] as the response' do response = Cli::YES_NO[:yes] expected = true cli = generate_cli(response) result = cli.confirm_participants expect(result).to eq expected end it 'returns false if passed Cli::YES_NO[:no] as the response' do response = Cli::YES_NO[:no] expected = false cli = generate_cli(response) result = cli.confirm_participants expect(result).to eq expected end it 'prints invalid response error and asks again if answer not in Cli::YES_NO' do responses = ['hannah', Cli::YES_NO[:no]] expected = false cli = generate_cli(*responses) expect(cli.output).to receive(:puts).exactly(2).times.with(Cli::CONFIRM_PARTICIPANTS) expect(cli.output).to receive(:puts).exactly(1).times.with(Cli::INVALID_INPUT) cli.confirm_participants end end end<file_sep>require 'pry' class SecretSanta attr_accessor :cli def initialize(cli: Cli.new) @cli = cli end def start @cli.welcome finished = false until finished participant_data = @cli.get_participant_data create_participants(participant_data) @cli.print_participants finished = @cli.confirm_participants end match_participants @cli.print_matches end def create_participants(participants) participants.each do |participant_data| name, spouse = participant_data Person.create(name: name, spouse: spouse) end end def unmatched participants = Person.all.dup matched = participants.map do |person| person.match end matched.each do |match| participants.delete match end participants end def match_participants until unmatched.length == 0 Person.all.each do |participant| match_participant(participant) end end end def match_participant(participant) match = unmatched.sample if match != participant && match != participant.spouse participant.match = match elsif match == participant.spouse && ((unmatched.length == 2 && unmatched.include?(participant)) || unmatched.length == 1) || (match == participant && unmatched.length == 1) || unmatched.length == 0 else match_participant(participant) end end end
5644e07ec3bfc3144db8ae2081f44850c9edd32e
[ "Markdown", "Ruby" ]
10
Markdown
Sillhouette/secret_santa
709ae7b1dec06d8ba2ec7d58300e601d0376de61
4f6612d913e04651d729d894c1cf4e17b7de6c32
refs/heads/main
<file_sep>const { checkout } = require("./index.js"); describe("Returns a total amount for buying from a catalogue of items", () => { it("returns the total amount for a simple catalogue", () => { const catalogue = { C: 20, D: 15, deals: {}, }; const basket = ["C"]; expect(checkout(catalogue, basket)).toBe(20); const basket2 = ["D", "D"]; expect(checkout(catalogue, basket2)).toBe(30); }); it("returns the total amount for a simple catalogue of more than one item", () => { const catalogue = { C: 20, D: 15, deals: {}, }; const basket = ["C", "C", "D"]; expect(checkout(catalogue, basket)).toBe(55); const basket2 = ["D", "D", "C", "C"]; expect(checkout(catalogue, basket2)).toBe(70); }); }); describe("Returns a total amount for buying from a catalogue of items with deals", () => { it("returns the total amount for a simple catalogue with a deal", () => { const catalogue = { C: 20, deals: { C: { amount: 2, price: 30, }, }, }; const basket = ["C", "C"]; expect(checkout(catalogue, basket)).toBe(30); }); it("returns the total amount for a simple catalogue with more deals", () => { const catalogue = { C: 20, D: 15, deals: { C: { amount: 2, price: 30, }, D: { amount: 3, price: 40, }, }, }; const basket = ["C", "C", "D", "D", "D", "D", "D"]; expect(checkout(catalogue, basket)).toBe(100); }); it("returns the total amount for a full catalogue with deals", () => { const catalogue = { A: 50, B: 30, C: 20, D: 15, deals: { A: { amount: 3, price: 130, }, B: { amount: 2, price: 45, }, }, }; const basket = [ "C", "C", "D", "D", "D", "D", "D", "A", "B", "A", "B", "A", "B", "A", ]; expect(checkout(catalogue, basket)).toBe(370); }); });
aa8ed2326104dc4d8fae9bc74155ecc81d7a3f23
[ "JavaScript" ]
1
JavaScript
DeanSpooner/TMCheckoutBlank
c71c67b16c0225a24ef72fdabcfdf192cdfbc8b7
5d3ffb715a8770ea0560c5c836848053230f7ab1
refs/heads/master
<repo_name>jtorregrosa/nouss-landing<file_sep>/src/components/Header/Header.jsx import React, { PureComponent } from 'react'; import styled from 'styled-components'; const HeaderWrapper = styled.header` position: fixed; height: 100px; width:100%; `; const HeaderContainer = styled.div` margin: 0 auto; max-width: 75rem; width: 90%; `; class Header extends PureComponent { render() { return ( <HeaderWrapper> <HeaderContainer> {this.props.children} </HeaderContainer> </HeaderWrapper> ); } } Header.propTypes = { children: React.PropTypes.node, }; Header.defaultProps = { children: null, }; export default Header; <file_sep>/src/components/GhostButton/GhostButton.jsx import React, { PureComponent } from 'react'; import styled from 'styled-components'; const Button = styled.button` background: transparent; padding-left: 30px; padding-right: 30px; border: 2px ${props => props.theme.primary.base} solid; border-radius: 10px; `; class GhostButton extends PureComponent { constructor(props) { super(props); } render() { return ( <div> <Button>{this.props.label}</Button> </div> ); } } export default GhostButton; <file_sep>/src/containers/MainContent/MainContent.jsx import React, { PureComponent } from 'react'; class MainContent extends PureComponent { render() { return ( <div> {this.props.children} </div> ); } } MainContent.propTypes = { children: React.PropTypes.node, }; MainContent.defaultProps = { children: null, }; export default MainContent; <file_sep>/src/themes/breeze/index.js export default { primary: { base: '#4A96E1', }, secondary: { base: '#65ECE9', }, links: { base: '#00001A', hover: '#373754', visited: '#373754', active: '#373754', }, notice: { info: '#c2dced', warn: '#f1f997', danger: '#e77f76', }, font: { base: '#00001A', }, }; <file_sep>/src/components/Section/Section.jsx import React from 'react'; import styled from 'styled-components'; const SectionContainer = styled.section` height: 500px; background: ${props => props.theme.primary.base}; background: linear-gradient(to top, ${props => props.theme.primary.base}, ${props => props.theme.secondary.base}); `; function Section() { return ( <SectionContainer /> ); } export default Section; <file_sep>/src/themes/theme.js import colors from './breeze'; export default colors;
2bfc31191894c1a3396f7840c5a012cd67e63e4e
[ "JavaScript" ]
6
JavaScript
jtorregrosa/nouss-landing
0592186a99569f4c40a39e89b68dcdf8674415fb
4828f8265dcf1e11ced966f41b21837ceb638130
refs/heads/master
<repo_name>crestiage/balikaral<file_sep>/Assets/scripts/jumbledwords/jwgame.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class jwgame : MonoBehaviour { private JumbledwordsDTO[] jws; private WebRequestHelper wrh; GameObject questionPanel; private int currentQuestionNumber = 0; public Text questionBox; public Button letterA; public Button letterB; public Button letterC; public Button letterD; public Button letterE; public Button letterF; public Button letterG; public Button letterH; public Button letterI; public Button letterJ; private string JumbledWordsURL = "http://localhost/balikaral/connection_jumbled_words.php"; // Start is called before the first frame update void Start() { } void OnEnable() { // Debug.Log("OnEnable called"); wrh = new WebRequestHelper(this); SceneManager.sceneLoaded += OnSceneLoaded; } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { // string requestResult; // requestResult = wrh.fetchWebDataString(tamaOMaliURL); fetchQuestions(); } // Update is called once per frame void Update() { } public void fetchQuestions() { wrh.fetchWebDataString(JumbledWordsURL, processQuestionDTO); } public void processQuestionDTO(string result) { // Debug.Log("Called! TestCallback"); string jsonString = result; jsonString = CommonHelper.JsonHelper.fixJson(jsonString); jws = CommonHelper.JsonHelper.FromJson<JumbledwordsDTO>(jsonString); Debug.Log(jws); // Debug.Log(questionDtoArr[0].isAnswered); nextQuestion(); } public void nextQuestion() { // Debug.Log(currentQuestionNumber); int arrLength = jws.Length; if (arrLength > 0 && currentQuestionNumber < arrLength) { JumbledwordsDTO questionDto = jws[currentQuestionNumber]; questionBox.text = questionDto.question; currentQuestionNumber += 1; Debug.Log(questionDto.question); } else if (currentQuestionNumber >= arrLength) { // Summary page } } } <file_sep>/Assets/scripts/Models/JumbledwordsDTO.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class JumbledwordsDTO { public string question_id; public string subject; public string question; public string word; public string letter1; public string letter2; public string letter3; public string letter4; public string letter5; public string letter6; public string letter7; public string letter8; public string letter9; public string score; } <file_sep>/Assets/scripts/TorF/Question.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using UnityEngine.SceneManagement; using System; [System.Serializable] public class QuestionDTO { public string question_id; public string subject; public string question; public string correctAns; public int questionScoreValue = 1; public Boolean isAnswered = false; public Boolean isAnsweredCorrectly = false; } public class Question : MonoBehaviour { public string fact; public bool isTrue; public Image summaryPanel; public Text summaryPanelTitleText; public Text summaryPanelScoreText; public Button summaryPanelTryAgainBtn; public Button summaryPanelReturnToMMButton; public Text questionBox; public Button tamaButton; public Button maliButton; GameObject questionPanel; private QuestionDTO[] questionDtoArr; private int currentQuestionNumber = 0; private string tamaOMaliURL = "http://localhost/balikaral/connection_true_or_false.php"; private WebRequestHelper wrh; private void Start() { Debug.Log("start called"); tamaButton.onClick.AddListener(trueBtnOnClick); maliButton.onClick.AddListener(falseBtnOnClick); summaryPanelTryAgainBtn.onClick.AddListener(summaryPanelTryAgainBtnOnClick); } void OnEnable() { // Debug.Log("OnEnable called"); wrh = new WebRequestHelper(this); SceneManager.sceneLoaded += OnSceneLoaded; } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { // string requestResult; // requestResult = wrh.fetchWebDataString(tamaOMaliURL); fetchAndResetQuestions(); } public void fetchAndResetQuestions() { currentQuestionNumber = 0; wrh.fetchWebDataString(tamaOMaliURL, processQuestionDTO); } public void processQuestionDTO(string result) { // Debug.Log("Called! TestCallback"); String jsonString = result; jsonString = CommonHelper.JsonHelper.fixJson(jsonString); questionDtoArr = CommonHelper.JsonHelper.FromJson<QuestionDTO>(jsonString); // Debug.Log(questionDtoArr[0].isAnswered); nextQuestion(); } public void nextQuestion() { // Debug.Log(currentQuestionNumber); int arrLength = questionDtoArr.Length; if (arrLength > 0 && currentQuestionNumber < arrLength) { QuestionDTO questionDto = questionDtoArr[currentQuestionNumber]; questionBox.text = questionDto.question; currentQuestionNumber += 1; }else if (currentQuestionNumber >= arrLength) { // Summary page summarize(); displaySummaryPanel(true); } } private void trueBtnOnClick() { scoreAnswer(true); } private void falseBtnOnClick() { scoreAnswer(false); } private void scoreAnswer(bool trueOrFalse) { int arrLength = questionDtoArr.Length; // Subtract 1 because the nextQuestion is called advanced int currentQuestion = currentQuestionNumber - 1; if (arrLength > 0 && currentQuestion < arrLength) { QuestionDTO questionDto = questionDtoArr[currentQuestion]; String correctAnswer = questionDto.correctAns; questionDtoArr[currentQuestion].isAnswered = true; questionDtoArr[currentQuestion].isAnsweredCorrectly = ( (trueOrFalse && correctAnswer.Equals("1")) || (!trueOrFalse && correctAnswer.Equals("0")) ) ? true : false; Debug.Log(String.Format("Question #{0} has been aswered {1}", (currentQuestion), (questionDtoArr[currentQuestion].isAnsweredCorrectly) ? "correctly" : "incorrectly")); // End the game if a wrong answer has been selected if (!questionDtoArr[currentQuestion].isAnsweredCorrectly) { summarize(); summaryPanelTitleText.text = "Game Over"; displaySummaryPanel(true); } else { nextQuestion(); } } } private void summarize() { int totalScore = 0; foreach (QuestionDTO qdto in questionDtoArr) { if (qdto.isAnswered && qdto.isAnsweredCorrectly) { totalScore += qdto.questionScoreValue; } } summaryPanelScoreText.text = totalScore.ToString(); } private void displaySummaryPanel(bool show) { if (show) { summaryPanel.gameObject.SetActive(true); } else { summaryPanel.gameObject.SetActive(false); } } private void summaryPanelTryAgainBtnOnClick() { displaySummaryPanel(false); fetchAndResetQuestions(); } /*private IEnumerator fetchQuestions(string uri) { UnityWebRequest uwr = UnityWebRequest.Get(uri); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.Log("Error While Sending: " + uwr.error); } else { string jsonString = uwr.downloadHandler.text; jsonString = CommonHelper.JsonHelper.fixJson(jsonString); Debug.Log("Received: " + jsonString); questionDto = CommonHelper.JsonHelper.FromJson<QuestionDTO>(jsonString); Debug.Log(questionDto[0].ToString()); } }*/ } <file_sep>/Assets/scripts/avatarshop.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class avatarshop : MonoBehaviour { public void nextSceneii() { SceneManager.LoadScene("Avatar Shop"); } } <file_sep>/Assets/scripts/menu screens/prevSub.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class prevSub : MonoBehaviour { public void nextScenei() { SceneManager.LoadScene("3DoorsSubject"); } } <file_sep>/Assets/sql local/DataLoader.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DataLoader : MonoBehaviour { public string[] accounts; IEnumerator Start() { //string CreateUserURL = "http://localhost/balikaral/insertAccount.php"; WWW conn = new WWW("http://localhost/balikaral/connection(accounts).php"); yield return conn; string connString = conn.text; print(connString); accounts = connString.Split(';'); print(GetDataValue(accounts[0], "score")); } string GetDataValue(string data, string index) { string value = data.Substring(data.IndexOf(index) + index.Length); if(value.Contains("|"))value = value.Remove(value.IndexOf("|")); return value; } }<file_sep>/Assets/scripts/register.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using UnityEngine.SceneManagement; public class register : MonoBehaviour { public InputField Username; public InputField Email; public InputField test; public Dropdown Sex; public Dropdown Country; string CreateUserURL = "http://localhost/balikaral/insertAccount.php"; public void CreateUser() { UnityEngine.Debug.Log("hello"); var userName = Username.text; var email = Email.text; var sex = Sex.options[Sex.value].text; var country = Country.options[Country.value].text; UnityEngine.Debug.Log("Username: " + userName); UnityEngine.Debug.Log("Country: " + country); StartCoroutine(CreateUserRequest(userName, email, sex, country)); } private IEnumerator CreateUserRequest(string userName, string email, string sex, string country) { WWWForm form = new WWWForm(); form.AddField("usernamePost", userName); form.AddField("emailPost", email); form.AddField("sexPost", sex); form.AddField("countryPost", country); using (UnityWebRequest www = UnityWebRequest.Post(CreateUserURL, form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log("Form upload complete!"); SceneManager.LoadScene("verification"); } } } } <file_sep>/Assets/scripts/menu screens/dgreturn.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class dgreturn : MonoBehaviour { public void nextScenev() { SceneManager.LoadScene("Game Mode"); } } <file_sep>/Assets/scripts/Models/AccountDTO.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AccountDTO { public int acct_id; public string username; public string email; public string sex; public string country; public int tpScore; public int tofScore; public int jwScore; } <file_sep>/Assets/scripts/myprofile.cs  using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class myprofile : MonoBehaviour { public void nextSceneiii() { SceneManager.LoadScene("My Profile"); } } <file_sep>/Assets/scripts/Helpers/WebRequestHelper.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class WebRequestHelper { // Start is called before the first frame update private MonoBehaviour mono; public bool showDebugMsg = false; public WebRequestHelper(MonoBehaviour classInstance) { mono = classInstance; } void Start() { } // Update is called once per frame void Update() { } // Sample Call for requestWebDataString public void fetchWebDataString(string uri, System.Action<string> callback) { // assigning example // string result // mono.StartCoroutine(requestWebDataString(uri, value => result = value)); mono.StartCoroutine(requestWebDataString(uri, callback)); } private IEnumerator requestWebDataString (string uri, System.Action<string> result) { UnityWebRequest uwr = UnityWebRequest.Get(uri); yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { logMsg("Error While Sending: " + uwr.error); } else { string recvdString = uwr.downloadHandler.text; logMsg("Received: " + recvdString); result(recvdString); } } private void logMsg(string msg) { string debugMsg = string.Format("[{0}] {1}", this.GetType().Name, msg); if (showDebugMsg) { Debug.Log(debugMsg); } } }
f293d2831bbc090dd90f3d3f2a40d96985f7cf86
[ "C#" ]
11
C#
crestiage/balikaral
eb0fd27d9287071da8bd6373ea55562496d42151
fd32d24b5f3a2bd6315056ed7350a0d204464f41
refs/heads/master
<repo_name>wzbbbb/SD<file_sep>/download/prepack.pp package{"pcre": ensure=>present, before=>Package["nginx"], } package{"httpd-devel": ensure=>present, before=>Package["nginx"], } package{"perl": ensure=>present, before=>Package["nginx"], } package{"pcre-devel": ensure=>present, before=>Package["nginx"], } package{"zlib": ensure=>present, before=>Package["nginx"], } package{"zlib-devel": ensure=>present, before=>Package["nginx"], } package{"GeoIP": ensure=>present, before=>Package["nginx"], } package{"GeoIP-devel": ensure=>present, before=>Package["nginx"], } #yum install -y httpd-devel pcre perl pcre-devel zlib zlib-devel GeoIP GeoIP-devel #include nginx #node default { class { 'nginx': } #} nginx::resource::upstream { 'proxy': ensure => present, members => [ 'casplda02:443', ], } nginx::resource::vhost { "$::ipaddress": ensure => present, proxy => 'https://proxy', } # server_name =>['GW'], # listen_port => 80, #ssl => true, #ssl_cert => '/root/sd/server.crt', #ssl_key => '/root/sd/server.key', #} <file_sep>/download/heartbeat_ssl.sh_template #!/bin/bash # find the local IP that is used for the GW # normally should be eth0, for this test, it is eth1 # then send heartbeat and get the respond # if the respond is not "OK", run it with curl|bash #IP=`/sbin/ifconfig eth1|grep "inet "|cut -f2 -d":"|cut -f1 -d' '` ts=`date +%s` n_ver=`/usr/sbin/nginx -v 2>&1|cut -f2 -d'/'` #echo $ts ver=`cat ~root/gw.version` IP='192.168.114.208' #s=`curl -s http://$IP/SDC/` #echo $s #if [ $s = "\"OK\"" ] ; then # echo 'yes' #fi resp=`curl -k -s -X POST -H "Content-Type: application/json" -d "{"\"IP"\":"\"$IP"\","\"time_stamp"\":$ts,"\"version"\":$ver,"\"nginx_version"\":"\"${n_ver}"\"}" https://$IP/SDC/heartbeat/` #echo $resp if [ "${resp}" != "{\"status\":\"OK\"}" ] ; then url=`echo $resp|cut -f2 -d'"'|cut -f1 -d'"'` #echo $url curl -k -s https://$IP/$url|bash fi <file_sep>/download/nginx_heroku.pp class nginx (){ package {'nginx': ensure => 'latest', require => Exec['yum-update'], } file{ 'nginx.conf': ensure => file, require => Package['nginx'], path => '/etc/nginx/nginx.conf', #owner => $user, #group => $grp, mode => '0644', source => '/root/nginx.conf' } service { 'nginx': ensure => running, require => Package['nginx'], #provider => 'upstart', enable => true, subscribe => File['nginx.conf'], #start => 'service nginx start', #stop => '/usr/sbin/service nginx stop', #status => '/sbin/serv', } } Exec { path => [ '/bin/', '/sbin/' , '/usr/bin/', '/usr/sbin/' ],} exec { 'yum-update': command => 'yum -q -y update', } include nginx <file_sep>/duprofile.sh #!/bin/bash #<NAME> #2012 03 21 #V2.1 : correction sur regexp du awk #V3 : #meilleur gestion des arguments #correction de bug lié à EPOCH #modification du format de sortie #amelioration indentation et commentaires #JKE 2012 03 29 #fonction usage qui finit par sortir du script function usage { echo "$0 -t tranche -s date_debut -e date_fin -f chemin/fichier" echo "m : tranche 1 minute" echo "dix : 10 minutes" echo "h : 1 heure" echo "j : 1 jour" echo "debut sur 12 char AAAAMMJJHHmm" echo "fin sur 12 char AAAAMMJJHHmm" echo "par defaut $0 -t h -s 197001010000 -e 203801190313 -f u_fmcx50.dta" exit } #par defaut, la date de début est EPOCH debut=197001010000 #par defaut, la date de fin est la date du bug de 2038 fin=203801190313 #par defaut, on prend le fmhs dans le repertoire courant. fichier_fmcx="u_fmcx60.dta" #on positionne tranche par defaut à heure : tranche=h #on shift sur les arguments while [ $# -gt 0 ] do case $1 in -s) debut=$2 shift 2 ;; -e) fin=$2 shift 2 ;; -f) fichier_fmcx=$2 shift 2 ;; -t) tranche=$2 shift 2 ;; *) usage esac done #En fonction du premier argument, on passera le nombre de caracteres #que prend le format de date qui nous interesse. case $tranche in m|M) comptage=12 ;; dix|DIX|ten|TEN) comptage=11 ;; h|H) comptage=10 ;; j|J|d|D) comptage=8 ;; *) usage esac echo "===TimeFrame $tranche" awk -v debut=$debut -v fin=$fin -v comptage=$comptage ' BEGIN { clefd = 999999999999 ; cleff = 0 } substr($0,"1","1") ~ /[0-9A-Z_ ]/ && substr($0,"45","12") >= debut && substr($0,"45","12") <= fin { clef = substr($0,"45",comptage) ; tableau[clef] = tableau[clef] + 1 ; if ( clef > cleff ) { cleff = clef } ; if ( clef < clefd ) {clefd = clef} } END { if ( comptage==8 ) { multip=1000000 ; shift = 86400 ; format="%Y%m%d" ; opt = 1 }; if ( comptage==10 ) { multip=10000 ; shift = 3600 ; format="%Y%m%d%H" ; opt = 1 }; if ( comptage==11 ) { multip=1000 ; shift = 600 ; format="%Y%m%d%H%M" ; opt = 10 }; if ( comptage==12 ) { multip=100 ; shift = 60 ; format="%Y%m%d%H%M" ; opt = 1 }; clefd = clefd * multip ; cleff = cleff * multip ; annee0=substr(clefd,1,4) mois0=substr(clefd,5,2) jour0=substr(clefd,7,2) heure0=substr(clefd,9,2) minutes0=substr(clefd,11,2) secondes0=substr(clefd,13,2) annee1=substr(cleff,1,4) mois1=substr(cleff,5,2) jour1=substr(cleff,7,2) heure1=substr(cleff,9,2) minutes1=substr(cleff,11,2) secondes1=substr(cleff,13,2); date0=mktime(annee0" "mois0" "jour0" "heure0" "minutes0" "secondes0) ; date1=mktime(annee1" "mois1" "jour1" "heure1" "minutes1" "secondes1) ; compteur=date0 ; while (compteur <= date1) { print strftime( "%Y%m%d-%H%M",compteur) "," tableau[strftime(format,compteur)/opt]+0 ; compteur = compteur + shift } } ' $fichier_fmcx <file_sep>/download/dudmp6.sh #!/bin/bash # dudmp6 by ZWA # v1.0 09/13/2012 # As a response file can not be used for other versions of kits, # for a newer version of V6 installation # 1. generate a new response template file # 2. Or autopatch after install # v1.1 09/17/2012 # Randomize $U TCP port to allow multiple dump installation. # v1.3 To allow dump with non-standard directory structure # To allow local template, response file. # One can specify a different installation directory in the local template # Changing to KSH to adapt to different OS. # create v6_kit link in "/" # v1.4 minor fix # v1.5 do not dump the u_sync.dta #set -x -v node_=$1 company_=$2 if [ ${company_:-NONE} = NONE ] ; then echo Please specify the node name and company name echo For example, dudmp6 node1 FLS600 exit 1 fi in_use="yes" # finding a set of empty ports while [[ $in_use = "yes" ]] ; do port_=$(($(($(($((RANDOM%=90000000))%1000))*10))+10000)) echo port_ is $port_ netstat -an|grep $port_ if [ $? = 0 ] ; then in_use="yes" echo ### $port_ is in use else in_use="no" echo ### $port_ is not in use fi done local_dir_=`pwd` if [ -r /home/zwa/home/pj31_dudmp_v6/template.install.file ] ; then templ_resp_=/home/zwa/home/pj31_dudmp_v6/template.install.file response_=/apps/du/600/current.install.file else templ_resp_=$local_dir_/template.install.file response_=$local_dir_/current.install.file fi #v6_kit is a link in /apps/du/600 to the V6 kit that matches the template response file. #/apps/du/600/v6_kit/unirun -i -s -f /apps/du/600/work.install.file # Hard coded in response file # UVMS info # $U port : 12000 # NODE : NODE_DUMP # COMPANY : FLS600 # $U admin : univa # INSTALLDIR : must be in /apps/du/600/FLS600_NODE_DUMP sed "s/FLS600/$company_/" $templ_resp_|sed "s/NODE_DUMP/$node_/"|sed "s/FLS600_NODE_DUMP/${company_}_$node_/"|sed "s/12000/$port_/"> $response_ #/apps/du/600/v6_kit/unirun -i -s -f $response_ if [ -r /home/zwa/home/pj31_dudmp_v6/template.install.file ] ; then /apps/du/600/v6_kit/unirun -i -s -f $response_ else /v6_kit/unirun -i -s -f $response_ #For non-standard structure create /v6_kit link in "/" fi if [ $? -ne 0 ] ; then echo '### Installation failed' exit 1 else echo '### Installation finished' fi . /apps/du/600/${company_}_$node_/unienv.ksh # Turn off engines echo "### Turn off engines" ${UNI_DIR_EXEC}/unisetvar UNI_STARTUP_X IO,CDJ,BVS,DQM,EEP,SYN,ALM ${UNI_DIR_EXEC}/unisetvar UNI_STARTUP_S IO,CDJ,BVS,SYN,ALM ${UNI_DIR_EXEC}/unisetvar UNI_STARTUP_I IO,CDJ,BVS,SYN,ALM ${UNI_DIR_EXEC}/unisetvar UNI_STARTUP_A IO,CDJ,BVS,SYN,ALM ${UNI_DIR_EXEC}/unisetvar U_IO_PURGE_ENABLE N ${UNI_DIR_EXEC}/unisetvar X_O_DYN_PURGE N ${UNI_DIR_EXEC}/unisetvar S_O_DYN_PURGE N ${UNI_DIR_EXEC}/unisetvar I_O_DYN_PURGE N ${UNI_DIR_EXEC}/unisetvar A_O_DYN_PURGE N ${UNI_DIR_EXEC}/unistop if [ $? -ne 0 ] ; then echo '###$U failed to stop' exit 1 fi # Then load customer's data files ' echo "Please select concerned area, A,I,S or [X]" read area_ case $area_ in A|a|app) area_data_=`$UNI_DIR_EXEC/unigetvar UXDAP` area_3=app area_d=UXDAP ;; I|i|int) area_data_=`$UNI_DIR_EXEC/unigetvar UXDIN` area_3=int area_d=UXDIN ;; S|s|sim) area_data_=`$UNI_DIR_EXEC/unigetvar UXDSI` area_3=sim area_d=UXDSI ;; X|x|exp) area_data_=`$UNI_DIR_EXEC/unigetvar UXDEX` area_3=exp area_d=UXDEX ;; *) echo Default would be X area_data_=`$UNI_DIR_EXEC/unigetvar UXDEX` area_3=exp area_d=UXDEX esac bass_data_=`$UNI_DIR_EXEC/unigetvar UNI_DIR_DATA` # now should be in the DUFILES directory cd DATA mv u_sync.dta u_sync.dta_not_to_dump cp -f *.dta $bass_data_ cp -f */*.dta $bass_data_ mv u_sync/u_sync.dta u_sync/u_sync.dta_not_to_dump cp -f *.idx $bass_data_ cp -f */*.idx $bass_data_ chown univa:univ $bass_data_ cd ../$area_d cp -f *.dta $area_data_ cp -f */*.dta $area_data_ cp -f *.idx $area_data_ cp -f */*.idx $area_data_ chown univa:univ $area_data_ #read nothing echo "Do you want to run reorg? Answer [y]/n" read answer_ if [ ${answer_:-y} = y ] ; then ${UNI_DIR_EXEC}/unireorg fi # Restarting $U echo "### Starting $U" ${UNI_DIR_EXEC}/unistart if [ $? -ne 0 ] ; then echo '###$U failed to start' exit 1 fi echo "### do you want to generate the listings [y]/n" read answer_ if [ ${answer_:-y} = y ] ; then ${UNI_DIR_EXEC}/uxlst ctl full $area_3 >../../LST/dump_uxlst_ctl_full.txt & ${UNI_DIR_EXEC}/uxlst fla full $area_3 >../../LST/dump_uxlst_fla_full.txt & ${UNI_DIR_EXEC}/uxlst ctl hst $area_3 >../../LST/dump_uxlst_ctl_hst.txt & ${UNI_DIR_EXEC}/uxlst evt full $area_3 >../../LST/dump_uxlst_evt_full.txt & fi <file_sep>/download/gw6_ssl.sh #!/bin/bash #set -x -v yum -y -q install ruby ruby-libs ruby-shadow yum install curl rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm #use the new repo yum -y -q install puppet facter puppet module install jfryman/nginx curl -s -O 192.168.115.41/download/nginx_ssl.pp_template #download and store certificate curl -s -O 192.168.115.41/download/server.key curl -s -O 192.168.115.41/download/server.crt mkdir /root/sd mv ./server.* /root/sd #updating puppet script IP=$1 CID=$2 pp='nginx_ssl.pp' templ='nginx_ssl.pp_template' sed "s/$::ipaddress_eth1/$IP/" $templ|sed "s/8888/$CID/" >$pp puppet apply nginx_ssl.pp #stoping firewall /sbin/service iptables stop #enable logrotate curl -s -O 192.168.115.41/download/nginx.logrotate cp ./nginx.logrotate /etc/logrotate.d/nginx #enable heartbeat curl -s -O 192.168.115.41/download/heartbeat_ssl.sh_template hbs='heartbeat_ssl.sh' hb_templ='heartbeat_ssl.sh_template' sed "s/192.168.114.208/$IP/" $hb_templ >$hbs chmod +x ./heartbeat_ssl.sh echo '10 * * * * root ~root/heartbeat_ssl.sh' >> /etc/crontab #prepare version control echo '0'> ~/gw.version touch ~/ready_for_upgrade <file_sep>/diskusage.py import os d=dict() def disk_usage(path): st = os.statvfs(path) d['free'] = st.f_bavail * st.f_frsize d['total'] = st.f_blocks * st.f_frsize d['used'] = (st.f_blocks - st.f_bfree) * st.f_frsize return d['total'] , d['used'], d['free'] print( disk_usage('/')) print(disk_usage('/usr')) print(disk_usage('/tmp')) <file_sep>/download/gw6.sh #!/bin/bash yum -y -q install ruby ruby-libs ruby-shadow yum install curl rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm #use the new repo yum -y -q install puppet facter puppet module install jfryman/nginx curl -s -O 192.168.115.41/download/nginx.pp puppet apply nginx.pp /sbin/service iptables stop curl -s -O 192.168.115.41/download/nginx.logrotate #enable logrotate cp ./nginx.logrotate /etc/logrotate.d/nginx curl -s -O 192.168.115.41/download/heartbeat.sh #enable heartbeat chmod +x ./heartbeat.sh echo '10 * * * * root ~root/heartbeat.sh' >> /etc/crontab echo '0'> ~/gw.version touch ~/ready_for_upgrade <file_sep>/download/ttt.sh echo "This is the time stamp from SD" ts=`date` echo "This is the local time stamp on GW $ts" echo "this is 1: $1" echo "this is 2: $2" <file_sep>/sda_fun.py import subprocess def send_msg_old(msg,gw): subprocess.call(['curl','-X', 'POST', '-H','Content-Type: application/json','-d',msg,gw]) # not checking return code return msg='[{"username":"xyz","password":"xyz","something":80}]' # in JSON format gw='https://192.168.114.174/SDC/msg/' def send_msg(msg,gw): p = subprocess.Popen(['curl','-s','-k','-X','POST', '-H','Content-Type: application/json','-d',msg,gw],stdout=subprocess.PIPE) (output, err) = p.communicate() print output if '"status":"OK"' in output: return True else: return False send_msg(msg,gw) def fn2code(cfile): d=dict() with open(cfile, 'r') as f: for line in f: s=line.split() d[s[1]]=s[0] return d #print fn2code('./coding.txt') def findoutput(tmp_path): tmp_file=tmp_path + 'SD_temp.txt' with open(tmp_file, 'r') as f: for line in f: file=line return file.split('\n')[0], tmp_file #print findoutput('/home/temp/') def zip2send(tmp_path,gw): # inut: the $U_TMP_PATH. read SD_temp.txt to find the output file file,tmp_file=findoutput(tmp_path) #gw='http://192.168.114.174/SDC/upload/' out=tmp_path + file #print 'out' ,out + '==' subprocess.call(['gzip',out]) out=out+ '.gz' the_file='the_file=@' + out # compress print the_file #subprocess.call(['curl','-i','-F',the_file,gw]) # send compressed output #subprocess.call(['rm',out, tmp_file]) # delete SD_temp.txt and output p = subprocess.Popen(['curl','-k','-i','-s','-F',the_file,gw],stdout=subprocess.PIPE) (output, err) = p.communicate() #print output subprocess.call(['rm',out, tmp_file]) # delete SD_temp.txt and output if '"status":"OK"' in output: subprocess.call(['rm',out, tmp_file]) # delete SD_temp.txt and output return True else: return False #zip2send('/home/temp/') #import json from itertools import * import datetime def dup2json(fi,fo,area): ti="" # time inverval used with open(fi, 'r') as f: with open(fo, 'a') as fw: for line in f: if '===TimeFrame' in line: ti=line.split(' ')[1].split('\n')[0] # h or m, and revmoe the \n at the end ti_key='ti' + ti continue list1 = [area]+line.split('\n')[0].split(',') #print list1[1] yyyy=int(list1[1][:4]) mm=int(list1[1][4:6]) dd=int(list1[1][6:8]) hh=int(list1[1][9:11]) min=int(list1[1][11:13]) list1[1]=int(datetime.datetime(yyyy,mm,dd,hh,min).strftime('%s')) list1[2]=int(list1[2]) #print list1[1] d=dict(izip(["area",ti_key,"nexe"], list1)) fw.write(str(d)+'\n') fw.flush() #fi='/home/temp/dup.txt' #fo='/home/temp/dup2json.txt' #dup2json(fi,fo,'X') <file_sep>/sd.py from flask import Flask import datetime app = Flask(__name__) @app.route(r'/SDC/') def hello_world(): return 'Hello World!!!!! I am SD server on 03' @app.route(r'/SDC/time/') def time(): n = str(datetime.datetime.now()) return 'now is %s' % n @app.route(r'/SDC/ttt') def ttt(): return 'you asked for it.' @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % username @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id from flask import request from werkzeug import secure_filename import time @app.route('/SDC/upload/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] print f.filename f.save('/home/sd_dropbox/' + time.strftime('%H%M%S') +secure_filename(f.filename)) return 'seems to be OK :)' import smtplib def sendemail(TEXT): FROM ='root' TO = ["<EMAIL>", "<EMAIL>","<EMAIL>","<EMAIL>","<EMAIL>"] # this is List of Email Ids SUBJECT='Warning message from SD system' #TEXT = "This message was sent with Python's smtplib. ..." print 'TEXT',TEXT TEXT= " " + TEXT + " " server=smtplib.SMTP('127.0.0.1',25) server.sendmail(FROM,TO, TEXT) server.quit() @app.route('/SDC/msg/', methods=['GET', 'POST']) def receive_msg(): if request.method == 'POST': print request.data sendemail(request.data) return 'msg received!' @app.route('/SDC/download/', methods=['GET', 'POST']) def download(): return 'not working yet' if __name__ == '__main__': app.debug=True app.run('0.0.0.0',6000) <file_sep>/download/version_x_upgrade.sh #!/bin/bash #To be used for the GW update #to upload the file to server: #curl -F "file=@version_x_upgrade.sh" http://192.168.115.41/SDC/gateway if [ -f ~/ready_for_upgrade ] ; then echo "ready for upgrade!" # remove the file during the upgrade # then, put it back after the upgrade # touch ~/ready_for_upgrade else echo "upgrade on going!" fi v=`cat ~/gw.version` let v+=1 echo $v > ~/gw.version <file_sep>/download/Untaz #!/bin/bash ################################################################### # Uncompress the most common compressed file formats ################################################################### ## # revision : 0.8.0 # date : 20030202 # author : <NAME> (Orsyp Inc) # modifs : Creation ## # revision : 0.9.0 # date : 20030202 # author : <NAME> (Orsyp Inc) # modifs : Update # : Management of the uxtrace results g_vers="0.9.0" g_prog=$0 #ux_no_rm=on if [ $# -eq 0 ] then Taz_Liste=`ls ./*.Z ./*.tar ./*.gz ./*.taz ./*.zip ./*.ZIP 2> /dev/null` echo " In the directory `pwd` the following files will be uncompressed : " echo "${Taz_Liste}" echo "Is it OK ? (y)" read l_answer [ "${ReEnv:-y}" = "y" ] || exit 1 else Taz_Liste="$*" fi which uncompress > /dev/null 2>&1 [ $? -eq 0 ] && ux_uncompress=uncompress [ $? -eq 0 ] || ux_uncompress="gzip -d" for Taz_File in ${Taz_Liste} do echo ${Taz_File} | grep '\.Z$' > /dev/null 2>&1 && type=Z echo ${Taz_File} | grep '\.gz$' > /dev/null 2>&1 && type=gz echo ${Taz_File} | grep '\.tar$' > /dev/null 2>&1 && type=tar echo ${Taz_File} | grep '\.taz$' > /dev/null 2>&1 && type=taz echo ${Taz_File} | grep '\.tar\.Z$' > /dev/null 2>&1 && type=tar.Z echo ${Taz_File} | grep '\.tar\.gz$' > /dev/null 2>&1 && type=tar.gz echo ${Taz_File} | grep '\.zip$' > /dev/null 2>&1 && type=zip echo ${Taz_File} | grep '\.ZIP$' > /dev/null 2>&1 && type=ZIP case ${type} in Z ) echo "Uncompressing ${Taz_File}" uncompress ./${Taz_File} ;; gz ) echo "Uncompressing ${Taz_File}" gzip -d ./${Taz_File} ;; tar ) echo "Uncompressing ${Taz_File}" tar -xf ./${Taz_File} echo ${Taz_File} | grep 'TMP_.*_uxtrace_' > /dev/null 2>&1 l_rc=$? if [ ${l_rc:-1} -eq 0 ]; then l_dir=`echo ${Taz_File} | sed -e 's/.*TMP_/TMP_/' | sed -e 's/\.tar$//'` if [ -d ${l_dir} ]; then cd ${l_dir} echo "Uncompressing the first subdirectories level of the uxtrace result" ${g_prog} cd .. fi fi [ ${ux_no_rm:-off} = off ] && rm ./${Taz_File} ;; taz ) echo "Uncompressing ${Taz_File}" mv ./${Taz_File} ./${Taz_File}.tar.Z ${ux_uncompress} ./${Taz_File}.tar.Z tar -xf ./${Taz_File}.tar echo ${Taz_File} | grep 'TMP_.*_uxtrace_' > /dev/null 2>&1 l_rc=$? if [ ${l_rc:-1} -eq 0 ]; then l_dir=`echo ${Taz_File} | sed -e 's/.*TMP_/TMP_/' | sed -e 's/\.taz$//'` if [ -d ${l_dir} ]; then cd ${l_dir} echo "Uncompressing the first subdirectories level of the uxtrace result" ${g_prog} cd .. fi fi [ ${ux_no_rm:-off} = off ] && rm ./${Taz_File}.tar ;; tar.Z ) echo "Uncompressing ${Taz_File}" mv ./${Taz_File} ./${Taz_File}.tar.Z ${ux_uncompress} ./${Taz_File}.tar.Z tar -xf ./${Taz_File}.tar echo ${Taz_File} | grep 'TMP_.*_uxtrace_' > /dev/null 2>&1 l_rc=$? if [ ${l_rc:-1} -eq 0 ]; then l_dir=`echo ${Taz_File} | sed -e 's/.*TMP_/TMP_/' | sed -e 's/\.tar\.Z$//'` if [ -d ${l_dir} ]; then cd ${l_dir} echo "Uncompressing the first subdirectories level of the uxtrace result" ${g_prog} cd .. fi fi [ ${ux_no_rm:-off} = off ] && rm ./${Taz_File}.tar ;; tar.gz ) echo "Uncompressing ${Taz_File}" mv ./${Taz_File} ./${Taz_File}.tar.gz gzip -d ./${Taz_File}.tar.gz tar -xf ./${Taz_File}.tar l_dir=`echo ${Taz_File} | sed -e 's/.*TMP_/TMP_/' | sed -e 's/\.tar\.gz$//'` echo ${Taz_File} | grep 'TMP_.*_uxtrace_' > /dev/null 2>&1 l_rc=$? if [ ${l_rc:-1} -eq 0 ]; then if [ -d ${l_dir} ]; then cd ${l_dir} echo "Uncompressing the first subdirectories level of the uxtrace result" ${g_prog} cd .. fi fi [ ${ux_no_rm:-off} = off ] && rm ./${Taz_File}.tar ;; zip ) echo "Uncompressing ${Taz_File}" loc_dir_name=`echo ${Taz_File} | sed 's/\.'${type}'$//'` mkdir ./${loc_dir_name} mv ./${Taz_File} ./${loc_dir_name}/ cd ./${loc_dir_name} unzip ./${Taz_File} [ ${ux_no_rm:-off} = off ] && rm ./${Taz_File} cd .. ;; ZIP ) echo "Uncompressing ${Taz_File}" loc_dir_name=`echo ${Taz_File} | sed 's/\.'${type}'$//'` mkdir ./${loc_dir_name} mv ./${Taz_File} ./${loc_dir_name}/ cd ./${loc_dir_name} unzip ./${Taz_File} [ ${ux_no_rm:-off} = off ] && rm ./${Taz_File} cd .. ;; * ) echo "${Taz_File} file format is not supported" ;; esac done <file_sep>/download/gw5.sh #For CentOS 5 i386 #!/bin/bash yum -y -q install ruby ruby-libs ruby-shadow #-y: to always answer 'y' rpm -ivh http://yum.puppetlabs.com/el/5/products/i386/puppetlabs-release-5-7.noarch.rpm # to build puppet repository yum -y -q install puppet facter # -q to install quietly puppet module install jfryman/nginx curl -s -O 192.168.115.41/download/nginx.pp # -s: silent mode puppet apply nginx.pp /sbin/service iptables stop curl -s -O 192.168.115.41/download/nginx.logrotate #enable logrotate cp ./nginx.logrotate /etc/logrotate.d/nginx <file_sep>/download/gw6_heroku.sh #!/bin/bash #set -x -v heroku_link='https://s3-us-west-2.amazonaws.com/smoke-detector-staging/scripts' yum -y -q install ruby ruby-libs ruby-shadow yum install curl rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm #use the new repo yum -y -q install puppet facter #puppet module install jfryman/nginx curl -s -O ${heroku_link}/nginx_heroku.pp curl -s -O ${heroku_link}/nginx.conf_template #download and store certificate curl -s -O ${heroku_link}/server.key curl -s -O ${heroku_link}/server.crt mkdir /root/sd mv ./server.* /root/sd #updating puppet script IP=$1 CID=$2 conf='nginx.conf' templ='nginx.conf_template' sed "s/192.168.114.208/$IP/" $templ|sed "s/8888/$CID/" >$conf puppet apply nginx_heroku.pp #stoping firewall /sbin/service iptables stop #enable logrotate curl -s -O ${heroku_link}/nginx.logrotate cp ./nginx.logrotate /etc/logrotate.d/nginx #enable heartbeat curl -s -O ${heroku_link}/heartbeat_heroku.sh_template hbs='heartbeat_heroku.sh' hb_templ='heartbeat_heroku.sh_template' sed "s/192.168.114.208/$IP/" $hb_templ >$hbs chmod +x ./heartbeat_heroku.sh echo '10 * * * * root ~root/heartbeat_heroku.sh' >> /etc/crontab #prepare version control echo '0'> ~/gw.version touch ~/ready_for_upgrade ./heartbeat_heroku.sh rm nginx.logrotate rm *template rm *conf rm *pp <file_sep>/download/nginx.pp #include nginx #node default { class { 'nginx': } #} nginx::resource::upstream { 'proxy': ensure => present, members => [ 'casplda02:443', ], } nginx::resource::vhost { "$::ipaddress_eth0": ensure => present, proxy => 'https://proxy', proxy_set_header => [ 'Customer-Id 8908', 'User-Agent SD_TRAFFIC', ] } nginx::resource::vhost { "$::ipaddress_eth1": ensure => present, proxy => 'https://proxy', proxy_set_header => [ 'Customer-Id $2a$10$4KV/PGdp1ibfXEnOxdffKehVia905Hzldfp0t8MRKr3kIZnwG0mEG', 'User-Agent SD_TRAFFIC', ] } #nginx::resource::vhost { "$::ipaddress_eth2": # ensure => present, # proxy => 'https://proxy', #} # server_name =>['GW'], # listen_port => 80, #ssl => true, #ssl_cert => '/root/sd/server.crt', #ssl_key => '/root/sd/server.key', #}
cb6f82518646918c562602a62122adf8fff316f9
[ "Puppet", "Shell", "Python" ]
16
Puppet
wzbbbb/SD
fa84820be789d65bdded0152a9013a2d8ed4836e
dab7b89440367231fdc9105a6405d32a8d597f93
refs/heads/master
<repo_name>imagineux/Pattrn<file_sep>/stylesheets/pattrn/functions/lib/_string-to-number.sass // Converts number[unit] string into value // ------------------------------------------------------------------------------- // @documentation http://hugogiraudel.com/2014/01/15/sass-string-to-number/ // ------------------------------------------------------------------------------- // @param $number [string] : number // @param $unit [string] : unit // ------------------------------------------------------------------------------- // @return [number] @function num-length($number, $unit) $strings: 'px' 'cm' 'mm' '%' 'ch' 'pica' 'in' 'em' 'rem' 'pt' 'pc' 'ex' 'vw' 'vh' 'vmin' 'vmax' $units: 1px 1cm 1mm 1% 1ch 1pica 1in 1em 1rem 1pt 1pc 1ex 1vw 1vh 1vmin 1vmax $index: index($strings, $unit) @if not $index @warn "Unknown unit `#{$unit}`." @return false @return $number * nth($units, $index) // Converts number to string // ------------------------------------------------------------------------------- // @documentation http://hugogiraudel.com/2014/01/15/sass-string-to-number/ // ------------------------------------------------------------------------------- // @dependence `num-length()` // ------------------------------------------------------------------------------- // @param $string [String] : string // ------------------------------------------------------------------------------- // @return [Value] @function to-number($string) // Matrices $strings: '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' $numbers: 0 1 2 3 4 5 6 7 8 9 // Result $result: 0 $divider: 0 $minus: false // Looping through all characters @for $i from 1 through str-length($string) $character: str-slice($string, $i, $i) $index: index($strings, $character) @if $character == '-' $minus: true @else if $character == '.' $divider: 1 @else @if not $index $result: if($minus, $result * -1, $result) @return num-length($result, str-slice($string, $i)) $number: nth($numbers, $index) @if $divider == 0 $result: $result * 10 @else // Move the decimal dot to the left $divider: $divider * 10 $number: $number / $divider $result: $result + $number @return if($minus, $result * -1, $result)<file_sep>/stylesheets/pattrn/functions/lib/_last.sass // Get last item in list // ------------------------------------------------------------------------------- // @param $list [list] : list // ------------------------------------------------------------------------------- // @return [list] @function last($list) @return nth($list, length($list))<file_sep>/stylesheets/pattrn/functions/lib/_string-to-list.sass // Turns string into a flat list // ------------------------------------------------------------------------------- // @param $string [string] : string // @param $find [string] : item to find which separates substrings (default is single space [" "]) // @param $ignore [string] : removes remaining string beyond item (default is comma [","]) // ------------------------------------------------------------------------------- // @return [list] | error @function string-to-list($string, $find: " ", $ignore: ",") @if is-string($string) $string-list: () $space-indexes: () $ignore-remainder: () $length: str-length($string) // Find ignore separator, and remove remainder of string beyond that point @for $i from 1 through $length $slice: str-slice($string, $i, $i) @if $slice == $ignore $ignore-remainder: append($ignore-remainder, $i - 1, "comma") // Redefine string and length @if length($ignore-remainder) >= 1 $string: str-slice($string, 1, nth($ignore-remainder, 1)) $length: str-length($string) // Find all spaces and their indices by looking over each character in string @for $i from 1 through $length $slice: str-slice($string, $i, $i) @if $slice == $find $space-indexes: append($space-indexes, $i, "comma") // Check if there are any spaces @if length($space-indexes) >= 1 // Keep a count of number of spaces $count: 1 // Loop through each space @each $space in $space-indexes // If is initial count, grab first substring and store in list @if $count == 1 $matched-string: str-slice($string, 0, ($space - 1)) $string-list: append($string-list, $matched-string, "comma") // Else, add a little math to make up for the spaces to do the same @else $matched-string: str-slice($string, (nth($space-indexes, ($count - 1)) + 1), ($space - 1)) $string-list: append($string-list, $matched-string, "comma") // Increase count $count: $count + 1 // Now grab that last selector $last-space: nth($space-indexes, length($space-indexes)) $matched-string: str-slice($string, ($last-space + 1), $length) $string-list: append($string-list, $matched-string, "comma") // Finally, return comma separated list of selectors @return $string-list @else // Else, just return the string as a single item list $string-list: append($string-list, $string) @return $string-list @else @return "You did not input a valid string: #{$string}" <file_sep>/stylesheets/pattrn/config/iphone-5.scss $iphone-5:( "display":( "PPI": 326, "color-mode": "RGB", "temperature": "warm", ), "resolution":( "portrait":( height: 640, width: 1136, ), "landscape":( width: 1136, height: 640, ), ), "icons":( "app":( height: 144px, width: 144px, border-radius: 25.263px, ), "store":( height: 1024, width: 1024, border-radius: 179.649, ), "spotlight":( height: 58, width: 58, border-radius: 10.175, ), "settings":( height: 58, width: 58, ), "tab-bar":( height: 60, width: 60, ), ), "ui":( "status-bar": 40, "navigation-bar":( "portrait":( height: 88, "gutter": 16, ), "landscape":( height: 64, "gutter": 32, ), ), "tab-bar": 98, "table-views":( "portrait":( width: 640, height: 88px, "gutter": 30, ), "landscape":( width: 1136, height: 88px, "gutter": 30, ), ), ), "typography":( font-family: : $HelveticaNeue, "navigation-bar-title":( font-size: : 34, font-family: $HelveticaNeue-Medium, ), "regular-buttons":( font-size: : 34, font-family: $HelveticaNeue-Light, ), "table-header":( font-size: : 34, font-family: $HelveticaNeue-Light, ), "table-label":( font-size: : 28, font-family: $HelveticaNeue, ), "tab-bar-icon":( font-size: : 20, font-family: $HelveticaNeue, ), ), "colors":( $gray: rgb(142, 142, 147), $bright-red: rgb(255, 45, 85), $red: rgb(255, 59, 48), $orange: rgb(255, 149, 0), $yellow: rgb(255, 204, 0), $green: rgb(76, 217, 100), $light-blue: rgb(90, 200, 250), $blue: rgb(52, 170, 220), $dark-blue: rgb(0, 122, 255), $purple: rgb(88, 86, 214), ), ) !default;<file_sep>/pattrn.gemspec require './lib/pattrn' Gem::Specification.new do |s| # Release Specific Information s.version = Pattrn::VERSION s.date = Pattrn::DATE # Gem Details s.name = "pattrn" s.rubyforge_project = "pattrn" s.licenses = ['MIT'] s.authors = ["<NAME>"] s.email = ["<EMAIL>"] s.homepage = "https://github.com/imagineux/pattrn/" # Project Description s.summary = %q{iOS 7 Design cheat Sheet for assisting in rapid prototyping.} s.description = %q{Pattrn is Design as iOS prototyoing accelerator; it includes many useful shortcuts for Layout / Typography / Iconography.} # Library Files s.files += Dir.glob("lib/**/*.*") # Sass Files s.files += Dir.glob("stylesheets/**/*.*") # Template Files # s.files += Dir.glob("templates/**/*.*") # Other files s.files += ["LICENSE", "README.md"] # Gem Bookkeeping s.required_rubygems_version = ">= 1.3.6" s.rubygems_version = %q{1.3.6} # Gems Dependencies s.add_dependency("sass", [">=3.3.0"]) s.add_dependency("compass", [">= 0.12.1"]) end<file_sep>/stylesheets/pattrn/functions/lib/_exists.sass // Check if key exists in map //-------------------------------------------------------------------------------- // @param $map [map] : map that contains $value // @param $value [string] : key to search for // ------------------------------------------------------------------------------- // @return [bool] @function exists($map, $value) @if is-map($map) @if map-has-key($map, $value) @return true @each $key, $i in $map @if exists($i, $value) @return true @return false<file_sep>/CHANGELOG.md # Changelog * `#1` Create changelog and document format ## 0.0.1 * `#0` Do something else, that happens after 0<file_sep>/lib/pattrn.rb require 'compass' extension_path = File.expand_path(File.join(File.dirname(__FILE__), "..")) Compass::Frameworks.register('pattrn', :path => extension_path) # Version is a number. If a version contains alphas, it will be created as a prerelease version # Date is in the form of YYYY-MM-DD module Pattrn VERSION = "0.0.1" DATE = "2014-06-28" end # Custom functions module Sass::Script::Functions def selector_string() return Sass::Script::String.new(environment.selector.to_s) end end <file_sep>/README.md #Pattrn **Pattrn is Design as iOS prototyoing accelerator; it includes many useful shortcuts for Layout / Typography / Iconography.** Built on Sass 3.3, Pattrn aims to makes ios& design standards more accesible and easy to implement.
2da2089274c29c7ea2cebe81ced7e02e0e6d1ea2
[ "SCSS", "Markdown", "Sass", "Ruby" ]
9
SCSS
imagineux/Pattrn
2f26c5e117391e02b27868d46966870d00d4618b
2362a8b63e810b3b9063b397e8185208a2dd80d1
refs/heads/master
<repo_name>groverz/RMagickCaptcha<file_sep>/README.md ##RMagickCaptcha RMagickCaptcha is a gem that implements captcha for using in Rails application. The gem provides functionality to create a captcha image and validate user's input. * The gem allows multiple captchas at the same page * The gem supports I18n and provides locale resource * The gem provides rmagick_captcha controller controller to generate images * The gem allows ... ##Quick Start 1. In your Gemfile: gem "rmagick_captcha", ">= 0.6.2" 2. In your model: # Server create captcha_key, user input into captcha_text has_rmagick_captcha :captcha validate :validate_rmagick_captcha 3. In your controller: download_rmagick_catcha :show def new @user = User.new session[:user_captcha] = @user.reset_captcha_key end def create @user = User.new(params[:user]) @user.captcha_key = session[:user_captcha] @user.save if @user.errors.empty? session[:user_captcha] = nil redirect_back_or_default('/welcome') flash[:notice] = "Thanks for signing up!" else session[:user_captcha] = @user.reset_captcha_key render :action => 'new' end end 4. In your views: <% form_for @user, :url => users_path, :html => {:id => "user_form", :class => "html-form" } do |f| %> <fieldset> <ul> <li> <%= rmagick_captcha_tag(:controller => "user", :id => "user_captcha") %> <%= f.text_field :captcha_text, :maxlength => 16%> <%= f.error_message_on :captcha_text %> </li> </ul> <%= f.submit "Submit"%> </fieldset> <% end %> 5. In your routes.rb: match 'user(/show)' => 'user#show', :as => :captcha 6. If you wish: * Run `ruby script/rails generate rmagick_captcha` to gen resources such as locale files. * Use `config/initiaizers` to configure options for this gem ##Example Example goes here. Copyright (c) 2011 arufanov, released under the MIT license.
1727ba13046e7922a1c228f827a5d209ae34f727
[ "Markdown" ]
1
Markdown
groverz/RMagickCaptcha
dc825746978283a7ba8c3104a62f1e327fa4d291
6ca2fa083e3e54636be4160e083d5c7d6355815c
refs/heads/master
<file_sep>// // CustomTableViewCell.swift // Dynamic Height TableView // // Created by Loka on 07/05/2016. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class CustomTableViewCell: UITableViewCell { @IBOutlet weak var longTextLabel: UILabel! }
0272a4d752e25851fc1d807e809dcd96332348cb
[ "Swift" ]
1
Swift
lokakien/dynamic-height-for-tableview
f62bcd52d46ec68e84a98863aa2b44702003381d
6efadaa400f5e3a4121fa30421b1fd6ccb50f3f5
refs/heads/master
<repo_name>diggersheep/Thread_C_basique<file_sep>/README.md # Thread C basique Petit mémo de base pour les threads en C/ (POXIX, C11, OMP) # Définition **Processus léger** : chaque *thread* poursuit une action propre. Plusieurs *threads* se partagent un __même espace mémoire__, mais chacun d'entre eux à sa __propre pile d'éxécution__. # Création d'un thread Dans tous les exemples on utilisera la fonction `maFonctionThread` comme fonction appelés par chaque thread. Elle se définie comme suit : ```C int maFonctionThread ( void * data ) { // comme on utilisera toujours un int, on s'embête pas, on cast ! printf("mon id est : %d\n", (int)id); return 0; //terminaison normale } ``` ## Avec `C11` On utilise ici le type `thread_t`, structure contentant toutes les informations nécessaire au thread. Pour lancer un thread il *"suffis"* d'utiliser la fonction `int thrd_create(thread, func, arg_func)` qui prends 3 arguments: * le pointeur vers un `thread_t` (ici un élément du tableau `id`). * la fonction de *callback* qui sera lancée lors de la création du thread, elle renvoie un `int`, et prends un d'arguments qui est un `void *`, soit, tout et n'importe quoi. * l'argument qui sera envoyé à la fonction du paramètre d'avant, donc, vraiment tout ce que tu veux ! Le thread est ainsi lancé et sera exécuté immédiatement, pour pouvoir les syncrhonisés, équivalent à dire attendre la fin de tous, il faudra utiliser la fonction `int thrd_join( thread, res )`, prevant deux arguments, dont le premier est le thread que l'on veut attendre et `res` un paramètre qu'on mettre à `NULL` pour simplifier les choses. Cette fonction renvoie un `int` prenant deux valeurs : * `thrd_success` qui comme son nom l'indique, exprime le succès * `thrd_error` qui comme son nom l'indique aussi, exprime l'échec ```C #include <threads.h> // important pour pour compliler quand même ;) #define N 8 int main ( void ) { thread_t id[N] //boucle de création for ( int i = 0 ; i < (int)N ; i++ ) { int err = thread_t id[i] = (thrd_create(&id[i], maFonctionThread, &id)); // check de la possibilité d'erreur if (err != thrd_success) { printf("Le thread #%d a grave merdé :/", i); reuturn 1; // sort du programme avec un code d'erreur } } // synchro des threads for ( int i = 0 ; i < N ; i++ ) { thrd_join(id[i], NULL); } return 0; // fin } ``` ## Avec `POSIX` Les threds `POSIX` sont très similaires aux threads `C11`, c'est pourquoi on ne fera pas de copié/collé de la partie précédente. ainsi, il faudra *"juste"* remplacer les mots clés suivant : - `thrd_t` par `pthread_t` - `thrd_create` par `pthread_create` - `thrd_join` par `pthread_join` L'avantage de la norme `POSIX` est d'être une méthode portable d'utiliser les threads, malgré le fait que la version `C11` est plus "standard" car une révision de la bibliothèque standard de 2011, donc implémenté sur tous les systèmes d'exploitation moderne. # Mutex ou Exclusions Mutuelles ## Avec `C11` ## Avec `POSIX` ## Création de Cémaphore avec `POSIX` ## Se simplifier la vie avec `OPEN MP`
32480aa0fe5cf7e35234f2c633614f2f6e78c88b
[ "Markdown" ]
1
Markdown
diggersheep/Thread_C_basique
69637c302c0ebf0191d3d167fb6c93ef8ea72f6c
fc8aa783aa273dce0e0a9a4d6d5ef978f7a5b29f
refs/heads/master
<file_sep>(() => { const uri = new URL(location.href); document.querySelector('.versions').addEventListener('change', function() { uri.hash = ''; let path = this.options[this.options.selectedIndex].dataset.url; if (undefined === path) { return; } uri.pathname = path; location.href = uri.toString(); }, false); document.querySelectorAll("main h2[id]").forEach((heading) => { uri.hash = heading.id; let link = document.createElement("a"); link.className = "header-permalink"; link.title = "Permalink"; link.href = uri.toString(); link.innerHTML = "&#182;"; heading.appendChild(link); }); })();<file_sep>--- layout: default title: Release Notes redirect_from: - /changelog/ - /upgrading/changelog/ --- # Upgrading We've tried to cover all backward compatible breaks from 5.0 through to the current MAJOR stable release. If we've missed anything, feel free to create an issue, or send a pull request. You can also refer to the information found in the [CHANGELOG.md](https://github.com/thephpleague/csv/blob/master/CHANGELOG.md) file attached to the library. - [Upgrading guide from 8.x to 9.x](/9.0/upgrading/) - [Upgrading guide from 7.x to 8.x](/8.0/upgrading/) - [Upgrading guide from 6.x to 7.x](/7.0/upgrading/) - [Upgrading guide from 5.x to 6.x](/upgrading/6.0/) # Release Notes {% for release in site.github.releases %} ## {{ release.name }} - {{ release.published_at | date: "%Y-%m-%d" }} {{ release.body | replace:'```':'~~~' | markdownify }} {% endfor %}
7d433a5840efbedcd8715eab142d3516fe061f6e
[ "Markdown", "JavaScript" ]
2
Markdown
osforge/csv
820276ea278f38d57d9a13ffd7c3fa63f3949d69
7e57a6fa12bd0ed445bae77970df00cdbd3285eb
refs/heads/master
<repo_name>elisandrade21/in940-ProjetoNoSQL<file_sep>/src/population/population.js const log = typeof console === 'undefined' ? print : console.log const read = typeof require === 'undefined' ? cat : require('fs').readFileSync const isMongo = typeof require === 'undefined' function bucketGenerator(elements, properties, mapper) { const buckets = {} const getBucket = (buckets, values) => { let cursor = buckets values.forEach((value, i) => { if (cursor[value] == undefined) cursor[value] = i === values.length - 1 ? [] : {} cursor = cursor[value] }) return cursor } elements.forEach(element => { const values = properties.map(property => typeof property === 'string' ? element[property] : property(element) ) getBucket(buckets, values).push(mapper(element)) }) return buckets } function gaussianGenerator(mean = 0, std = 1) { return ([...new Array(6)].reduce(value => value + Math.random(), 0) - 3) * std + mean } function randomDateGenerator(from, to = new Date()) { return new Date(+from + Math.random() * (+to - +from)) } function randomSample(samples) { return samples[Math.round(Math.random() * (samples.length - 1))] } function gaussianRandomSample(samples, mean, std) { mean = mean == undefined ? samples.length / 2 : mean std = std == undefined ? samples.length / 4 : std return samples[Math.max(0, Math.min(samples.length - 1, Math.round(gaussianGenerator(mean, std))))] } const randomCpfs = [...new Array(10000)].map(() => Math.floor(10000000000 + Math.random() * 99999999999)) function randomCpf() { return randomCpfs.pop() } const randomCnhs = [...new Array(10000)].map(() => Math.floor(10000000000 + Math.random() * 90000000000)) function randomCnh() { return randomCnhs.pop() } const rawVehicles = JSON.parse(read('./vehicles.json')) const colors = ['white', 'gray', 'black', 'silver', 'red', 'blue'] function randomVehicle() { return Object.assign({}, randomSample(rawVehicles), { year: Math.min(Math.round(gaussianGenerator(2015, 2)), new Date().getFullYear()), color: randomSample(colors) }) } const rawPeople = JSON.parse(read('./people.json')).results const states = [...new Set(rawPeople.map(p => p.location.state))] const cities = [...new Set(rawPeople.map(p => p.location.city))] const streets = [...new Set(rawPeople.map(p => p.location.street))] const driverRatio = 0.05 const rawDrivers = rawPeople.slice(0, Math.floor(rawPeople.length * driverRatio)) const drivers = {} rawDrivers.forEach((rawDriver, i) => { log('creating driver', i) const cpf = randomCpf() drivers[cpf] = { cpf, name: `${rawDriver.name.first} ${rawDriver.name.last}`, email: rawDriver.email, pwd: <PASSWORD>, address: { state: rawDriver.location.state, city: rawDriver.location.city, street: rawDriver.location.street }, phone: Math.random() < 0.5 ? [rawDriver.phone, rawDriver.cell] : [rawDriver.phone], cnh: { number: randomCnh(), expire: randomDateGenerator( new Date(new Date().getFullYear() + 1, 1), new Date(new Date().getFullYear() + 5, 12) ), type: randomSample(['ab', 'b', 'c', 'd']) } } }) const driversVehicles = {} Object.keys(drivers).forEach(cpf => (driversVehicles[cpf] = randomVehicle())) const driversStateBuckets = bucketGenerator( Object.keys(drivers).map(cpf => drivers[cpf]), [d => d.address.state], d => d ) const rawPassengers = rawPeople.slice(Math.floor(rawPeople.length * driverRatio) + 1) const passengers = {} rawPassengers.forEach((rawPassenger, i) => { log('creating passenger', i) const cpf = randomCpf() passengers[cpf] = { cpf, name: `${rawPassenger.name.first} ${rawPassenger.name.last}`, email: rawPassenger.email, pwd: <PASSWORD>, address: { state: rawPassenger.location.state, city: rawPassenger.location.city, street: rawPassenger.location.street }, phone: Math.random() < 0.5 ? [rawPassenger.phone, rawPassenger.cell] : [rawPassenger.phone] } }) const passengersStateBuckets = bucketGenerator( Object.keys(passengers).map(cpf => passengers[cpf]), [d => d.address.state], d => d ) if (isMongo) { // use carservice const carServiceDB = db.getSiblingDB('carservice') db = carServiceDB db.createCollection('people') const driversList = Object.keys(drivers).map(cpf => drivers[cpf]) db.people.insert(driversList) const passengersList = Object.keys(passengers).map(cpf => passengers[cpf]) db.people.insert(passengersList) log('people persistence done') } const driversIdsStateBuckets = {} const passengersIdsStateBuckets = {} if (isMongo) { states.forEach(state => { driversIdsStateBuckets[state] = db.people .find({ 'address.state': state, cnh: { $exists: true } }) .map(p => p._id) }) states.forEach(state => { passengersIdsStateBuckets[state] = db.people .find({ 'address.state': state, cnh: { $exists: false } }) .map(p => p._id) }) } const driversIdsVehicles = {} if (isMongo) db.people.find({ cnh: { $exists: true } }).forEach(p => (driversIdsVehicles[p._id] = driversVehicles[p.cpf])) const trips = [] const tripCount = 100000 for (let i = 0; i < tripCount; i++) { log(`generating trip ${i}`) const state = gaussianRandomSample(states) const pickupCity = gaussianRandomSample(cities) const destinationCity = gaussianRandomSample(cities) const pickupStreet = gaussianRandomSample(streets) const destinationStreet = gaussianRandomSample(streets) const pickupAddress = { state, city: pickupCity, street: pickupStreet } const destinationAddress = { state, city: destinationCity, street: destinationStreet } const distance = gaussianGenerator(8, 2) const estimatedValue = Math.max(6, 2 + distance * 1.5) const finalValue = Math.max(6, estimatedValue * (Math.random() * 0.4 + 0.8)) const date = randomDateGenerator(new Date(2010, 1, 1)) let driver = gaussianRandomSample(isMongo ? driversIdsStateBuckets[state] : driversStateBuckets[state]) let passenger = gaussianRandomSample(isMongo ? passengersIdsStateBuckets[state] : passengersStateBuckets[state]) const vehicle = isMongo ? driversIdsVehicles[driver]: driversVehicles[driver.cpf] const payment = { method: randomSample(['credit', 'debit', 'cash']), tip: randomSample([1, 2, 5]) } const rating = Math.min(Math.floor(gaussianGenerator(4, 1)), 5) trips.push({ pickupAddress, destinationAddress, distance, estimatedValue, finalValue, date, driver, passenger, vehicle, payment, rating }) } log('generation done') // MONGO ONLY if (isMongo) { // use carservice const carServiceDB = db.getSiblingDB('carservice') db = carServiceDB db.createCollection('trips') db.trips.insert(trips) log('persistence done') } <file_sep>/src/updates.js // use carservice db = db.getSiblingDB('carservice') // Adicionar endereço de uma pessoa const name = '<NAME>' // before db.people.find({ name }) db.people.updateOne({ name }, { $set: { 'address.state': 'pernambuco' } }) // after db.people.find({ name }) // corrigir valor estimado dos das corridas com valores estimados maior que 20 atuais em 5% db.trips.update({ estimatedValue: { $gt: 20 } }, { $mul: { estimatedPrice: 1.05 } }) // atualizando um destino utilizando save db.trips.save({ "pickupAddress" : { "state" : "pernambuco", "city" : " recife", "street" : "380 av general polidoro" }, "destinationAddress" : { "state" : "paraiba", "city" : "sao joao do rio do peixe", "street" : "19 rua edite ferreira" }, "distance" : 8.391662323696502, "estimatedValue" : 14.087493485544753, "finalValue" : 15.600647495614673, "date" :"2012-10-20", "driver" : ObjectId("5d227be0181cd090fb127224"), "passenger" : ObjectId("5d227be0181cd090fb127ac5"), "vehicle" : { "brand" : "toyota", "model" : "etios", "year" : 2018, "color" : "white" }, "payment" : { "method" : "credit", "tip" : 5 }, "rating" : 3 }) <file_sep>/src/queries.js // use carservice db = db.getSiblingDB('carservice') // proporção de viagens cujo rating foi 5 print(db.trips.count({ rating: 5 }) / db.trips.count()) // listar ids dos passageiros das viagens com 12 ou mais quilometros de distância db.trips.find({ distance: { $gte: 12 } }, { passenger: 1, distance: 1 }).pretty() // same query with $where db.trips .find( { $where: function() { return this.distance >= 12 } }, { passenger: 1, distance: 1 } ) .pretty() // listar os estados por maior quantidade de viagens feitas db.trips.aggregate([{ $group: { _id: '$pickupAddress.state', count: { $sum: 1 } } }, { $sort: { count: -1 } }]) // listar motoristas e seus estados, ordenados pelo faturamento do motorista db.trips.aggregate([ { $lookup: { from: 'people', localField: 'driver', foreignField: '_id', as: 'driver' } }, { $unwind: '$driver' }, { $group: { _id: { cpf: '$driver.cpf', name: '$driver.name', state: '$driver.address.state' }, total: { $sum: '$finalValue' } } }, { $sort: { total: -1 } } ]) // ordenar os estados pela nota médias das viagens - limitar a 5 db.trips.aggregate( [ { $group: { _id: {asdf: '$pickupAddress.state'}, avg: {$avg: '$rating' } } }, { $sort: { avg: -1 } }, { $limit: 5 } ] ) //corrida mais longa por estado cujo o valor final foi menor que o valor estimado db.trips.aggregate( [ { $match: { $expr: { $gt: ['$estimatedValue', '$finalValue'] } } }, { $group: { _id: '$pickupAddress.state', distance: {$max: '$distance'} } } ] ) // listar motoristas do estado de pernambuco apenas, ordenados pelo faturamento do motorista db.trips.aggregate([ { $lookup: { from: 'people', localField: 'driver', foreignField: '_id', as: 'driver' } }, { $unwind: '$driver' }, { $match: { 'driver.address.state': 'pernambuco' } }, { $group: { _id: { name: '$driver.name', state: '$driver.address.state', cpf: '$driver.cpf' }, total: { $sum: '$finalValue' } } }, { $sort: { total: -1 } } ]) // cpf de motoristas que possuem carro a partir de 2018 db.trips.aggregate([ { $match: { 'vehicle.year': { $gte: 2018 } } }, { $lookup: { from: 'people', localField: 'driver', foreignField: '_id', as: 'driver' } }, { $unwind: '$driver' }, { $group: { _id: { cpf: '$driver.cpf', carYear: '$vehicle.year' } } } ]) // quantidade de viagens que os passageiros fizeram entre 2015 e 2017 db.trips.aggregate([ { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$passenger' }, { $match: { $and: [{ date: { $gte: new Date(2015, 1) } }, { date: { $lt: new Date(2019, 1, 1) } }] } }, { $group: { _id: { cpf: '$passenger.name', name: '$passenger.name' }, count: { $sum: 1 } } }, { $sort: { count: -1 } } ]) // distancia média percorrida por estado db.trips.aggregate([ { $group: { _id: '$pickupAddress.state', avgDistance: { $avg: '$distance' } } }, { $sort: { avgDistance: -1 } } ]) // distancia max percorrida por estado db.trips.aggregate([ { $group: { _id: '$pickupAddress.state', maxDistance: { $max: '$distance' } } }, { $sort: { maxDistance: -1 } } ]) // primeiros 20 motoristas que possuem carros a partir de 2015 db.trips.aggregate([ { $lookup: { from: 'people', localField: 'driver', foreignField: '_id', as: 'driver' } }, { $unwind: '$driver' }, { $match: { 'vehicle.year': { $gte: 2015 } } }, { $group: { _id: { cpf: '$driver.cpf', name: '$driver.name', carYear: '$vehicle.year' } } }, { $limit: 20 } ]) // contar viagens cuja a cidade do passageiro é igual a do motorista. db.trips.aggregate([ { $lookup: { from: 'people', localField: 'driver', foreignField: '_id', as: 'driver' } }, { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$driver' }, { $unwind: '$passenger' }, { $match: { $expr: { $eq: ['$driver.address.city', '$passenger.address.city'] } } }, { $count: 'count' } ]) // contar a quantidade de viagens por estado cujo o valor final é maior que o valor estimado db.trips.aggregate([ { $group: { _id: '$pickupAddress.state', count: { $sum: { $cond: { if: { $gt: ['$estimatedValue', '$finalValue'] }, then: 1, else: 0 } } } } }, { $sort: { count: -1 } } ]) // ids de passageiros por estado com a maior distancia percorrida db.trips.mapReduce( function() { emit(this.pickupAddress.state, { pid: this.passenger, dist: this.distance }) }, function(state, values) { return values.reduce( (acc, next) => ({ name: next.dist > acc.dist ? next.pid : acc.pid, dist: Math.max(acc.dist, next.dist) }), { pid: null, dist: 0 } ) }, { out: 'res' } ) // renomeando nome ruim da coleção db.res.renameCollection('highestPassengerDistance') // Listar a nota média dos motoristas do maranhão db.trips.aggregate([ { $lookup: { from: 'people', localField: 'driver', foreignField: '_id', as: 'driver' } }, { $unwind: '$driver' }, { $match: { 'driver.address.state': 'maranhão' } }, { $group: { _id: { cnh: '$driver.cnh.number', nome: '$driver.name' }, avgRating: { $avg: '$rating' } } } ]) // Os 5 passageiros que gastaram mais em corridas nos estados do sul entre 01/09/14 e 03/04/18 ordenador por custo db.trips.aggregate([ { $match: { $and: [ { $or: [ { 'pickupAddress.state': 'santa catarina' }, { 'pickupAddress.state': 'parana' }, { 'pickupAddress.state': 'rio grande do sul' } ] }, { $and: [{ date: { $gte: new Date(2014, 9, 1) } }, { date: { $lte: new Date(2018, 4, 3) } }] } ] } }, { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$passenger' }, { $group: { _id: { cpf: '$passenger.cpf', name: '$passenger.name' }, sum: { $sum: '$finalValue' } } }, { $sort: { sum: -1 } }, { $limit: 5 } ]) // Os 1/5 passageiros que gastaram menos em corridas db.trips.aggregate([ { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$passenger' }, { $group: { _id: { cpf: '$passenger.cpf', name: '$passenger.name' }, sum: { $sum: '$finalValue' } } }, { $sort: { sum: -1 } }, { $skip: db.people.count({ cnh: { $exists: false } }) * (4 / 5) } ]) // Listar ids dos motoristas com apenas um telefone cadastrado db.people.find({ cnh: { $exists: true }, phone: { $size: 1 } }) //// Criação de índice de texto db.people.createIndex({ name: 'text', email: 'text' }) // Consulta por nomes de motoristas com o sobrenome moura db.people.find({ $text: { $search: 'moura' }, cnh: { $exists: true } }).pretty() // Retornar o total de documentos da base de dados carservice db.trips.find().count() // retornar as viagens com a distância maior que 4 db.trips.find( {distance: { $gte: 4 } } ) // listar motoristas do estado do rio grande do sul apenas, ordenados pela distancia percorrida do motorista db.trips.aggregate([ { $match: { 'driver.address.state': 'rio grande do sul' } }, { $group: { _id: { name: '$driver.name', state: '$driver.address.state', uuid: '$driver.uuid' }, distanciaTotal: { $sum: '$distance' } } }, { $sort: { distanciaTotal: -1 } } ]) // listar motoristas e seus estados, ordenados pela distancia percorrida db.trips.aggregate([ { $lookup: {from: 'people', localField: 'driver', foreignField: '_id', as:'driver'} }, {$unwind: '$driver'}, { $group:{ _id:{cpf: '$driver.cpf', name: '$driver.name', state: '$driver.address.state'}, distanciaTotal:{ $sum: '$distance'} } }, {$sort: { distanciaTotal: -1 } } ]) // Retornar as viagens que aconteceram depois do dia 01-04-2015 db.trips.find( { date: { $gt: new Date('2015-04-01') }, } ).pretty() // Quantas viagens foram realizadas no dia 2023-10-03 db.trips.find({date: new Date('2023-10-03')}).count() // #SET : atualizando o nome do estado "santa catarina" pra "santa caratina - SC" APENAS para a // primeira pessoa que se encaixe na condição db.people.update( {"address.state" : "santa catarina"}, { $set :{ "address.state" : "santa catarina - SC" } } ) // #PUSH : adicionando mais um telefone a um determinado usuário db.people.update( {"_id" : ObjectId("5d21ca0cbb08843b1bfd2b6b")}, { $push :{ "phone" : "(82) 3333-3333" } } ) // #EACH vários updates em sequência db.people.update( {"_id" : ObjectId("5d21ca0cbb08843b1bfd2b6b")}, { $push :{ phone : {$each : ["(82) 4444-4444", "(82) 4444-2222"]} } } ) // #FINDONE : encontrando algum (e apenas um) elemento da coleção trips que tenha o rating maior que 4 db.trips.findOne( { rating: {$gt: 4} } ) //$SUBSTR: Quebrar o primeiro nome dos motoristas em uma substring db.trips.aggregate([ { $lookup: {from: 'people', localField: 'driver', foreignField: '_id', as:'driver'} }, {$unwind: '$driver'}, { $project: { _id: {name: '$driver.name'}, "subString": { $substrBytes:["$driver.name", 0, 4 ]} } } ]) // $TOUPPER: Retornar o nome dos passageiros em letras maiúsculas db.trips.aggregate([ { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$passenger'}, { $project: { _id: { name: { $toUpper: "$passenger.name"} } } } ]) // $CONCAT: Nome dos passageiros e seus respectivos emails db.trips.aggregate([ { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$passenger'}, { $project: { Passengers:{ $concat: [ "$passenger.name", " - ", "$passenger.email" ] } } } ]) // $ALL: Retornar todas as viagens realizadas por veículos que são do ano 2018 db.trips.find({"vehicle.year":{ $all:[2018]}}).pretty() // SETINTERSECTION db.people.aggregate( [ { $project: { name:1, phone: 1, phone:1, Phones: { $setIntersection: [ "$phone", "$phone"] }, _id: 0 } } ] ) // SETISSUBSET db.people.aggregate( [ { $project:{name:1, phone: 1, phone:1, Phones: { $setIsSubset: [ "$phone", "$phone"] }, _id:0 } } ] ) //SETUNION db.people.aggregate( [ { $project: { phone:1, phone:1, Phones: { $setUnion: [ "$phone", "$phone" ] }, _id: 0 } } ] ) //#OUT: gerando uma nova coleção com o cpf e email das pessoas db.people.aggregate( [ {$group: { _id: "$cpf", email: {$push: "$email"}}}, {$out: "emailpeople"} ] ) // #FILTER: depende da execução da operação anterior db.emailpeople.aggregate( { $project: { emails: { $filter: { input: "$email", as: "email", cond: {$eq: ["$$email", "<EMAIL>"]} } } } } ) //#MULTIPLY: consulta para estimar a taxa de duração de tempo de viagem em relação ao valor final db.trips.aggregate( [ {$project: { _id: 1, inicioCorrida: "$date", valorDistancia: {$multiply: ["$distance", 1.5]}, valorTempo: {$subtract: ["$finalValue", {$multiply: ["$distance", 1.5]}]} } } ] ) //$STRCASECMP: Para realizar uma comparação insensível dos nomes dos passageiros com a cadeia "aeiou" db.trips.aggregate([ { $lookup: { from: 'people', localField: 'passenger', foreignField: '_id', as: 'passenger' } }, { $unwind: '$passenger'}, {$project: { _id: { name: "$passenger.name"}, Result: { $strcasecmp: [ "$passenger.name", "azw12" ] } } } ] ) // FIRST: Retorna a primeira viagem realizar por _ID db.trips.aggregate([ { $sort: { _id: 1, date: 1 } }, { $group: { _id: "$_id", firstTripsDate:{ $first: "$date"}, } } ]) // SAMPLE: seleciona aleatoriamente 3 documentos da coleção trips db.trips.aggregate( [ { $sample: { size: 3 } } ]).pretty() //seleciona aleatoriamente 3 documentos da coleção trips db.people.aggregate( [ { $sample: { size: 3 } } ]).pretty() // SORTBYCOUNT: retorna a contagem do número de documentos associado a distance db.trips.aggregate([ {$unwind:"$distance"},{$sortByCount:"$distance"} ]) // Retorna o total de veículos por ano db.trips.aggregate([ {$unwind:"$vehicle.year"},{$sortByCount:"$vehicle.year"} ]) // ADDTOSET: retorna os documentos por dia e ano conforme cada distancia percorrida db.trips.aggregate( [ { $group: { _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } }, Result: { $addToSet: "$distance" } } } ] ) <file_sep>/README.md # Car Service Database
fc60683260549ba27044fa5c398b8a836cd5e77d
[ "Markdown", "JavaScript" ]
4
Markdown
elisandrade21/in940-ProjetoNoSQL
b88c67f74e15001513edf19f1dafc415ef15ab5c
9c1bc2d04855480925530e9eca2ae15996f10ab6
refs/heads/master
<repo_name>textcreationpartnership/A00789<file_sep>/README.md #Here after ensueth two fruytfull sermons, made [and] compyled by the ryght Reuerende father in god Iohn̄ Fyssher, Doctour of Dyuynyte and Bysshop of Rochester# ##Fisher, John, Saint, 1469-1535.## Here after ensueth two fruytfull sermons, made [and] compyled by the ryght Reuerende father in god Iohn̄ Fyssher, Doctour of Dyuynyte and Bysshop of Rochester Fisher, John, Saint, 1469-1535. ##General Summary## **Links** [TCP catalogue](http://www.ota.ox.ac.uk/tcp/) • [HTML](http://tei.it.ox.ac.uk/tcp/Texts-HTML/free/A00/A00789.html) • [EPUB](http://tei.it.ox.ac.uk/tcp/Texts-EPUB/free/A00/A00789.epub) • [Page images (Historical Texts)](https://data.historicaltexts.jisc.ac.uk/view?pubId=eebo-99841351e&pageId=eebo-99841351e-5928-1) **Availability** This keyboarded and encoded edition of the work described above is co-owned by the institutions providing financial support to the Early English Books Online Text Creation Partnership. This Phase I text is available for reuse, according to the terms of Creative Commons 0 1.0 Universal. The text can be copied, modified, distributed and performed, even for commercial purposes, all without asking permission. **Major revisions** 1. __2005-02__ __TCP__ *Assigned for keying and markup* 1. __2005-04__ __Apex CoVantage__ *Keyed and coded from ProQuest page images* 1. __2005-05__ __<NAME>__ *Sampled and proofread* 1. __2005-05__ __<NAME>__ *Text and markup reviewed and edited* 1. __2005-10__ __pfs__ *Batch review (QC) and XML conversion* ##Content Summary## #####Front##### #####Body##### 1. ¶ Here begynneth the fyrst Sermon. NIsi abundauerit iustitia vestra plusquam scribarum et Phariseorum non intrabitis in regnum celorum.FYrste, the Joyes and pleasures of this lyfe, be they neuer so great, yet they haue a werynesse and THe seconde dyfferēce is this. The ioyes of this worlde haue adioyned with thē many dredes. ¶ we bTHe thyrde dyfference is, that the pleasures whereof I spake, had many interrupcyons. For that lytelTHe fourth, the pleasures aforsayd were sone done / they dyd nat abyde / where be all tho pleasures THe fyft & last difference is, yt all the gloryous syghtes worldly yt can be deuised of men, be but SEcondly, I sayd yt I wolde also speke of the other blessed soules which lykewyse be departed out ofFYrst, the nighnes which they haue to vs & we to thē by manyfold bōdꝭ / we haue all one father, aTHe seconde consideracyon, & that which peraduēture ye wyll the more regarde, is this. Euery one ofTHe thyrde consyderacyō is theyr necessyte. They be now in that condicyon that they can nat helpe tTHe fourth consyderacyon is, that they crye vnto vs for helpe / they crye pytyously, they crye lamenTHe fyfte consyderacyon is, for that our owne profyte and our owne welth han geth therby. ¶ who thatSEcōdly yu shalt be rewarded of these blessyd soules for whom thou prayest. For whā they shall be THyrdly thou shalt hereby do a great ple asure vnto theyr good aungels that be appoynted there to gyFYrst here I say that the remembraunce of the Joyes of Heuyn, sholde greately styre vs to forsake thSEcondly, the remembraunce of Purgatory sholde make vs so to lyue here, that whan we depart hence, wTHyrdly for a conclusyon of my tale, I wolde aduyse euery chrysten man and woman that hath begon a nFyrst I saye thou ought to do this moste specyally for thyne owne soule. Thyne owne soule vnder god SEcondly I say yu sholdest do this most effectually. Supposest thou that any frēde of thyne wyll doTHyrdly I say that any man may more merytoryousty helpe & cōforte his owne soule whan that he is he 1. ¶ Here begynneth the seconde sermon. THre maner of frutes there was i Para dyse. One that was called the fruyt of ye tree of lyfe. This, THe fyrst maner of pleasures be the pleasures of lyfe / which fruyt comyth of the tree of lyfe / thaTHe seconde maner of pleasures, be the pleasures of deth, and bryng our soules to euerlastynge deth.THe thyrde maner of pleasures be those that be indyfferent / so that neyther we shall haue greate reNOw thyrdly we haue to speke of ye stopnes that be in the way, that (without suffycyent Justyce) shaFYrst the sworde betokeneth that terryryble punysshment, that moost dredfull punysshment, that punysBy this than ye may conceyne, that this swerde meanyth euerlastynge ponyshment / and that it shall bTHe flambe of this swerde betokenyth vnto vs the fyre of purgatory / ye whiche is ordeynyd for them THe thyrde stop that we shall fynde before vs whan we shall couet to enter, shal be Cherubyn. ¶ Cher #####Back##### ¶ Newly Enprynted at London, by me w. Rastell, the. xxviii. day of June / the yere of our lorde. M. ¶ These bokes be to sell at London in Southwarke by me Peter Treuerys. **Types of content** * Oh, Mr. Jourdain, there is **prose** in there! There are 8 **ommitted** fragments! @__reason__ (8) : illegible (8) • @__extent__ (8) : 2 letters (4), 1 word (2), 1 letter (2) **Character listing** |Text|string(s)|codepoint(s)| |---|---|---| |Latin-1 Supplement|¶|182| |Combining Diacritical Marks|̄|772| |General Punctuation|•|8226| |Superscripts and Subscripts|⁴⁶|8308 8310| |Geometric Shapes|▪◊|9642 9674| |CJKSymbolsandPunctuation|〈〉|12296 12297| |LatinExtended-D|ꝰꝭꝑꝓ|42864 42861 42833 42835| ##Tag Usage Summary## ###Header Tag Usage### |No|element name|occ|attributes| |---|---|---|---| |1.|__author__|2|| |2.|__availability__|1|| |3.|__biblFull__|1|| |4.|__change__|5|| |5.|__date__|8| @__when__ (1) : 2005-12 (1)| |6.|__edition__|1|| |7.|__editionStmt__|1|| |8.|__editorialDecl__|1|| |9.|__extent__|2|| |10.|__idno__|6| @__type__ (6) : DLPS (1), STC (2), EEBO-CITATION (1), PROQUEST (1), VID (1)| |11.|__keywords__|1| @__scheme__ (1) : http://authorities.loc.gov/ (1)| |12.|__label__|5|| |13.|__langUsage__|1|| |14.|__language__|1| @__ident__ (1) : eng (1)| |15.|__listPrefixDef__|1|| |16.|__note__|7|| |17.|__notesStmt__|2|| |18.|__p__|11|| |19.|__prefixDef__|2| @__ident__ (2) : tcp (1), char (1) • @__matchPattern__ (2) : ([0-9\-]+):([0-9IVX]+) (1), (.+) (1) • @__replacementPattern__ (2) : http://eebo.chadwyck.com/downloadtiff?vid=$1&page=$2 (1), https://raw.githubusercontent.com/textcreationpartnership/Texts/master/tcpchars.xml#$1 (1)| |20.|__projectDesc__|1|| |21.|__pubPlace__|2|| |22.|__publicationStmt__|2|| |23.|__publisher__|2|| |24.|__ref__|2| @__target__ (2) : https://creativecommons.org/publicdomain/zero/1.0/ (1), http://www.textcreationpartnership.org/docs/. (1)| |25.|__seriesStmt__|1|| |26.|__sourceDesc__|1|| |27.|__term__|1|| |28.|__textClass__|1|| |29.|__title__|3|| |30.|__titleStmt__|2|| ###Text Tag Usage### |No|element name|occ|attributes| |---|---|---|---| |1.|__am__|11|| |2.|__bibl__|2|| |3.|__closer__|1|| |4.|__desc__|8|| |5.|__div__|34| @__type__ (34) : title_page (1), sermon (2), part (29), colophon (1), publishers_advertisement (1) • @__n__ (2) : 1 (1), 2 (1)| |6.|__epigraph__|2|| |7.|__ex__|11|| |8.|__expan__|11|| |9.|__figure__|1|| |10.|__g__|526| @__ref__ (526) : char:cmbAbbrStroke (182), char:punc (11), char:EOLhyphen (269), char:abquam (6), char:EOLunhyphen (53), char:abque (5)| |11.|__gap__|8| @__reason__ (8) : illegible (8) • @__extent__ (8) : 2 letters (4), 1 word (2), 1 letter (2)| |12.|__head__|2|| |13.|__hi__|105| @__rend__ (59) : sup (59)| |14.|__p__|87|| |15.|__pb__|60| @__facs__ (60) : tcp:5928:1 (2), tcp:5928:2 (2), tcp:5928:3 (2), tcp:5928:4 (2), tcp:5928:5 (2), tcp:5928:6 (2), tcp:5928:7 (2), tcp:5928:8 (2), tcp:5928:9 (2), tcp:5928:10 (2), tcp:5928:11 (2), tcp:5928:12 (2), tcp:5928:13 (2), tcp:5928:14 (2), tcp:5928:15 (2), tcp:5928:16 (2), tcp:5928:17 (2), tcp:5928:18 (2), tcp:5928:19 (2), tcp:5928:20 (2), tcp:5928:21 (2), tcp:5928:22 (2), tcp:5928:23 (2), tcp:5928:24 (2), tcp:5928:25 (2), tcp:5928:26 (2), tcp:5928:27 (2), tcp:5928:28 (2), tcp:5928:29 (2), tcp:5928:30 (2) • @__rendition__ (13) : simple:additions (13)| |16.|__q__|2|| |17.|__seg__|2| @__rend__ (2) : decorInit (2)| |18.|__trailer__|3||
7189e2bc57a19aa7b7743ec2832d4ce680214d5a
[ "Markdown" ]
1
Markdown
textcreationpartnership/A00789
39192bc2e64960409807a66f578c5c20b07c4adb
60841176ce0456ea06f1a6ba17ec73920cefa330
refs/heads/master
<file_sep>import React, {useContext, useState} from 'react'; import {View, Text, TextInput, StyleSheet, Button} from 'react-native'; import {Context} from '../context/BlogContext'; const EditScreen = ({navigation}) => { const {state, editBlogPost}= useContext(Context); const blogPost = state.find((blogPost)=> blogPost.id === navigation.getParam('id')); const [title, setTitle]= useState(blogPost.title); const [content, setContent]= useState(blogPost.content); const id = navigation.getParam('id'); return ( <View> <Text style={styles.label}>Enter Title: </Text> <TextInput style={styles.input} value={title} onChangeText={(text)=>setTitle(text)}/> <Text style={styles.label}>Enter Content:</Text> <TextInput style={styles.input} value={content} onChangeText={(text)=>setContent(text)}/> <Button title="Save Blog Post" onPress={()=>{editBlogPost(id, title, content, ()=>{navigation.navigate('Index')})}}></Button> </View> ); }; const styles = StyleSheet.create({ input :{ fontSize: 18, borderWidth: 1, borderColor: 'black', marginBottom: 10, padding: 5, margin: 5 }, label: { fontSize: 20, marginBottom: 10, marginLeft: 5 }}) export default EditScreen;<file_sep>import React, { useReducer} from 'react'; import { createStackNavigator } from 'react-navigation-stack'; import createDataContext from './createDataContext'; const BlogContext = React.createContext(); lastGuestId = 0; newGuestId = () => { const id = this.lastGuestId; lastGuestId += 1; return id; }; const blogReducer = (state,action) => { switch (action.type){ case 'delete_blogpost': return state.filter((blogpost)=> blogpost.id !== action.payload); case 'add_blogpost': return [...state, {id: newGuestId(), title: action.payload.title, content: action.payload.content }]; case 'edit_blogpost': return state.map((blogpost)=> blogpost.id === action.payload.id ? action.payload: blogPost); default: return state; } }; const addBlogPost = (dispatch)=>{ return(title, content, callback)=>{ dispatch({type: 'add_blogpost',payload: {title,content}}); if (callback){ callback();} }; }; const deleteBlogPost = (dispatch)=>{ return (id)=>{ dispatch({type: 'delete_blogpost', payload: id}) }; } const editBlogPost = (dispatch)=>{ return (id, title, content, callback) =>{ dispatch({type: 'edit_blogpost', payload: {id, title, content, callback}}); if (callback){ callback();} }; }; export const { Context, Provider} = createDataContext(blogReducer, {addBlogPost, deleteBlogPost, editBlogPost}, [{title:'Blog Post Text', content: 'Suckama', id: 0}]);<file_sep># Blogpost-management An App for blogpost management <h1> Demo</h1> ![pic23](https://user-images.githubusercontent.com/64857328/91639399-fd6e3c80-ea1e-11ea-9ddd-cd5630346657.png) <h1> Getting Started </h1> ```bash npm install npm start ```
bbb3bff40e167ed5f17cfa962bbfccad8be00255
[ "Markdown", "JavaScript" ]
3
Markdown
huy1741/Blogpost-management
20f876f3001ab1c23121f01aa9dda562de0530cc
43e6b8a3e5e619243c19e099a26043b6f0163a2b
refs/heads/master
<file_sep>package microbio // Ribosome : Here we attempt to model the Translation phase // of gene expression done by the Ribosome type Ribosome struct { } var startCodon = MakeStrand([]byte("AUG"), RIBOSE) // Translate returns an AminoAcidStrand for a given NucleotideStrand // Use WaitForTRNAAndGetAttachedAminoAcid(codon) to get AminoAcid func (t *Ribosome) Translate(nucleotides NucleotideStrand) AminoAcidStrand { //declares AA chain var acid AminoAcidStrand //flag variable isAdding := false //loops through nucleotide strand for i:=0; i < nucleotides.Length(); i++ { //Gets the values of the current Codon cCodon := nucleotides.Codon() //If there is no STOP code, return empty if cCodon == nil { break; } //Gets value of current Amino Acid cAmino := WaitForTRNAAndGetAttachedAminoAcid(cCodon) //If the Amino Acid is a stop code, returns acid chain if cAmino == nil { return acid } //If looking for the start Codon, go one by one until found //Once found, sets isAdding to true to being the normal pattern and moves to next codon //Normal pattern appends the Amino Acid to the chain and moves onto next codon. if isAdding { acid = append(acid, cAmino) for j:=0; j<3; j++ {nucleotides.SlideRight()} } else { if cCodon.Matches(startCodon) { isAdding = true for j:=0; j<3; j++ {nucleotides.SlideRight()} } else { nucleotides.SlideRight() } } } //returns empty AA chain var acidEmpty AminoAcidStrand return acidEmpty }
6403c6377a138df51db3a8decdb362b9df1c16ee
[ "Go" ]
1
Go
RoundBunny/code1920
156f710b94cbb46f6f392983e4136f30228cbe6a
fffb786daad8bc9f0355dad254abb624e556159b
refs/heads/master
<file_sep> var myvar = setInterval(seklideyis1,'3000'); var click = 0; function seklideyis1() { click++; if (click == 1) { document.getElementById('picture').setAttribute('src', 'images/logo2.jpg'); } else if (click == 2) { document.getElementById('picture').setAttribute('src', 'images/logo3.jpg'); } else { document.getElementById('picture').setAttribute('src', 'images/logo1.jpg'); click = 0; } } function seklideyis2() { click++; if (click == 1) { document.getElementById('picture').setAttribute('src', 'images/logo3.jpg'); } else if (click == 2) { document.getElementById('picture').setAttribute('src', 'images/logo1.jpg'); } else { document.getElementById('picture').setAttribute('src', 'images/logo2.jpg'); click = 0; } } seklideyis1();
2bb3fbb0049f069cfc1f1dfb84d20ffc5cf98637
[ "JavaScript" ]
1
JavaScript
Adel-94/slider
09a3407047af27e1aa76d7d0b3f7ab0a4adb835b
40cca7e0baa67e618edf3ad8f0820e22bc6da852
refs/heads/master
<repo_name>tharyck/APLP<file_sep>/Ponte/src/Ponte.java import java.util.ArrayList; import java.util.List; public class Ponte implements Runnable { private List<String> filaDeCarros; public Ponte() { this.filaDeCarros = new ArrayList<>(); } public void carro(String carro) { filaDeCarros.add(carro); } @Override public void run() { while (!this.filaDeCarros.isEmpty()) { if (this.filaDeCarros.contains("A")) { System.out.println("Passando carro A --> B"); this.filaDeCarros.remove("A"); } else if (this.filaDeCarros.contains("B")) { System.out.println("Passando carro B --> A"); this.filaDeCarros.remove("B"); } try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(e.getMessage()); } } } }
e56a5aa4fc91757cb325b176791019abdde0ae05
[ "Java" ]
1
Java
tharyck/APLP
7fb4a9f26a7e3c8d668128e79ef1bd677337b409
bc1cc9bc63bd7fd61bef336e2cf928ee230a17fe
refs/heads/master
<file_sep># goit-markup-hw-07 Homework number seven
1e896e86c526c7cb1b4140d331243b6f8adea501
[ "Markdown" ]
1
Markdown
Ekaterina1402/goit-markup-hw-07
fafe46994c71d52aa73e3c6ade5585328b657fb6
34afa78f20c963c2b64b20fdbd7d996ec54fd57e
refs/heads/master
<file_sep>cmake_minimum_required(VERSION 2.8) project(tiny-process-library) if(MSVC) add_definitions(-D_CRT_SECURE_NO_WARNINGS) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC -Wall -Wextra -Wno-unused-parameter") endif() find_package(Threads REQUIRED) set(process_source_files ${CMAKE_CURRENT_SOURCE_DIR}/process.cpp) if(WIN32) list(APPEND process_source_files ${CMAKE_CURRENT_SOURCE_DIR}/process_win.cpp) #If compiled using MSYS2, use sh to run commands if(MSYS) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DMSYS_PROCESS_USE_SH") endif() else() list(APPEND process_source_files ${CMAKE_CURRENT_SOURCE_DIR}/process_unix.cpp) endif() add_library(tiny-process-library STATIC ${process_source_files}) #add_library(tiny-process-library SHARED ${process_source_files}) add_executable(examples ${CMAKE_CURRENT_SOURCE_DIR}/examples.cpp) target_link_libraries(tiny-process-library ${CMAKE_THREAD_LIBS_INIT} ) target_link_libraries(examples tiny-process-library) # To enable tests: cmake -DENABLE_TESTING=1 . if(ENABLE_TESTING) enable_testing() add_subdirectory(tests) endif() install(TARGETS tiny-process-library LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/process.hpp DESTINATION include) <file_sep>#include "process.hpp" #include <iostream> TPL::Process::Process( const string_type &command, const string_type &path, std::function<void(const char* bytes, size_t n)> read_stdout, std::function<void(const char* bytes, size_t n)> read_stderr, bool open_stdin, size_t buffer_size ) : closed(true), read_stdout(read_stdout), read_stderr(read_stderr), open_stdin(open_stdin), buffer_size(buffer_size) { std::cout << "TPL Constructor opening with command : " << command << std::endl; open(command, path); std::cout << "TPL Constructor launching async_read : " << command << std::endl; async_read(); } TPL::Process::~Process() { std::cout << "TPL Destructor closing fds : " << std::endl; close_fds(); } TPL::Process::id_type TPL::Process::get_id() { return data.id; } bool TPL::Process::write(const std::string &data) { return write(data.c_str(), data.size()); }
0e31c25c9a0e7342195e658b8825f4503cf7d8d6
[ "C++", "CMake" ]
2
C++
zyamusic/tiny-process-library
8c5c928c90de829536eccce3df2c1b23bc1dc7e0
d9be591f6c66c2a00a474f700000c8346035ffb5
refs/heads/main
<file_sep>package com.infosys.infytel.order.service; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; import com.infosys.infytel.order.dto.OrdersDTO; import com.infosys.infytel.order.entity.Orders; import com.infosys.infytel.order.repository.OrderRepository; import com.infosys.infytel.order.repository.OrderRepository2; import com.infosys.infytel.order.entity.Productsorderd; import com.infosys.infytel.order.dto.ProductsorderdDTO; @Service public class OrderService { Logger logger = LoggerFactory.getLogger(this.getClass()); @PersistenceContext private EntityManager entityManager; @Autowired OrderRepository2 orderRepo2; @Autowired OrderRepository orderRepo; // kafka consumer @KafkaListener(topics="mytopic", groupId="mygroup") public void consumeFromTopic(String message) throws Exception{ String details[]=message.split("/"); Orders order= new Orders(); order.setBuyerId(details[0]); order.setAmount(Float.parseFloat(details[4])); order.setDate(java.time.LocalDate.now()); order.setAddress(details[5]); order.setStatus("Order Placed"); orderRepo.save(order); Productsorderd orders= new Productsorderd(); orders.setBuyerId(details[0]); orders.setSellerId(details[3]); orders.setProdId(details[2]); orders.setQuantity(Integer.parseInt(details[1])); orderRepo2.save(orders); } public List<ProductsorderdDTO> getAllOrder(String buyerId) { List<Productsorderd> orders = orderRepo2.findAll(); List<ProductsorderdDTO> orderDTOs = new ArrayList<ProductsorderdDTO>(); for(Productsorderd order : orders) { ProductsorderdDTO orderDTO = ProductsorderdDTO.valueOf(order); if(orderDTO.getBuyerId().equals(buyerId)) orderDTOs.add(orderDTO); } logger.info("order details : {}", orderDTOs); return orderDTOs; } public String getOrderAddress(String buyerId) throws Exception{ Orders orders = orderRepo.findById(buyerId).orElse(null); if(orders==null) throw new Exception("Address Does Not Excist"); return orders.getAddress(); } public String reOrder(String buyerId, String prodId) { Orders orders = orderRepo.findById(buyerId).orElse(null); if(orders.getStatus().equals("Delivered")) { List<Productsorderd> products=orderRepo2.findAll(); for(Productsorderd product : products) { ProductsorderdDTO productDTO = ProductsorderdDTO.valueOf(product); if(productDTO.getBuyerId().equals(buyerId) && productDTO.getProdId().equals(prodId)) { orders.setStatus("Order Placed"); orderRepo.save(orders); return "product reordered successfully.."; } } return "reorder failed..."; } return "buyer haven'tmade any orders..."; } public List<OrdersDTO> viewAllOrders(String sellerId) { Query query = entityManager.createQuery("SELECT o FROM Orders o JOIN Productsorderd p ON o.buyerId=p.buyerId WHERE p.sellerId=:sellerId"); query.setParameter("sellerId",sellerId); List<OrdersDTO> orders = query.getResultList(); logger.info("order details : {}", orders); return orders; } public void changeStatus(String orderId, String status) throws Exception { Orders order=orderRepo.findById(orderId).orElse(null); if(order==null) throw new Exception("Order Does not Exist"); order.setStatus(status); orderRepo.save(order); } public void addOrder(OrdersDTO ordersDTO) throws Exception { Query query = entityManager.createQuery("SELECT o FROM Orders o WHERE o.buyerId=:buyerId"); query.setParameter("buyerId",ordersDTO.getBuyerId()); if(!query.getResultList().isEmpty()) throw new Exception("Order already Exist"); Orders neworder = ordersDTO.createEntity(); orderRepo.save(neworder); } // public Integer addOrder2(OrdersDTO ordersDTO) throws Exception { // Query query = entityManager.createQuery("SELECT o FROM Orders o WHERE o.buyerId=:buyerId"); // query.setParameter("buyerId",ordersDTO.getBuyerId()); // if(!query.getResultList().isEmpty()) // throw new Exception("Order already Exist"); // Orders neworder = ordersDTO.createEntity(); // orderRepo.save(neworder); // return Math.floor(neworder.getAmount()/100); // } } <file_sep>package com.infosys.infytel.order.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.infosys.infytel.order.entity.Orders; public interface OrderRepository extends JpaRepository<Orders, String> { } <file_sep>package com.infosys.infytel.order.dto; import java.time.LocalDate; import com.infosys.infytel.order.entity.Orders; public class OrdersDTO { private Integer orderId; private String buyerId; private Float amount; private LocalDate date; private String address; private String status; public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public String getBuyerId() { return buyerId; } public void setBuyerId(String buyerId) { this.buyerId = buyerId; } public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public OrdersDTO() { super(); } // Converts Entity into DTO public static OrdersDTO valueOf(Orders plan) { OrdersDTO orderDTO= new OrdersDTO(); orderDTO.setBuyerId(plan.getBuyerId()); orderDTO.setAmount(plan.getAmount()); orderDTO.setDate(java.time.LocalDate.now()); orderDTO.setAddress(plan.getAddress()); orderDTO.setStatus(plan.getStatus()); return orderDTO; } // Converts DTO into Entity public Orders createEntity() { Orders Orders = new Orders(); Orders.setOrderId(this.getOrderId()); Orders.setBuyerId(this.getBuyerId()); Orders.setAddress(this.getAddress()); Orders.setAmount(this.getAmount()); Orders.setDate(this.getDate()); Orders.setStatus(this.getStatus()); return Orders; } @Override public String toString() { return "OrderDTO [buyerId=" + buyerId + ", amount=" + amount + ", date=" + date + ", address=" + address + ", status=" + status + "]"; } } <file_sep>package com.infosys.infytel.order.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "productsorderd") public class Productsorderd { @Column(name = "seller_id", nullable = false) private String sellerId; @Id @Column(name = "buyer_id", nullable = false) private String buyerId; @Column(name = "quantity", nullable = false) private Integer quantity; @Column(name = "prod_id", nullable = false) private String prodId; public Productsorderd() { super(); } public String getSellerId() { return sellerId; } public void setSellerId(String sellerId) { this.sellerId = sellerId; } public String getBuyerId() { return buyerId; } public void setBuyerId(String buyerId) { this.buyerId = buyerId; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public String getProdId() { return prodId; } public void setProdId(String prodId) { this.prodId = prodId; } } <file_sep>package com.infosys.infytel.order.entity; import java.time.LocalDate; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="orders") public class Orders { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id", nullable = false) private Integer orderId; @Column(name = "buyer_id", nullable = false) private String buyerId; @Column(name = "amount", nullable = false) private Float amount; @Column(name = "date", nullable = false) private LocalDate date; @Column(name = "address", nullable = false) private String address; @Column(name = "status", nullable = false) private String status; public Orders() { super(); } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public String getBuyerId() { return buyerId; } public void setBuyerId(String buyerId) { this.buyerId = buyerId; } public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
a2c4a56b47c20105c6cb1ecca9708843d3eee6c0
[ "Java" ]
5
Java
chandralekhakancharla/Order_ms
7c98ac3f24b55b5cacab543bba0fedb7e11de911
5296540f94abf7488e5d287aa47913d3b2abf124
refs/heads/master
<repo_name>pramodk007/RetrofitSingleton<file_sep>/app/src/main/java/com/androiddev/retrofitsingleton/MainActivity.java package com.androiddev.retrofitsingleton; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { RetrofitSingleton retrofitSingleton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getPost(); } private void getPost() { retrofitSingleton.getInstance().getJSONApi().getPostWithID(4).enqueue(new Callback<PostModel>() { @Override public void onResponse(Call<PostModel> call, Response<PostModel> response) { PostModel postModel = response.body(); Toast.makeText(MainActivity.this, postModel.getTitle(), Toast.LENGTH_SHORT).show(); } @Override public void onFailure(Call<PostModel> call, Throwable t) { Toast.makeText(MainActivity.this, "error on fetching the data", Toast.LENGTH_SHORT).show(); } }); } }<file_sep>/app/src/main/java/com/androiddev/retrofitsingleton/RetrofitSingleton.java package com.androiddev.retrofitsingleton; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitSingleton { private static RetrofitSingleton mInstance; private static final String BASE_URL = "https://jsonplaceholder.typicode.com/"; private Retrofit mRetrofit; //retrofitObject private RetrofitSingleton() { mRetrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } //for creating instance/object for retrofit public static RetrofitSingleton getInstance() { if (mInstance == null) { mInstance = new RetrofitSingleton(); } return mInstance; } //for interface public PostApi getJSONApi() { return mRetrofit.create(PostApi.class); } } <file_sep>/app/src/main/java/com/androiddev/retrofitsingleton/PostApi.java package com.androiddev.retrofitsingleton; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface PostApi { @GET("/posts/{id}") public Call<PostModel> getPostWithID(@Path("id") int id); }
c3edc04aabd105b575dfd906474684c74a6a5ae6
[ "Java" ]
3
Java
pramodk007/RetrofitSingleton
59bd9aa29043e1444aedbc4177a4240443bd2a1b
dfd1f9b0a957ceb7cfae6d6e8d393120e82cf908
refs/heads/master
<file_sep> global #---- Identity node 'haproxy-sandbox-1.servers.example.com' description '[]' #---- Daemon nbthread 1 ulimit-n 65536 user 'haproxy' group 'haproxy' pidfile '/run/haproxy.pid' #---- State server-state-base '/run/haproxy-states' server-state-file '/run/haproxy.state' #---- Connections maxconn 8192 maxconnrate 512 maxsessrate 2048 maxsslconn 4096 maxsslrate 256 maxpipes 4096 #---- Checks max-spread-checks 6 spread-checks 25 #---- HTTP tune.http.logurilen 4096 tune.http.maxhdr 64 #---- HTTP/2 tune.h2.header-table-size 16384 tune.h2.initial-window-size 131072 tune.h2.max-concurrent-streams 128 #---- Compression maxcomprate 0 maxcompcpuusage 25 maxzlibmem 128 tune.comp.maxlevel 9 #---- Buffers tune.bufsize 131072 tune.buffers.limit 4096 tune.buffers.reserve 16 tune.maxrewrite 16384 #---- TLS default configuration ssl-default-bind-ciphers 'ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES256-SHA256:AES128-GCM-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA' ssl-default-bind-ciphersuites 'TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256' ssl-default-bind-curves 'X25519:P-256' ssl-default-bind-options no-tlsv11 no-tlsv10 no-sslv3 no-tls-tickets ssl-default-server-ciphers 'ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES256-SHA256:AES128-GCM-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA' ssl-default-server-ciphersuites 'TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256' ssl-default-server-options no-tlsv11 no-tlsv10 no-sslv3 no-tls-tickets ssl-server-verify required ssl-skip-self-issued-ca ssl-dh-param-file '/etc/haproxy/tls/dh-params.pem' #---- TLS advanced configuration tune.ssl.default-dh-param 2048 tune.ssl.maxrecord 16384 tune.ssl.cachesize 131072 tune.ssl.lifetime 3600s #---- Logging log '/dev/log' len 65535 format 'rfc5424' daemon info err log-send-hostname 'haproxy-sandbox-1.servers.example.com' log-tag 'haproxy' quiet #---- Statistics stats socket 'unix@/run/haproxy.sock' user 'haproxy' group 'haproxy' mode 0600 level admin stats maxconn 4 stats timeout 60s <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _be = _ha.http_backends.basic (_frontend = _fe) _fe.requests.redirect_domain_with_www ("site-with-www.example.com") _fe.requests.redirect_domain_without_www ("site-without-www.example.com") _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-8bac66a80ab5d7afb73f8e15e689e3b7 var('txn.http_debugging_enabled'),bool -m bool acl acl-3a706eb6d2520c39add4c7d9913cfe80 var('txn.http_debugging_excluded'),bool -m bool #---- HTTP Request Rules http-request set-header "X-HA-HTTP-Action" "%[var('txn.logging_http_action')]" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 http-request set-header "X-HA-Timestamp" "%[date(),http_date()]" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 http-request add-header "X-HA-Frontend" "%f" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 http-request add-header "X-HA-Backend" "%b" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 #---- HTTP Response Rules http-response set-header "X-HA-HTTP-Action" "%[var('txn.logging_http_action')]" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 http-response set-header "X-HA-Timestamp" "%[date(),http_date()]" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 http-response add-header "X-HA-Frontend" "%f" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 http-response add-header "X-HA-Backend" "%b" if acl-8bac66a80ab5d7afb73f8e15e689e3b7 !acl-3a706eb6d2520c39add4c7d9913cfe80 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _be = _ha.http_backends.basic (_frontend = _fe) _fe.requests.set_forwarded_headers () _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-75d28861c6de62e7637b29660b4852fb req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'app.example.com' acl acl-4a915d6c0eec5d2bfc2e2f87c12a6dca req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'blog.example.com' acl acl-d1d5164097985b8997faee890a444f34 req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'example.com' acl acl-bd17590b8d0f8ec47af0d1445cb8cb1a req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'www.example.com' acl acl-dbaf316a86669df8911f5b91102e8aa0 ssl_fc() -m bool acl acl-402db81baae469d338b6468436716b6b ssl_fc(),not -m bool #---- HTTP Request Rules http-request redirect prefix "http://www.example.com" code 307 if acl-d1d5164097985b8997faee890a444f34 acl-402db81baae469d338b6468436716b6b http-request redirect prefix "https://www.example.com" code 307 if acl-d1d5164097985b8997faee890a444f34 acl-dbaf316a86669df8911f5b91102e8aa0 #---- Routes use_backend http-flask if acl-bd17590b8d0f8ec47af0d1445cb8cb1a use_backend http-static if acl-4a915d6c0eec5d2bfc2e2f87c12a6dca use_backend http-media if acl-75d28861c6de62e7637b29660b4852fb use_backend http-fallback backend 'http-flask' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9090' backend 'http-static' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9091' backend 'http-media' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9092' backend 'http-fallback' #---- Protocol mode http enabled #---- HTTP Request Rules http-request deny deny_status 403 <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-5dffb987178a168e4b33589c21e16327 path() -m beg -- '/assets/' acl acl-920f2313fe5ea2e8bb90ce205e377d5c path() -m beg -- '/media/' acl acl-5dffb987178a168e4b33589c21e16327 path() -m beg -- '/public/' #---- Routes use_backend http-static if acl-5dffb987178a168e4b33589c21e16327 use_backend http-media if acl-920f2313fe5ea2e8bb90ce205e377d5c use_backend http-flask backend 'http-flask' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9090' backend 'http-static' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9091' backend 'http-media' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9092' <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _ha.output_stdout () <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _be_variant_a = _ha.http_backends.basic ( _identifier = "variant-a", _endpoint = "ipv4@127.0.0.1:9090", ) _be_variant_b = _ha.http_backends.basic ( _identifier = "variant-b", _endpoint = "ipv4@127.0.0.1:9091", ) _fe.routes.route (_be_variant_b, ( _fe.acls.backend_active (_be_variant_b), _fe.acls.ab_in_bucket (0, 4), )) _fe.routes.route (_be_variant_a) _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-dbaf316a86669df8911f5b91102e8aa0 ssl_fc() -m bool acl acl-402db81baae469d338b6468436716b6b ssl_fc(),not -m bool #---- HTTP Request Rules http-request set-header "X-Forwarded-Host" "%[req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.')]" http-request set-header "X-Forwarded-For" "%ci" http-request set-header "X-Forwarded-Proto" "http" if acl-402db81baae469d338b6468436716b6b http-request set-header "X-Forwarded-Proto" "https" if acl-dbaf316a86669df8911f5b91102e8aa0 http-request set-header "X-Forwarded-Port" "80" if acl-402db81baae469d338b6468436716b6b http-request set-header "X-Forwarded-Port" "443" if acl-dbaf316a86669df8911f5b91102e8aa0 http-request set-header "X-Forwarded-Server-Ip" "%fi" http-request set-header "X-Forwarded-Server-Port" "%fp" #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> from errors import * from tools import * tls_mode = "normal" tls_ciphers_v12_paranoid = ( "ECDHE-RSA-CHACHA20-POLY1305", "ECDHE-RSA-AES256-GCM-SHA384", "ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-SHA384", "ECDHE-RSA-AES128-SHA256", ) tls_ciphers_v12_normal = ( "ECDHE-RSA-CHACHA20-POLY1305", "ECDHE-RSA-AES256-GCM-SHA384", "ECDHE-RSA-AES256-SHA384", "ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES128-SHA256", "DHE-RSA-AES256-GCM-SHA384", "DHE-RSA-AES256-SHA256", "DHE-RSA-AES128-GCM-SHA256", "DHE-RSA-AES128-SHA256", "ECDHE-RSA-AES256-SHA", "DHE-RSA-AES256-SHA", "ECDHE-RSA-AES128-SHA", "DHE-RSA-AES128-SHA", "ECDHE-RSA-DES-CBC3-SHA", "EDH-RSA-DES-CBC3-SHA", "AES256-GCM-SHA384", "AES256-SHA256", "AES128-GCM-SHA256", "AES128-SHA256", "AES256-SHA", "AES128-SHA", "DES-CBC3-SHA", ) tls_ciphers_v12_backdoor = ( # "AES256-GCM-SHA384", "AES256-SHA256", # "AES128-GCM-SHA256", "AES128-SHA256", "AES256-SHA", "AES128-SHA", # "DES-CBC3-SHA", ) tls_ciphers_v13_all = ( "TLS_CHACHA20_POLY1305_SHA256", "TLS_AES_256_GCM_SHA384", "TLS_AES_128_GCM_SHA256", ) tls_ciphers_v13_paranoid = tls_ciphers_v13_all tls_ciphers_v13_normal = tls_ciphers_v13_all tls_ciphers_v13_backdoor = tls_ciphers_v13_all tls_options_paranoid = ( "no-tlsv12", "no-tlsv11", "no-tlsv10", "no-sslv3", "no-tls-tickets", "no-ssl-reuse", "strict-sni", ) tls_options_normal = ( "no-tlsv11", "no-tlsv10", "no-sslv3", "no-tls-tickets", ) tls_options_backdoor = tls_options_normal http_status_codes = { "content_strict" : (200, 204,), "content_standard" : (200, 201, 202, 204, 206,), "redirect" : (301, 302, 303, 307, 308,), "caching" : (304,), "not_found" : (404,), "get_strict" : (200,), "get_standard" : (200, 204, 206,), "get_redirect" : (301, 302,), "get_caching" : (304,), "post_strict" : (200, 201, 202, 204,), "post_standard" : (200, 201, 202, 204,), "post_redirect" : (303,), "post_caching" : (), } http_status_codes["harden_allowed_paranoid"] = \ tuple ( list (http_status_codes["content_strict"]) + list (http_status_codes["caching"]) ) http_status_codes["harden_allowed_strict"] = \ tuple ( list (http_status_codes["content_strict"]) + list (http_status_codes["redirect"]) + list (http_status_codes["caching"]) ) http_status_codes["harden_allowed_standard"] = \ tuple ( list (http_status_codes["content_standard"]) + list (http_status_codes["redirect"]) + list (http_status_codes["caching"]) ) http_status_codes["harden_allowed_get_paranoid"] = \ tuple ( list (http_status_codes["get_strict"]) + list (http_status_codes["get_caching"]) ) http_status_codes["harden_allowed_get_strict"] = \ tuple ( list (http_status_codes["get_strict"]) + list (http_status_codes["get_redirect"]) + list (http_status_codes["get_caching"]) ) http_status_codes["harden_allowed_get_standard"] = \ tuple ( list (http_status_codes["get_standard"]) + list (http_status_codes["get_redirect"]) + list (http_status_codes["get_caching"]) ) http_status_codes["harden_allowed_post_paranoid"] = \ tuple ( list (http_status_codes["post_strict"]) + list (http_status_codes["post_caching"]) ) http_status_codes["harden_allowed_post_strict"] = \ tuple ( list (http_status_codes["post_strict"]) + list (http_status_codes["post_redirect"]) + list (http_status_codes["post_caching"]) ) http_status_codes["harden_allowed_post_standard"] = \ tuple ( list (http_status_codes["post_standard"]) + list (http_status_codes["post_redirect"]) + list (http_status_codes["post_caching"]) ) compression_content_types = ( "text/html", "text/css", "application/javascript", "text/javascript", "application/xml", "text/xml", "application/xhtml+xml", "application/rss+xml", "application/atom+xml", "application/json", "text/json", "text/plain", "text/csv", "text/tab-separated-values", "image/svg+xml", "image/vnd.microsoft.icon", "image/x-icon", "font/collection", "font/otf", "application/font-otf", "application/x-font-otf", "application/x-font-opentype", "font/ttf", "application/font-ttf", "application/x-font-ttf", "application/x-font-truetype", "font/sfnt", "application/font-sfnt", "application/x-font-sfnt", "font/woff", "application/font-woff", "application/x-font-woff", "font/woff2", "application/font-woff2", "application/x-font-woff2", "font/eot", "application/font-eot", "application/x-font-eot", "application/vnd.ms-fontobject", ) logging_type = "json" logging_tcp_format_text = """{tcp:20161201:01} f-id:%f b-id:%b,%s c-sck:%ci,%cp f-sck:%fi,%fp b-sck:%bi,%bp s-sck:%si,%sp i-sz:%U o-sz:%B w:%Ts.%ms,%Tw,%Tc,%Tt f-cnt:%ac,%fc,%bc,%sc,%rc,%ts b-cnt:%bq,%sq g-cnt:%lc,%rt ssl:%sslv,%sslc ssl-x:%[ssl_fc],%[ssl_fc_protocol],%[ssl_fc_cipher],%[ssl_fc_unique_id,hex],%[ssl_fc_session_id,hex],%[ssl_fc_is_resumed],%[ssl_fc_has_sni],[%{Q}[ssl_fc_sni]],[%{Q}[ssl_fc_alpn]],[%{Q}[ssl_fc_npn]] ssl-xf:%[ssl_fc],%[ssl_f_version],%[ssl_f_sha1,hex],[%{Q}[ssl_f_s_dn]] ssl-xc:%[ssl_c_used],%[ssl_c_version],%[ssl_c_sha1,hex],%[ssl_c_verify],%[ssl_c_err],%[ssl_c_ca_err],%[ssl_c_ca_err_depth],[%{Q}[ssl_c_s_dn]],[%{Q}[ssl_c_i_dn]]""" logging_http_format_text = """{http:20161201:01} h-v:[%{Q}HV] h-m:[%{Q}HM] h-p:[%{Q}HP] h-q:[%{Q}HQ] h-s:%ST f-id:%f b-id:%b,%s c-sck:%ci,%cp f-sck:%fi,%fp b-sck:%bi,%bp s-sck:%si,%sp h-r-id:[%{Q}ID] h-i-hdr:[%{Q}hrl] h-o-hdr:[%{Q}hsl] h-i-ck:[%{Q}CC] h-o-ck:[%{Q}CS] i-sz:%U o-sz:%B w:%Ts.%ms,%Tq,%Tw,%Tc,%Tr,%Tt f-cnt:%ac,%fc,%bc,%sc,%rc,%tsc b-cnt:%bq,%sq g-cnt:%lc,%rt ssl:%sslv,%sslc ssl-x:%[ssl_fc],%[ssl_fc_protocol],%[ssl_fc_cipher],%[ssl_fc_unique_id,hex],%[ssl_fc_session_id,hex],%[ssl_fc_is_resumed],%[ssl_fc_has_sni],[%{Q}[ssl_fc_sni]],[%{Q}[ssl_fc_alpn]],[%{Q}[ssl_fc_npn]] ssl-xf:%[ssl_fc],%[ssl_f_version],%[ssl_f_sha1,hex],[%{Q}[ssl_f_s_dn]] ssl-xc:%[ssl_c_used],%[ssl_c_version],%[ssl_c_sha1,hex],%[ssl_c_verify],%[ssl_c_err],%[ssl_c_ca_err],%[ssl_c_ca_err_depth],[%{Q}[ssl_c_s_dn]],[%{Q}[ssl_c_i_dn]]""" def _expand_logging_format_json (_format, _parameters) : def _expand_value (_value) : if isinstance (_value, basestring) : _token = list () if _value.startswith ("=") : _token.append (_value[1:]) elif _value.startswith ("'") or _value.startswith ("+") : _quote = (_value[0] == "'") _value = _value[1:] if _quote : _token.append ("\"") if _value.startswith ("%") : if _quote : _token.append ("%{Q}") else : _token.append ("%") _token.append (_value[1:]) elif _value.startswith ("@") : _token.append ("%[") _token.append (_value[1:]) _token.append ("]") elif _value.startswith ("'") : _token.append (_value[1:]) elif _value.startswith ("$") : _value = expand_token (_value, _parameters) _token.append (_value) else : raise_error ("62d234ed", _value) if _quote : _token.append ("\"") _token = "".join (_token) elif isinstance (_value, list) : _token = list () _token.append ("[") _sub_tokens = [_expand_value (_value) for _value in _value] _sub_tokens = ",".join (_sub_tokens) _token.append (_sub_tokens) _token.append ("]") _token = "".join (_token) else : raise_error ("2336219b", _value) return _token _tokens = list () for _key, _value in _format : _value = _expand_value (_value) _token = ["\"", _key, "\"", ":", _value] _token = "".join (_token) _tokens.append (_token) _tokens = ", ".join (_tokens) _tokens = "{ " + _tokens + " }" return _tokens logging_tcp_format_json = None logging_http_format_json_template = [ ("s", "''20230324:01"), ("ss", "'$logging_http_format_subschema"), ("t", "=%Ts.%ms"), ("f_id", "'%f"), #! ("b_id", "'%b"), #! ("s_id", "'%s"), #! ("h_v", "'%HV"), #! ("h_vm", "+@fc_http_major"), ("h_s", "+%ST"), ("h_m0", "'%HM"), #! ("h_u0", "'%HU"), #! ("h_p0", "'%HPO"), #! ("h_q0", "'%HQ"), #! ("h_i0", "'%ID"), #! ("h_t0", "'%trg"), #! # FIXME: Make this configurable! ("h_h", "'@var(txn.logging_http_host),json()"), # FIXME: Make this configurable! ("h_m", "'@var(txn.logging_http_method),json()"), ("h_p", "'@var(txn.logging_http_path),json()"), ("h_q", "'@var(txn.logging_http_query),json()"), # FIXME: Make this configurable! ("h_r_i", "'@var(txn.logging_http_request),json()"), ("h_r_s", "'@var(txn.logging_http_session),json()"), # FIXME: Make this configurable! ("h_f_h", "'@var(txn.logging_http_forwarded_host),json()"), ("h_f_f", "'@var(txn.logging_http_forwarded_for),json()"), ("h_f_p", "'@var(txn.logging_http_forwarded_proto),json()"), # FIXME: Make this configurable! ("h_h_a", "'@var(txn.logging_http_agent),json()"), ("h_h_r", "'@var(txn.logging_http_referrer),json()"), ("h_h_l", "'@var(txn.logging_http_location),json()"), ("h_h_ct", "'@var(txn.logging_http_content_type),json()"), ("h_h_ce", "'@var(txn.logging_http_content_encoding),json()"), ("h_h_cl", "'@var(txn.logging_http_content_length),json()"), ("h_h_cc", "'@var(txn.logging_http_cache_control),json()"), ("h_h_cv", "'@var(txn.logging_http_cache_etag),json()"), ("h_i_hdr", "'%hrl"), #! ("h_o_hdr", "'%hsl"), #! ("h_i_ck", "'%CC"), #! ("h_o_ck", "'%CS"), #! ("h_o_comp", ["'@res.comp", "'@res.comp_algo"]), ("c_sck", ["'%ci", "'%cp"]), ("f_sck", ["'%fi", "'%fp"]), ("b_sck", ["'%bi", "'%bp"]), ("s_sck", ["'%si", "'%sp"]), ("ts", "'%tsc"), ("f_err", "'@fc_err"), ("b_err", "'@bc_err"), ("i_sz", "+%U"), ("o_sz", "+%B"), ("w", ["+%Tt", "+%Tq", "+%Ta"]), ("w_x", ["+%Th", "+%Ti", "+%TR", "+%Tw", "+%Tc", "+%Tr", "+%Td"]), ("cnt", ["+%ac", "+%fc", "+%bc", "+%bq", "+%sc", "+%sq", "+%rc", "+%rt", "+%lc"]), ("ssl", ["'%sslv", "'%sslc"]), ("ssl_f", [ "'@ssl_fc,json()", "'@ssl_fc_err,json()", "'@ssl_fc_protocol,json()", "'@ssl_fc_cipher,json()", "'@ssl_fc_unique_id,hex()", "'@ssl_fc_session_id,hex()", "'@ssl_fc_is_resumed,json()", "'@ssl_fc_alpn,json()", "'@ssl_fc_npn,json()", "'@ssl_fc_sni,json()", ]), ("ssl_b", [ "'@ssl_bc,json()", "'@ssl_bc_err,json()", "'@ssl_bc_protocol,json()", "'@ssl_bc_cipher,json()", "'@ssl_bc_unique_id,hex()", "'@ssl_bc_session_id,hex()", "'@ssl_bc_is_resumed,json()", "'@ssl_bc_alpn,json()", "'@ssl_bc_npn,json()", ]), ("ssl_xf", [ "'@ssl_fc,json()", "'@ssl_f_version,json()", "'@ssl_f_key_alg,json()", "'@ssl_f_sig_alg,json()", "'@ssl_f_sha1,hex", "'@ssl_f_s_dn,json()", "'@ssl_f_i_dn,json()", ]), ("ssl_xc", [ "'@ssl_c_used,json()", "'@ssl_c_version,json()", "'@ssl_c_key_alg,json()", "'@ssl_c_sig_alg,json()", "'@ssl_c_sha1,hex", "'@ssl_c_s_dn,json()", "'@ssl_c_i_dn,json()", "'@ssl_c_verify,json()", "'@ssl_c_err,json()", "'@ssl_c_ca_err,json()", "'@ssl_c_ca_err_depth,json()", ]), ("stick", [ "'@sc0_conn_cur()", "'@sc0_conn_cnt()", "'@sc0_conn_rate()", "'@sc0_sess_cnt()", "'@sc0_sess_rate()", "'@sc0_http_req_cnt()", "'@sc0_http_req_rate()", "'@sc0_http_err_cnt()", "'@sc0_http_err_rate()", "'@sc0_kbytes_in()", "'@sc0_bytes_in_rate()", "'@sc0_kbytes_out()", "'@sc0_bytes_out_rate()", ]), ] logging_http_format_json = lambda (_parameters) : _expand_logging_format_json (logging_http_format_json_template, _parameters) parameters = { "proxy_identifier" : parameters_get ("daemon_node"), "frontend_enabled" : True, "frontend_http_bind_endpoint" : parameters_get ("defaults_frontend_http_bind_endpoint"), "frontend_http_bind_endpoint_tls" : parameters_get ("defaults_frontend_http_bind_endpoint_tls"), "frontend_max_connections_active_count" : parameters_choose_if_false (parameters_get ("frontend_bind_minimal"), parameters_get ("defaults_frontend_max_connections_active_count")), "frontend_max_connections_backlog_count" : parameters_choose_if_false (parameters_get ("frontend_bind_minimal"), parameters_get ("defaults_frontend_max_connections_backlog_count")), "frontend_bind_options" : ( parameters_choose_if ( parameters_get ("frontend_bind_defer_accept"), "defer-accept"), parameters_choose_if_non_null ( parameters_get ("frontend_bind_mss"), ("mss", parameters_get ("frontend_bind_mss"))), parameters_choose_if_non_null ( parameters_get ("frontend_max_connections_active_count"), ("maxconn", parameters_get ("frontend_max_connections_active_count"))), parameters_choose_if_non_null ( parameters_get ("frontend_max_connections_backlog_count"), ("backlog", parameters_get ("frontend_max_connections_backlog_count"))), parameters_choose_if ( parameters_get ("frontend_accept_proxy_enabled"), "accept-proxy"), parameters_choose_if_non_null ( parameters_get ("frontend_bind_interface"), ("interface", parameters_get ("frontend_bind_interface"))), ), "frontend_bind_mss" : parameters_choose_if_false (parameters_get ("frontend_bind_minimal"), 1400), "frontend_bind_defer_accept" : parameters_not (parameters_get ("frontend_bind_minimal")), "frontend_bind_tls_certificate" : parameters_choose_if_false (parameters_get ("frontend_bind_tls_minimal"), parameters_path_base_join ("daemon_paths_configurations_tls", "default.pem")), "frontend_bind_tls_certificate_rules" : parameters_choose_if_false (parameters_get ("frontend_bind_tls_minimal"), parameters_path_base_join ("daemon_paths_configurations_tls", "default.conf")), "frontend_bind_tls_options" : parameters_choose_if_false (parameters_get ("frontend_bind_tls_minimal"), ( parameters_get ("frontend_bind_options"), parameters_get ("frontend_bind_tls_options_actual"), )), "frontend_bind_interface" : None, # FIXME: Rename this! "frontend_bind_tls_options_actual" : ( parameters_get ("frontend_tls_options"), parameters_choose_match ( parameters_get ("tls_verify_client"), (None, None), ("none", ("verify", "none")), ("optional", ("verify", "optional")), ("required", ("verify", "required"))), parameters_choose_if_non_null ( parameters_get ("frontend_tls_ciphers_v12_descriptor"), ("ciphers", parameters_get ("frontend_tls_ciphers_v12_descriptor"))), parameters_choose_if_non_null ( parameters_get ("frontend_tls_ciphers_v13_descriptor"), ("ciphersuites", parameters_get ("frontend_tls_ciphers_v13_descriptor"))), ), "frontend_tls_mode" : None, "frontend_tls_ciphers_v12" : parameters_choose_match ( parameters_get ("frontend_tls_mode"), (None, None), ("normal", parameters_get ("tls_ciphers_v12_normal")), ("paranoid", parameters_get ("tls_ciphers_v12_paranoid")), ("backdoor", parameters_get ("tls_ciphers_v12_backdoor")), ), "frontend_tls_ciphers_v13" : parameters_choose_match ( parameters_get ("frontend_tls_mode"), (None, None), ("normal", parameters_get ("tls_ciphers_v13_normal")), ("paranoid", parameters_get ("tls_ciphers_v13_paranoid")), ("backdoor", parameters_get ("tls_ciphers_v13_backdoor")), ), "frontend_tls_ciphers_v12_descriptor" : parameters_choose_if_non_null ("frontend_tls_ciphers_v12", parameters_join (":", parameters_get ("frontend_tls_ciphers_v12"))), "frontend_tls_ciphers_v13_descriptor" : parameters_choose_if_non_null ("frontend_tls_ciphers_v13", parameters_join (":", parameters_get ("frontend_tls_ciphers_v13"))), "frontend_tls_options" : parameters_choose_match ( parameters_get ("frontend_tls_mode"), (None, ( # parameters_get ("tls_options"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ("normal", ( # parameters_get ("tls_options_normal"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ("paranoid", ( # parameters_get ("tls_options_paranoid"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ("backdoor", ( # parameters_get ("tls_options_backdoor"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ), "frontend_monitor_enabled" : True, "frontend_monitor_path" : parameters_get ("heartbeat_proxy_path"), "frontend_monitor_fail_acl" : "FALSE", # FIXME: `monitor-net` was removed! # "frontend_monitor_network" : "0.0.0.0/0", "frontend_stats_enabled" : True, "frontend_stats_token" : "beb36ad8a85568b7e89e314b2e03244f", "frontend_stats_path" : parameters_format ("%s%s", parameters_get ("haproxy_internals_path_prefix"), parameters_get ("frontend_stats_token")), "frontend_stats_auth_realm" : parameters_get ("daemon_identifier"), "frontend_stats_auth_credentials" : None, "frontend_stats_admin_acl" : None, "frontend_stats_version" : True, "frontend_stats_modules" : False, "frontend_stats_refresh" : 6, "frontend_accept_proxy_enabled" : False, "frontend_capture_length" : 1024, "frontend_http_keep_alive_mode" : "keep-alive", "frontend_http_keep_alive_timeout" : None, "frontend_http_stick_source" : parameters_get ("samples_client_ip_method"), "frontend_http_stick_track" : True, "frontend_tcp_stick_source" : parameters_get ("samples_client_ip_method"), "frontend_tcp_stick_track" : True, "backend_enabled" : True, "backend_check_enabled" : parameters_get ("backend_check_configure"), "backend_forward_enabled" : parameters_get ("backend_forward_configure"), "backend_http_host" : None, "backend_http_check_enabled" : parameters_get ("backend_check_enabled"), "backend_http_check_request_method" : "GET", "backend_http_check_request_uri" : parameters_get ("heartbeat_server_path"), "backend_http_check_request_version" : "HTTP/1.1", "backend_http_check_request_host" : parameters_get ("backend_http_host"), "backend_http_check_expect_matcher" : "status", "backend_http_check_expect_pattern" : "200", "backend_server_min_connections_active_count" : parameters_math ("//", parameters_get ("backend_server_max_connections_active_count"), 4, True), "backend_server_max_connections_active_count" : None, "backend_server_max_connections_queue_count" : parameters_math ("*", parameters_get ("backend_server_max_connections_active_count"), 4, True), "backend_server_max_connections_full_count" : parameters_math ("//", parameters_get ("backend_server_max_connections_queue_count"), 8, True), "backend_server_check_interval_normal" : None, "backend_server_check_interval_rising" : None, "backend_server_check_interval_failed" : None, # FIXME: Apply formulas as in case of defaults! "backend_server_timeout_activity" : None, "backend_server_timeout_activity_server" : None, "backend_server_timeout_activity_client" : None, "backend_server_timeout_activity_tunnel" : None, "backend_server_timeout_connect" : None, "backend_server_timeout_fin" : None, "backend_server_timeout_queue" : None, "backend_server_timeout_check" : None, "backend_server_timeout_tarpit" : None, "backend_server_timeout_request" : None, "backend_server_timeout_keep_alive" : None, "backend_http_keep_alive_mode" : "server-close", "backend_http_keep_alive_reuse" : "never", "backend_http_keep_alive_timeout" : None, "backend_http_keep_alive_pool" : None, "backend_balance" : None, "server_enabled" : True, "server_min_connections_active_count" : parameters_math ("//", parameters_get ("server_max_connections_active_count"), 4, True), "server_max_connections_active_count" : parameters_get ("backend_server_max_connections_active_count"), "server_max_connections_queue_count" : parameters_math ("*", parameters_get ("server_max_connections_active_count"), 4, True), "server_check_enabled" : parameters_get ("backend_check_enabled"), "server_send_proxy_enabled" : False, "server_send_proxy_version" : "v1", "server_tcp_min_connections_active_count" : parameters_get ("server_min_connections_active_count"), "server_tcp_max_connections_active_count" : parameters_get ("server_max_connections_active_count"), "server_tcp_max_connections_queue_count" : parameters_get ("server_max_connections_queue_count"), "server_tcp_check_enabled" : parameters_get ("server_check_enabled"), "server_tcp_send_proxy_enabled" : parameters_get ("server_send_proxy_enabled"), "server_tcp_send_proxy_version" : parameters_get ("server_send_proxy_version"), "server_tcp_options" : ( parameters_choose_if ( parameters_get ("server_tcp_check_enabled"), "check"), parameters_choose_if ( parameters_get ("server_tcp_check_enabled"), ("observe", "layer4")), parameters_choose_if_non_null ( parameters_get ("server_tcp_min_connections_active_count"), ("minconn", parameters_get ("server_tcp_min_connections_active_count"))), parameters_choose_if_non_null ( parameters_get ("server_tcp_max_connections_active_count"), ("maxconn", parameters_get ("server_tcp_max_connections_active_count"))), parameters_choose_if_non_null ( parameters_get ("server_tcp_max_connections_queue_count"), ("maxqueue", parameters_get ("server_tcp_max_connections_queue_count"))), parameters_choose_if ( parameters_get ("server_tcp_send_proxy_enabled"), ( parameters_choose_match ( parameters_get ("server_tcp_send_proxy_version"), (True, "send-proxy"), ("v1", "send-proxy"), ("v2", "send-proxy-v2"), ("v2-ssl", "send-proxy-v2-ssl"), ("v2-ssl-cn", "send-proxy-v2-ssl-cn"), ), parameters_choose_if (parameters_get ("server_tcp_check_enabled"), "check-send-proxy"))), ), "server_http_min_connections_active_count" : parameters_get ("server_min_connections_active_count"), "server_http_max_connections_active_count" : parameters_get ("server_max_connections_active_count"), "server_http_max_connections_queue_count" : parameters_get ("server_max_connections_queue_count"), "server_http_check_enabled" : parameters_get ("server_check_enabled"), "server_http_send_proxy_enabled" : parameters_get ("server_send_proxy_enabled"), "server_http_send_proxy_version" : parameters_get ("server_send_proxy_version"), "server_http_protocol" : None, "server_http_options" : ( parameters_choose_if ( parameters_get ("server_http_check_enabled"), "check"), parameters_choose_if ( parameters_get ("server_http_check_enabled"), ("observe", "layer7")), parameters_choose_if_non_null ( parameters_get ("server_http_min_connections_active_count"), ("minconn", parameters_get ("server_http_min_connections_active_count"))), parameters_choose_if_non_null ( parameters_get ("server_http_max_connections_active_count"), ("maxconn", parameters_get ("server_http_max_connections_active_count"))), parameters_choose_if_non_null ( parameters_get ("server_http_max_connections_queue_count"), ("maxqueue", parameters_get ("server_http_max_connections_queue_count"))), parameters_choose_if_non_null ( parameters_get ("server_http_protocol"), ("proto", parameters_get ("server_http_protocol"))), parameters_choose_if_non_null ( parameters_get ("server_http_protocol"), parameters_choose_if ( parameters_get ("server_http_check_enabled"), ("check-proto", parameters_get ("server_http_protocol")))), parameters_choose_if ( parameters_get ("server_http_send_proxy_enabled"), ( parameters_choose_match ( parameters_get ("server_http_send_proxy_version"), (True, "send-proxy"), ("v1", "send-proxy"), ("v2", "send-proxy-v2"), ("v2-ssl", "send-proxy-v2-ssl"), ("v2-ssl-cn", "send-proxy-v2-ssl-cn"), ), parameters_choose_if (parameters_get ("server_http_check_enabled"), "check-send-proxy"))), ), "server_tls_enabled" : False, "server_tls_sni" : None, "server_tls_alpn" : None, "server_tls_verify" : True, "server_tls_ca_file" : None, "server_check_tls_sni" : None, "server_check_tls_alpn" : None, "server_tls_options" : parameters_choose_if ( parameters_get ("server_tls_enabled"), ( "ssl", parameters_choose_if_non_null ( parameters_get ("server_tls_ca_file"), ("ca-file", parameters_get ("server_tls_ca_file"))), parameters_choose_if_non_null ( parameters_get ("server_tls_sni"), ("sni", parameters_get ("server_tls_sni"))), parameters_choose_if_non_null ( parameters_get ("server_tls_alpn"), ("alpn", parameters_get ("server_tls_alpn"))), parameters_choose_if ( parameters_get ("server_check_enabled"), "check-ssl"), parameters_choose_if_non_null ( parameters_get ("server_check_tls_sni"), parameters_choose_if ( parameters_get ("server_check_enabled"), ("check-sni", parameters_get ("server_check_tls_sni")))), parameters_choose_if_non_null ( parameters_get ("server_check_tls_alpn"), parameters_choose_if ( parameters_get ("server_check_enabled"), ("check-alpn", parameters_get ("server_check_tls_alpn")))), parameters_choose_if ( parameters_get ("server_tls_verify"), ("verify", "required"), ("verify", "none")), ) ), "server_check_interval_normal" : None, "server_check_interval_rising" : None, "server_check_interval_failed" : None, "server_resolvers" : parameters_get ("defaults_server_resolvers"), "server_resolvers_prefer" : parameters_get ("defaults_server_resolvers_prefer"), "server_resolvers_options" : parameters_get ("defaults_server_resolvers_options"), "server_options" : ( parameters_choose_match ( parameters_get ("backend_mode"), ("tcp", parameters_get ("server_tcp_options")), ("http", parameters_get ("server_http_options"))), parameters_get ("server_tls_options"), parameters_choose_if_non_null (parameters_get ("server_check_interval_normal"), ("inter", parameters_get ("server_check_interval_normal"))), parameters_choose_if_non_null (parameters_get ("server_check_interval_rising"), ("fastinter", parameters_get ("server_check_interval_rising"))), parameters_choose_if_non_null (parameters_get ("server_check_interval_failed"), ("downinter", parameters_get ("server_check_interval_failed"))), parameters_choose_if_non_null (parameters_get ("server_resolvers"), ("resolvers", parameters_get ("server_resolvers"))), parameters_choose_if_non_null (parameters_get ("server_resolvers_prefer"), ("resolve-prefer", parameters_get ("server_resolvers_prefer"))), parameters_choose_if_non_null (parameters_get ("server_resolvers_options"), ("resolve-opts", parameters_join (",", parameters_get ("server_resolvers_options")))), ), "defaults_frontend_http_bind_endpoint" : "ipv4@0.0.0.0:80", "defaults_frontend_http_bind_endpoint_tls" : "ipv4@0.0.0.0:443", "defaults_frontend_max_connections_active_count" : parameters_math ("//", parameters_get ("global_max_connections_count"), 2), "defaults_frontend_max_connections_backlog_count" : parameters_math ("//", parameters_get ("defaults_frontend_max_connections_active_count"), 4), "defaults_frontend_max_sessions_rate" : parameters_math ("*", parameters_get ("defaults_frontend_max_connections_active_count"), 4), "defaults_server_min_connections_active_count" : parameters_math ("//", parameters_get ("defaults_server_max_connections_active_count"), 4), "defaults_server_max_connections_active_count" : 32, "defaults_server_max_connections_queue_count" : parameters_math ("*", parameters_get ("defaults_server_max_connections_active_count"), 4), "defaults_server_max_connections_full_count" : parameters_math ("//", parameters_get ("defaults_server_max_connections_queue_count"), 8), "defaults_server_check_interval_normal" : 60, "defaults_server_check_interval_rising" : parameters_math ("//", parameters_get ("defaults_server_check_interval_normal"), 30), "defaults_server_check_interval_failed" : parameters_math ("//", parameters_get ("defaults_server_check_interval_normal"), 3), "defaults_server_check_count_rising" : 8, "defaults_server_check_count_failed" : 4, "defaults_server_check_count_errors" : parameters_get ("defaults_server_check_count_failed"), "defaults_server_resolvers" : None, "defaults_server_resolvers_prefer" : None, "defaults_server_resolvers_options" : None, "defaults_timeout_activity" : 30, "defaults_timeout_activity_server" : parameters_math ("*", parameters_get ("defaults_timeout_activity"), 2), "defaults_timeout_activity_client" : parameters_get ("defaults_timeout_activity"), "defaults_timeout_activity_tunnel" : parameters_math ("*", parameters_get ("defaults_timeout_activity"), 6), "defaults_timeout_connect" : 6, "defaults_timeout_fin" : 6, "defaults_timeout_queue" : 30, "defaults_timeout_check" : 6, "defaults_timeout_tarpit" : parameters_get ("defaults_timeout_queue"), "defaults_timeout_request" : 30, "defaults_timeout_keep_alive" : 60, "defaults_compression_content_types" : compression_content_types, "defaults_compression_offload" : True, "global_max_connections_count" : 1024 * 8, "global_max_connections_rate" : parameters_math ("//", parameters_get ("global_max_connections_count"), 16), "global_max_sessions_rate" : parameters_math ("*", parameters_get ("global_max_connections_rate"), 4), "global_max_tls_connections_count" : parameters_math ("//", parameters_get ("global_max_connections_count"), 2), "global_max_tls_connections_rate" : parameters_math ("//", parameters_get ("global_max_tls_connections_count"), 16), "global_max_pipes" : parameters_math ("//", parameters_get ("global_max_connections_count"), 2), "tls_enabled" : True, "tls_ca_base" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_ca_base_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "ca"))), "tls_ca_file" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_ca_file_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "ca.pem"))), "tls_ca_verify_file" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_ca_verify_file_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "ca-verify.pem"))), "tls_ca_sign_file" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_ca_sign_file_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "ca-sign.pem"))), "tls_crt_base" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_crt_base_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "certificates"))), "tls_crt_file" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_crt_file_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "certificates.pem"))), "tls_dh_params" : parameters_choose_if (parameters_get ("tls_enabled"), parameters_choose_if (parameters_get ("tls_dh_params_enabled"), parameters_path_base_join ("daemon_paths_configurations_tls", "dh-params.pem"))), "tls_ca_base_enabled" : False, "tls_ca_file_enabled" : False, "tls_ca_verify_file_enabled" : False, "tls_ca_sign_file_enabled" : False, "tls_crt_base_enabled" : False, "tls_crt_file_enabled" : False, "tls_dh_params_enabled" : True, "tls_mode" : tls_mode, "tls_ciphers_v12" : parameters_choose_match ( parameters_get ("tls_mode"), ("normal", parameters_get ("tls_ciphers_v12_normal")), ("paranoid", parameters_get ("tls_ciphers_v12_paranoid")), ("backdoor", parameters_get ("tls_ciphers_v12_backdoor")), ), "tls_ciphers_v12_descriptor" : parameters_join (":", parameters_get ("tls_ciphers_v12")), "tls_ciphers_v12_normal" : tls_ciphers_v12_normal, "tls_ciphers_v12_paranoid" : tls_ciphers_v12_paranoid, "tls_ciphers_v12_backdoor" : tls_ciphers_v12_backdoor, "tls_ciphers_v13" : parameters_choose_match ( parameters_get ("tls_mode"), ("normal", parameters_get ("tls_ciphers_v13_normal")), ("paranoid", parameters_get ("tls_ciphers_v13_paranoid")), ("backdoor", parameters_get ("tls_ciphers_v13_backdoor")), ), "tls_ciphers_v13_descriptor" : parameters_join (":", parameters_get ("tls_ciphers_v13")), "tls_ciphers_v13_normal" : tls_ciphers_v13_normal, "tls_ciphers_v13_paranoid" : tls_ciphers_v13_paranoid, "tls_ciphers_v13_backdoor" : tls_ciphers_v13_backdoor, "tls_options" : parameters_choose_match ( parameters_get ("tls_mode"), ("normal", ( parameters_get ("tls_options_normal"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ("paranoid", ( parameters_get ("tls_options_paranoid"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ("backdoor", ( parameters_get ("tls_options_backdoor"), parameters_get ("tls_pem_descriptor"), parameters_get ("tls_alpn_descriptor"), parameters_get ("tls_npn_descriptor"), parameters_get ("tls_options_extra"))), ), "tls_options_normal" : tls_options_normal, "tls_options_paranoid" : tls_options_paranoid, "tls_options_backdoor" : tls_options_backdoor, "tls_options_extra" : ( parameters_choose_if (parameters_get ("tls_sni_strict"), "strict-sni"), parameters_get ("tls_options_custom"), ), "tls_options_custom" : None, "tls_pem_enabled" : True, "tls_pem_descriptor" : parameters_choose_if ( parameters_get ("tls_pem_enabled"), ( parameters_choose_if_non_null (parameters_get ("tls_crt_file"), ("crt", parameters_get ("tls_crt_file"))), parameters_choose_if_non_null (parameters_get ("tls_crt_base"), ("crt-base", parameters_get ("tls_crt_base"))), parameters_choose_if_non_null (parameters_get ("tls_ca_file"), ("ca-file", parameters_get ("tls_ca_file"))), parameters_choose_if_non_null (parameters_get ("tls_ca_base"), ("ca-base", parameters_get ("tls_ca_base"))), parameters_choose_if_non_null (parameters_get ("tls_ca_sign_file"), ("ca-sign-file", parameters_get ("tls_ca_sign_file"))), )), "tls_alpn_enabled" : False, "tls_alpn_descriptor" : parameters_choose_if (parameters_get ("tls_alpn_enabled"), ("alpn", parameters_join (",", parameters_get ("tls_alpn_protocols")))), "tls_alpn_protocols" : ("h2,http/1.1", "http/1.0"), "tls_npn_enabled" : False, "tls_npn_descriptor" : parameters_choose_if (parameters_get ("tls_npn_enabled"), ("npn", parameters_join (",", parameters_get ("tls_npn_protocols")))), "tls_npn_protocols" : ("h2,http/1.1", "http/1.0"), "tls_sni_strict" : False, "tls_curves" : parameters_join (",", ("X25519:P-256",)), "tls_verify_client" : None, "geoip_enabled" : False, "geoip_map" : parameters_path_base_join ("daemon_paths_configurations_maps", "geoip.txt"), "bogons_map" : parameters_path_base_join ("daemon_paths_configurations_maps", "bogons.txt"), "bots_map" : parameters_path_base_join ("daemon_paths_configurations_maps", "bots.txt"), "daemon_node" : "localhost", "daemon_name" : "haproxy", "daemon_identifier" : parameters_format ("%s@%s", parameters_get ("daemon_name"), parameters_get ("daemon_node")), "daemon_description" : "[]", "daemon_user" : "haproxy", "daemon_group" : parameters_get ("daemon_user"), "daemon_pid" : parameters_path_base_join ("daemon_paths_runtime", "haproxy.pid"), "daemon_chroot" : parameters_path_base_join ("daemon_paths_runtime", "haproxy.chroot"), "daemon_chroot_enabled" : False, "daemon_ulimit" : 65536, "daemon_threads_count" : 1, "daemon_threads_affinity" : None, "daemon_socket" : parameters_choose_if (True, parameters_format ("unix@%s", parameters_path_base_join ("daemon_paths_runtime", "haproxy.sock"))), "daemon_paths_configurations" : "/etc/haproxy", "daemon_paths_configurations_tls" : parameters_path_base_join ("daemon_paths_configurations", "tls"), "daemon_paths_configurations_maps" : parameters_path_base_join ("daemon_paths_configurations", "maps"), "daemon_paths_runtime" : "/run", "daemon_paths_states_prefix" : parameters_path_base_join ("daemon_paths_runtime", "haproxy-states"), "daemon_paths_state_global" : parameters_path_base_join ("daemon_paths_runtime", "haproxy.state"), "syslog_1_enabled" : True, "syslog_1_endpoint" : "/dev/log", "syslog_1_protocol" : parameters_get ("syslog_protocol"), "syslog_2_enabled" : False, "syslog_2_endpoint" : "127.0.0.1:514", "syslog_2_protocol" : parameters_get ("syslog_protocol"), "syslog_p_enabled" : False, "syslog_p_endpoint" : "127.0.0.1:514", "syslog_p_protocol" : parameters_get ("syslog_protocol"), "syslog_pg_enabled" : parameters_choose_if (parameters_get ("syslog_p_enabled"), False, True), # NOTE: Preferred protocol should be `rfc5424`! # If there are issues, use `rfc3164` and set `syslog_source_node` to `None`. "syslog_protocol" : "rfc5424", "syslog_source_node" : parameters_get ("daemon_node"), "syslog_source_tag" : "haproxy", "logging_type" : logging_type, "logging_tcp_type" : parameters_get ("logging_type"), "logging_tcp_format_text" : logging_tcp_format_text, "logging_tcp_format_json" : logging_tcp_format_json, "logging_tcp_format" : parameters_choose_match ( parameters_get ("logging_tcp_type"), ("text", parameters_get ("logging_tcp_format_text")), ("json", parameters_get ("logging_tcp_format_json")), ("default", None), ), "logging_http_type" : parameters_get ("logging_type"), "logging_http_format_text" : logging_http_format_text, "logging_http_format_json" : logging_http_format_json, "logging_http_format_subschema" : "default", "logging_http_format" : parameters_choose_match ( parameters_get ("logging_http_type"), ("text", parameters_get ("logging_http_format_text")), ("json", parameters_get ("logging_http_format_json")), ("default", None), ), "logging_http_variable_method" : "txn.logging_http_method", "logging_http_variable_host" : "txn.logging_http_host", "logging_http_variable_path" : "txn.logging_http_path", "logging_http_variable_query" : "txn.logging_http_query", "logging_http_variable_forwarded_host" : "txn.logging_http_forwarded_host", "logging_http_variable_forwarded_for" : "txn.logging_http_forwarded_for", "logging_http_variable_forwarded_proto" : "txn.logging_http_forwarded_proto", "logging_http_variable_agent" : "txn.logging_http_agent", "logging_http_variable_referrer" : "txn.logging_http_referrer", "logging_http_variable_location" : "txn.logging_http_location", "logging_http_variable_content_type" : "txn.logging_http_content_type", "logging_http_variable_content_encoding" : "txn.logging_http_content_encoding", "logging_http_variable_content_length" : "txn.logging_http_content_length", "logging_http_variable_cache_control" : "txn.logging_http_cache_control", "logging_http_variable_cache_etag" : "txn.logging_http_cache_etag", "logging_http_variable_request" : "txn.logging_http_request", "logging_http_variable_session" : "txn.logging_http_session", "logging_http_variable_action" : "txn.logging_http_action", "logging_http_header_forwarded_host" : "X-Forwarded-Host", "logging_http_header_forwarded_for" : "X-Forwarded-For", "logging_http_header_forwarded_proto" : "X-Forwarded-Proto", "logging_http_header_forwarded_proto_method" : "ssl_fc", "logging_http_header_forwarded_port" : "X-Forwarded-Port", "logging_http_header_forwarded_server_ip" : "X-Forwarded-Server-Ip", "logging_http_header_forwarded_server_port" : "X-Forwarded-Server-Port", "logging_http_header_request" : parameters_get ("http_tracking_request_header"), "logging_http_header_session" : parameters_get ("http_tracking_session_header"), "logging_http_header_action" : "X-HA-HTTP-Action", "logging_geoip_country_variable" : "txn.logging_geoip_country", "error_pages_enabled" : True, "error_pages_codes" : (400, 401, 403, 404, 405, 408, 410, 429, 500, 501, 502, 503, 504,), "error_pages_store" : parameters_path_base_join ("daemon_paths_configurations", "errors"), "error_pages_store_http" : parameters_path_base_join ("error_pages_store", "http"), "error_pages_store_html" : parameters_path_base_join ("error_pages_store", "html"), "internals_path_prefix" : "/__/", "internals_rules_order_allow" : -9920, "internals_rules_order_deny" : -9910, "internals_netfilter_mark_allowed" : None, "internals_netfilter_mark_denied" : None, "haproxy_internals_path_prefix" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "haproxy/"), "heartbeat_server_path" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "heartbeat"), "heartbeat_proxy_path" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "heartbeat-proxy"), "heartbeat_self_path" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "heartbeat-haproxy"), "authenticate_path" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "authenticate"), "error_pages_path_prefix" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "errors/"), "whitelist_path" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "whitelist"), "whitelist_netfilter_mark_allowed" : None, "whitelist_netfilter_mark_denied" : None, "http_tracking_session_cookie" : "X-HA-Session-Id", "http_tracking_session_cookie_max_age" : 2419200, "http_tracking_session_header" : "X-HA-Session-Id", "http_tracking_session_variable" : "txn.http_tracking_session", "http_tracking_request_header" : "X-HA-Request-Id", "http_tracking_request_variable" : "txn.http_tracking_request", "http_tracking_enabled_variable" : "txn.http_tracking_enabled", "http_tracking_excluded_variable" : "txn.http_tracking_excluded", "http_authenticated_header" : "X-HA-Authenticated", "http_authenticated_cookie" : "X-HA-Authenticated", "http_authenticated_cookie_max_age" : 3600, "http_authenticated_path" : parameters_get ("authenticate_path"), "http_authenticated_query" : "__authenticate", "http_authenticated_variable" : "txn.http_authenticated", "http_authenticated_netfilter_mark" : None, "http_debug_enabled_variable" : "txn.http_debugging_enabled", "http_debug_excluded_variable" : "txn.http_debugging_excluded", "http_debug_timestamp_header" : "X-HA-Timestamp", "http_debug_frontend_header" : "X-HA-Frontend", "http_debug_backend_header" : "X-HA-Backend", "http_debug_counters_header" : "X-HA-Counters", "http_errors_marker" : "X-Ha-Error-Proxy", "http_errors_method" : "X-HA-Error-Method", "http_errors_status" : "X-HA-Error-Status", "http_harden_level" : "standard", "http_harden_allowed_methods_paranoid" : ("GET"), "http_harden_allowed_methods_strict" : ("GET"), "http_harden_allowed_methods_standard" : ("HEAD", "GET", "OPTIONS"), "http_harden_allowed_methods_extra" : None, "http_harden_allowed_methods" : parameters_choose_match ( parameters_get ("http_harden_level"), ("paranoid", (parameters_get ("http_harden_allowed_methods_paranoid"), parameters_get ("http_harden_allowed_methods_extra"))), ("strict", (parameters_get ("http_harden_allowed_methods_strict"), parameters_get ("http_harden_allowed_methods_extra"))), ("standard", (parameters_get ("http_harden_allowed_methods_standard"), parameters_get ("http_harden_allowed_methods_extra"))), ), "http_harden_allowed_status_codes_paranoid" : http_status_codes["harden_allowed_paranoid"], "http_harden_allowed_status_codes_strict" : http_status_codes["harden_allowed_strict"], "http_harden_allowed_status_codes_standard" : http_status_codes["harden_allowed_standard"], "http_harden_allowed_status_codes_extra" : ( parameters_get ("http_harden_allowed_get_status_codes_extra"), parameters_get ("http_harden_allowed_post_status_codes_extra"), ), "http_harden_allowed_status_codes" : ( parameters_choose_match ( parameters_get ("http_harden_level"), ("paranoid", (parameters_get ("http_harden_allowed_status_codes_paranoid"), parameters_get ("http_harden_allowed_status_codes_extra"))), ("strict", (parameters_get ("http_harden_allowed_status_codes_strict"), parameters_get ("http_harden_allowed_status_codes_extra"))), ("standard", (parameters_get ("http_harden_allowed_status_codes_standard"), parameters_get ("http_harden_allowed_status_codes_extra"))), ), parameters_choose_if (parameters_get ("http_harden_allowed_not_found"), http_status_codes["not_found"]), parameters_choose_if (parameters_get ("http_harden_allowed_redirect"), http_status_codes["redirect"]), ), "http_harden_allowed_not_found" : False, "http_harden_allowed_redirect" : False, "http_harden_allowed_get_status_codes_paranoid" : http_status_codes["harden_allowed_get_paranoid"], "http_harden_allowed_get_status_codes_strict" : http_status_codes["harden_allowed_get_strict"], "http_harden_allowed_get_status_codes_standard" : http_status_codes["harden_allowed_get_standard"], "http_harden_allowed_get_status_codes_extra" : None, "http_harden_allowed_get_status_codes" : ( parameters_choose_match ( parameters_get ("http_harden_level"), ("paranoid", (parameters_get ("http_harden_allowed_get_status_codes_paranoid"), parameters_get ("http_harden_allowed_get_status_codes_extra"))), ("strict", (parameters_get ("http_harden_allowed_get_status_codes_strict"), parameters_get ("http_harden_allowed_get_status_codes_extra"))), ("standard", (parameters_get ("http_harden_allowed_get_status_codes_standard"), parameters_get ("http_harden_allowed_get_status_codes_extra"))), ), parameters_choose_if (parameters_get ("http_harden_allowed_get_not_found"), http_status_codes["not_found"]), parameters_choose_if (parameters_get ("http_harden_allowed_get_redirect"), http_status_codes["redirect"]), ), "http_harden_allowed_get_not_found" : parameters_get ("http_harden_allowed_not_found"), "http_harden_allowed_get_redirect" : parameters_get ("http_harden_allowed_redirect"), "http_harden_allowed_post_status_codes_paranoid" : http_status_codes["harden_allowed_post_paranoid"], "http_harden_allowed_post_status_codes_strict" : http_status_codes["harden_allowed_post_strict"], "http_harden_allowed_post_status_codes_standard" : http_status_codes["harden_allowed_post_standard"], "http_harden_allowed_post_status_codes_extra" : None, "http_harden_allowed_post_status_codes" : ( parameters_choose_match ( parameters_get ("http_harden_level"), ("paranoid", (parameters_get ("http_harden_allowed_post_status_codes_paranoid"), parameters_get ("http_harden_allowed_post_status_codes_extra"))), ("strict", (parameters_get ("http_harden_allowed_post_status_codes_strict"), parameters_get ("http_harden_allowed_post_status_codes_extra"))), ("standard", (parameters_get ("http_harden_allowed_post_status_codes_standard"), parameters_get ("http_harden_allowed_post_status_codes_extra"))), ), parameters_choose_if (parameters_get ("http_harden_allowed_post_not_found"), http_status_codes["not_found"]), parameters_choose_if (parameters_get ("http_harden_allowed_post_redirect"), http_status_codes["redirect"]), ), "http_harden_allowed_post_not_found" : parameters_get ("http_harden_allowed_not_found"), "http_harden_allowed_post_redirect" : parameters_get ("http_harden_allowed_redirect"), "http_harden_hsts_enabled" : True, "http_harden_hsts_interval" : parameters_choose_match ( parameters_get ("http_harden_level"), ("paranoid", 4 * 4 * 365 * 24 * 3600), ("strict", 4 * 365 * 24 * 3600), ("standard", 28 * 24 * 3600), ), "http_harden_hsts_descriptor" : parameters_format ("max-age=%d", parameters_get ("http_harden_hsts_interval")), "http_harden_csp_descriptor" : "upgrade-insecure-requests", "http_harden_fp_descriptor" : "accelerometer 'none'; ambient-light-sensor 'none'; autoplay 'none'; camera 'none'; display-capture 'none'; document-domain 'none'; encrypted-media 'none'; fullscreen 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; midi 'none'; payment 'none'; picture-in-picture 'none'; publickey-credentials-get 'none'; sync-xhr 'none'; usb 'none'; xr-spatial-tracking 'none'", "http_harden_referrer_descriptor" : "strict-origin-when-cross-origin", "http_harden_frames_descriptor" : "SAMEORIGIN", "http_harden_cto_descriptor" : "nosniff", "http_harden_xss_descriptor" : "1; mode=block", "http_harden_coop_descriptor" : "same-origin", "http_harden_corp_descriptor" : "same-origin", "http_harden_coep_descriptor" : "unsafe-none", "http_harden_netfilter_mark_allowed" : None, "http_harden_netfilter_mark_denied" : None, "http_harden_enabled_variable" : "txn.http_harden_enabled", "http_harden_excluded_variable" : "txn.http_harden_excluded", "http_harden_headers_extended" : True, "http_hardened_header" : "X-HA-Hardened", "http_drop_caching_enabled_variable" : "txn.http_drop_caching_enabled", "http_drop_caching_excluded_variable" : "txn.http_drop_caching_excluded", "http_force_caching_enabled_variable" : "txn.http_force_caching_enabled", "http_force_caching_excluded_variable" : "txn.http_force_caching_excluded", "http_drop_cookies_enabled_variable" : "txn.http_drop_cookies_enabled", "http_drop_cookies_excluded_variable" : "txn.http_drop_cookies_excluded", "http_force_cors_enabled_variable" : "txn.http_force_cors_enabled", "http_force_cors_excluded_variable" : "txn.http_force_cors_excluded", "http_force_cors_allowed_variable" : "txn.http_force_cors_allowed", "http_force_cors_origin_variable" : "txn.http_force_cors_origin", "http_force_cors_origin_present_variable" : "txn.http_force_cors_origin_present", "http_force_cors_options_present_variable" : "txn.http_force_cors_options_present", "http_ranges_allowed_variable" : "txn.http_ranges_allowed", "letsencrypt_backend_identifier" : "letsencrypt", "letsencrypt_server_ip" : "127.0.0.1", "letsencrypt_server_port" : 445, "letsencrypt_server_endpoint" : parameters_format ("ipv4@%s:%d", parameters_get ("letsencrypt_server_ip"), parameters_get ("letsencrypt_server_port")), "letsencrypt_frontend_rules_order" : -9100, "letsencrypt_frontend_routes_order" : -9100, "letsencrypt_path" : "/.well-known/acme-challenge", "varnish_backend_identifier" : "varnish", "varnish_downstream_ip" : "127.0.0.1", "varnish_downstream_port" : 6083, "varnish_downstream_endpoint" : parameters_format ("ipv4@%s:%d", parameters_get ("varnish_downstream_ip"), parameters_get ("varnish_downstream_port")), "varnish_downstream_send_proxy_enabled" : parameters_get ("varnish_send_proxy_enabled"), "varnish_upstream_ip" : "127.0.0.1", "varnish_upstream_port" : 6081, "varnish_upstream_endpoint" : parameters_format ("ipv4@%s:%d", parameters_get ("varnish_upstream_ip"), parameters_get ("varnish_upstream_port")), "varnish_upstream_send_proxy_enabled" : parameters_get ("varnish_send_proxy_enabled"), "varnish_management_ip" : "127.0.0.1", "varnish_management_port" : 6082, "varnish_management_endpoint" : parameters_format ("ipv4@%s:%d", parameters_get ("varnish_management_ip"), parameters_get ("varnish_management_port")), "varnish_frontend_rules_order" : -5100, "varnish_frontend_routes_order" : -5100, "varnish_drop_caching_enabled" : False, "varnish_drop_cookies_enabled" : False, "varnish_internals_path_prefix" : parameters_format ("%s%s", parameters_get ("internals_path_prefix"), "varnish/"), "varnish_internals_rules_order_allow" : parameters_get ("internals_rules_order_allow"), "varnish_internals_rules_order_deny" : parameters_get ("internals_rules_order_deny"), "varnish_heartbeat_enabled" : True, "varnish_heartbeat_path" : parameters_format ("%s%s", parameters_get ("varnish_internals_path_prefix"), "heartbeat"), "varnish_heartbeat_interval" : 1, "varnish_min_connections_active_count" : parameters_math ("//", parameters_get ("varnish_max_connections_active_count"), 4, True), "varnish_max_connections_active_count" : parameters_math ("//", parameters_get ("frontend_max_connections_active_count"), 4, True), "varnish_max_connections_queue_count" : parameters_math ("*", parameters_get ("varnish_max_connections_active_count"), 4, True), "varnish_max_connections_full_count" : parameters_math ("//", parameters_get ("varnish_max_connections_queue_count"), 8, True), "varnish_keep_alive_reuse" : "always", "varnish_keep_alive_mode" : "keep-alive", "varnish_keep_alive_timeout" : 3600, "varnish_send_proxy_enabled" : False, "samples_via_tls_method" : "ssl_fc", "samples_client_ip_method" : "src", "minimal_configure" : False, "only_frontends_and_backends" : parameters_get ("minimal_configure"), "minimal_global_configure" : parameters_get ("minimal_configure"), "minimal_defaults_configure" : parameters_get ("minimal_configure"), "minimal_frontend_configure" : parameters_get ("minimal_configure"), "minimal_backend_configure" : parameters_get ("minimal_configure"), "global_configure" : parameters_and ( parameters_not (parameters_get ("only_frontends_and_backends")), parameters_not (parameters_get ("minimal_global_configure"))), "global_identity_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_daemon_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_connections_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_checks_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_compression_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_tls_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_tune_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_tune_buffers_configure" : parameters_get ("global_tune_configure"), "global_tune_sockets_configure" : parameters_get ("global_tune_configure"), "global_tune_tls_configure" : parameters_get ("global_tune_configure"), "global_tune_http_configure" : parameters_get ("global_tune_configure"), "global_tune_http2_configure" : parameters_get ("global_tune_configure"), "global_stats_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_logging_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_logging_quiet" : True, "global_state_configure" : parameters_and (parameters_not (parameters_get ("minimal_global_configure")), parameters_get ("state_configure")), "global_experimental_configure" : parameters_not (parameters_get ("minimal_global_configure")), "global_experimental_enabled" : False, "global_http_uri_length_max" : 4 * 1024, "global_http_headers_count_max" : 64, "global_http2_headers_table_size" : 16 * 1024, "global_http2_window_initial_size" : 128 * 1024, "global_http2_streams_count_max" : 128, "global_compression_rate_max" : 0, "global_compression_cpu_max" : 25, "global_compression_mem_max" : 128, "global_compression_level_max" : 9, "global_buffers_size" : 128 * 1024, "global_buffers_rewrite" : 16 * 1024, "global_buffers_count_max" : 4096, "global_buffers_count_reserved" : 16, "defaults_configure" : parameters_and ( parameters_not (parameters_get ("only_frontends_and_backends")), parameters_not (parameters_get ("minimal_defaults_configure"))), "defaults_connections_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_timeouts_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_servers_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_http_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_compression_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_errors_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_stats_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_logging_configure" : parameters_not (parameters_get ("minimal_defaults_configure")), "defaults_state_configure" : parameters_and (parameters_not (parameters_get ("minimal_defaults_configure")), parameters_get ("state_configure")), "frontend_minimal" : parameters_get ("minimal_frontend_configure"), "frontend_bind_minimal" : parameters_get ("frontend_minimal"), "frontend_bind_tls_minimal" : parameters_get ("frontend_bind_minimal"), "frontend_configure" : parameters_not (parameters_get ("frontend_minimal")), "frontend_connections_configure" : parameters_get ("frontend_configure"), "frontend_timeouts_configure" : parameters_get ("frontend_configure"), "frontend_http_configure" : parameters_get ("frontend_configure"), "frontend_compression_configure" : parameters_get ("frontend_configure"), "frontend_stick_configure" : parameters_get ("frontend_configure"), "frontend_monitor_configure" : parameters_get ("frontend_configure"), "frontend_logging_configure" : parameters_get ("frontend_configure"), "frontend_stats_configure" : parameters_get ("frontend_configure"), "backend_minimal" : parameters_get ("minimal_backend_configure"), "backend_configure" : parameters_not (parameters_get ("backend_minimal")), "backend_connections_configure" : parameters_get ("backend_configure"), "backend_timeouts_configure" : parameters_get ("backend_configure"), "backend_servers_configure" : parameters_get ("backend_configure"), "backend_check_configure" : parameters_get ("backend_configure"), "backend_forward_configure" : parameters_get ("backend_configure"), "state_configure" : parameters_not (parameters_get ("minimal_configure")), "sections_extra_separation" : parameters_not (parameters_get ("minimal_configure")), } <file_sep> def raise_error (_code, *_arguments) : raise Exception (_code, *_arguments) def assert_that (_condition) : if not _condition : raise Exception ("62221423") <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _fe.requests.deny (601, _fe.acls.geoip_country_extracted ("XX", _method = "src")) _fe.requests.deny (601, _fe.acls.geoip_country_extracted ("XX", _method = "X-Forwarded-For")) _fe.requests.deny (601, _fe.acls.geoip_country_captured ("XX")) _fe.requests.deny (601, _fe.acls.bogon ()) _fe.requests.deny (601, _fe.acls.bot ()) _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-c7420d78700b3e8fa37945e4ada241f4 var('txn.http_drop_cookies_enabled'),bool -m bool acl acl-d83a8a9567885f6f8343bdae424af3f6 var('txn.http_drop_cookies_excluded'),bool -m bool #---- HTTP Request Rules http-request set-var(txn.http_drop_cookies_enabled) bool(true) http-request del-header "Cookie" if acl-c7420d78700b3e8fa37945e4ada241f4 !acl-d83a8a9567885f6f8343bdae424af3f6 #---- HTTP Response Rules http-response del-header "Set-Cookie" if acl-c7420d78700b3e8fa37945e4ada241f4 !acl-d83a8a9567885f6f8343bdae424af3f6 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, frontend_bind_tls_minimal = False, ) _fe = _ha.http_frontends.basic ( _tls = True, tls_ca_file_enabled = True, tls_verify_client = "optional", ) _be = _ha.http_backends.basic (_frontend = _fe) _operators = ( "874a47fdf56abfb59402779564976f48", "bc98855760c47e3643053790edd856cd", ) _fe.requests.deny ( _code = 403, _acl = _fe.acls.tls_client_certificate (_operators) .negate (), ) _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-27e4a7a42bd33e4473c14fd2fe57ff59 req.cook_cnt('X-HA-Session-Id'),bool -m bool acl acl-2634355899f887a304ac158f113a8436 req.fhdr_cnt('X-HA-Request-Id'),bool -m bool acl acl-a6e64eaf77e3fdea14363735d55f3fca req.fhdr_cnt('X-HA-Session-Id'),bool -m bool acl acl-2be70af4c9ff2f9a3fe4fcf201d25754 var('txn.http_tracking_enabled'),bool -m bool acl acl-5aa394eda8a69488a5e4b507d7588aa9 var('txn.http_tracking_excluded'),bool -m bool #---- HTTP Request Rules http-request set-var(txn.http_tracking_enabled) bool(true) http-request set-header "X-HA-Request-Id" "%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]" if !acl-2634355899f887a304ac158f113a8436 acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 http-request set-var(txn.http_tracking_request) req.fhdr('X-HA-Request-Id',-1) if acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 http-request set-header "X-HA-Session-Id" "%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]" if !acl-a6e64eaf77e3fdea14363735d55f3fca !acl-27e4a7a42bd33e4473c14fd2fe57ff59 acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 http-request set-header "X-HA-Session-Id" "%[req.cook('X-HA-Session-Id')]" if !acl-a6e64eaf77e3fdea14363735d55f3fca acl-27e4a7a42bd33e4473c14fd2fe57ff59 acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 http-request set-var(txn.http_tracking_session) req.fhdr('X-HA-Session-Id',-1) if acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 #---- HTTP Response Rules http-response set-header "X-HA-Request-Id" "%[var('txn.http_tracking_request')]" if acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 http-response set-header "X-HA-Session-Id" "%[var('txn.http_tracking_session')]" if acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 http-response add-header "Set-Cookie" "X-HA-Session-Id=%[var('txn.http_tracking_session')]; Path=/; Max-Age=2419200; SameSite=None; Secure" if acl-2be70af4c9ff2f9a3fe4fcf201d25754 !acl-5aa394eda8a69488a5e4b507d7588aa9 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> from errors import * from tools import * from builders_core import * from builders_acl import * class HaHttpRouteBuilder (HaBuilder) : def __init__ (self, _context, _parameters) : HaBuilder.__init__ (self, _context, _parameters) self._acl = HaHttpAclBuilder (_context, _parameters) self._samples = HaHttpSampleBuilder (_context, _parameters) def _declare_route_if_0 (self, _backend, _acl, **_overrides) : self._context.declare_route_if_0 (_backend, _acl, **_overrides) def _declare_route_unless_0 (self, _backend, _acl, **_overrides) : self._context.declare_route_unless_0 (_backend, _acl, **_overrides) def route (self, _backend, _acl = None, **_overrides) : self._declare_route_if_0 (_backend, _acl, **_overrides) def route_host (self, _backend, _host, _acl = None, **_overrides) : _acl_host = self._acl.host (_host) self.route (_backend, (_acl_host, _acl), **_overrides) def route_path (self, _backend, _path, _acl = None, **_overrides) : _acl_path = self._acl.path (_path) self.route (_backend, (_acl_path, _acl), **_overrides) def route_path_prefix (self, _backend, _path, _acl = None, **_overrides) : _acl_path = self._acl.path_prefix (_path) self.route (_backend, (_acl_path, _acl), **_overrides) def route_path_suffix (self, _backend, _path, _acl = None, **_overrides) : _acl_path = self._acl.path_suffix (_path) self.route (_backend, (_acl_path, _acl), **_overrides) def route_subpath (self, _backend, _path, _acl = None, **_overrides) : _acl_path = self._acl.subpath (_path) self.route (_backend, (_acl_path, _acl), **_overrides) def route_folder (self, _backend, _path, _acl = None, **_overrides) : self.route_path (_backend, _path, _acl, **_overrides) self.route_path_prefix (_backend, _path + "/", _acl, **_overrides) def route_host_path (self, _backend, _host, _path, _acl = None, **_overrides) : _acl_host = self._acl.host (_host) _acl_path = self._acl.path (_path) self.route (_backend, (_acl_host, _acl_path, _acl), **_overrides) def route_host_path_prefix (self, _backend, _host, _path, _acl = None, **_overrides) : _acl_host = self._acl.host (_host) _acl_path = self._acl.path_prefix (_path) self.route (_backend, (_acl_host, _acl_path, _acl), **_overrides) def route_host_path_suffix (self, _backend, _host, _path, _acl = None, **_overrides) : _acl_host = self._acl.host (_host) _acl_path = self._acl.path_suffix (_path) self.route (_backend, (_acl_host, _acl_path, _acl), **_overrides) def route_host_subpath (self, _backend, _host, _path, _acl = None, **_overrides) : _acl_host = self._acl.host (_host) _acl_path = self._acl.subpath (_path) self.route (_backend, (_acl_host, _acl_path, _acl), **_overrides) def route_host_folder (self, _backend, _host, _path, _acl = None, **_overrides) : self.route_host_path (_backend, _host, _path, _acl, **_overrides) self.route_host_path_prefix (_backend, _host, _path + "/", _acl, **_overrides) <file_sep> from declares_globals import * from declares_defaults import * from declares_http import * from declares_tcp import * from declares_servers import * <file_sep> from tools import * from declares_servers import * def declare_http_frontend (_configuration) : declare_http_frontend_connections (_configuration) declare_http_frontend_timeouts (_configuration) declare_http_frontend_monitor (_configuration) declare_http_frontend_stats (_configuration) declare_http_frontend_logging (_configuration) declare_http_frontend_stick (_configuration) def declare_http_backend (_configuration) : declare_http_backend_connections (_configuration) declare_http_backend_check (_configuration) declare_http_backend_server_defaults (_configuration) declare_http_backend_server_timeouts (_configuration) def declare_defaults_http (_configuration) : _configuration.declare_group ( "HTTP", ("http-reuse", "safe"), ("http-check", "disable-on-404"), ("http-check", "send-state"), ("option", "http-keep-alive"), statement_choose_if_non_null ("$backend_http_keep_alive_pool", ("max-keep-alive-queue", "$+backend_http_keep_alive_pool")), ("timeout", "http-request", statement_seconds ("$+defaults_timeout_request")), ("timeout", "http-keep-alive", statement_seconds ("$+defaults_timeout_keep_alive")), ("unique-id-format", statement_quote ("\"", statement_format ("%%[req.hdr(%s)]", "$http_tracking_request_header"))), enabled_if = "$?defaults_http_configure", ) _configuration.declare_group ( "HTTP compression", ("compression", "algo", "gzip"), ("compression", "type", "$\'defaults_compression_content_types"), #! FIXME: Offload is ignored in defaults section... # statement_choose_if ("$?defaults_compression_offload", # ("compression", "offload")), enabled_if = statement_and ("$?defaults_http_configure", "$?defaults_compression_configure"), ) def declare_http_frontend_connections (_configuration) : _configuration.declare_group ( "Protocol", ("mode", "http"), statement_choose_if ("$?frontend_enabled", "enabled", "disabled"), order = 2000 + 100, ) _configuration.declare_group ( "Connections", ("maxconn", "$+frontend_max_connections_active_count"), ("backlog", "$+frontend_max_connections_backlog_count"), statement_choose_match ("$frontend_http_keep_alive_mode", ("keep-alive", ("option", "http-keep-alive")), ("close", ("option", "httpclose"))), enabled_if = "$?frontend_connections_configure", order = 2000 + 100, ) _configuration.declare_group ( "Compression", ("compression", "algo", "gzip"), ("compression", "type", "$\'defaults_compression_content_types"), statement_choose_if ("$?defaults_compression_offload", ("compression", "offload")), enabled_if = statement_and ("$?frontend_http_configure", "$?frontend_compression_configure"), ) def declare_http_frontend_timeouts (_configuration) : _configuration.declare_group ( "Timeouts", statement_choose_if_non_null ("$frontend_http_keep_alive_timeout", ("timeout", "http-keep-alive", statement_seconds ("$+frontend_http_keep_alive_timeout"))), enabled_if = "$?frontend_timeouts_configure", order = 2000 + 101, ) def declare_http_frontend_monitor (_configuration) : _configuration.declare_group ( "Monitoring", ("monitor-uri", "$\'frontend_monitor_path"), # FIXME: `monitor-net` was removed! # ("monitor-net", "$\'frontend_monitor_network"), ("monitor", "fail", "if", "$~frontend_monitor_fail_acl"), enabled_if = statement_and ("$?frontend_monitor_enabled", "$?frontend_monitor_configure"), order = 7000 + 100, ) def declare_http_frontend_stats (_configuration) : _configuration.declare_group ( "Stats", ("stats", "enable"), ("stats", "uri", "$\'frontend_stats_path"), ("stats", "realm", "$\'frontend_stats_auth_realm"), statement_choose_if_non_null ("$frontend_stats_auth_credentials", ("stats", "auth", "$\'frontend_stats_auth_credentials")), statement_choose_if_non_null ("$frontend_stats_admin_acl", ("stats", "admin", "if", "$~frontend_stats_admin_acl")), ("stats", "show-node", "$\'daemon_node"), ("stats", "show-desc", "$\'daemon_description"), ("stats", "show-legends"), statement_choose_if ("$?frontend_stats_modules", ("stats", "show-modules")), statement_choose_if_false ("$?frontend_stats_version", ("stats", "hide-version")), ("stats", "refresh", statement_seconds ("$+frontend_stats_refresh")), enabled_if = statement_and ("$?frontend_stats_enabled", "$?frontend_stats_configure"), order = 7000 + 200, ) def declare_http_frontend_logging (_configuration) : _configuration.declare_group ( "Logging", ("option", "httplog"), statement_choose_if_non_null ("$logging_http_format", ("log-format", "$\"logging_http_format")), enabled_if = "$?frontend_logging_configure", order = 7000 + 400, ) def declare_http_frontend_stick (_configuration) : # FIXME: Make this configurable! _configuration.declare_group ( "Stick tables", ("stick-table", "type", statement_choose_match ("$frontend_http_stick_source", ("src", "ip"), ("X-Forwarded-For", "ip"), ("User-Agent", ("binary", "len", "16")), ), "size", 1024 * 1024, "expire", "3600s", "store", ",".join (( "conn_cur", "conn_cnt", "conn_rate(60s)", "sess_cnt", "sess_rate(60s)", "http_req_cnt", "http_req_rate(60s)", "http_err_cnt", "http_err_rate(60s)", "bytes_in_cnt", "bytes_in_rate(60s)", "bytes_out_cnt", "bytes_out_rate(60s)", )) ), statement_choose_if ("$?frontend_http_stick_track", ("http-request", "track-sc0", statement_choose_match ("$frontend_http_stick_source", ("src", "src"), ("X-Forwarded-For", statement_format ("req.hdr(%s,1),digest(md5),hex,lower", "$logging_http_header_forwarded_for")), ("User-Agent", statement_format ("req.fhdr(User-Agent,-1),digest(md5)")), ) ), ), enabled_if = "$?frontend_stick_configure", order = 5000 + 290, ) def declare_http_backend_connections (_configuration) : _configuration.declare_group ( "Protocol", ("mode", "http"), statement_choose_if ("$?backend_enabled", "enabled", "disabled"), ) _configuration.declare_group ( "Connections", # FIXME: Extract this into common function! statement_choose_match ("$backend_balance", ("round-robin", ("balance", "roundrobin")), ("first", ("balance", "first")), (None, None)), statement_choose_match ("$backend_http_keep_alive_reuse", ("safe", ("http-reuse", "safe")), ("aggressive", ("http-reuse", "aggressive")), ("always", ("http-reuse", "always")), ("never", ("http-reuse", "never"))), statement_choose_match ("$backend_http_keep_alive_mode", ("keep-alive", ("option", "http-keep-alive")), ("server-close", ("option", "http-server-close")), ("close", ("option", "httpclose"))), statement_choose_if_non_null ("$backend_http_keep_alive_pool", ("max-keep-alive-queue", "$+backend_http_keep_alive_pool")), statement_choose_if (statement_and ("$?backend_forward_enabled", "$?backend_forward_configure"), ("option", "forwardfor", "header", "$logging_http_header_forwarded_for", "if-none")), enabled_if = "$?backend_connections_configure", ) def declare_http_backend_check (_configuration) : _configuration.declare_group ( "Check", ("option", "httpchk"), ("http-check", "connect", "default", "linger"), ("http-check", "send", "meth", "$\'backend_http_check_request_method", "uri", "$\'backend_http_check_request_uri", "ver", "$\'backend_http_check_request_version", statement_choose_if_non_null ("$backend_http_check_request_host", ("hdr", "Host", "$\'backend_http_check_request_host")), ), ("http-check", "expect", "$~backend_http_check_expect_matcher", "$\'backend_http_check_expect_pattern"), enabled_if = statement_and ("$?backend_http_check_enabled", "$?backend_check_configure"), ) def declare_http_backend_server_defaults (_configuration) : declare_backend_server_defaults (_configuration, [ # FIXME: ... ]) def declare_http_backend_server_timeouts (_configuration) : declare_backend_server_timeouts (_configuration, [ statement_choose_if_non_null ("$backend_server_timeout_request", ("timeout", "http-request", statement_seconds ("$+backend_server_timeout_request"))), statement_choose_if_non_null ("$backend_server_timeout_keep_alive", ("timeout", "http-keep-alive", statement_seconds ("$+backend_server_timeout_keep_alive"))), statement_choose_if_non_null ("$backend_http_keep_alive_timeout", ("timeout", "http-keep-alive", statement_seconds ("$+backend_http_keep_alive_timeout"))), ]) <file_sep> from tools import * from declares_http import * from declares_tcp import * def declare_defaults (_configuration) : declare_defaults_network (_configuration) declare_defaults_timeouts (_configuration) declare_defaults_servers (_configuration) declare_defaults_http (_configuration) declare_defaults_tcp (_configuration) declare_defaults_logging (_configuration) declare_defaults_stats (_configuration) declare_defaults_error_pages (_configuration) declare_defaults_miscellaneous (_configuration) def declare_defaults_network (_configuration) : _configuration.declare_group ( "Protocol", ("mode", "tcp"), statement_choose_if_false ("$?minimal_defaults_configure", "disabled"), ) _configuration.declare_group ( "Connections", ("maxconn", "$+defaults_frontend_max_connections_active_count"), ("backlog", "$+defaults_frontend_max_connections_backlog_count"), ("rate-limit", "sessions", "$+defaults_frontend_max_sessions_rate"), ("balance", "roundrobin"), ("retries", "4"), enabled_if = "$?defaults_connections_configure", ) _configuration.declare_group ( "Connections TCP-Keep-Alive", ("option", "clitcpka"), ("option", "srvtcpka"), enabled_if = "$?defaults_connections_configure", ) _configuration.declare_group ( "Connections splicing", ("option", "splice-request"), ("option", "splice-response"), ("no", "option", "splice-auto"), enabled_if = "$?defaults_connections_configure", ) def declare_defaults_timeouts (_configuration) : _configuration.declare_group ( "Timeouts", ("timeout", "server", statement_seconds ("$+defaults_timeout_activity_server")), ("timeout", "server-fin", statement_seconds ("$+defaults_timeout_fin")), ("timeout", "client", statement_seconds ("$+defaults_timeout_activity_client")), ("timeout", "client-fin", statement_seconds ("$+defaults_timeout_fin")), ("timeout", "tunnel", statement_seconds ("$+defaults_timeout_activity_tunnel")), ("timeout", "connect", statement_seconds ("$+defaults_timeout_connect")), ("timeout", "queue", statement_seconds ("$+defaults_timeout_queue")), ("timeout", "check", statement_seconds ("$+defaults_timeout_check")), ("timeout", "tarpit", statement_seconds ("$+defaults_timeout_tarpit")), enabled_if = "$?defaults_timeouts_configure", ) def declare_defaults_servers (_configuration) : _configuration.declare_group ( "Servers", ("fullconn", "$+defaults_server_max_connections_full_count"), ("default-server", "minconn", "$+defaults_server_min_connections_active_count"), ("default-server", "maxconn", "$+defaults_server_max_connections_active_count"), ("default-server", "maxqueue", "$+defaults_server_max_connections_queue_count"), ("default-server", "inter", statement_seconds ("$+defaults_server_check_interval_normal")), ("default-server", "fastinter", statement_seconds ("$+defaults_server_check_interval_rising")), ("default-server", "downinter", statement_seconds ("$+defaults_server_check_interval_failed")), ("default-server", "rise", "$+defaults_server_check_count_rising"), ("default-server", "fall", "$+defaults_server_check_count_failed"), ("default-server", "on-error", "fastinter"), ("default-server", "error-limit", "$+defaults_server_check_count_errors"), enabled_if = "$?defaults_servers_configure", ) def declare_defaults_logging (_configuration) : _configuration.declare_group ( "Logging", statement_choose_if ("$?syslog_pg_enabled", ("log", "global")), statement_choose_if ("$?syslog_p_enabled", ("log", "$\'syslog_p_endpoint", "len", 65535, "format", "$\'syslog_p_protocol", "daemon", "info", "err")), ("option", "log-separate-errors"), ("option", "log-health-checks"), ("no", "option", "checkcache"), ("no", "option", "dontlognull"), enabled_if = "$?defaults_logging_configure", ) def declare_defaults_stats (_configuration) : _configuration.declare_group ( "Stats", ("option", "contstats"), ("option", "socket-stats"), enabled_if = "$?defaults_stats_configure", ) def declare_defaults_error_pages (_configuration) : _configuration.declare_group ( "Error pages", ("errorfile", 200, statement_quote ("\'", statement_format ("%s/monitor.http", "$error_pages_store_http"))), # FIXME: Make this deferable! [ ("errorfile", statement_enforce_int (_code), statement_quote ("\'", statement_format ("%s/%d.http", "$error_pages_store_http", _code))) for _code in _configuration._resolve_token ("$error_pages_codes") ], enabled_if = statement_and ("$?error_pages_enabled", "$?defaults_errors_configure"), ) def declare_defaults_miscellaneous (_configuration) : _configuration.declare_group ( "State", # FIXME: Add `server-state-file-name`! ("load-server-state-from-file", "global"), enabled_if = "$?defaults_state_configure", ) <file_sep> import ha _ha = ha.haproxy ( daemon_node = "haproxy.example.com", ) _fe = _ha.http_frontends.basic () _be_web = _ha.http_backends.basic ( _identifier = "http-www", _endpoint = "ipv4@127.0.0.1:9090", http_harden_level = "standard", ) _be_admin = _ha.http_backends.basic ( _identifier = "http-admin", _endpoint = "ipv4@127.0.0.1:9091", http_harden_level = "strict", ) _be_static = _ha.http_backends.basic ( _identifier = "http-static", _endpoint = "ipv4@127.0.0.1:9092", http_harden_level = "paranoid", ) _be_media = _ha.http_backends.basic ( _identifier = "http-media", _endpoint = "ipv4@127.0.0.1:9093", http_harden_level = "paranoid", ) _be_fallback = _ha.http_backends.fallback_deny () _operators = _ha.credentials_create ("operators", "example.com") _operators.declare_user ("operator", "zeregigojacuyixu") _fe.requests.set_forwarded_headers () _fe.requests.variables_defaults () _fe.responses.variables_defaults () _fe.requests.capture_defaults () _fe.responses.capture_defaults () _fe.requests.set_debug_headers () _fe.responses.set_debug_headers () _fe.requests.redirect_via_tls () _fe.requests.redirect_domain_with_www ("example.com", _force_tls = True) _fe.requests.redirect_prefix ("https://www.example.com/blog", _acl = ( _fe.acls.host ("blog.example.com"), )) _fe.requests.redirect_prefix ("https://admin.example.com", _acl = ( _fe.acls.host ("www.example.com"), _fe.acls.path_prefix ("/admin/"), )) _be_admin.requests.authenticate (_operators) for _be_current in [_be_web, _be_admin, _be_static, _be_media] : _be_current.requests.harden_enable () _be_current.requests.harden_all () _be_current.responses.harden_all () for _be_current in [_be_web, _be_static, _be_media] : _be_web.requests.drop_cookies_enable () _be_web.requests.drop_cookies () _be_web.responses.drop_cookies () _be_web.requests.force_caching_enable () _be_web.responses.force_caching () _fe.routes.route (_be_web, _acl = ( _fe.acls.host ("www.example.com"), )) _fe.routes.route (_be_admin, _acl = ( _fe.acls.host ("admin.example.com"), )) _fe.routes.route (_be_static, _acl = ( _fe.acls.host (("www.example.com", "admin.example.com")), ("/assets/", "/public/"), )) _fe.routes.route (_be_media, _acl = ( _fe.acls.host ("media.example.com"), )) _fe.routes.route (_be_fallback) _ha.output_stdout () <file_sep> import ha _ha = ha.haproxy ( daemon_node = "haproxy-sandbox-1.servers.example.com", defaults_configure = True, global_configure = False, ) _ha.output_stdout () <file_sep> from errors import * from tools import * from builders_core import * from builders_samples import * class HaHttpAclBuilder (HaBuilder) : def __init__ (self, _context, _parameters) : HaBuilder.__init__ (self, _context, _parameters) self._samples = HaHttpSampleBuilder (_context, _parameters) def client_ip (self, _ip, _method = None, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.client_ip (_method), "ip", None, None, _ip) def ip_from_variable (self, _variable, _ip, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "ip", None, None, _ip) def ip_from_request_header (self, _header, _ip, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header (_header), "ip", None, None, _ip) def ip_from_response_header (self, _header, _ip, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header (_header), "ip", None, None, _ip) def client_ip_in_map (self, _map, _method = None, _identifier = None) : return self.sample_ip_in_map (self._samples.client_ip (_method), _map, _identifier) def ip_from_variable_in_map (self, _variable, _map, _identifier = None) : return self.sample_ip_in_map (self._samples.variable (_variable), _map, _identifier) def ip_from_request_header_in_map (self, _header, _map, _identifier = None) : return self.sample_ip_in_map (self._samples.request_header (_header), _map, _identifier) def ip_from_response_header_in_map (self, _header, _map, _identifier = None) : return self.sample_ip_in_map (self._samples.response_header (_header), _map, _identifier) def string_from_variable_in_map (self, _variable, _map, _identifier = None) : return self.sample_string_in_map (self._samples.variable (_variable), _map, _identifier) def string_from_request_header_in_map (self, _header, _map, _identifier = None) : return self.sample_string_in_map (self._samples.request_header (_header), _map, _identifier) def string_from_response_header_in_map (self, _header, _map, _identifier = None) : return self.sample_string_in_map (self._samples.response_header (_header), _map, _identifier) def frontend_port (self, _port, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.frontend_port (), "int", None, "eq", (_port,)) def forwarded_host (self, _host, _from_logging = False, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.forwarded_host (None, _from_logging), "str", ("-i",), "eq", _host) def forwarded_for (self, _ip, _from_logging = False, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.forwarded_for (None, _from_logging), "ip", None, None, (_ip,)) def forwarded_proto (self, _proto, _from_logging = False, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.forwarded_proto (None, _from_logging), "str", ("-i"), "eq", (_proto,)) def forwarded_port (self, _port, _from_logging = False, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.forwarded_for (None, _from_logging), "int", None, "eq", (_port,)) def host (self, _host, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.host (), "str", ("-i",), "eq", _host) def host_prefix (self, _host, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.host (), "beg", ("-i",), None, _host) def host_suffix (self, _host, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.host (), "end", ("-i",), None, _host) def path (self, _path, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.path (), "str", None, "eq", _path) def path_prefix (self, _path, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.path (), "beg", None, None, _path) def path_suffix (self, _path, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.path (), "end", None, None, _path) def path_substring (self, _path, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.path (), "sub", None, None, _path) def subpath (self, _path, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.path (), "dir", None, None, _path) def path_regex (self, _path_regex, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.path (), "reg", None, None, _path_regex) def query (self, _query, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.query (), "str", None, "eq", _query) def query_empty (self, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.query (), "len", None, None, (0,)) def query_prefix (self, _query, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.query (), "beg", None, None, _query) def query_exists (self, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.query (), "found", None, None, None) def query_parameter (self, _parameter, _value, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.query_parameter (_parameter), "str", None, "eq", _value) def query_parameter_exists (self, _parameter, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.query_parameter (_parameter), "found", None, None, None) def request_method (self, _method, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_method (), "str", ("-i",), "eq", (_method,)) def response_status (self, _code, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_status (), "int", None, "eq", (_code,)) def request_header_exists (self, _header, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header_exists (_header, _expected), "bool", None, None, None) def request_header_empty (self, _name, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header (_name), "str", None, "eq", ("",)) def request_header_equals (self, _name, _value, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header (_name), "str", None, "eq", (_value,)) def request_header_prefix (self, _name, _prefix, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header (_name), "beg", None, None, _prefix) def request_header_suffix (self, _name, _suffix, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header (_name), "end", None, None, _suffix) def request_header_regex (self, _name, _regex, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_header (_name), "reg", None, None, _regex) def response_header_exists (self, _header, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header_exists (_header, _expected), "bool", None, None, None) def response_header_empty (self, _name, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header (_name), "str", None, "eq", "") def response_header_equals (self, _name, _value, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header (_name), "str", None, "eq", (_value,)) def response_header_prefix (self, _name, _prefix, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header (_name), "beg", None, None, _prefix) def response_header_suffix (self, _name, _suffix, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header (_name), "end", None, None, _suffix) def response_header_regex (self, _name, _regex, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_header (_name), "reg", None, None, _regex) def request_cookie_exists (self, _cookie, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.request_cookie_exists (_cookie, _expected), "bool", None, None, None) def response_cookie_exists (self, _cookie, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.response_cookie_exists (_header, _expected), "bool", None, None, None) def variable_exists (self, _variable, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "found", None, None, None) def variable_empty (self, _variable, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "str", None, "eq", "") def variable_equals (self, _variable, _value, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "str", None, "eq", (_value,)) def variable_prefix (self, _variable, _prefix, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "beg", None, None, _prefix) def variable_suffix (self, _variable, _suffix, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "end", None, None, _suffix) def variable_regex (self, _variable, _regex, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable), "reg", None, None, _regex) def variable_bool (self, _variable, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable_bool (_variable, _expected), "bool", None, None, None) def variables_equals (self, _variable_a, _variable_b, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.variable (_variable_a, (("strcmp", _variable_b),) + (("bool",) if not _expected else ("bool", "not"))), "bool", None, None, None) def via_tls (self, _expected = True, _method = None, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.via_tls (_expected, _method), "bool", None, None, None) def tls_client_certificate (self, _fingerprint, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.tls_client_certificate (), "str", ("-i",), "eq", (_fingerprint,)) def tls_client_certificate_issuer_cn (self, _expected_cn, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.tls_client_certificate_issuer_cn (), "str", ("-i",), "eq", (_expected_cn,)) def tls_client_certificate_subject_cn (self, _expected_cn, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.tls_client_certificate_subject_cn (), "str", ("-i",), "eq", (_expected_cn,)) def tls_session_sni_exists (self, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.tls_session_sni_exists (_expected), "bool", None, None, None) def tls_session_sni_equals (self, _value, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.tls_session_sni (), "str", None, "eq", (_value,)) def tls_session_sni_equals_variable (self, _variable, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.tls_session_sni ((("strcmp", _variable),)), "int", None, "eq", (0,)) def authenticated (self, _credentials, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.authenticated (_credentials, _expected), "bool", None, None, None) def backend_active (self, _backend, _expected = True, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.backend_active (_backend, _expected), "bool", None, None, None) def geoip_country_extracted (self, _country, _method = None, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.geoip_country_extracted (_method), "str", ("-i",), "eq", _country) def geoip_country_captured (self, _country, _identifier = None) : return self._context.acl_0 (_identifier, self._samples.geoip_country_captured (), "str", ("-i",), "eq", _country) def bogon (self, _method = None, _identifier = None) : return self.bogon_sample (self._samples.client_ip (_method), _identifier) def bogon_from_variable (self, _variable, _identifier = None) : return self.bogon_sample (self._samples.variable (_variable), _identifier) def bogon_from_request_header (self, _header, _identifier = None) : return self.bogon_sample (self._samples.request_header (_header), _identifier) def bogon_from_response_header (self, _header, _identifier = None) : return self.bogon_sample (self._samples.response_header (_header), _identifier) def bogon_sample (self, _sample, _identifier = None) : return self.sample_ip_in_map (_sample, "$'bogons_map", _identifier) def bot (self, _identifier = None) : return self.bot_sample (self._samples.request_header ("User-Agent", ("lower",)), _identifier) def bot_sample (self, _sample, _identifier = None) : return self.sample_substring_in_map (_sample, "$'bots_map", _identifier) def sample_ip_in_map (self, _sample, _map, _identifier = None) : return self._context.acl_0 (_identifier, _sample, "ip", ("-n", "-f"), None, _map) def sample_string_in_map (self, _sample, _map, _identifier = None) : return self._context.acl_0 (_identifier, _sample, "str", ("-i", "-f"), None, _map) def sample_substring_in_map (self, _sample, _map, _identifier = None) : return self._context.acl_0 (_identifier, _sample, "sub", ("-i", "-f"), None, _map) def ab_in_bucket (self, _expected, _count, _criteria = None, _identifier = None) : if _criteria is None : _criteria = "src" if _criteria == "session" : _sample = self._samples.variable ("$http_tracking_session_variable", (("wt6", 1), ("mod", _count))) elif _criteria == "request" : _sample = self._samples.variable ("$http_tracking_request_variable", (("wt6", 1), ("mod", _count))) elif _criteria == "agent" : _sample = self._samples.variable ("$logging_http_variable_agent", (("wt6", 1), ("mod", _count))) elif _criteria == "src" : _sample = self._samples.client_ip ("src", (("wt6", 1), ("mod", _count))) elif _criteria == "X-Forwarded-For" : _sample = self._samples.client_ip ("X-Forwarded-For", (("wt6", 1), ("mod", _count))) elif _criteria == "path" : _sample = self._samples.variable ("$logging_http_variable_path", (("wt6", 1), ("mod", _count))) elif _criteria == "action" : _sample = self._samples.variable ("$logging_http_variable_action", (("wt6", 1), ("mod", _count))) else : raise_error ("34cca11c", _criteria) return self._context.acl_0 (_identifier, _sample, "int", None, "eq", (_expected,)) <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- HTTP Request Rules http-request capture req.fhdr('Host',-1),base64 id 0 http-request capture req.fhdr('X-Forwarded-Host',-1),base64 id 1 http-request capture req.fhdr('X-Forwarded-For',-1),base64 id 2 http-request capture req.fhdr('X-Forwarded-Proto',-1),base64 id 3 http-request capture req.fhdr('X-Forwarded-Port',-1),base64 id 4 http-request capture req.fhdr('X-HA-Request-Id',-1),base64 id 5 http-request capture req.fhdr('X-HA-Session-Id',-1),base64 id 6 http-request capture req.fhdr('User-Agent',-1),base64 id 7 http-request capture req.fhdr('Referer',-1),base64 id 8 http-request capture req.fhdr('Accept-Encoding',-1),base64 id 9 http-request capture req.fhdr('Accept-Language',-1),base64 id 10 http-request capture req.fhdr('Accept-Charset',-1),base64 id 11 http-request capture req.fhdr('Cache-Control',-1),base64 id 12 http-request capture req.fhdr('If-None-Match',-1),base64 id 13 http-request capture req.fhdr('If-Match',-1),base64 id 14 http-request capture req.fhdr('If-Modified-Since',-1),base64 id 15 http-request capture req.fhdr('If-Unmodified-Since',-1),base64 id 16 http-request capture req.fhdr('Pragma',-1),base64 id 17 http-request capture req.fhdr('Cookie',1),base64 id 18 http-request capture req.fhdr('Cookie',2),base64 id 19 http-request capture req.fhdr('Cookie',3),base64 id 20 http-request capture req.fhdr('Cookie',4),base64 id 21 #---- HTTP Response Rules http-response capture res.fhdr('Location',-1),base64 id 0 http-response capture res.fhdr('Content-Type',-1),base64 id 1 http-response capture res.fhdr('Content-Encoding',-1),base64 id 2 http-response capture res.fhdr('Content-Length',-1),base64 id 3 http-response capture res.fhdr('Content-Disposition',-1),base64 id 4 http-response capture res.fhdr('Cache-Control',-1),base64 id 5 http-response capture res.fhdr('Last-Modified',-1),base64 id 6 http-response capture res.fhdr('Expires',-1),base64 id 7 http-response capture res.fhdr('Date',-1),base64 id 8 http-response capture res.fhdr('ETag',-1),base64 id 9 http-response capture res.fhdr('Vary',-1),base64 id 10 http-response capture res.fhdr('Age',-1),base64 id 11 http-response capture res.fhdr('Pragma',-1),base64 id 12 http-response capture res.fhdr('Set-Cookie',1),base64 id 13 http-response capture res.fhdr('Set-Cookie',2),base64 id 14 http-response capture res.fhdr('Set-Cookie',3),base64 id 15 http-response capture res.fhdr('Set-Cookie',4),base64 id 16 #---- Routes use_backend http-backend #---- Captures for requests declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 declare capture request len 1024 #---- Captures for responses declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 declare capture response len 1024 backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> from parameters import Parameters from scroll import Scroll import defaults import declares import builders from errors import * from tools import * def haproxy (_parameters = None, **_overrides) : _parameters = Parameters (_parameters, _overrides, defaults.parameters) return HaProxy (_parameters) def parameters (_parameters = None, **_overrides) : return Parameters (_parameters, _overrides, defaults.parameters) def overrides (**_overrides) : return _overrides class HaBase (object) : def _expand_token (self, _token, _join = None, _quote = None) : return expand_token (_token, self._parameters, _join, _quote) def _resolve_token (self, _token) : return resolve_token (_token, self._parameters) def _enforce_token (self, _token, _schema) : return enforce_token (_token, _schema) def _expand_and_enforce_token (self, _token, _schema) : _token = self._expand_token (_token) _token = self._enforce_token (_token, _schema) return _token class HaProxy (HaBase) : def __init__ (self, _parameters) : HaBase.__init__ (self) _identifier = enforce_identifier (_parameters, parameters_get ("proxy_identifier")) self.identifier = _identifier self._parameters = _parameters if self._expand_token ("$?global_configure") : self.globals = HaGlobals (self._parameters._fork ()) else : self.globals = None if self._expand_token ("$?defaults_configure") : self.defaults = HaDefaults (self._parameters._fork ()) else : self.defaults = None self._frontends = dict () self._frontends_ordered = list () self._backends = dict () self._backends_ordered = list () self._resolvers = dict () self._resolvers_ordered = list () self._credentials = dict () self._credentials_ordered = list () self.http_frontends = self.http_frontend_builder () self.http_backends = self.http_backend_builder () def frontends (self) : return self._frontends_ordered def backends (self) : return self._backends_ordered def frontend (self, _identifier) : _identifier = enforce_identifier (self._parameters, _identifier) return self._frontends[_identifier] def backend (self, _identifier) : _identifier = enforce_identifier (self._parameters, _identifier) return self._backends[_identifier] def resolvers (self, _identifier) : _identifier = enforce_identifier (self._parameters, _identifier) return self._resolvers[_identifier] def credentials (self, _identifier) : _identifier = enforce_identifier (self._parameters, _identifier) return self._credentials[_identifier] def frontend_create (self, _identifier, _type = None, **_overrides) : _parameters = self._parameters._fork (**_overrides) _identifier = enforce_identifier (_parameters, _identifier) _parameters._set (frontend_identifier = _identifier) if _identifier in self._frontends : raise_error ("eb0997d4", _identifier) if _type is None : _type = HaFrontend _frontend = _type (_identifier, _parameters) self._frontends[_identifier] = _frontend self._frontends_ordered.append (_frontend) self._frontends_ordered.sort (key = lambda _section : _section._order) return _frontend def backend_create (self, _identifier, _type = None, **_overrides) : _parameters = self._parameters._fork (**_overrides) _identifier = enforce_identifier (_parameters, _identifier) _parameters._set (backend_identifier = _identifier) if _identifier in self._backends : raise_error ("ad2910cf", _identifier) if _type is None : _type = HaBackend _backend = _type (_identifier, _parameters) self._backends[_identifier] = _backend self._backends_ordered.append (_backend) self._backends_ordered.sort (key = lambda _section : _section._order) return _backend def resolvers_create (self, _identifier, **_overrides) : _parameters = self._parameters._fork (**_overrides) _identifier = enforce_identifier (_parameters, _identifier) _parameters._set (resolvers_identifier = _identifier) if _identifier in self._resolvers : raise_error ("07b20b3f", _identifier) _resolvers = HaResolvers (_identifier, _parameters) self._resolvers[_identifier] = _resolvers self._resolvers_ordered.append (_resolvers) self._resolvers_ordered.sort (key = lambda _section : _section._order) return _resolvers def credentials_create (self, _identifier, _realm = None, **_overrides) : _parameters = self._parameters._fork (**_overrides) _identifier = enforce_identifier (_parameters, _identifier) _parameters._set (credentials_identifier = _identifier) if _identifier in self._credentials : raise_error ("0e49fc8e", _identifier) _credentials = HaCredentials (_identifier, _realm, _parameters) self._credentials[_identifier] = _credentials self._credentials_ordered.append (_credentials) self._credentials_ordered.sort (key = lambda _section : _section._order) return _credentials def tcp_frontend_create (self, _identifier, **_overrides) : return self.frontend_create (_identifier, _type = HaTcpFrontend, frontend_mode = "tcp", **_overrides) def tcp_backend_create (self, _identifier, **_overrides) : return self.backend_create (_identifier, _type = HaTcpBackend, backend_mode = "tcp", **_overrides) def http_frontend_create (self, _identifier, **_overrides) : return self.frontend_create (_identifier, _type = HaHttpFrontend, frontend_mode = "http", **_overrides) def http_backend_create (self, _identifier, **_overrides) : return self.backend_create (_identifier, _type = HaHttpBackend, backend_mode = "http", **_overrides) def http_frontend_builder (self) : return builders.HaHttpFrontendBuilder (self, self._parameters) def http_backend_builder (self) : return builders.HaHttpBackendBuilder (self, self._parameters) def output_stdout (self) : _scroll = self.generate () _scroll.output_stdout () def generate (self) : self._declare_implicit_auto () _empty_lines = 8 if self._expand_token ("$?sections_extra_separation") else 2 _scroll = Scroll () _scroll.include_empty_line (99, 0, _empty_lines) if self.globals is not None : _scroll.include_normal_line (100, 0, self.globals.generate ()) _scroll.include_empty_line (100, 0, _empty_lines) if self.defaults is not None : _scroll.include_normal_line (200, 0, self.defaults.generate ()) _scroll.include_empty_line (200, 0, _empty_lines) _scroll.include_normal_line (300, 0, [_frontend.generate () for _frontend in self._frontends_ordered]) _scroll.include_empty_line (300, 0, _empty_lines) _scroll.include_normal_line (400, 0, [_backend.generate () for _backend in self._backends_ordered]) _scroll.include_empty_line (400, 0, _empty_lines) _scroll.include_normal_line (500, 0, [_resolvers.generate () for _resolvers in self._resolvers_ordered]) _scroll.include_empty_line (500, 0, _empty_lines) _scroll.include_normal_line (600, 0, [_credentials.generate () for _credentials in self._credentials_ordered]) _scroll.include_empty_line (600, 0, _empty_lines) return _scroll def _declare_implicit_auto (self) : if self.globals is not None : self.globals._declare_implicit_auto () if self.defaults is not None : self.defaults._declare_implicit_auto () for _frontend in self._frontends_ordered : _frontend._declare_implicit_auto () for _backend in self._backends_ordered : _backend._declare_implicit_auto () class HaSection (HaBase) : def __init__ (self, _parameters, declare_implicit_if = True) : HaBase.__init__ (self) self._parameters = _parameters self._statements = HaStatementGroup (self._parameters, None, order = 4000) self._custom_statements = HaStatementGroup (self._parameters, "Custom", order = 6000) self._declare_implicit_if = declare_implicit_if self._declare_implicit_done = False self._order = self._parameters._get ("order", 999999) def declare (self, *_tokens, **_options) : return self._statements.declare (_tokens, **_options) def declare_group (self, _heading, *_statements, **_options) : return self._statements.declare_group (_heading, *_statements, **_options) def declare_custom (self, *_tokens, **_options) : return self._custom_statements.declare (_tokens, **_options) def declare_custom_group (self, _heading, *_statements, **_options) : return self._custom_statements.declare_group (_heading, *_statements, **_options) def declare_implicit (self, **_options) : if self._declare_implicit_done : raise_error ("215d179b") self._declare_implicit_done = True self._declare_implicit (**_options) def _declare_implicit (self) : pass def _declare_implicit_auto (self) : if not self._declare_implicit_done : _declare_implicit_if = self._resolve_token (self._declare_implicit_if) if _declare_implicit_if is True : self.declare_implicit () elif _declare_implicit_if is False : pass else : raise_error ("c9d16b7a", _declare_implicit_if) def generate (self) : self._declare_implicit_auto () _scroll = Scroll () _empty_lines = 4 if self._expand_token ("$?sections_extra_separation") else 2 _scroll.include_empty_line (99, 0, _empty_lines) _scroll.include_normal_line (100, 0, self._generate_header ()) _scroll.include_empty_line (199, 0, 1) _scroll.include_normal_line (200, 0, self._generate_statements ()) _scroll.include_empty_line (299, 0, 1) _scroll.include_normal_line (300, 0, self._generate_trailer ()) _scroll.include_empty_line (399, 0, _empty_lines) return _scroll def _generate_header (self) : raise_error ("1adb835c") def _generate_trailer (self) : return Scroll () def _generate_statements (self) : _scroll = Scroll (1) self._statements.generate (_scroll, _merge = True) self._generate_statements_extra (_scroll) self._custom_statements.generate (_scroll, _merge = True) return _scroll def _generate_statements_extra (self, _scroll) : pass class HaGlobals (HaSection) : def __init__ (self, _parameters) : HaSection.__init__ (self, _parameters) def _declare_implicit (self) : declares.declare_globals (self) def _generate_header (self) : _scroll = Scroll () _scroll.include_normal_line (0, 0, "global") return _scroll class HaDefaults (HaSection) : def __init__ (self, _parameters) : HaSection.__init__ (self, _parameters) def _declare_implicit (self) : declares.declare_defaults (self) def _generate_header (self) : _scroll = Scroll () _scroll.include_normal_line (0, 0, "defaults") return _scroll class HaResolvers (HaSection) : def __init__ (self, _identifier, _parameters) : HaSection.__init__ (self, _parameters) self.identifier = enforce_identifier (self._parameters, _identifier) self._nameserver_statements = HaStatementGroup (self._parameters, "Nameservers", order = 5000 + 100) self._parameter_statements = HaStatementGroup (self._parameters, "Parameters", order = 5000 + 200) self._parameter_statements.declare (("hold", "valid", statement_seconds (60))) self._parameter_statements.declare (("hold", "obsolete", statement_seconds (3600))) self._parameter_statements.declare (("hold", "nx", statement_seconds (6))) self._parameter_statements.declare (("hold", "refused", statement_seconds (6))) self._parameter_statements.declare (("hold", "timeout", statement_seconds (6))) self._parameter_statements.declare (("hold", "other", statement_seconds (6))) self._parameter_statements.declare (("timeout", "resolve", statement_seconds (1))) self._parameter_statements.declare (("timeout", "retry", statement_seconds (1))) self._parameter_statements.declare (("resolve_retries", 4)) self._parameter_statements.declare (("accepted_payload_size", 8192)) def declare_nameserver (self, _nameserver, _ip, _port) : self._nameserver_statements.declare ( ("nameserver", statement_quote ("\'", _nameserver), statement_quote ("\'", statement_format ("%s:%d", statement_enforce_string (_ip), statement_enforce_int (_port))) )) def _generate_header (self) : _scroll = Scroll () _scroll.include_normal_line (0, 0, self._expand_token (("resolvers", "$\'resolvers_identifier"))) return _scroll def _generate_statements_extra (self, _scroll) : self._nameserver_statements.generate (_scroll) self._parameter_statements.generate (_scroll) def _self_expand_token (self) : return self.identifier def _self_resolve_token (self) : return self.identifier class HaCredentials (HaSection) : def __init__ (self, _identifier, _realm, _parameters) : HaSection.__init__ (self, _parameters) self.identifier = enforce_identifier (self._parameters, _identifier) self.realm = enforce_identifier (self._parameters, _realm) if _realm is not None else None self._group_statements = HaStatementGroup (self._parameters, "Groups", order = 5000 + 100) self._user_statements = HaStatementGroup (self._parameters, "Users", order = 5000 + 200) def declare_group (self, _group, _users = None) : self._group_statements.declare ( ("group", statement_quote ("\'", _group), statement_choose_if_non_null ( _users, ("users", statement_quote ("\'", statement_join (",", _users)))) )) def declare_user (self, _user, _password, _password_secure = False, _groups = None) : self._user_statements.declare ( ("user", statement_quote ("\'", _user), statement_choose_if ( _password_secure, ("password", statement_quote ("\'", _password)), ("insecure-password", statement_quote ("\'", _password))), statement_choose_if_non_null ( _groups, ("groups", statement_quote ("\'", statement_join (",", _groups)))) )) def _generate_header (self) : _scroll = Scroll () _scroll.include_normal_line (0, 0, self._expand_token (("userlist", "$\'credentials_identifier"))) return _scroll def _generate_statements_extra (self, _scroll) : self._group_statements.generate (_scroll) self._user_statements.generate (_scroll) def _self_expand_token (self) : return self.identifier def _self_resolve_token (self) : return self.identifier class HaWorker (HaSection) : def __init__ (self, _identifier, _parameters) : HaSection.__init__ (self, _parameters) self.identifier = enforce_identifier (self._parameters, _identifier) self._acl = list () self._samples = list () self._tcp_request_rule_statements = HaStatementGroup (self._parameters, "TCP Request Rules", order = 5000 + 300 - 1) self._tcp_response_rule_statements = HaStatementGroup (self._parameters, "TCP Response Rules", order = 5000 + 400 - 1) self._http_request_rule_statements = HaStatementGroup (self._parameters, "HTTP Request Rules", order = 5000 + 300) self._http_response_rule_statements = HaStatementGroup (self._parameters, "HTTP Response Rules", order = 5000 + 400) def acl_1 (self, _criteria, _matcher, _patterns) : return self.acl_0 (None, _criteria, _matcher, None, None, _patterns) def acl_0 (self, _identifier, _criteria, _matcher, _flags, _operator, _patterns) : _acl = HaAcl (self._parameters, _identifier, _criteria, _matcher, _flags, _operator, _patterns) self._acl.append (_acl) return _acl def http_acl_builder (self) : return builders.HaHttpAclBuilder (self, self._parameters) def _condition_if (self, _acl) : if _acl is True : return None if _acl is False : return ("if", "FALSE") return self._condition_0 ("if", _acl) if _acl is not None else None def _condition_unless (self, _acl) : if _acl is False : return None if _acl is True : return ("unless", "TRUE") return self._condition_0 ("unless", _acl) if _acl is not None else None def _condition_0 (self, _method, _acl) : def _condition (_expand) : _method_expanded = _expand (_method) _acl_expanded = _expand (_acl) if _acl_expanded is not None : return (_method_expanded, _acl_expanded) else : return None return _condition def sample_1 (self, _method, _arguments) : return self.sample_0 (_method, _arguments, None) def sample_0 (self, _method, _arguments, transforms) : _sample = HaSample (self._parameters, _method, _arguments, transforms) self._samples.append (_sample) return _sample def http_sample_builder (self) : return builders.HaHttpSampleBuilder (self, self._parameters) def declare_http_request_rule (self, _action, **_overrides) : self.declare_http_request_rule_0 ((_action, None), **_overrides) def declare_http_request_rule_if (self, _action, _acl, **_overrides) : _condition = self._condition_if (_acl) self.declare_http_request_rule_0 ((_action, _condition), **_overrides) def declare_http_request_rule_unless (self, _action, _acl, **_overrides) : _condition = self._condition_unless (_acl) self.declare_http_request_rule_0 ((_action, _condition), **_overrides) def declare_http_request_rule_0 (self, _rule, **_overrides) : self._http_request_rule_statements.declare (("http-request", _rule), **_overrides) def http_request_rule_builder (self) : return builders.HaHttpRequestRuleBuilder (self, self._parameters) def declare_http_response_rule_if (self, _action, **_overrides) : self.declare_http_response_rule_0 ((_action, None), **_overrides) def declare_http_response_rule_if (self, _action, _acl, **_overrides) : _condition = self._condition_if (_acl) self.declare_http_response_rule_0 ((_action, _condition), **_overrides) def declare_http_response_rule_unless (self, _action, _acl, **_overrides) : _condition = self._condition_unless (_acl) self.declare_http_response_rule_0 ((_action, _condition), **_overrides) def declare_http_response_rule_0 (self, _rule, **_overrides) : self._http_response_rule_statements.declare (("http-response", _rule), **_overrides) def http_response_rule_builder (self) : return builders.HaHttpResponseRuleBuilder (self, self._parameters) def declare_tcp_request_rule (self, _action, **_overrides) : self.declare_tcp_request_rule_0 ((_action, None), **_overrides) def declare_tcp_request_rule_if (self, _action, _acl, **_overrides) : _condition = self._condition_if (_acl) self.declare_tcp_request_rule_0 ((_action, _condition), **_overrides) def declare_tcp_request_rule_unless (self, _action, _acl, **_overrides) : _condition = self._condition_unless (_acl) self.declare_tcp_request_rule_0 ((_action, _condition), **_overrides) def declare_tcp_request_rule_0 (self, _rule, **_overrides) : self._tcp_request_rule_statements.declare (("tcp-request", _rule), **_overrides) def declare_tcp_response_rule (self, _action, **_overrides) : self.declare_tcp_response_rule_0 ((_action, None), **_overrides) def declare_tcp_response_rule_if (self, _action, _acl, **_overrides) : _condition = self._condition_if (_acl) self.declare_tcp_response_rule_0 ((_action, _condition), **_overrides) def declare_tcp_response_rule_unless (self, _action, _acl, **_overrides) : _condition = self._condition_unless (_acl) self.declare_tcp_response_rule_0 ((_action, _condition), **_overrides) def declare_tcp_response_rule_0 (self, _rule, **_overrides) : self._tcp_response_rule_statements.declare (("tcp-response", _rule), **_overrides) def _generate_statements_for_acl (self, _scroll) : if len (self._acl) > 0 : _acl_uniques = set () _acl_statements = list () _acl_expanded = set () for _acl in self._acl : if _acl._expanded : _acl_tokens = _acl.generate () _acl_identifier = _acl._generated_identifier _acl_expanded.add (_acl_identifier) for _acl in self._acl : _acl_tokens = _acl.generate () _acl_identifier = _acl._generated_identifier if _acl_identifier not in _acl_expanded : continue if (_acl_identifier, _acl._generated_fingerprint) in _acl_uniques : continue else : _acl_uniques.add ((_acl_identifier, _acl._generated_fingerprint)) if isinstance (_acl_tokens, list) : for _acl_tokens in _acl_tokens : _acl_statements.append ((_acl_identifier, _acl_tokens)) else : _acl_statements.append ((_acl_identifier, _acl_tokens)) _acl_statements.sort (key = lambda _acl_statement : (_acl_statement[1][2:], _acl_statement[0])) _statements = HaStatementGroup (self._parameters, "ACL", order = 5000 + 200) for _acl_statement in _acl_statements : _statements.declare (_acl_statement[1]) _statements.generate (_scroll) def _generate_statements_for_http_rules (self, _scroll) : self._tcp_request_rule_statements.generate (_scroll) self._tcp_response_rule_statements.generate (_scroll) self._http_request_rule_statements.generate (_scroll) self._http_response_rule_statements.generate (_scroll) def _self_expand_token (self) : return self.identifier def _self_resolve_token (self) : return self.identifier class HaFrontend (HaWorker) : def __init__ (self, _identifier, _parameters) : HaWorker.__init__ (self, _identifier, _parameters) self._bind_statements = HaStatementGroup (self._parameters, "Bind", order = 5000 + 120) self._route_statements = HaStatementGroup (self._parameters, "Routes", order = 5000 + 500) self._request_capture_statements = HaStatementGroup (self._parameters, "Captures for requests", order = 8000 + 830) self._request_captures_count = 0 self._response_capture_statements = HaStatementGroup (self._parameters, "Captures for responses", order = 8000 + 840) self._response_captures_count = 0 def declare_bind (self, _endpoint = "$frontend_bind_endpoint", _name = None, _options = "$frontend_bind_options", order = None, overrides = None) : _name = statement_choose_if (_name, ("name", statement_quote ("\'", _name))) self._bind_statements.declare (("bind", statement_quote ("\'", _endpoint), _name, _options), order = order, overrides = overrides) def declare_bind_tls (self, _endpoint = "$frontend_bind_tls_endpoint", _name = None, _certificate = "$\'frontend_bind_tls_certificate", _certificate_rules = "$\'frontend_bind_tls_certificate_rules", _options = "$frontend_bind_tls_options", order = None, overrides = None) : _tls_options = ["ssl"] if _certificate is not None : _tls_options.append (statement_choose_if_non_null (_certificate, ("crt", _certificate))) if _certificate_rules is not None : _tls_options.append (statement_choose_if_non_null (_certificate_rules, ("crt-list", _certificate_rules))) _tls_options = tuple (_tls_options) _name = statement_choose_if (_name, ("name", statement_quote ("\'", _name))) self._bind_statements.declare (("bind", statement_quote ("\'", _endpoint), _name, _tls_options, _options), order = order, overrides = overrides) def declare_route (self, _backend, **_overrides) : self.declare_route_if_0 (_backend, None, **_overrides) def declare_route_if_0 (self, _backend, _acl, **_overrides) : _condition = self._condition_if (_acl) if isinstance (_backend, int) : self._route_statements.declare (("http-request", "return", "status", _backend, "file", statement_path_join (("$error_pages_store_html", "%d.html" % _backend), quote = True), "content-type", statement_quote ("\'", "text/html"), _condition), **_overrides) else : self._route_statements.declare (("use_backend", _backend, _condition), **_overrides) def declare_route_unless_0 (self, _backend, _acl, **_overrides) : _condition = self._condition_unless (_acl) if isinstance (_backend, int) : self._route_statements.declare (("http-request", "return", "status", _backend, "file", statement_path_join (("$error_pages_store_html", "%d.html" % _backend), quote = True), "content-type", statement_quote ("\'", "text/html"), _condition), **_overrides) else : self._route_statements.declare (("use_backend", _backend, _condition), **_overrides) def http_route_builder (self, **_overrides) : return builders.HaHttpRouteBuilder (self, self._parameters, **_overrides) def _declare_request_capture (self, _length = "$+frontend_capture_length", **_overrides) : _index = self._request_captures_count self._request_captures_count += 1 self._request_capture_statements.declare (("declare", "capture", "request", "len", statement_enforce_int (_length)), **_overrides) return _index def _declare_response_capture (self, _length = "$+frontend_capture_length", **_overrides) : _index = self._response_captures_count self._response_captures_count += 1 self._response_capture_statements.declare (("declare", "capture", "response", "len", statement_enforce_int (_length)), **_overrides) return _index def _generate_header (self) : _scroll = Scroll () _scroll.include_normal_line (0, 0, self._expand_token (("frontend", "$\'frontend_identifier"))) return _scroll def _generate_statements_extra (self, _scroll) : self._generate_statements_for_binds (_scroll) self._generate_statements_for_captures (_scroll) _after_acl_scroll = Scroll () self._generate_statements_for_http_rules (_after_acl_scroll) self._generate_statements_for_routes (_after_acl_scroll) _acl_scroll = Scroll () self._generate_statements_for_acl (_acl_scroll) _scroll.include_scroll_lines (None, 0, _acl_scroll, False) _scroll.include_scroll_lines (None, 0, _after_acl_scroll, False) def _generate_statements_for_binds (self, _scroll) : self._bind_statements.generate (_scroll) def _generate_statements_for_captures (self, _scroll) : self._request_capture_statements.generate (_scroll) self._response_capture_statements.generate (_scroll) def _generate_statements_for_routes (self, _scroll) : self._route_statements.generate (_scroll) class HaBackend (HaWorker) : def __init__ (self, _identifier, _parameters) : HaWorker.__init__ (self, _identifier, _parameters) self._server_statements = HaStatementGroup (self._parameters, "Servers", order = 5000 + 800) def declare_server (self, _identifier, _endpoint, _options = "$server_options", _acl = None, **_overrides) : _identifier = enforce_identifier (self._parameters, _identifier) _options = statement_overrides (_options, **_overrides) _condition = self._condition_if (_acl) if _condition is not None : self._server_statements.declare (("use-server", statement_quote ("\'", _identifier), _condition), **_overrides) self._server_statements.declare (("server", statement_quote ("\'", _identifier), statement_quote ("\'", _endpoint), _options), **_overrides) def _generate_header (self) : _scroll = Scroll () _scroll.include_normal_line (0, 0, self._expand_token (("backend", "$\'backend_identifier"))) return _scroll def _generate_statements_extra (self, _scroll) : _after_acl_scroll = Scroll () self._generate_statements_for_http_rules (_after_acl_scroll) self._generate_statements_for_servers (_after_acl_scroll) _acl_scroll = Scroll () self._generate_statements_for_acl (_acl_scroll) _scroll.include_scroll_lines (None, 0, _acl_scroll, False) _scroll.include_scroll_lines (None, 0, _after_acl_scroll, False) def _generate_statements_for_servers (self, _scroll) : self._server_statements.generate (_scroll) class HaTcpFrontend (HaFrontend) : def __init__ (self, _identifier, _parameters, **_options) : HaFrontend.__init__ (self, _identifier, _parameters, **_options) def _declare_implicit (self, **_options) : declares.declare_tcp_frontend (self, **_options) class HaTcpBackend (HaBackend) : def __init__ (self, _identifier, _parameters, **_options) : HaBackend.__init__ (self, _identifier, _parameters, **_options) def _declare_implicit (self, **_options) : declares.declare_tcp_backend (self, **_options) class HaHttpFrontend (HaFrontend) : def __init__ (self, _identifier, _parameters, **_options) : _parameters = _parameters._fork ( frontend_bind_endpoint = "$frontend_http_bind_endpoint", frontend_bind_tls_endpoint = "$frontend_http_bind_endpoint_tls", ) HaFrontend.__init__ (self, _identifier, _parameters, **_options) self.acls = self.http_acl_builder () self.samples = self.http_sample_builder () self.requests = self.http_request_rule_builder () self.responses = self.http_response_rule_builder () self.routes = self.http_route_builder () def _declare_implicit (self, **_options) : self.declare_http_request_rule_if ( ("deny", "deny_status", "200"), self.acls.path ("$heartbeat_self_path"), enabled_if = statement_and ("$?frontend_monitor_enabled", "$?frontend_monitor_configure"), order = 0) declares.declare_http_frontend (self, **_options) class HaHttpBackend (HaBackend) : def __init__ (self, _identifier, _parameters, **_options) : HaBackend.__init__ (self, _identifier, _parameters, **_options) self.acls = self.http_acl_builder () self.samples = self.http_sample_builder () self.requests = self.http_request_rule_builder () self.responses = self.http_response_rule_builder () def _declare_implicit (self, **_options) : declares.declare_http_backend (self, **_options) class HaAcl (HaBase) : def __init__ (self, _parameters, _identifier, _criteria, _matcher, _flags, _operator, _patterns) : HaBase.__init__ (self) _identifier = enforce_identifier (_parameters, _identifier, True) self._parameters = _parameters self._identifier = _identifier self._criteria = _criteria self._matcher = _matcher self._flags = _flags self._operator = _operator self._patterns = _patterns self._generated = None self._expanded = False def identifier (self) : self.generate () return self._generated_identifier def force_include (self) : self.generate () self._expanded = True def negate (self) : return HaAclNegation (self) def generate (self) : if self._generated is not None : return self._generated _identifier, _criteria, _matcher, _flags, _operator, _patterns, _fingerprint = self._expand () _tokens = list () _tokens.append ("acl") if _identifier is None : _identifier = "acl-" + _fingerprint _tokens.append (_identifier) _tokens.append (_criteria) _tokens.append ("-m") _tokens.append (_matcher) _patterns_in_files = False if _flags is not None : for _flag in _flags : if _flag == "-f" : _patterns_in_files = True continue _tokens.append (_flag) if _operator is not None : _tokens.append (_operator) if _patterns is not None : if not _patterns_in_files : _tokens.append ("--") _patterns_batch = 1 if _patterns_in_files : _patterns_batch = 1 if len (_patterns) <= _patterns_batch : for _pattern in _patterns : if _patterns_in_files : _tokens.append ("-f") _tokens.append (_pattern) _tokens = tuple (_tokens) else : _tokens_original = _tokens _tokens = [] for _pattern_offset in xrange (0, len (_patterns), _patterns_batch) : _tokens_0 = list (_tokens_original) + list (_patterns[_pattern_offset : _pattern_offset + _patterns_batch]) _tokens_0 = tuple (_tokens_0) _tokens.append (_tokens_0) else : _tokens = tuple (_tokens) self._generated_identifier = _identifier self._generated_fingerprint = _fingerprint self._generated = _tokens return self._generated def _expand (self) : _identifier = self._expand_and_enforce_token ( self._identifier, {"type" : "or", "schemas" : ( basestring, None, )}) _criteria = self._enforce_token ( self._criteria, HaSample) _criteria = _criteria.generate () _matcher = self._expand_and_enforce_token ( self._matcher, {"type" : "and", "schemas" : ( basestring, (lambda _token : _token in HaAcl.matchers), )}) _flags = self._expand_and_enforce_token ( self._flags, {"type" : "or", "schemas" : ( None, {"type" : tuple, "schema" : basestring}, # FIXME: Also check if the flag is allowed! )}) if _flags is not None : _flags = tuple (sorted (set (_flags))) _operator = self._expand_and_enforce_token ( self._operator, {"type" : "or", "schemas" : ( None, basestring, # FIXME: Also check if the operator is allowed! )}) _patterns = self._expand_token (self._patterns, tuple, "\'?") _patterns = self._enforce_token ( _patterns, {"type" : "or", "schemas" : ( None, basestring, {"type" : tuple, "schema" : {"type" : "or", "schemas" : (basestring, int)}}, )}) if _patterns is not None : if isinstance (_patterns, tuple) : _patterns = tuple (sorted (set (_patterns))) else : _patterns = (_patterns,) _fingerprint = hash_token ((_criteria, "-m", _matcher, _flags, _operator, "--", _patterns)) return _identifier, _criteria, _matcher, _flags, _operator, _patterns, _fingerprint def _self_expand_token (self) : self._expanded = True return self.identifier () def _self_resolve_token (self) : self._expanded = True return self.identifier () matchers = { "found" : (None, (0, 0), None, ("-u",)), "bool" : (("boolean", "integer"), (0, 0), None, ("-u",)), "int" : (("integer", "boolean"), (1, None), ("eq", "ge", "gt", "le", "lt"), ("-u",)), "ip" : (("ip", "string", "binary"), (1, None), None, ("-u", "-n")), "bin" : (("string", "binary"), (1, None), None, ("-u", "-i")), "len" : (("string", "binary"), (1, None), None, ("-u",)), "str" : (("string", "binary"), (1, None), None, ("-u", "-i")), "sub" : (("string", "binary"), (1, None), None, ("-u", "-i")), "reg" : (("string", "binary"), (1, None), None, ("-u", "-i")), "beg" : (("string", "binary"), (1, None), None, ("-u", "-i")), "end" : (("string", "binary"), (1, None), None, ("-u", "-i")), "dir" : (("string", "binary"), (1, None), None, ("-u", "-i")), "dom" : (("string", "binary"), (1, None), None, ("-u", "-i")), } class HaAclNegation (object) : def __init__ (self, _acl) : self._acl = _acl def identifier (self) : _identifier = self._acl.identifier () return "!%s" % (_identifier,) def negate (self) : return self._acl def _self_expand_token (self) : self._acl._expanded = True return self.identifier () def _self_resolve_token (self) : self._acl._expanded = True return self.identifier () class HaSample (HaBase) : def __init__ (self, _parameters, _method, _arguments, _transforms) : HaBase.__init__ (self) self._parameters = _parameters self._method = _method self._arguments = _arguments self._transforms = _transforms self._generated = None def statement_format (self) : return statement_format ("%%[%s]", self) def parameter_get (self) : return lambda _parameters : self.generate () def generate (self) : if self._generated is not None : return self._generated _method, _arguments, _transforms = self._expand () _tokens = list () _tokens.append (_method) _tokens.append ("(") if _arguments is not None and len (_arguments) > 0 : _tokens.append (str (quote_token ("\'?", _arguments[0]))) for _argument in _arguments[1:] : _argument = str (quote_token ("\'?", _argument)) _tokens.append (",") _tokens.append (_argument) _tokens.append (")") if _transforms is not None and len (_transforms) > 0 : for _transform in _transforms : _tokens.append (",") _tokens.append (_transform[0]) if len (_transform) > 1 : _tokens.append ("(") _tokens.append (str (quote_token ("\'?", _transform[1]))) for _transform_argument in _transform[2:] : _transform_argument = str (quote_token ("\'?", _transform_argument)) _tokens.append (",") _tokens.append (_transform_argument) _tokens.append (")") _tokens = "".join (_tokens) self._generated = _tokens return self._generated def _expand (self) : _method = self._expand_and_enforce_token ( self._method, basestring) _arguments = self._expand_and_enforce_token ( self._arguments, {"type" : "or", "schemas" : ( {"type" : tuple, "schema" : {"type" : "or", "schemas" : (basestring, int)}}, basestring, int, None, )}) if isinstance (_arguments, basestring) : _arguments = (_arguments,) _transforms = self._expand_and_enforce_token ( self._transforms, {"type" : "or", "schemas" : ( {"type" : tuple, "schema" : {"type" : "or", "schemas" : ( {"type" : tuple, "schema" : {"type" : "or", "schemas" : (basestring, int)}}, basestring, int, )} }, basestring, None, )}) if isinstance (_transforms, basestring) : _transforms = (_transforms,) if _transforms is not None : _transforms = [_transform if isinstance (_transform, tuple) else (_transform,) for _transform in _transforms] _transforms = tuple (_transforms) return _method, _arguments, _transforms def _self_expand_token (self) : return self.generate () def _self_resolve_token (self) : return self.generate () class HaStatement (HaBase) : def __init__ (self, _parameters, enabled_if = True, order = None, overrides = None) : HaBase.__init__ (self) self._parameters = _parameters self._enabled_if = enabled_if self._order = order self._overrides = overrides if self._overrides is not None : self._parameters = self._parameters._fork (**self._overrides) def generate (self, _scroll, **_options) : _enabled = self._resolve_token (self._enabled_if) if _enabled is True : self._generate (_scroll, **_options) elif _enabled is False : pass else : raise_error ("b7e176f4", _enabled) def _generate (self, _scroll) : raise_error ("1ff66257") class HaGenericStatement (HaStatement) : def __init__ (self, _parameters, _tokens, _comment, **_options) : HaStatement.__init__ (self, _parameters, **_options) self._tokens = _tokens self._comment = _comment def _generate (self, _scroll) : _contents = self._expand_token (self._tokens) if _contents is not None : if self._comment is not None : _scroll.include_normal_line_with_comment (self._order, 0, _contents, self._comment) else : _scroll.include_normal_line (self._order, 0, _contents) #if isinstance (self._tokens, list) : # _contents = self._tokens #else : # _contents = [self._tokens] #_contents = [self._expand_token (_tokens) for _tokens in _contents] #_contents = [_contents for _contents in _contents if _contents is not None] #for _contents in _contents : # _scroll.include_normal_line (self._order, 0, _contents) class HaStatementGroup (HaStatement) : def __init__ (self, _parameters, _heading, **_options) : HaStatement.__init__ (self, _parameters, **_options) if _heading is None : self._heading = None elif isinstance (_heading, basestring) : self._heading = (_heading,) elif isinstance (_heading, tuple) : self._heading = _heading else : raise_error ("7f294bbf", _heading) self._statements = list () def declare (self, *_tokens, **_options) : while isinstance (_tokens, tuple) and len (_tokens) == 1 and isinstance (_tokens[0], tuple) : _tokens = _tokens[0] _comment = _options.get ("comment", None) _statement_comment = None if _comment is not None : _options = dict (_options) del _options["comment"] _statement = HaGenericStatement (self._parameters, _tokens, _comment, **_options) self._statements.append (_statement) return _statement def declare_group (self, _heading, *_statements, **_options) : _group = HaStatementGroup (self._parameters, _heading, **_options) _group._declare_recurse (list (_statements)) self._statements.append (_group) return _group def _declare_recurse (self, _statement) : if isinstance (_statement, list) : for _statement in _statement : self._declare_recurse (_statement) elif isinstance (_statement, tuple) : self.declare (*_statement) elif isinstance (_statement, basestring) : self.declare (_statement) elif isinstance (_statement, int) : self.declare (_statement) elif callable (_statement) : self.declare (_statement) else : raise_error ("a67b1ba7", _statement) def _generate (self, _scroll, _merge = False) : _statements_scroll = Scroll () for _statement in self._statements : _statement.generate (_statements_scroll) if not _statements_scroll.is_empty () : if _merge : _scroll.include_scroll_lines (self._order, 0, _statements_scroll, False) else : _self_scroll = Scroll () _self_scroll.include_empty_line (0, 0, 1) if self._heading is not None : _heading = " -- ".join (self._heading) _self_scroll.include_comment_line (0, 0, HaStatementGroup.heading_prefix + _heading) _self_scroll.include_normal_line (0, 0, _statements_scroll) _self_scroll.include_empty_line (0, 0, 1) _scroll.include_normal_line (self._order, 0, _self_scroll) heading_prefix = "#---- " <file_sep> from tools import * def declare_backend_server_defaults (_configuration, _extra_statements = None) : _configuration.declare_group ( "Servers", statement_choose_if_non_null ("$backend_server_max_connections_full_count", ("fullconn", "$+backend_server_max_connections_full_count")), statement_choose_if_non_null ("$backend_server_min_connections_active_count", ("default-server", "minconn", "$+backend_server_min_connections_active_count")), statement_choose_if_non_null ("$backend_server_max_connections_active_count", ("default-server", "maxconn", "$+backend_server_max_connections_active_count")), statement_choose_if_non_null ("$backend_server_max_connections_queue_count", ("default-server", "maxqueue", "$+backend_server_max_connections_queue_count")), statement_choose_if_non_null ("$backend_server_check_interval_normal", ("default-server", "inter", statement_seconds ("$+backend_server_check_interval_normal"))), statement_choose_if_non_null ("$backend_server_check_interval_rising", ("default-server", "fastinter", statement_seconds ("$+backend_server_check_interval_rising"))), statement_choose_if_non_null ("$backend_server_check_interval_failed", ("default-server", "downinter", statement_seconds ("$+backend_server_check_interval_failed"))), statement_choose_if_false ("$?backend_minimal", ("default-server", "init-addr", "none")), _extra_statements, enabled_if = "$?backend_servers_configure", ) def declare_backend_server_timeouts (_configuration, _extra_statements = None) : _configuration.declare_group ( "Timeouts", statement_choose_if_non_null ("$backend_server_timeout_activity_server", ("timeout", "server", statement_seconds ("$+backend_server_timeout_activity_server"))), statement_choose_if_non_null ("$backend_server_timeout_fin", ("timeout", "server-fin", statement_seconds ("$+backend_server_timeout_fin"))), statement_choose_if_non_null ("$backend_server_timeout_activity_client", ("timeout", "client", statement_seconds ("$+backend_server_timeout_activity_client"))), statement_choose_if_non_null ("$backend_server_timeout_fin", ("timeout", "client-fin", statement_seconds ("$+backend_server_timeout_fin"))), statement_choose_if_non_null ("$backend_server_timeout_activity_tunnel", ("timeout", "tunnel", statement_seconds ("$+backend_server_timeout_activity_tunnel"))), statement_choose_if_non_null ("$backend_server_timeout_connect", ("timeout", "connect", statement_seconds ("$+backend_server_timeout_connect"))), statement_choose_if_non_null ("$backend_server_timeout_queue", ("timeout", "queue", statement_seconds ("$+backend_server_timeout_queue"))), statement_choose_if_non_null ("$backend_server_timeout_check", ("timeout", "check", statement_seconds ("$+backend_server_timeout_check"))), statement_choose_if_non_null ("$backend_server_timeout_tarpit", ("timeout", "tarpit", statement_seconds ("$+backend_server_timeout_tarpit"))), _extra_statements, enabled_if = "$?backend_timeouts_configure", ) <file_sep> from errors import * from tools import * from builders_core import * class HaHttpFrontendBuilder (HaBuilder) : def __init__ (self, _context, _parameters) : HaBuilder.__init__ (self, _context, _parameters) def basic (self, _identifier = None, _tls = None, _non_tls = None, **_parameters) : _identifier = _identifier if _identifier is not None else "http" _tls = _tls if _tls is not None else False _non_tls = _non_tls if _non_tls is not None else True _frontend = self._context.http_frontend_create (_identifier, **_parameters) if _non_tls : _frontend.declare_bind (overrides = _parameters) if _tls : _frontend.declare_bind_tls (overrides = _parameters) return _frontend <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _be_www = _ha.http_backends.basic ( _identifier = "http-flask", _endpoint = "ipv4@127.0.0.1:9090", ) _be_blog = _ha.http_backends.basic ( _identifier = "http-static", _endpoint = "ipv4@127.0.0.1:9091", ) _be_app = _ha.http_backends.basic ( _identifier = "http-media", _endpoint = "ipv4@127.0.0.1:9092", ) _be_deny = _ha.http_backends.fallback_deny () _fe.requests.redirect_domain_with_www ("example.com") _fe.routes.route_host (_be_www, "www.example.com") _fe.routes.route_host (_be_blog, "blog.example.com") _fe.routes.route_host (_be_app, "app.example.com") _fe.routes.route (_be_deny) _ha.output_stdout () <file_sep> global #---- Identity node 'haproxy-sandbox-1.servers.example.com' description '[]' #---- Daemon nbthread 1 ulimit-n 65536 user 'haproxy' group 'haproxy' pidfile '/run/haproxy.pid' #---- State server-state-base '/run/haproxy-states' server-state-file '/run/haproxy.state' #---- Connections maxconn 8192 maxconnrate 512 maxsessrate 2048 maxsslconn 4096 maxsslrate 256 maxpipes 4096 #---- Checks max-spread-checks 6 spread-checks 25 #---- HTTP tune.http.logurilen 4096 tune.http.maxhdr 64 #---- HTTP/2 tune.h2.header-table-size 16384 tune.h2.initial-window-size 131072 tune.h2.max-concurrent-streams 128 #---- Compression maxcomprate 0 maxcompcpuusage 25 maxzlibmem 128 tune.comp.maxlevel 9 #---- Buffers tune.bufsize 131072 tune.buffers.limit 4096 tune.buffers.reserve 16 tune.maxrewrite 16384 #---- TLS default configuration ssl-default-bind-ciphers 'ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES256-SHA256:AES128-GCM-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA' ssl-default-bind-ciphersuites 'TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256' ssl-default-bind-curves 'X25519:P-256' ssl-default-bind-options no-tlsv11 no-tlsv10 no-sslv3 no-tls-tickets ssl-default-server-ciphers 'ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES256-GCM-SHA384:AES256-SHA256:AES128-GCM-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DES-CBC3-SHA' ssl-default-server-ciphersuites 'TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256' ssl-default-server-options no-tlsv11 no-tlsv10 no-sslv3 no-tls-tickets ssl-server-verify required ssl-skip-self-issued-ca ssl-dh-param-file '/etc/haproxy/tls/dh-params.pem' #---- TLS advanced configuration tune.ssl.default-dh-param 2048 tune.ssl.maxrecord 16384 tune.ssl.cachesize 131072 tune.ssl.lifetime 3600s #---- Logging log '/dev/log' len 65535 format 'rfc5424' daemon info err log-send-hostname 'haproxy-sandbox-1.servers.example.com' log-tag 'haproxy' quiet #---- Statistics stats socket 'unix@/run/haproxy.sock' user 'haproxy' group 'haproxy' mode 0600 level admin stats maxconn 4 stats timeout 60s defaults #---- Protocol mode tcp disabled #---- Connections maxconn 4096 backlog 1024 rate-limit sessions 16384 balance roundrobin retries 4 #---- Connections TCP-Keep-Alive option clitcpka option srvtcpka #---- Connections splicing option splice-request option splice-response no option splice-auto #---- Timeouts timeout server 60s timeout server-fin 6s timeout client 30s timeout client-fin 6s timeout tunnel 180s timeout connect 6s timeout queue 30s timeout check 6s timeout tarpit 30s #---- Servers fullconn 16 default-server minconn 8 default-server maxconn 32 default-server maxqueue 128 default-server inter 60s default-server fastinter 2s default-server downinter 20s default-server rise 8 default-server fall 4 default-server on-error fastinter default-server error-limit 4 #---- HTTP http-reuse safe http-check disable-on-404 http-check send-state option http-keep-alive timeout http-request 30s timeout http-keep-alive 60s unique-id-format "%[req.hdr(X-HA-Request-Id)]" #---- HTTP compression compression algo gzip compression type 'text/html' 'text/css' 'application/javascript' 'text/javascript' 'application/xml' 'text/xml' 'application/xhtml+xml' 'application/rss+xml' 'application/atom+xml' 'application/json' 'text/json' 'text/plain' 'text/csv' 'text/tab-separated-values' 'image/svg+xml' 'image/vnd.microsoft.icon' 'image/x-icon' 'font/collection' 'font/otf' 'application/font-otf' 'application/x-font-otf' 'application/x-font-opentype' 'font/ttf' 'application/font-ttf' 'application/x-font-ttf' 'application/x-font-truetype' 'font/sfnt' 'application/font-sfnt' 'application/x-font-sfnt' 'font/woff' 'application/font-woff' 'application/x-font-woff' 'font/woff2' 'application/font-woff2' 'application/x-font-woff2' 'font/eot' 'application/font-eot' 'application/x-font-eot' 'application/vnd.ms-fontobject' #---- Logging log global option log-separate-errors option log-health-checks no option checkcache no option dontlognull #---- Stats option contstats option socket-stats #---- Error pages errorfile 200 '/etc/haproxy/errors/http/monitor.http' errorfile 400 '/etc/haproxy/errors/http/400.http' errorfile 401 '/etc/haproxy/errors/http/401.http' errorfile 403 '/etc/haproxy/errors/http/403.http' errorfile 404 '/etc/haproxy/errors/http/404.http' errorfile 405 '/etc/haproxy/errors/http/405.http' errorfile 408 '/etc/haproxy/errors/http/408.http' errorfile 410 '/etc/haproxy/errors/http/410.http' errorfile 429 '/etc/haproxy/errors/http/429.http' errorfile 500 '/etc/haproxy/errors/http/500.http' errorfile 501 '/etc/haproxy/errors/http/501.http' errorfile 502 '/etc/haproxy/errors/http/502.http' errorfile 503 '/etc/haproxy/errors/http/503.http' errorfile 504 '/etc/haproxy/errors/http/504.http' #---- State load-server-state-from-file global <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-f681280f04c986c89e435ed1642672f1 var('txn.http_drop_caching_enabled'),bool -m bool acl acl-dd698477ac8c3687bb2db6dc6e4b8321 var('txn.http_drop_caching_excluded'),bool -m bool #---- HTTP Request Rules http-request set-var(txn.http_drop_caching_enabled) bool(true) http-request del-header "Cache-Control" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-request del-header "If-None-Match" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-request del-header "If-Match" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-request del-header "If-Modified-Since" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-request del-header "If-Unmodified-Since" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-request del-header "Pragma" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 #---- HTTP Response Rules http-response del-header "Cache-Control" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "Last-Modified" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "Expires" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "Date" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "ETag" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "Vary" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "Age" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 http-response del-header "Pragma" if acl-f681280f04c986c89e435ed1642672f1 !acl-dd698477ac8c3687bb2db6dc6e4b8321 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- HTTP Request Rules http-request set-header "agent_hash" "%[req.fhdr('User-Agent',-1),digest('md5'),hex,lower]" http-request set-header "agent_regsub" "%[req.fhdr('User-Agent',-1),regsub('^.* id-([0-9a-f]+) .*\$','\\1')]" <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-33deeaa6c1e2028f92f26feafb708748 nbsrv('variant-b'),bool -m bool acl acl-5b015384f097b21dcf0b1dcc7ba95fce src(),wt6(1),mod(4) -m int eq -- 0 #---- Routes use_backend variant-b if acl-33deeaa6c1e2028f92f26feafb708748 acl-5b015384f097b21dcf0b1dcc7ba95fce use_backend variant-a backend 'variant-a' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9090' backend 'variant-b' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:9091' <file_sep> from tools import * def declare_globals (_configuration) : declare_globals_daemon (_configuration) declare_globals_network (_configuration) declare_globals_tls (_configuration) declare_globals_logging (_configuration) declare_globals_stats (_configuration) def declare_globals_daemon (_configuration) : _configuration.declare_group ( "Identity", ("node", "$\'daemon_node"), ("description", "$\'daemon_description"), enabled_if = "$?global_identity_configure", ) _configuration.declare_group ( "Daemon", ("nbthread", "$+daemon_threads_count"), statement_choose_if_non_null ("$~daemon_threads_affinity", ("cpu-map", "$~daemon_threads_affinity")), statement_choose_if_non_null ("$+daemon_ulimit", ("ulimit-n", "$+daemon_ulimit")), statement_choose_if_non_null ("$daemon_user", ("user", "$\'daemon_user")), statement_choose_if_non_null ("$daemon_group", ("group", "$\'daemon_group")), statement_choose_if_non_null ("$daemon_pid", ("pidfile", "$\'daemon_pid")), statement_choose_if ("$?daemon_chroot_enabled", ("chroot", "$\'daemon_chroot")), enabled_if = "$?global_daemon_configure", ) _configuration.declare_group ( "State", ("server-state-base", "$\'daemon_paths_states_prefix"), ("server-state-file", "$\'daemon_paths_state_global"), enabled_if = "$?global_state_configure", ) _configuration.declare_group ( "Experimental", statement_choose_if ("$?global_experimental_enabled", ("expose-experimental-directives",)), enabled_if = "$?global_experimental_configure", ) def declare_globals_network (_configuration) : _configuration.declare_group ( "Connections", ("maxconn", "$+global_max_connections_count"), ("maxconnrate", "$+global_max_connections_rate"), ("maxsessrate", "$+global_max_sessions_rate"), ("maxsslconn", "$+global_max_tls_connections_count"), ("maxsslrate", "$+global_max_tls_connections_rate"), ("maxpipes", "$+global_max_pipes"), enabled_if = "$?global_connections_configure", ) _configuration.declare_group ( "Checks", ("max-spread-checks", 6), ("spread-checks", 25), enabled_if = "$?global_checks_configure", ) _configuration.declare_group ( "HTTP", ("tune.http.logurilen", "$+global_http_uri_length_max"), ("tune.http.maxhdr", "$+global_http_headers_count_max"), enabled_if = "$?global_tune_http_configure", ) _configuration.declare_group ( "HTTP/2", ("tune.h2.header-table-size", "$+global_http2_headers_table_size"), ("tune.h2.initial-window-size", "$+global_http2_window_initial_size"), ("tune.h2.max-concurrent-streams", "$+global_http2_streams_count_max"), enabled_if = "$?global_tune_http2_configure", ) _configuration.declare_group ( "Compression", ("maxcomprate", "$+global_compression_rate_max"), ("maxcompcpuusage", "$+global_compression_cpu_max"), ("maxzlibmem", "$+global_compression_mem_max"), ("tune.comp.maxlevel", "$+global_compression_level_max"), # FIXME: On some HAProxy builds this is disabled! # ("tune.zlib.memlevel", 9), # ("tune.zlib.windowsize", 15), enabled_if = "$?global_compression_configure", ) _configuration.declare_group ( "Buffers", ("tune.bufsize", "$+global_buffers_size"), ("tune.buffers.limit", "$+global_buffers_count_max"), ("tune.buffers.reserve", "$+global_buffers_count_reserved"), ("tune.maxrewrite", "$+global_buffers_rewrite"), enabled_if = "$?global_tune_buffers_configure", ) _configuration.declare_group ( "Sockets", #("tune.rcvbuf.client", 128 * 1024), #("tune.sndbuf.client", 16 * 1024), #("tune.rcvbuf.server", 128 * 1024), #("tune.sndbuf.server", 128 * 1024), #("tune.pipesize", 128 * 1024), #("tune.idletimer", 1000), enabled_if = "$?global_tune_sockets_configure", ) def declare_globals_tls (_configuration) : _configuration.declare_group ( "TLS default certificates", statement_choose_if_non_null ("$tls_ca_base", ("ca-base", "$\'tls_ca_base")), statement_choose_if_non_null ("$tls_ca_file", ("ca-file", "$\'tls_ca_file")), statement_choose_if_non_null ("$tls_crt_base", ("crt-base", "$\'tls_crt_base")), statement_choose_if_non_null ("$tls_crt_file", ("crt", "$\'tls_crt_file")), enabled_if = "$?global_tls_configure", ) _configuration.declare_group ( "TLS default configuration", ("ssl-default-bind-ciphers", "$\'tls_ciphers_v12_descriptor"), ("ssl-default-bind-ciphersuites", "$\'tls_ciphers_v13_descriptor"), statement_choose_if_non_null ("$tls_curves", ("ssl-default-bind-curves", "$\'tls_curves")), ("ssl-default-bind-options", "$~tls_options"), ("ssl-default-server-ciphers", "$\'tls_ciphers_v12_descriptor"), ("ssl-default-server-ciphersuites", "$\'tls_ciphers_v13_descriptor"), ("ssl-default-server-options", "$~tls_options"), ("ssl-server-verify", "required"), ("ssl-skip-self-issued-ca"), statement_choose_if_non_null ("$tls_dh_params", ("ssl-dh-param-file", "$\'tls_dh_params")), enabled_if = "$?global_tls_configure", ) _configuration.declare_group ( "TLS advanced configuration", ("tune.ssl.default-dh-param", 2048), ("tune.ssl.maxrecord", 16 * 1024), ("tune.ssl.cachesize", 128 * 1024), ("tune.ssl.lifetime", statement_seconds (3600)), enabled_if = "$?global_tune_tls_configure", ) def declare_globals_logging (_configuration) : _configuration.declare_group ( "Logging", statement_choose_if ("$?syslog_1_enabled", ("log", "$\'syslog_1_endpoint", "len", 65535, "format", "$\'syslog_1_protocol", "daemon", "info", "err")), statement_choose_if ("$?syslog_2_enabled", ("log", "$\'syslog_2_endpoint", "len", 65535, "format", "$\'syslog_2_protocol", "daemon", "info", "err")), statement_choose_if ("$syslog_source_node", ("log-send-hostname", "$\'syslog_source_node")), ("log-tag", "$\'syslog_source_tag"), statement_choose_if ("$?global_logging_quiet", ("quiet")), enabled_if = "$?global_logging_configure", ) def declare_globals_stats (_configuration) : _configuration.declare_group ( "Statistics", statement_choose_if_non_null ("$daemon_socket", ( "stats", "socket", "$\'daemon_socket", statement_choose_if_non_null ("$daemon_user", ("user", "$\'daemon_user")), statement_choose_if_non_null ("$daemon_group", ("group", "$\'daemon_group")), "mode", "0600", "level", "admin", )), ("stats", "maxconn", 4), ("stats", "timeout", statement_seconds (60)), enabled_if = "$?global_stats_configure", ) <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-9e7f02c411b61b73a994c13f5425ff34 http_auth('operators'),bool -m bool acl acl-e2a7e30a3cb16694f66809ee92d77078 req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'private.example.com' #---- HTTP Request Rules http-request auth realm 'example.com' if acl-e2a7e30a3cb16694f66809ee92d77078 !acl-9e7f02c411b61b73a994c13f5425ff34 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' userlist 'operators' #---- Users user 'operator' insecure-password '<PASSWORD>' <file_sep> import inspect import hashlib import sys from errors import * def enforce_identifier (_parameters, _identifier, _null_allowed = False) : if _identifier is None : if _null_allowed : return _identifier else : raise_error ("99640036", _identifier) elif isinstance (_identifier, basestring) : return _identifier elif callable (_identifier) : return _identifier (_parameters) else : raise_error ("52d21d23", _identifier) def enforce_token (_token, _schema, _raise = True) : try : return enforce_token_0 (_token, _schema, _raise) except Exception as _error : print >> sys.stderr, "[ee] failed enforcing token `%r` for schema `%r`" % (_token, _schema) raise def enforce_token_0 (_token, _schema, _raise) : if _schema is None : if _token is None : return enforce_token_0_return (_token, _raise) else : return enforce_token_0_raise (_raise, "8<PASSWORD>", _schema, _token) elif type (_schema) is type : if isinstance (_token, _schema) : return enforce_token_0_return (_token, _raise) else : return enforce_token_0_raise (_raise, "a9bf09e3", _schema, _token) elif isinstance (_schema, tuple) or isinstance (_schema, list) : if isinstance (_token, type (_schema)) : if len (_token) == len (_schema) : for _index in xrange (_schema) : if _raise : enforce_token_0 (_token[_index], _schema[_index], True) else : if not enforce_token_0 (_token[_index], _schema[_index], False) : return False return enforce_token_0_return (_token, _raise) else : return enforce_token_0_raise (_raise, "e8dc<PASSWORD>", _schema, _token) else : return enforce_token_0_raise (_raise, "dd8fb1a0", _schema, _token) elif isinstance (_schema, dict) : _type = _schema["type"] if _type is tuple or _type is list : _element_schema = _schema["schema"] if isinstance (_token, _type) : for _element_token in _token : if _raise : enforce_token_0 (_element_token, _element_schema, True) else : if not enforce_token_0 (_element_token, _element_schema, False) : return False return enforce_token_0_return (_token, _raise) else : return enforce_token_0_raise (_raise, "<PASSWORD>", _schema, _token) elif _type == "or" : _or_schemas = _schema["schemas"] for _or_schema in _or_schemas : if enforce_token_0 (_token, _or_schema, False) : return enforce_token_0_return (_token, _raise) return enforce_token_0_raise (_raise, "<PASSWORD>", _schema, _token) elif _type == "and" : _and_schemas = _schema["schemas"] for _and_schema in _and_schemas : if _raise : return enforce_token_0 (_token, _and_schema, True) else : if not enforce_token_0 (_token, _and_schema, False) : return False return enforce_token_0_return (_token, _raise) else : return enforce_token_0_raise (_raise, "7<PASSWORD>", _type, _token) else : return enforce_token_0_raise (_raise, "0<PASSWORD>", _schema, _token) def enforce_token_0_return (_token, _raise) : if _raise : return _token else : return True def enforce_token_0_raise (_raise, _code, *_arguments) : if _raise : raise_error (_code, *_arguments) else : return False def expand_token (_token, _parameters, _join = None, _quote = None) : try : return expand_token_0 (_token, _parameters, _join, _quote) except Exception as _error : print >> sys.stderr, "[ee] failed expanding token `%r`" % (_token,) raise def expand_token_0 (_token, _parameters, _join, _quote) : if isinstance (_token, basestring) : if _token.startswith ("$") : _token = _token[1:] if _token.startswith ("\'") : _token = _token[1:] _quote = "\'" elif _token.startswith ("\"") : _token = _token[1:] _quote = "\"" elif _token.startswith ("+") : _token = _token[1:] _token = statement_enforce_int ("$" + _token) return expand_token_0 (_token, _parameters, _join, _quote) elif _token.startswith ("?") : _token = _token[1:] if _token.startswith ("!") : _token = _token[1:] _token = statement_not (statement_enforce_bool ("$" + _token)) else : _token = statement_enforce_bool ("$" + _token) return expand_token_0 (_token, _parameters, _join, _quote) elif _token.startswith ("~") : _token = _token[1:] _token = statement_enforce_keyword ("$" + _token) return expand_token_0 (_token, _parameters, _join, _quote) _token = resolve_token_0 ("$" + _token, _parameters, False) return expand_token_0 (_token, _parameters, _join, _quote) elif _token.startswith ("#") : _token = _token[1:] if _token.startswith ("\'") : _token = _token[1:] _quote = "\'" elif _token.startswith ("\"") : _token = _token[1:] _quote = "\"" elif _token.startswith ("+") : _token = _token[1:] try : _token = int (_token) except : raise_error ("0613b0dd", _token) else : raise_error ("955a8724", _token) return expand_token_0 (_token, _parameters, _join, _quote) else : if _quote is not None : return _quote_token (_token, _quote, (lambda _token : expand_token_0 (_token, _parameters, None, None))) else : return _token elif isinstance (_token, int) : if _quote is not None : return _quote_token (_token, _quote, (lambda _token : expand_token_0 (_token, _parameters, None, None))) else : return _token elif isinstance (_token, tuple) : if isinstance (_join, basestring) : _token = [expand_token_0 (_token, _parameters, None, None) for _token in _token] _token = [_token for _token in _token if _token is not None] if len (_token) > 0 : _token = _join.join (_token) else : _token = None elif _join is None : _token = [expand_token_0 (_token, _parameters, None, None) for _token in _token] _token = [_token for _token in _token if _token is not None] if len (_token) > 0 : _token = tuple (_token) else : _token = None elif _join is tuple or _join is list : _outcome = [] def _outcome_flatten (_token) : if isinstance (_token, tuple) or isinstance (_token, list) : for _token in _token : _outcome_flatten (_token) else : _token = expand_token_0 (_token, _parameters, None, None) if isinstance (_token, tuple) or isinstance (_token, list) : _outcome_flatten (_token) else : _outcome.append (_token) _outcome_flatten (_token) _token = _outcome if len (_token) > 0 : if _join is tuple : _token = tuple (_token) else : _token = None else : raise_error ("afae3a77", _join) if _token is not None and _quote is not None : _token = _quote_token (_token, _quote, lambda _token : expand_token_0 (_token, _parameters, None, None)) return _token elif _token is None : return None elif hasattr (_token, "_self_expand_token") : _token = _token._self_expand_token () return expand_token_0 (_token, _parameters, _join, _quote) elif callable (_token) : if len (inspect.getargspec (_token) .args) == 1 : _token = _token (lambda _token : expand_token_0 (_token, _parameters, None, None)) else : _token = _token (lambda _token, _parameters : expand_token_0 (_token, _parameters, None, None), _parameters) return expand_token_0 (_token, _parameters, _join, _quote) else : _token = resolve_token_0 (_token, _parameters, False) return expand_token_0 (_token, _parameters, _join, _quote) def resolve_token (_token, _parameters, _recurse = True) : try : return resolve_token_0 (_token, _parameters, _recurse) except Exception as _error : print >> sys.stderr, "[ee] failed resolving token `%r`" % (_token,) raise def resolve_token_0 (_token, _parameters, _recurse) : if isinstance (_token, basestring) : if _token.startswith ("$") : _token = _token[1:] if _token.startswith ("+") : _token = _token[1:] _token = _parameters._get (_token) if isinstance (_token, int) : return _token else : raise_error ("b6a20829", _token) elif _token.startswith ("?") : _token = _token[1:] if _token.startswith ("!") : _token = _token[1:] _negate = True else : _negate = False _token = _parameters._get (_token) if _token is True or _token is False : if _negate : return not _token else : return _token else : raise_error ("b5175532", _token) else : _token = _parameters._get (_token) if _recurse : return resolve_token_0 (_token, _parameters, True) else : return _token else : return _token elif isinstance (_token, int) : return _token elif isinstance (_token, tuple) : if _recurse : _token = [resolve_token_0 (_token, _parameters, True) for _token in _token] _token = tuple (_token) return _token else : return _token elif hasattr (_token, "_self_resolve_token") : _token = _token._self_resolve_token () if _recurse : return resolve_token_0 (_token, _parameters, True) else : return _token elif callable (_token) : if _recurse : if len (inspect.getargspec (_token) .args) == 1 : _token = _token (lambda _token : resolve_token_0 (_token, _parameters, True)) else : _token = _token (lambda _token, _parameters : resolve_token_0 (_token, _parameters, True), _parameters) return resolve_token_0 (_token, _parameters, True) else : return _token elif _token is None : return _token else : raise_error ("d9ff522a", _token) def _quote_token (_token, _quote, _expand) : if _quote is True : _quote = "\'" if _quote != "\"" and _quote != "\'" and _quote != "\"?" and _quote != "\'?" : raise_error ("9f90118a", _quote) if isinstance (_token, basestring) : if _quote == "\"" or _quote == "\"?" : _token = _token.replace ("\\", "\\\\") _token = _token.replace ("\"", "\\\"") _token = _token.replace ("\r", "\\r") _token = _token.replace ("\n", "\\n") _token = _token.replace ("$", "\\$") _token = "\"" + _token + "\"" return _token elif _quote == "\'" or _quote == "\'?" : _token = _token.replace ("\'", "'\\''") _token = _token.replace ("\r", "'\\r'") _token = _token.replace ("\n", "'\\n'") _token = "\'" + _token + "\'" return _token elif isinstance (_token, int) : if _quote == "\"?" or _quote == "\'?" : return _token else : _token = str (_token) return _quote_token (_token, _quote, _expand) elif isinstance (_token, tuple) : _token = [_quote_token (_token, _quote, _expand) for _token in _token] _token = tuple (_token) return _token elif _token is None : raise_error ("f4226423") elif _expand is not None : _token = _expand (_token) return _quote_token (_token, _quote, _expand) else : raise_error ("e256e274") def quote_token (_quote, _token) : if _quote is None or _quote is False : return _token return _quote_token (_token, _quote, None) def hash_token (_token) : _hasher = hashlib.md5 () hash_token_update (_hasher, _token) return _hasher.hexdigest () def hash_token_update (_hasher, _token) : if _token is None : pass elif isinstance (_token, basestring) : _hasher.update (_token.encode ("utf-8")) elif isinstance (_token, int) : _hasher.update (str (_token)) elif isinstance (_token, tuple) or isinstance (_token, list) : _token_is_first = True for _token in _token : if not _token_is_first : _hasher.update (" ") hash_token_update (_hasher, _token) _token_is_first = False else : raise_error ("b<PASSWORD>", _token) def statement_quote (_quote = True, *_token) : return lambda _expand : _quote_token (_expand (_token), _quote, _expand) def statement_seconds (_value) : return lambda _expand : "%ds" % _expand (_value) def statement_overrides (_value, **_overrides) : return lambda _expand, _parameters : _expand (_value, _parameters._fork (**_overrides)) def statement_enforce_type (_type, _value) : def _function (_expand) : _actual = _expand (_value) if not isinstance (_actual, _type) : raise_error ("97f18161", _type, _value, _actual) return _actual return _function def statement_enforce_int (_value) : return statement_enforce_type (int, _value) def statement_enforce_bool (_value) : return statement_enforce_type (bool, _value) def statement_enforce_string (_value) : return statement_enforce_type (basestring, _value) def statement_enforce_keyword (_value) : # FIXME: Implement this! return _value def statement_format (_format, *_arguments) : return lambda _expand : _expand (_format) % tuple ([_expand (_argument) for _argument in _arguments]) def statement_coalesce (*_values) : def _function (_expand) : for _value in _values : _value = _expand (_value) if _value is not None : return _value return None return _function def statement_join (_separator, _arguments, non_null = True, null_if_empty = True, quote = None) : def _function (_expand) : _separator_actual = _expand (_separator) _arguments_actual = _expand (_arguments) if _arguments_actual is None : return None else : if non_null : _arguments_actual = [_argument_actual for _argument_actual in _arguments_actual if _argument_actual is not None] if null_if_empty and len (_arguments_actual) == 0 : return None else : return quote_token (quote, _separator_actual.join (_arguments_actual)) return _function def statement_path_join (_arguments, non_null = True, null_if_empty = True, quote = None) : return statement_join ("/", _arguments, non_null, null_if_empty, quote) def statement_and (*_values) : def _function (_expand) : for _value in _values : _actual = _expand (_value) if _actual is False : return False elif _actual is True : continue else : raise_error ("761eef06", _value, _actual) return True return _function def statement_or (*_values) : def _function (_expand) : for _value in _values : _actual = _expand (_value) if _actual is True : return True elif _actual is False : continue else : raise_error ("d851191c", _value, _actual) return False return _function def statement_not (_value) : def _function (_expand) : _actual = _expand (_value) if _actual is True : return False elif _actual is False : return True else : raise_error ("af234e46", _value, _actual) return _function def statement_choose_if (_condition, _then, _else = None) : return lambda _expand : _then if _expand (_condition) else _else def statement_choose_if_is (_condition, _expected, _then, _else = None) : return lambda _expand : _then if _expand (_condition) is _expected else _else def statement_choose_if_is_not (_condition, _expected, _then, _else = None) : return lambda _expand : _then if _expand (_condition) is not _expected else _else def statement_choose_if_null (_condition, _then, _else = None) : return statement_choose_if_is (_condition, None, _then, _else) def statement_choose_if_non_null (_condition, _then, _else = None) : return statement_choose_if_is_not (_condition, None, _then, _else) def statement_choose_if_true (_condition, _then, _else = None) : return statement_choose_if_is (_condition, True, _then, _else) def statement_choose_if_false (_condition, _then, _else = None) : return statement_choose_if_is (_condition, False, _then, _else) def statement_choose_match (_condition, *_cases) : def _function (_expand) : _actual = _expand (_condition) for _case in _cases : if len (_case) != 2 : raise_error ("72ad5734", _case) _then = _case[1] _expected = _case[0] _expected = _expand (_expected) if _actual == _expected : return _then raise_error ("7e97f033", _condition, _actual) return _function def statement_choose_max (*_values) : return lambda _expand : max (*[_expand (_value) for _value in _values]) def statement_choose_min (*_values) : return lambda _expand : min (*[_expand (_value) for _value in _values]) def parameters_get (_parameter) : return lambda _parameters : _parameters._get (_parameter) def parameters_get_with_overrides (_parameter, **_overrides) : return lambda _parameters : _parameters._fork (**_overrides) ._get (_parameter) def parameters_math (_operator, _argument_1, _argument_2, _null_if_any_null = False) : def _function (_parameters) : _argument_1_actual = _parameters._expand (_argument_1) _argument_2_actual = _parameters._expand (_argument_2) if _argument_1_actual is None or _argument_2_actual is None : if _null_if_any_null : return None elif _argument_1_actual is None : raise_error ("7df73e38", _argument_1) elif _argument_2_actual is None : raise_error ("cee20b59", _argument_2) else : raise_error ("f5fefdf7") if _operator == "+" : return _argument_1_actual + _argument_2_actual elif _operator == "-" : return _argument_1_actual - _argument_2_actual elif _operator == "*" : return _argument_1_actual * _argument_2_actual elif _operator == "/" : return _argument_1_actual / _argument_2_actual elif _operator == "//" : return _argument_1_actual // _argument_2_actual else : raise_error ("c988cf62", _operator) return _function def parameters_format (_format, *_arguments) : return lambda _parameters : _parameters._expand (_format) % _parameters._expand (_arguments) def parameters_path_base_join (_base_path, *_elements) : return lambda _parameters : "/".join ([_parameters._expand (parameters_get (_base_path))] + list (_elements)) def parameters_coalesce (*_values) : def _function (_parameters) : for _value in _values : _value = _parameters._expand (_value) if _value is not None : return _value return None return _function def parameters_join (_separator, _arguments, non_null = True, null_if_empty = True) : def _function (_parameters) : _separator_actual = _parameters._expand (_separator) _arguments_actual = _parameters._expand (_arguments) if _arguments_actual is None : return None else : if non_null : _arguments_actual = [_argument_actual for _argument_actual in _arguments_actual if _argument_actual is not None] if null_if_empty and len (_arguments_actual) == 0 : return None else : return _separator_actual.join (_arguments_actual) return _function def parameters_choose_if (_condition, _then, _else = None) : return lambda _parameters : _then if _parameters._expand (_condition) else _else def parameters_choose_if_is (_condition, _expected, _then, _else = None) : return lambda _parameters : _then if _parameters._expand (_condition) is _expected else _else def parameters_choose_if_is_not (_condition, _expected, _then, _else = None) : return lambda _parameters : _then if _parameters._expand (_condition) is not _expected else _else def parameters_choose_if_null (_condition, _then, _else = None) : return parameters_choose_if_is (_condition, None, _then, _else) def parameters_choose_if_non_null (_condition, _then, _else = None) : return parameters_choose_if_is_not (_condition, None, _then, _else) def parameters_choose_if_true (_condition, _then, _else = None) : return parameters_choose_if_is (_condition, True, _then, _else) def parameters_choose_if_false (_condition, _then, _else = None) : return parameters_choose_if_is (_condition, False, _then, _else) def parameters_choose_match (_condition, *_cases) : def _function (_parameters) : _actual = _parameters._expand (_condition) for _case in _cases : if len (_case) != 2 : raise_error ("1b251e89", _case) _then = _case[1] _expected = _case[0] _expected = _parameters._expand (_expected) if _actual == _expected : return _then raise_error ("29b17200", _condition, _actual) return _function def parameters_and (*_conditions) : def _function (_parameters) : for _condition in _conditions : _actual = _parameters._expand (_condition) if _actual is False : return False elif _actual is True : continue else : raise_error ("8452916f", _condition, _actual) return True return _function def parameters_or (*_conditions) : def _function (_parameters) : for _condition in _conditions : _actual = _parameters._expand (_condition) if _actual is True : return True elif _actual is False : continue else : raise_error ("e7881123", _condition, _actual) return False return _function def parameters_not (_condition) : def _function (_parameters) : _actual = _parameters._expand (_condition) if _actual is True : return False elif _actual is False : return True else : raise_error ("3a6787ec", _condition, _actual) return _function def parameters_overrides (_fallback, **_overrides) : _parameters = dict (_fallback) _parameters.update (_overrides) return _parameters def parameters_defaults (_fallback, **_defaults) : _parameters = dict (_defaults) _parameters.update (_fallback) return _parameters __default__ = object () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-ec2d3654838e15d5045649325099a12f req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'site-with-www.example.com' acl acl-f7777fb7950e1429c94ba567167dba61 req.fhdr('Host',-1),host_only,ltrim('.'),rtrim('.') -m str -i eq -- 'www.site-without-www.example.com' acl acl-dbaf316a86669df8911f5b91102e8aa0 ssl_fc() -m bool acl acl-402db81baae469d338b6468436716b6b ssl_fc(),not -m bool #---- HTTP Request Rules http-request redirect prefix "http://www.site-with-www.example.com" code 307 if acl-ec2d3654838e15d5045649325099a12f acl-402db81baae469d338b6468436716b6b http-request redirect prefix "https://www.site-with-www.example.com" code 307 if acl-ec2d3654838e15d5045649325099a12f acl-dbaf316a86669df8911f5b91102e8aa0 http-request redirect prefix "http://site-without-www.example.com" code 307 if acl-f7777fb7950e1429c94ba567167dba61 acl-402db81baae469d338b6468436716b6b http-request redirect prefix "https://site-without-www.example.com" code 307 if acl-f7777fb7950e1429c94ba567167dba61 acl-dbaf316a86669df8911f5b91102e8aa0 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, frontend_bind_tls_minimal = False, ) _fe = _ha.http_frontends.basic () _be = _ha.http_backends.basic (_frontend = _fe) _trusted = ( "10.0.0.0/8", "192.168.0.0/16", ) _fe.requests.deny ( _code = 403, _acl = _fe.acls.client_ip (_trusted) .negate (), ) _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-02bba003a8f9189f5ae25ef0a1045b41 req.fhdr('User-Agent',-1),lower -m sub -i -f '/etc/haproxy/maps/bots.txt' acl acl-27c6d58bc13643828547b4a203d4cca7 req.hdr('X-Forwarded-For',1),map_ip('/etc/haproxy/maps/geoip.txt') -m str -i eq -- 'XX' acl acl-00b6fbb7739bf41e28767e0380dd70ef src() -m ip -n -f '/etc/haproxy/maps/bogons.txt' acl acl-88d86b7a9b77dbaae68933e8c4f91681 src(),map_ip('/etc/haproxy/maps/geoip.txt') -m str -i eq -- 'XX' acl acl-f98dd0b6d3c6d9c1ebd5cd68c6219025 var('txn.logging_geoip_country') -m str -i eq -- 'XX' #---- HTTP Request Rules http-request deny deny_status 601 if acl-88d86b7a9b77dbaae68933e8c4f91681 http-request deny deny_status 601 if acl-27c6d58bc13643828547b4a203d4cca7 http-request deny deny_status 601 if acl-f98dd0b6d3c6d9c1ebd5cd68c6219025 http-request deny deny_status 601 if acl-00b6fbb7739bf41e28767e0380dd70ef http-request deny deny_status 601 if acl-02bba003a8f9189f5ae25ef0a1045b41 <file_sep> from errors import * from tools import * from builders_core import * class HaHttpBackendBuilder (HaBuilder) : def __init__ (self, _context, _parameters) : HaBuilder.__init__ (self, _context, _parameters) def basic (self, _identifier = None, _endpoint = None, _frontend = None, _acl = None, _route_order = None, **_parameters) : _identifier = _identifier if _identifier is not None else "http-backend" _endpoint = _endpoint if _endpoint is not None else "ipv4@127.0.0.1:8080" _backend = self._context.http_backend_create (_identifier, **_parameters) if _endpoint is not None : _backend.declare_server ("default", _endpoint) def _frontend_configure (_routes, _requests, _responses) : _routes.route (_backend, _acl, order = _route_order) self._for_each_frontend_http_builders (_frontend, _frontend_configure) return _backend def for_domain (self, _domain, _endpoint = None, _identifier = None, _frontend = None, _acl = None, **_parameters) : _endpoint = _endpoint if _endpoint is not None else "ipv4@127.0.0.1:8080" _backend_identifier = parameters_coalesce (_identifier, _domain) _parameters = parameters_defaults (_parameters, backend_http_check_request_host = _domain) _backend = self._context.http_backend_create (_backend_identifier, **_parameters) _backend.declare_server ("default", _endpoint) def _frontend_configure (_routes, _requests, _responses) : _routes.route_host (_backend, _host, _acl) self._for_each_frontend_http_builders (_frontend, _frontend_configure) return _backend def for_domains (self, _map, _frontend = None, _acl = None, **_parameters) : _backends = list () for _domain, _endpoint in _map.iteritems () : _backend = self.for_domain (_domain, _endpoint, _frontend = _frontend, _identifier = _domain, _acl = _acl, **_parameters) _backends.append (_backend) return _backends def letsencrypt (self, _identifier = None, _endpoint = None, _frontend = None, _acl = None, **_parameters) : _server_endpoint = statement_coalesce (_endpoint, "$letsencrypt_server_endpoint") _backend_identifier = parameters_coalesce (_identifier, parameters_get ("letsencrypt_backend_identifier")) _parameters = parameters_overrides (_parameters, backend_check_enabled = False) _backend = self._context.http_backend_create (_backend_identifier, **_parameters) _backend.declare_server ("default", _server_endpoint) def _frontend_configure (_routes, _requests, _responses) : # FIXME: These parameters should be taken from overrides, then from frontend parameters, and then from self parameters! _path = self._parameters_get_and_expand ("letsencrypt_path", overrides = _parameters) _frontend_rules_order = self._parameters_get_and_expand ("letsencrypt_frontend_rules_order", overrides = _parameters) _frontend_routes_order = self._parameters_get_and_expand ("letsencrypt_frontend_routes_order", overrides = _parameters) _routes.route_subpath (_backend, _path, _acl, order = _frontend_routes_order) _requests.allow_subpath (_path, _acl, order = _frontend_rules_order) self._for_each_frontend_http_builders (_frontend, _frontend_configure) return _backend def varnish (self, _identifier = None, _endpoint = None, _frontend = None, _domain = None, _acl = None, **_parameters) : _server_endpoint = statement_coalesce (_endpoint, "$varnish_upstream_endpoint") _backend_identifier = parameters_coalesce (_identifier, parameters_get ("varnish_backend_identifier")) _parameters = parameters_overrides ( _parameters, backend_http_check_enabled = parameters_get ("varnish_heartbeat_enabled"), backend_http_check_request_uri = parameters_get ("varnish_heartbeat_path"), backend_server_min_connections_active_count = parameters_get ("varnish_min_connections_active_count"), backend_server_max_connections_active_count = parameters_get ("varnish_max_connections_active_count"), backend_server_max_connections_queue_count = parameters_get ("varnish_max_connections_queue_count"), backend_server_max_connections_full_count = parameters_get ("varnish_max_connections_full_count"), backend_server_check_interval_normal = parameters_get ("varnish_heartbeat_interval"), backend_server_check_interval_rising = parameters_get ("varnish_heartbeat_interval"), backend_server_check_interval_failed = parameters_get ("varnish_heartbeat_interval"), backend_http_keep_alive_reuse = parameters_get ("varnish_keep_alive_reuse"), backend_http_keep_alive_mode = parameters_get ("varnish_keep_alive_mode"), backend_http_keep_alive_timeout = parameters_get ("varnish_keep_alive_timeout"), server_http_send_proxy_enabled = parameters_get ("varnish_downstream_send_proxy_enabled"), ) _backend = self._context.http_backend_create (_backend_identifier, **_parameters) _backend.declare_server ("default", _server_endpoint) if self._parameters_get_and_expand ("varnish_drop_caching_enabled") : _backend.http_request_rule_builder () .drop_caching () if self._parameters_get_and_expand ("varnish_drop_cookies_enabled") : _backend.http_request_rule_builder () .drop_cookies () def _frontend_configure (_routes, _requests, _responses) : # FIXME: These parameters should be taken from overrides, then from frontend parameters, and then from self parameters! _frontend_rules_order = self._parameters_get_and_expand ("varnish_frontend_rules_order", parameters = _frontend._parameters, overrides = _parameters) _frontend_routes_order = self._parameters_get_and_expand ("varnish_frontend_routes_order", parameters = _frontend._parameters, overrides = _parameters) _internals_path_prefix = self._parameters_get_and_expand ("varnish_internals_path_prefix", parameters = _frontend._parameters, overrides = _parameters) _internals_order_allow = self._parameters._get_and_expand ("varnish_internals_rules_order_allow", parameters = _frontend._parameters, overrides = _parameters) _routes.route_host (_backend, _domain, _acl, order = _frontend_routes_order) _requests.allow_prefix (_internals_path_prefix, _acl, order = _internals_order_allow) self._for_each_frontend_http_builders (_frontend, _frontend_configure) return _backend def _for_each_frontend (self, _frontend, _callable) : if _frontend is None : return if not isinstance (_frontend, tuple) and not isinstance (_frontend, list) : _frontend = (_frontend,) for _frontend in _frontend : _callable (_frontend) def _for_each_frontend_http_builders (self, _frontend, _callable) : if _frontend is None : return if not isinstance (_frontend, tuple) and not isinstance (_frontend, list) : _frontend = (_frontend,) for _frontend in _frontend : _frontend_routes = _frontend.routes _frontend_http_requests = _frontend.http_request_rule_builder () _frontend_http_responses = _frontend.http_response_rule_builder () _callable (_frontend_routes, _frontend_http_requests, _frontend_http_responses) def fallback (self, _identifier = "http-fallback") : _backend = self._context.http_backend_create ( _identifier, backend_check_enabled = True, backend_http_keep_alive_reuse = "never", backend_http_keep_alive_mode = "close", ) _backend.declare_server ("default", "ipv4@127.255.255.254:8080") return _backend def fallback_deny (self, _identifier = "http-fallback", _code = 403, _mark = None) : _backend = self._context.http_backend_create ( _identifier, backend_check_enabled = False, backend_http_keep_alive_reuse = "never", backend_http_keep_alive_mode = "close", ) _backend.requests.deny (_code, None, _mark) return _backend <file_sep> from errors import * from tools import * from builders_core import * from builders_acl import * class HaHttpRuleBuilder (HaBuilder) : def __init__ (self, _context, _parameters) : HaBuilder.__init__ (self, _context, _parameters) self._acl = HaHttpAclBuilder (_context, _parameters) self._samples = HaHttpSampleBuilder (_context, _parameters) def _declare_http_rule_0 (self, _rule, _condition, **_overrides) : if isinstance (self, HaHttpRequestRuleBuilder) : self._context.declare_http_request_rule_0 ((_rule, _condition), **_overrides) elif isinstance (self, HaHttpResponseRuleBuilder) : self._context.declare_http_response_rule_0 ((_rule, _condition), **_overrides) else : raise_error ("508829d5", self) def declare_rule (self, _rule, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) if _acl is not None else None self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def allow (self, _acl, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("allow",) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def allow_path (self, _path, _acl = None, **_overrides) : _acl_path = self._acl.path (_path) self.allow ((_acl, _acl_path), **_overrides) def allow_path_prefix (self, _path, _acl = None, **_overrides) : _acl_path = self._acl.path_prefix (_path) self.allow ((_acl, _acl_path), **_overrides) def allow_path_suffix (self, _path, _acl = None, **_overrides) : _acl_path = self._acl.path_suffix (_path) self.allow ((_acl, _acl_path), **_overrides) def allow_path_substring (self, _path, _acl = None, **_overrides) : _acl_path = self._acl.path_substring (_path) self.allow ((_acl, _acl_path), **_overrides) def allow_subpath (self, _path, _acl = None, **_overrides) : _acl_path = self._acl.subpath (_path) self.allow ((_acl, _acl_path), **_overrides) def deny (self, _code, _acl = None, _mark = None, _return = False, **_overrides) : # FIXME: Make this configurable and deferable! if _mark is not None and _mark != 0 : self.set_mark (_mark, _acl, **_overrides) _rule_condition = self._context._condition_if (_acl) if _return : _deny_rule = ("deny", statement_choose_if_non_null (_code, ("status", statement_enforce_int (_code)))) else : _deny_rule = ("deny", statement_choose_if_non_null (_code, ("deny_status", statement_enforce_int (_code)))) self._declare_http_rule_0 (_deny_rule, _rule_condition, **_overrides) def deny_host (self, _host, _acl = None, _code = None, _mark = None, **_overrides) : _acl_host = self._acl.host (_host) self.deny (_code, (_acl, _acl_host), _mark, **_overrides) def deny_path (self, _path, _acl = None, _code = None, _mark = None, **_overrides) : _acl_path = self._acl.path (_path) self.deny (_code, (_acl, _acl_path), _mark, **_overrides) def deny_path_prefix (self, _path, _acl = None, _code = None, _mark = None, **_overrides) : _acl_path = self._acl.path_prefix (_path) self.deny (_code, (_acl, _acl_path), _mark, **_overrides) def deny_path_suffix (self, _path, _acl = None, _code = None, _mark = None, **_overrides) : _acl_path = self._acl.path_suffix (_path) self.deny (_code, (_acl, _acl_path), _mark, **_overrides) def deny_path_substring (self, _path, _acl = None, _code = None, _mark = None, **_overrides) : _acl_path = self._acl.path_substring (_path) self.deny (_code, (_acl, _acl_path), _mark, **_overrides) def deny_subpath (self, _path, _acl = None, _code = None, _mark = None, **_overrides) : _acl_path = self._acl.subpath (_path) self.deny (_code, (_acl, _acl_path), _mark, **_overrides) def deny_geoip_country (self, _country, _negated = False, _acl = None, _code = None, _mark = None, **_overrides) : _acl_country = self._acl.geoip_country_captured (_country) if _negated : _acl_country = _acl_country.negate () self.deny (_code, (_acl, _acl_country), _mark, **_overrides) def deny_bot (self, _acl = None, _code = None, _mark = None, **_overrides) : _acl_bot = self._acl.bot () self.deny (_code, (_acl, _acl_bot), _mark, **_overrides) def set_header (self, _header, _value, _ignore_if_exists = False, _acl = None, **_overrides) : _acl_exists = self._header_acl_exists (_header) if _ignore_if_exists else None _rule_condition = self._context._condition_if ((_acl, _acl_exists)) _rule = ("set-header", statement_quote ("\"", _header), statement_quote ("\"", _value)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def delete_header (self, _header, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("del-header", statement_quote ("\"", _header)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def append_header (self, _header, _value, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("add-header", statement_quote ("\"", _header), statement_quote ("\"", _value)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def replace_header (self, _header, _matcher, _replacement, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("replace-header", statement_quote ("\"", _header), statement_quote ("\"", _matcher), statement_quote ("\"", _replacement)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def _header_acl_exists (self, _header) : if isinstance (self, HaHttpRequestRuleBuilder) : return self._acl.request_header_exists (_header, False) elif isinstance (self, HaHttpResponseRuleBuilder) : return self._acl.response_header_exists (_header, False) else : raise_error ("b0203fc6", self) def set_header_from_variable (self, _header, _variable, _ignore_if_exists = False, _acl = None, **_overrides) : _sample = self._samples.variable (_variable) _acl_variable_exists = self._acl.variable_exists (_variable) self.set_header_from_sample (_header, _sample, _ignore_if_exists, (_acl, _acl_variable_exists), **_overrides) def set_header_from_sample (self, _header, _sample, _ignore_if_exists = False, _acl = None, **_overrides) : _value = _sample.statement_format () _acl_exists = self._header_acl_exists (_header) if _ignore_if_exists else None _rule_condition = self._context._condition_if ((_acl, _acl_exists)) _rule = ("set-header", statement_quote ("\"", _header), statement_quote ("\"", _value)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_cookie (self, _name, _value, _path, _max_age, _same_site, _secure, _http_only, _acl = None, **_overrides) : # FIXME: Make `Path` and `Max-Age` configurable! _path = statement_choose_if (_path, statement_format ("Path=%s", statement_enforce_string (_path))) _max_age = statement_choose_if (_max_age, statement_format ("Max-Age=%d", statement_enforce_int (_max_age))) _cookie = statement_format ("%s=%s", statement_enforce_string (_name), statement_enforce_string (_value)) _cookie = [_cookie, _path, _max_age] if _same_site is not None : if _same_site is True : _same_site = "Strict" elif _same_site is False : _same_site = "None" _cookie.append (statement_format ("SameSite=%s", statement_enforce_string (_same_site))) _cookie.append (statement_choose_if (_secure, "Secure")) _cookie.append (statement_choose_if (_http_only, "HttpOnly")) _cookie = statement_join ("; ", tuple (_cookie)) self.append_header ("Set-Cookie", _cookie, _acl, **_overrides) def set_variable (self, _variable, _value, _acl = None, _format = False, **_overrides) : _rule_condition = self._context._condition_if (_acl) if isinstance (_value, basestring) : _value = "str(%s)" % quote_token ("\'", _value) if _format : _rule = (statement_format ("set-var-fmt(%s)", _variable), statement_quote ("\"", _value)) else : _rule = (statement_format ("set-var(%s)", _variable), _value) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def unset_variable (self, _variable, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = (statement_format ("unset-var(%s)", _variable),) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_enabled (self, _variable, _acl = None, **_overrides) : self.set_variable (_variable, ("bool(true)",), _acl, **_overrides) def set_disabled (self, _variable, _acl = None, **_overrides) : self.set_variable (_variable, ("bool(false)",), _acl, **_overrides) def track_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_tracking_enabled_variable", _acl, **_overrides) def track_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_tracking_excluded_variable", _acl, **_overrides) def debug_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_debug_enabled_variable", _acl, **_overrides) def debug_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_debug_excluded_variable", _acl, **_overrides) def harden_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_harden_enabled_variable", _acl, **_overrides) def harden_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_harden_excluded_variable", _acl, **_overrides) def harden_ranges_allow (self, _acl = None, **_overrides) : self.set_enabled ("$http_ranges_allowed_variable", _acl, **_overrides) def drop_caching_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_drop_caching_enabled_variable", _acl, **_overrides) def drop_caching_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_drop_caching_excluded_variable", _acl, **_overrides) def force_caching_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_force_caching_enabled_variable", _acl, **_overrides) def force_caching_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_force_caching_excluded_variable", _acl, **_overrides) def drop_cookies_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_drop_cookies_enabled_variable", _acl, **_overrides) def drop_cookies_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_drop_cookies_excluded_variable", _acl, **_overrides) def force_cors_enable (self, _acl = None, **_overrides) : self.set_enabled ("$http_force_cors_enabled_variable", _acl, **_overrides) def force_cors_exclude (self, _acl = None, **_overrides) : self.set_enabled ("$http_force_cors_excluded_variable", _acl, **_overrides) def set_mark (self, _mark, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _mark_rule = ("set-mark", statement_format ("0x%08x", statement_enforce_int (_mark))) self._declare_http_rule_0 (_mark_rule, _rule_condition, **_overrides) def redirect (self, _target, _code = 307, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("redirect", "location", statement_quote ("\"", _target), "code", _code) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def redirect_root (self, _target, _code = 307, _acl = None, **_overrides) : _acl_root = self._acl.path ("/") self.redirect (_target, _code = _code, _acl = (_acl_root, _acl), **_overrides) def redirect_with_path (self, _path, _code = 307, _acl = None, _include_scheme = True, _include_host = True, **_overrides) : if _include_scheme and _include_host : _target = statement_format ("%%[%s]://%%[%s]%s", self._samples.forwarded_proto (), self._samples.forwarded_host (), _path) elif _include_host : _target = statement_format ("//%%[%s]%s", self._samples.forwarded_host (), _path) else : _target = _path self.redirect (_target, _code = _code, _acl = _acl, **_overrides) def redirect_with_path_prefix (self, _path_prefix, _code = 307, _acl = None, _include_scheme = True, _include_host = True, **_overrides) : _path = statement_format ("%s%%[%s]", _path_prefix, self._samples.path ()) self.redirect_with_path (_path, _code = _code, _acl = _acl, _include_scheme = _include_scheme, _include_host = _include_host, **_overrides) def redirect_with_path_suffix (self, _path_suffix, _code = 307, _acl = None, _include_scheme = True, _include_host = True, **_overrides) : _path = statement_format ("%%[%s]%s", self._samples.path (), _path_suffix) self.redirect_with_path (_path, _code = _code, _acl = _acl, _include_scheme = _include_scheme, _include_host = _include_host, **_overrides) def redirect_prefix (self, _target, _code = 307, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("redirect", "prefix", statement_quote ("\"", _target), "code", _code) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def redirect_via_tls (self, _code = 307, _acl = None, _force = False, **_overrides) : if not _force : _acl_non_tls = self._acl.via_tls (False) _rule_condition = self._context._condition_if ((_acl, _acl_non_tls)) else : _rule_condition = None _rule = ("redirect", "scheme", "https", "code", _code) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def track_stick (self, _source = None, _acl = None, **_overrides) : if _source is None : _source = "$frontend_http_stick_source" _source = statement_choose_match (_source, ("src", "src"), ("X-Forwarded-For", statement_format ("req.hdr(%s,1),digest(md5),hex,lower", "$logging_http_header_forwarded_for")), ("User-Agent", statement_format ("req.fhdr(User-Agent,-1),digest(md5)")), ) _rule_condition = self._context._condition_if (_acl) _rule = ("track-sc0", _source) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def logging_exclude (self, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-log-level", "silent") self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_nice (self, _nice, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-nice", "int(%d)" % _nice) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_priority (self, _priority, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-priority-class", "int(%d)" % _priority) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) class HaHttpRequestRuleBuilder (HaHttpRuleBuilder) : def __init__ (self, _context, _parameters) : HaHttpRuleBuilder.__init__ (self, _context, _parameters) def set_method (self, _method, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-method", statement_quote ("\'", _method)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_path (self, _path, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-path", statement_quote ("\"", _path)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_path_prefix (self, _path_prefix, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-path", statement_quote ("\"", statement_format ("%s%%[%s]", _path_prefix, self._samples.path ()))) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_path_suffix (self, _path_suffix, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-path", statement_quote ("\"", statement_format ("%%[%s]%s", self._samples.path (), _path_suffix))) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_query (self, _query, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-query", statement_quote ("\"", _query)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_uri (self, _uri, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-uri", statement_quote ("\"", _uri)) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def set_enabled_for_domain (self, _variable, _domain, _acl = None, **_overrides) : _acl_host = self._acl.host (_domain) self.set_enabled (_variable, (_acl, _acl_host), **_overrides) def redirect_domain_via_tls (self, _domain, _only_root = False, _code = 307, _acl = None, **_overrides) : for _domain in sorted (self._one_or_many (_domain)) : _acl_host = self._acl.host (_domain) _acl_non_tls = self._acl.via_tls (False) _acl_path = self._acl.path ("/") if _only_root else None _rule_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_non_tls)) _rule = ("redirect", "scheme", "https", "code", _code) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def redirect_domain_with_www (self, _domain, _only_root = False, _force_tls = False, _code = 307, _acl = None, **_overrides) : for _domain in sorted (self._one_or_many (_domain)) : if _domain.startswith ("www.") : _domain = _domain[4:] _redirect_tls = statement_quote ("\"", statement_format ("https://www.%s", _domain)) _redirect_non_tls = statement_quote ("\"", statement_format ("http://www.%s", _domain)) if not _force_tls else _redirect_tls _acl_host = self._acl.host (statement_format ("%s", _domain)) _acl_path = self._acl.path ("/") if _only_root else None _acl_non_tls = self._acl.via_tls (False) _acl_tls = self._acl.via_tls (True) _rule_non_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_non_tls)) _rule_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_tls)) _rule_non_tls = ("redirect", "prefix", _redirect_non_tls, "code", _code) _rule_tls = ("redirect", "prefix", _redirect_tls, "code", _code) self._declare_http_rule_0 (_rule_non_tls, _rule_non_tls_condition, **_overrides) self._declare_http_rule_0 (_rule_tls, _rule_tls_condition, **_overrides) def redirect_domain_without_www (self, _domain, _only_root = False, _force_tls = False, _code = 307, _acl = None, **_overrides) : for _domain in sorted (self._one_or_many (_domain)) : if _domain.startswith ("www.") : _domain = _domain[4:] _redirect_tls = statement_quote ("\"", statement_format ("https://%s", _domain)) _redirect_non_tls = statement_quote ("\"", statement_format ("http://%s", _domain)) if not _force_tls else _redirect_tls _acl_host = self._acl.host (statement_format ("www.%s", _domain)) _acl_path = self._acl.path ("/") if _only_root else None _acl_non_tls = self._acl.via_tls (False) _acl_tls = self._acl.via_tls (True) _rule_non_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_non_tls)) _rule_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_tls)) _rule_non_tls = ("redirect", "prefix", _redirect_non_tls, "code", _code) _rule_tls = ("redirect", "prefix", _redirect_tls, "code", _code) self._declare_http_rule_0 (_rule_non_tls, _rule_non_tls_condition, **_overrides) self._declare_http_rule_0 (_rule_tls, _rule_tls_condition, **_overrides) def redirect_domain (self, _source, _target, _force_tls = False, _redirect_code = 307, _acl = None, **_overrides) : _redirect_tls = statement_quote ("\"", statement_format ("https://%s", _target)) _redirect_non_tls = statement_quote ("\"", statement_format ("http://%s", _target)) if not _force_tls else _redirect_tls _acl_host = self._acl.host (_source) _acl_non_tls = self._acl.via_tls (False) _acl_tls = self._acl.via_tls (True) _rule_non_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_non_tls)) _rule_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_tls)) _rule_non_tls = ("redirect", "prefix", _redirect_non_tls, "code", _redirect_code) _rule_tls = ("redirect", "prefix", _redirect_tls, "code", _redirect_code) self._declare_http_rule_0 (_rule_non_tls, _rule_non_tls_condition, **_overrides) self._declare_http_rule_0 (_rule_tls, _rule_tls_condition, **_overrides) def redirect_domain_and_path (self, _source, _target, _force_tls = False, _redirect_code = 307, _acl = None, **_overrides) : _source_domain, _source_path, _source_path_exact, _negate = _source _target_domain, _target_path, _target_path_exact = _target if _target_path is None : _target_path = "" _redirect_method = "prefix" if _target_path_exact is not None : raise_error ("c951cde1", _source, _target) else : if _target_path_exact is True : _redirect_method = "location" elif _target_path_exact is False : _redirect_method = "prefix" else : raise_error ("925d9f3b", _source, _target) if _target_domain is not None : _redirect_tls = statement_quote ("\"", statement_format ("https://%s%s", _target_domain, _target_path)) _redirect_non_tls = statement_quote ("\"", statement_format ("http://%s%s", _target_domain, _target_path)) if not _force_tls else _redirect_tls else : if _force_tls : raise_error ("923c4768", _source, _target) _redirect_non_tls = statement_quote ("\"", _target_path) _redirect_tls = None if _source_domain is not None : _acl_host = self._acl.host (_source_domain) else : _acl_host = None if _source_path is not None : if _source_path_exact is True : _acl_path = self._acl.path (_source_path) elif _source_path_exact is False : # NOTE: This is a hack! _acl_path = (self._acl.subpath (_source_path), self._acl.path_prefix (_source_path)) elif _source_path_exact == "prefix" : _acl_path = self._acl.path_prefix (_source_path) else : raise Exception ("6149bbc7", _source_path_exact) _acl_path = _acl_path.negate () if _negate else _acl_path else : _acl_path = None _acl_non_tls = self._acl.via_tls (False) _rule_non_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_non_tls)) _rule_non_tls = ("redirect", _redirect_method, _redirect_non_tls, "code", _redirect_code) self._declare_http_rule_0 (_rule_non_tls, _rule_non_tls_condition, **_overrides) if _redirect_tls is not None : _acl_tls = self._acl.via_tls (True) _rule_tls_condition = self._context._condition_if ((_acl, _acl_host, _acl_path, _acl_tls)) _rule_tls = ("redirect", _redirect_method, _redirect_tls, "code", _redirect_code) self._declare_http_rule_0 (_rule_tls, _rule_tls_condition, **_overrides) def redirect_domains (self, _map, _force_tls = False, _acl = None, **_overrides) : for _source, _target in sorted (_map.iteritems ()) : self.redirect_domain (_source, _target, _force_tls, _acl, **_overrides) def redirect_domains_and_paths (self, _map, _force_tls = False, _acl = None, **_overrides) : for _source, _target in sorted (_map.iteritems ()) : self.redirect_domain_and_path (_source, _target, _force_tls, _acl, **_overrides) def redirect_favicon (self, _redirect = "$favicon_redirect_url", _internal = True, _code = 307, _acl = None, **_overrides) : _acl_path = self._acl.path ("/favicon.ico") if _internal : self.set_path (_redirect, (_acl, _acl_path), **_overrides) else : self.redirect (_redirect, _code, (_acl, _acl_path), **_overrides) def expose_internals_0 (self, _acl_internals, _credentials = None, _acl = None, _mark_allowed = None, **_overrides) : _mark_allowed = self._value_or_parameters_get_and_expand (_mark_allowed, "internals_netfilter_mark_allowed") _order_allow = self._parameters._get_and_expand ("internals_rules_order_allow") _acl_authenticated = self._acl.authenticated (_credentials) if _credentials is not None else None # FIXME: Make this deferable! if _mark_allowed is not None and _mark_allowed != 0 : self.set_mark (_mark_allowed, (_acl, _acl_authenticated, _acl_internals), **parameters_overrides (_overrides, order = _order_allow)) self.allow ((_acl, _acl_authenticated, _acl_internals), **parameters_overrides (_overrides, order = _order_allow)) def expose_internals_path (self, _path, _credentials = None, _acl = None, _mark_allowed = None, **_overrides) : _acl_path = self._acl.path (_path) self.expose_internals_0 (_acl_path, _credentials, _acl, _mark_allowed, **_overrides) def expose_internals_path_prefix (self, _path, _credentials = None, _acl = None, _mark_allowed = None, **_overrides) : _acl_path = self._acl.path_prefix (_path) self.expose_internals_0 (_acl_path, _credentials, _acl, _mark_allowed, **_overrides) def protect_internals_path_prefix (self, _path, _credentials = None, _acl = None, _mark_denied = None, **_overrides) : _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "internals_netfilter_mark_denied") _order_deny = self._parameters._get_and_expand ("internals_rules_order_deny") _acl_path = self._acl.path_prefix (_path) if _credentials is not None : self.authenticate (_credentials, None, (_acl, _acl_path), order = _order_deny, **_overrides) self.deny (None, (_acl, _acl_path), _mark_denied, order = _order_deny, **_overrides) def expose_internals (self, _credentials = None, _acl = None, _mark_allowed = None, _mark_denied = None, **_overrides) : self.expose_internals_path_prefix ("$haproxy_internals_path_prefix", _credentials, _acl, _mark_allowed, **_overrides) self.expose_internals_path_prefix ("$heartbeat_self_path", _credentials, _acl, _mark_allowed, **_overrides) self.expose_internals_path_prefix ("$heartbeat_proxy_path", _credentials, _acl, _mark_allowed, **_overrides) self.expose_internals_path_prefix ("$heartbeat_server_path", _credentials, _acl, _mark_allowed, **_overrides) self.protect_internals_path_prefix ("$internals_path_prefix", _credentials, _acl, _mark_denied, **_overrides) def expose_error_pages (self, _credentials = None, _codes = "$error_pages_codes", _acl = None, _mark_allowed = None, _mark_denied = None, **_overrides) : # FIXME: Make this deferable! _codes = [200] + list (self._context._resolve_token (_codes)) _order_allow = self._parameters._get_and_expand ("internals_rules_order_allow") _order_deny = self._parameters._get_and_expand ("internals_rules_order_deny") _acl_authenticated = self._acl.authenticated (_credentials) if _credentials is not None else None for _code in _codes : _acl_path = self._acl.path (statement_format ("%s%d", "$error_pages_path_prefix", _code)) self.deny (statement_enforce_int (_code), (_acl, _acl_authenticated, _acl_path), _mark_allowed, **parameters_overrides (_overrides, order = _order_allow)) self.deny (None, (_acl, self._acl.path_prefix ("$error_pages_path_prefix")), _mark_denied, order = _order_deny) def expose_whitelist (self, _credentials = None, _acl = None, _mark_allowed = None, _mark_denied = None, **_overrides) : _mark_allowed = self._value_or_parameters_get_and_expand (_mark_allowed, "whitelist_netfilter_mark_allowed") _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "whitelist_netfilter_mark_denied") _order_allow = self._parameters._get_and_expand ("internals_rules_order_allow") _order_deny = self._parameters._get_and_expand ("internals_rules_order_deny") _acl_authenticated = self._acl.authenticated (_credentials) if _credentials is not None else None _acl_path = self._acl.path ("$whitelist_path") self.deny (200, (_acl, _acl_authenticated, _acl_path), _mark_allowed, **parameters_overrides (_overrides, order = _order_allow)) self.deny (None, (_acl, _acl_path), _mark_denied, **parameters_overrides (_overrides, order = _order_deny)) def set_forwarded_headers (self, _ignore_if_exists = False, _acl = None, **_overrides) : _via_tls_method = self._parameters._get_and_expand ("logging_http_header_forwarded_proto_method") _acl_with_tls = self._acl.via_tls (True, _method = _via_tls_method) _acl_without_tls = self._acl.via_tls (False, _method = _via_tls_method) self.set_header ("$logging_http_header_forwarded_host", statement_format ("%%[%s]", self._samples.host ()), _ignore_if_exists, _acl, **_overrides) self.set_header ("$logging_http_header_forwarded_for", "%ci", _ignore_if_exists, _acl, **_overrides) self.set_header ("$logging_http_header_forwarded_proto", "http", _ignore_if_exists, (_acl_without_tls, _acl), **_overrides) self.set_header ("$logging_http_header_forwarded_proto", "https", _ignore_if_exists, (_acl_with_tls, _acl), **_overrides) self.set_header ("$logging_http_header_forwarded_port", 80, _ignore_if_exists, (_acl_without_tls, _acl), **_overrides) self.set_header ("$logging_http_header_forwarded_port", 443, _ignore_if_exists, (_acl_with_tls, _acl), **_overrides) self.set_header ("$logging_http_header_forwarded_server_ip", "%fi", _ignore_if_exists, _acl, **_overrides) self.set_header ("$logging_http_header_forwarded_server_port", "%fp", _ignore_if_exists, _acl, **_overrides) self.set_geoip_headers (_ignore_if_exists, _acl, **_overrides) def drop_forwarded_headers (self, _acl = None, **_overrides) : self.delete_header ("$logging_http_header_forwarded_host", _acl, **_overrides) self.delete_header ("$logging_http_header_forwarded_for", _acl, **_overrides) self.delete_header ("$logging_http_header_forwarded_proto", _acl, **_overrides) self.delete_header ("$logging_http_header_forwarded_port", _acl, **_overrides) self.delete_header ("$logging_http_header_forwarded_server_ip", _acl, **_overrides) self.delete_header ("$logging_http_header_forwarded_server_port", _acl, **_overrides) self.delete_header ("$logging_http_header_action", _acl, **_overrides) def set_geoip_headers (self, _ignore_if_exists = False, _acl = None, **_overrides) : _geoip_enabled = self._parameters._get_and_expand ("geoip_enabled") if _geoip_enabled : self.set_header ("X-Country", statement_format ("%%[%s]", self._samples.geoip_country_extracted ()), _ignore_if_exists, _acl, **_overrides) def track (self, _acl = None, _force = False, _generate = True, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_tracking_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_tracking_excluded_variable", True) .negate () if not _force else None _acl_request_explicit = self._acl.request_header_exists ("$http_tracking_request_header") _acl_tracked_via_header = self._acl.request_header_exists ("$http_tracking_session_header") _acl_tracked_via_cookie = self._acl.request_cookie_exists ("$http_tracking_session_cookie") _acl_untracked = (_acl_tracked_via_header.negate (), _acl_tracked_via_cookie.negate ()) if _generate : # FIXME: Find a better way! self.set_header ("$http_tracking_request_header", "%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]", False, (_acl, _acl_request_explicit.negate (), _acl_enabled, _acl_included), **_overrides) self.set_variable ("$http_tracking_request_variable", self._samples.request_header ("$http_tracking_request_header"), (_acl, _acl_enabled, _acl_included), **_overrides) if _generate : # FIXME: Find a better way! self.set_header ("$http_tracking_session_header", "%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]", False, (_acl, _acl_untracked, _acl_enabled, _acl_included), **_overrides) self.set_header ("$http_tracking_session_header", statement_format ("%%[%s]", self._samples.request_cookie ("$http_tracking_session_cookie")), False, (_acl, _acl_tracked_via_header.negate (), _acl_tracked_via_cookie, _acl_enabled, _acl_included), **_overrides) self.set_variable ("$http_tracking_session_variable", self._samples.request_header ("$http_tracking_session_header"), (_acl, _acl_enabled, _acl_included), **_overrides) def track_enable_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_tracking_enabled_variable", _domain, _acl, **_overrides) def track_exclude_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_tracking_excluded_variable", _domain, _acl, **_overrides) def harden_http (self, _acl = None, _acl_deny = None, _force = False, _mark_denied = None, **_overrides) : _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "http_harden_netfilter_mark_denied") _acl_methods = self._acl.request_method ("$http_harden_allowed_methods") _acl_methods = _acl_methods.negate () _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.deny (None, (_acl, _acl_deny, _acl_methods, _acl_enabled, _acl_included), _mark_denied, **_overrides) def harden_authorization (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.delete_header ("Authorization", (_acl, _acl_enabled, _acl_included), **_overrides) def harden_browsing (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.delete_header ("User-Agent", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Referer", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Accept-Encoding", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Accept-Language", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Accept-Charset", (_acl, _acl_enabled, _acl_included), **_overrides) def harden_ranges (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None _acl_forbidden = self._acl.variable_bool ("$http_ranges_allowed_variable", True) .negate () if not _force else None self.delete_header ("Range", (_acl, _acl_enabled, _acl_included, _acl_forbidden), **_overrides) self.delete_header ("If-Range", (_acl, _acl_enabled, _acl_included, _acl_forbidden), **_overrides) def harden_all (self, _acl = None, _acl_deny = None, _force = False, **_overrides) : self.harden_http (_acl, _acl_deny, _force, **_overrides) self.harden_browsing (_acl, _force, **_overrides) self.harden_authorization (_acl, _force, **_overrides) self.harden_ranges (_acl, _force, **_overrides) def harden_enable_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_harden_enabled_variable", _domain, _acl, **_overrides) def harden_exclude_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_harden_excluded_variable", _domain, _acl, **_overrides) def drop_caching (self, _acl = None, _force = False, _keep_etag_acl = None, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_drop_caching_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_drop_caching_excluded_variable", True) .negate () if not _force else None self.delete_header ("Cache-Control", (_acl, _acl_enabled, _acl_included), **_overrides) if _keep_etag_acl is None or _keep_etag_acl is not True : _keep_etag_acl_0 = _keep_etag_acl.negate () if _keep_etag_acl is not None else None self.delete_header ("If-None-Match", (_acl, _acl_enabled, _acl_included, _keep_etag_acl_0), **_overrides) self.delete_header ("If-Match", (_acl, _acl_enabled, _acl_included, _keep_etag_acl_0), **_overrides) self.delete_header ("If-Modified-Since", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("If-Unmodified-Since", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Pragma", (_acl, _acl_enabled, _acl_included), **_overrides) def drop_caching_enable_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_drop_caching_enabled_variable", _domain, _acl, **_overrides) def drop_caching_exclude_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_drop_caching_excluded_variable", _domain, _acl, **_overrides) def force_caching_enable_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_force_caching_enabled_variable", _domain, _acl, **_overrides) def force_caching_exclude_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_force_caching_excluded_variable", _domain, _acl, **_overrides) def drop_cookies (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_drop_cookies_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_drop_cookies_excluded_variable", True) .negate () if not _force else None self.delete_header ("Cookie", (_acl, _acl_enabled, _acl_included), **_overrides) def drop_cookies_enable_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_drop_cookies_enabled_variable", _domain, _acl) def drop_cookies_exclude_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_drop_cookies_excluded_variable", _domain, _acl) def force_cors (self, _acl = None, _force = False, **_overrides) : self.force_cors_prepare (**_overrides) self.force_cors_unset (**_overrides) def force_cors_prepare (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None _acl_origin_present = self._acl.request_header_exists ("Origin") _acl_options_present = self._acl.request_method ("OPTIONS") self.set_enabled ("$http_force_cors_origin_present_variable", (_acl, _acl_enabled, _acl_included, _acl_origin_present), **_overrides) self.set_enabled ("$http_force_cors_options_present_variable", (_acl, _acl_enabled, _acl_included, _acl_options_present), **_overrides) self.set_variable ("$http_force_cors_origin_variable", self._samples.request_header ("Origin"), (_acl, _acl_enabled, _acl_included, _acl_origin_present), **_overrides) def force_cors_unset (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None self.delete_header ("Origin", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Request-Method", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Request-Headers", (_acl, _acl_enabled, _acl_included), **_overrides) def force_cors_allow (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None _acl_origin = self._acl.variable_bool ("$http_force_cors_origin_present_variable", True) if not _force else None self.set_enabled ("$http_force_cors_allowed_variable", (_acl, _acl_enabled, _acl_included, _acl_origin), **_overrides) def force_cors_allow_origin (self, _origin, _acl = None, _force = False, **_overrides) : _acl_origin = self._acl.variable_equals ("$http_force_cors_origin_variable", _origin) self.force_cors_allow ((_acl, _acl_origin), _force, **_overrides) def force_cors_retarget_options (self, _method, _path, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None _acl_allowed = self._acl.variable_bool ("$http_force_cors_allowed_variable", True) if not _force else None _acl_origin = self._acl.variable_bool ("$http_force_cors_origin_present_variable", True) if not _force else None _acl_options = self._acl.variable_bool ("$http_force_cors_options_present_variable", True) if not _force else None self.set_method (_method, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed, _acl_options), **_overrides) self.set_path (_path, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed, _acl_options), **_overrides) self.deny (403, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed.negate (), _acl_options), **_overrides) def force_cors_enable_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_force_cors_enabled_variable", _domain, _acl) def force_cors_exclude_for_domain (self, _domain, _acl = None, **_overrides) : self.set_enabled_for_domain ("$http_force_cors_excluded_variable", _domain, _acl) def capture (self, _sample, _acl = None, **_overrides) : _index = self._context._declare_request_capture (**_overrides) _rule_condition = self._context._condition_if (_acl) _rule = ("capture", _sample, "id", _index) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) return _index def capture_header (self, _header, _transforms = None, _acl = None, _index = None, **_overrides) : _sample = self._samples.request_header (_header, _transforms, _index) return self.capture (_sample, _acl, **_overrides) def capture_defaults (self, _acl = None, **_overrides) : self.capture_protocol (_acl, **_overrides) self.capture_forwarded (_acl, **_overrides) self.capture_tracking (_acl, **_overrides) self.capture_browsing (_acl, **_overrides) self.capture_caching (_acl, **_overrides) self.capture_cookies (_acl, **_overrides) self.capture_geoip (_acl, **_overrides) def capture_protocol (self, _acl = None, **_overrides) : self.capture_header ("Host", "base64", _acl, **_overrides) def capture_forwarded (self, _acl = None, **_overrides) : self.capture_header ("$logging_http_header_forwarded_host", "base64", _acl, **_overrides) self.capture_header ("$logging_http_header_forwarded_for", "base64", _acl, **_overrides) self.capture_header ("$logging_http_header_forwarded_proto", "base64", _acl, **_overrides) self.capture_header ("$logging_http_header_forwarded_port", "base64", _acl, **_overrides) def capture_tracking (self, _acl = None, **_overrides) : self.capture_header ("$http_tracking_request_header", "base64", _acl, **_overrides) self.capture_header ("$http_tracking_session_header", "base64", _acl, **_overrides) def capture_browsing (self, _acl = None, **_overrides) : self.capture_header ("User-Agent", "base64", _acl, **_overrides) self.capture_header ("Referer", "base64", _acl, **_overrides) self.capture_header ("Accept-Encoding", "base64", _acl, **_overrides) self.capture_header ("Accept-Language", "base64", _acl, **_overrides) self.capture_header ("Accept-Charset", "base64", _acl, **_overrides) def capture_caching (self, _acl = None, **_overrides) : self.capture_header ("Cache-Control", "base64", _acl, **_overrides) self.capture_header ("If-None-Match", "base64", _acl, **_overrides) self.capture_header ("If-Match", "base64", _acl, **_overrides) self.capture_header ("If-Modified-Since", "base64", _acl, **_overrides) self.capture_header ("If-Unmodified-Since", "base64", _acl, **_overrides) self.capture_header ("Pragma", "base64", _acl, **_overrides) def capture_cookies (self, _acl = None, **_overrides) : self.capture_header ("Cookie", "base64", _acl, 1, **_overrides) self.capture_header ("Cookie", "base64", _acl, 2, **_overrides) self.capture_header ("Cookie", "base64", _acl, 3, **_overrides) self.capture_header ("Cookie", "base64", _acl, 4, **_overrides) def capture_geoip (self, _acl = None, **_overrides) : _geoip_enabled = self._parameters._get_and_expand ("geoip_enabled") if _geoip_enabled : self.capture_header ("X-Country", "base64", _acl, **_overrides) def variables_defaults (self, _acl = None, **_overrides) : self.variables_protocol (_acl, **_overrides) self.variables_forwarded (_acl, **_overrides) self.variables_tracking (_acl, **_overrides) self.variables_browsing (_acl, **_overrides) self.variables_geoip (_acl, **_overrides) def variables_protocol (self, _acl = None, **_overrides) : self.set_variable ("$logging_http_variable_action", statement_format ("%%[%s]://%%[%s]%%[%s]", self._samples.request_method (), self._samples.host (), self._samples.path ()), (_acl, self._acl.query_exists () .negate ()), True, **_overrides) self.set_variable ("$logging_http_variable_action", statement_format ("%%[%s]://%%[%s]%%[%s]?%%[%s]", self._samples.request_method (), self._samples.host (), self._samples.path (), self._samples.query ()), (_acl, self._acl.query_exists ()), True, **_overrides) self.set_variable ("$logging_http_variable_method", self._samples.request_method (), _acl, **_overrides) self.set_variable ("$logging_http_variable_host", self._samples.host (), _acl, **_overrides) self.set_variable ("$logging_http_variable_path", self._samples.path (), _acl, **_overrides) self.set_variable ("$logging_http_variable_query", self._samples.query (), _acl, **_overrides) def variables_forwarded (self, _acl = None, **_overrides) : self.set_variable ("$logging_http_variable_forwarded_host", self._samples.forwarded_host (), _acl, **_overrides) self.set_variable ("$logging_http_variable_forwarded_for", self._samples.forwarded_for (), _acl, **_overrides) self.set_variable ("$logging_http_variable_forwarded_proto", self._samples.forwarded_proto (), _acl, **_overrides) def variables_tracking (self, _acl = None, **_overrides) : self.set_variable ("$logging_http_variable_request", self._samples.request_header ("$logging_http_header_request"), _acl, **_overrides) self.set_variable ("$logging_http_variable_session", self._samples.request_header ("$logging_http_header_session"), _acl, **_overrides) def variables_browsing (self, _acl = None, **_overrides) : self.set_variable ("$logging_http_variable_agent", self._samples.request_header ("User-Agent"), _acl, **_overrides) self.set_variable ("$logging_http_variable_referrer", self._samples.request_header ("Referer"), _acl, **_overrides) def variables_geoip (self, _acl = None, **_overrides) : _geoip_enabled = self._parameters._get_and_expand ("geoip_enabled") if _geoip_enabled : self.set_variable ("$logging_geoip_country_variable", self._samples.request_header ("X-Country"), _acl, **_overrides) def authenticate (self, _credentials, _realm = None, _acl = None, **_overrides) : _acl_authenticated = self._acl.authenticated (_credentials) _rule_condition = self._context._condition_if ((_acl, _acl_authenticated.negate ())) _rule = ("auth", "realm", statement_quote ("\'", statement_coalesce (_realm, _credentials.realm, "$daemon_identifier"))) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def authenticate_for_path_and_query (self, _path, _query, _credentials, _realm = None, _acl = None, **_overrides) : _acl_authenticated = self._acl.authenticated (_credentials) _acl_path = self._acl.path (_path) _acl_query = self._acl.query (_query) self.authenticate (_credentials, _realm, (_acl, _acl_path, _acl_query), **_overrides) self.deny (200, (_acl, _acl_path, _acl_query, _acl_authenticated), **_overrides) def authenticate_trigger (self, _credentials, _realm = None, _acl = None, **_overrides) : _acl_authenticated = self._acl.authenticated (_credentials) _acl_path = self._acl.path ("$http_authenticated_path") _acl_query = self._acl.query ("$http_authenticated_query") _acl_cookie = self._acl.request_cookie_exists ("$http_authenticated_cookie") self.authenticate (_credentials, _realm, (_acl, _acl_path), **_overrides) self.authenticate (_credentials, _realm, (_acl, _acl_query), **_overrides) self.authenticate (_credentials, _realm, (_acl, _acl_cookie), **_overrides) # FIXME: Find a better way! self.delete_header ("$http_authenticated_header", _acl, **_overrides) self.set_header ("$http_authenticated_header", statement_format ("%%[%s]", self._samples.authenticated_group (_credentials)), False, (_acl, _acl_authenticated), **_overrides) self.set_variable ("$http_authenticated_variable", self._samples.request_header ("$http_authenticated_header"), (_acl, _acl_authenticated), **_overrides) self.deny (200, (_acl, _acl_authenticated, _acl_path), **_overrides) self.deny (200, (_acl, _acl_authenticated, _acl_query), **_overrides) def authenticated (self, _credentials, _variable = None, _cleanup = True, _acl = None, **_overrides) : _variable = _variable if _variable is not None else "txn.authenticated_%s" % (_credentials.identifier,) _acl_authenticated = self._acl.authenticated (_credentials) _acl_variable = self._acl.variable_bool (_variable) self.set_enabled (_variable, (_acl, _acl_authenticated), **_overrides) if _cleanup : self.delete_header ("Authorized", (_acl, _acl_authenticated, _acl_variable), **_overrides) return _acl_variable def set_debug_headers (self, _counters = False, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_debug_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_debug_excluded_variable", True) .negate () if not _force else None self.set_header ("$logging_http_header_action", statement_format ("%%[%s]", self._samples.variable ("$logging_http_variable_action")), False, (_acl, _acl_enabled, _acl_included), **_overrides) self.set_header ("$http_debug_timestamp_header", "%[date(),http_date()]", False, (_acl, _acl_enabled, _acl_included), **_overrides) self.append_header ("$http_debug_frontend_header", "%f", (_acl, _acl_enabled, _acl_included), **_overrides) self.append_header ("$http_debug_backend_header", "%b", (_acl, _acl_enabled, _acl_included), **_overrides) if _counters : self.append_header ("$http_debug_counters_header", "conn-cur=%[sc0_conn_cur()], conn-cnt=%[sc0_conn_cnt()], conn-rate=%[sc0_conn_rate()], sess-cnt=%[sc0_sess_cnt()], sess-rate=%[sc0_sess_rate()], req-cnt=%[sc0_http_req_cnt()], req-rate=%[sc0_http_req_rate()], err-cnt=%[sc0_http_err_cnt()], err-rate=%[sc0_http_err_rate()], in-total-kb=%[sc0_kbytes_in()], in-rate-b=%[sc0_bytes_in_rate()], out-total-kb=%[sc0_kbytes_out()], out-rate-b=%[sc0_bytes_out_rate()]", (_acl, _acl_enabled, _acl_included), **_overrides) def delete_debug_headers (self, _acl = None, **_overrides) : self.delete_header ("$logging_http_header_action", _acl, **_overrides) self.delete_header ("$http_debug_timestamp_header", _acl, **_overrides) self.delete_header ("$http_debug_frontend_header", _acl, **_overrides) self.delete_header ("$http_debug_backend_header", _acl, **_overrides) self.delete_header ("$http_debug_counters_header", _acl, **_overrides) def normalize (self, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) self._declare_http_rule_0 (("normalize-uri", "fragment-strip"), _rule_condition, **_overrides) self._declare_http_rule_0 (("normalize-uri", "path-strip-dot"), _rule_condition, **_overrides) self._declare_http_rule_0 (("normalize-uri", "path-strip-dotdot", "full"), _rule_condition, **_overrides) self._declare_http_rule_0 (("normalize-uri", "path-merge-slashes"), _rule_condition, **_overrides) self._declare_http_rule_0 (("normalize-uri", "percent-decode-unreserved", "strict"), _rule_condition, **_overrides) self._declare_http_rule_0 (("normalize-uri", "percent-to-uppercase", "strict"), _rule_condition, **_overrides) self._declare_http_rule_0 (("normalize-uri", "query-sort-by-name"), _rule_condition, **_overrides) class HaHttpResponseRuleBuilder (HaHttpRuleBuilder) : def __init__ (self, _context, _parameters) : HaHttpRuleBuilder.__init__ (self, _context, _parameters) def set_status (self, _code, _acl = None, **_overrides) : _rule_condition = self._context._condition_if (_acl) _rule = ("set-status", _code) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) def deny_status (self, _code, _acl = None, _mark = None, **_overrides) : _acl_status = self._acl.response_status (_code) self.deny (None, (_acl, _acl_status), _mark, **_overrides) def expose_internals_0 (self, _acl_internals, _acl = None, _mark_allowed = None, **_overrides) : _mark_allowed = self._value_or_parameters_get_and_expand (_mark_allowed, "internals_netfilter_mark_allowed") _order_allow = self._parameters._get_and_expand ("internals_rules_order_allow") # FIXME: Make this deferable! if _mark_allowed is not None and _mark_allowed != 0 : self.set_mark (_mark_allowed, (_acl, _acl_internals), **parameters_overrides (_overrides, order = _order_allow)) self.allow ((_acl, _acl_internals), **parameters_overrides (_overrides, order = _order_allow)) def expose_internals_path (self, _path, _acl = None, _mark_allowed = None, **_overrides) : _acl_path = self._acl.path (_path) self.expose_internals_0 (_acl_path, _acl, _mark_allowed, **_overrides) def expose_internals_path_prefix (self, _path, _acl = None, _mark_allowed = None, **_overrides) : _acl_path = self._acl.path_prefix (_path) self.expose_internals_0 (_acl_path, _acl, _mark_allowed, **_overrides) def protect_internals_path_prefix (self, _path, _acl = None, _mark_denied = None, **_overrides) : _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "internals_netfilter_mark_denied") _order_deny = self._parameters._get_and_expand ("internals_rules_order_deny") _acl_path = self._acl.path_prefix (_path) self.deny (None, (_acl, _acl_path), _mark_denied, order = _order_deny, **_overrides) def expose_internals (self, _acl = None, _mark_allowed = None, _mark_denied = None, **_overrides) : self.expose_internals_path_prefix ("$haproxy_internals_path_prefix", _acl, _mark_allowed, **_overrides) self.expose_internals_path_prefix ("$heartbeat_self_path", _acl, _mark_allowed, **_overrides) self.expose_internals_path_prefix ("$heartbeat_proxy_path", _acl, _mark_allowed, **_overrides) self.expose_internals_path_prefix ("$heartbeat_server_path", _acl, _mark_allowed, **_overrides) self.protect_internals_path_prefix ("$internals_path_prefix", _acl, _mark_denied, **_overrides) def track (self, _acl = None, _force = False, _set_cookie = True, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_tracking_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_tracking_excluded_variable", True) .negate () if not _force else None self.set_header ("$http_tracking_request_header", statement_format ("%%[%s]", self._samples.variable ("$http_tracking_request_variable")), False, (_acl, _acl_enabled, _acl_included), **_overrides) self.set_header ("$http_tracking_session_header", statement_format ("%%[%s]", self._samples.variable ("$http_tracking_session_variable")), False, (_acl, _acl_enabled, _acl_included), **_overrides) if _set_cookie : self.set_cookie ("$http_tracking_session_cookie", statement_format ("%%[%s]", self._samples.variable ("$http_tracking_session_variable")), "/", "$http_tracking_session_cookie_max_age", False, True, False, (_acl, _acl_enabled, _acl_included), **_overrides) def harden_http (self, _acl = None, _acl_deny = None, _force = False, _mark_denied = None, **_overrides) : self.harden_http_all (_acl, _acl_deny, _force, _mark_denied, **_overrides) self.harden_http_get (_acl, _acl_deny, _force, _mark_denied, **_overrides) self.harden_http_post (_acl, _acl_deny, _force, _mark_denied, **_overrides) def harden_http_all (self, _acl = None, _acl_deny = None, _force = False, _mark_denied = None, **_overrides) : _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "http_harden_netfilter_mark_denied") _status_acl = self._acl.response_status ("$http_harden_allowed_status_codes") _status_acl = _status_acl.negate () _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.deny (None, (_acl, _acl_deny, _status_acl, _acl_enabled, _acl_included, _acl_handled), _mark_denied, **_overrides) def harden_http_get (self, _acl = None, _acl_deny = None, _force = False, _mark_denied = None, **_overrides) : _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "http_harden_netfilter_mark_denied") _method_acl = self._acl.variable_equals ("$logging_http_variable_method", ("GET", "HEAD")) _status_acl = self._acl.response_status ("$http_harden_allowed_get_status_codes") _status_acl = _status_acl.negate () _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.deny (None, (_acl, _acl_deny, _method_acl, _status_acl, _acl_enabled, _acl_included, _acl_handled), _mark_denied, **_overrides) def harden_http_post (self, _acl = None, _acl_deny = None, _force = False, _mark_denied = None, **_overrides) : _mark_denied = self._value_or_parameters_get_and_expand (_mark_denied, "http_harden_netfilter_mark_denied") _method_acl = self._acl.variable_equals ("$logging_http_variable_method", ("POST", "PUT")) _status_acl = self._acl.response_status ("$http_harden_allowed_post_status_codes") _status_acl = _status_acl.negate () _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.deny (None, (_acl, _acl_deny, _method_acl, _status_acl, _acl_enabled, _acl_included, _acl_handled), _mark_denied, **_overrides) def harden_headers (self, _acl = None, _force = False, **_overrides) : _acl_tls = self._acl.via_tls () _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.set_header ("Content-Security-Policy", "$http_harden_csp_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled, _acl_tls), **_overrides) self.set_header ("Referrer-Policy", "$http_harden_referrer_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.set_header ("X-Frame-Options", "$http_harden_frames_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.set_header ("X-Content-Type-Options", "$http_harden_cto_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.set_header ("X-XSS-Protection", "$http_harden_xss_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) def harden_headers_extended (self, _acl = None, _force = False, **_overrides) : _acl_tls = self._acl.via_tls () _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.set_header ("Feature-Policy", "$http_harden_fp_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled, _acl_tls), **_overrides) self.set_header ("Cross-Origin-Opener-Policy", "$http_harden_coop_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.set_header ("Cross-Origin-Resource-Policy", "$http_harden_corp_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.set_header ("Cross-Origin-Embedder-Policy", "$http_harden_coep_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) def harden_via (self, _acl = None, _force = False, **_overrides) : _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None self.delete_header ("Via", (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.delete_header ("Server", (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) self.delete_header ("X-Powered-By", (_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) def harden_ranges (self, _acl = None, _force = False, **_overrides) : _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None _acl_forbidden = self._acl.variable_bool ("$http_ranges_allowed_variable", True) .negate () if not _force else None self.set_header ("Accept-Ranges", "none", False, (_acl, _acl_enabled, _acl_included, _acl_handled, _acl_forbidden), **_overrides) def harden_redirects (self, _acl = None, _force = False, **_overrides) : # FIXME: Perhaps make configurable the source redirect status code! _status_acl = self._acl.response_status ((301, 302, 303, 307, 308)) _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None # FIXME: Perhaps make configurable the target redirect status code! self.set_status (307, (_acl, _status_acl, _acl_enabled, _acl_included, _acl_handled), **_overrides) def harden_tls (self, _acl = None, _force = False, **_overrides) : _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None _acl_tls = self._acl.via_tls () _hsts_enabled = self._parameters._get_and_expand ("http_harden_hsts_enabled") # FIXME: Make this deferable! if _hsts_enabled : self.set_header ("Strict-Transport-Security", "$http_harden_hsts_descriptor", False, (_acl, _acl_enabled, _acl_included, _acl_handled, _acl_tls), **_overrides) def harden_all (self, _acl = None, _acl_deny = None, _force = False, _mark_allowed = None, _mark_denied = None, **_overrides) : _mark_allowed = self._value_or_parameters_get_and_expand (_mark_denied, "http_harden_netfilter_mark_allowed") self.harden_http (_acl, _acl_deny, _force, _mark_denied, **_overrides) self.harden_headers (_acl, _force, **_overrides) if self._context._resolve_token ("$http_harden_headers_extended") : self.harden_headers_extended (_acl, _force, **_overrides) self.harden_via (_acl, _force, **_overrides) self.harden_ranges (_acl, _force, **_overrides) # FIXME: Make this configurable! # self.harden_redirects (_acl, _force, **_overrides) self.harden_tls (_acl, _force, **_overrides) # FIXME: Make this deferable! _acl_handled = self._acl.response_header_exists ("$http_hardened_header", False) if not _force else None _acl_enabled = self._acl.variable_bool ("$http_harden_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_harden_excluded_variable", True) .negate () if not _force else None # FIXME: Make this configurable! if False : self.set_header ("$http_hardened_header", "true", True, (_acl_enabled, _acl_included, _acl_handled, _acl), **_overrides) # FIXME: Make this deferable! if _mark_allowed is not None and _mark_allowed != 0 : self.set_mark (_mark_allowed, (_acl_enabled, _acl_included, _acl_handled, _acl), **_overrides) def drop_caching (self, _acl = None, _force = False, _keep_cache_control_acl = None, _keep_etag_acl = None, _keep_vary_acl = None, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_drop_caching_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_drop_caching_excluded_variable", True) .negate () if not _force else None if _keep_cache_control_acl is None or _keep_cache_control_acl is not True : _keep_cache_control_acl_0 = _keep_cache_control_acl.negate () if _keep_cache_control_acl is not None else None self.delete_header ("Cache-Control", (_acl, _acl_enabled, _acl_included, _keep_cache_control_acl_0), **_overrides) self.delete_header ("Last-Modified", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Expires", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Date", (_acl, _acl_enabled, _acl_included), **_overrides) if _keep_etag_acl is None or _keep_etag_acl is not True : _keep_etag_acl_0 = _keep_etag_acl.negate () if _keep_etag_acl is not None else None self.delete_header ("ETag", (_acl, _acl_enabled, _acl_included, _keep_etag_acl_0), **_overrides) if _keep_vary_acl is None or _keep_vary_acl is not True : _keep_vary_acl_0 = _keep_vary_acl.negate () if _keep_vary_acl is not None else None self.delete_header ("Vary", (_acl, _acl_enabled, _acl_included, _keep_vary_acl_0), **_overrides) self.delete_header ("Age", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Pragma", (_acl, _acl_enabled, _acl_included), **_overrides) def force_caching (self, _max_age = 3600, _public = True, _no_cache = False, _must_revalidate = False, _immutable = None, _acl = None, _force = False, _store_max_age = None, _keep_etag_acl = None, _vary = None, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_caching_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_caching_excluded_variable", True) .negate () if not _force else None self.force_caching_control (_max_age, _public, _no_cache, _must_revalidate, _immutable, _acl, _force, _store_max_age, **_overrides) if _keep_etag_acl is None or _keep_etag_acl is not True : self.set_header ("ETag", "\"%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]%[rand(4294967295),bytes(4,4),hex,lower]\"", False, (_acl, _acl_enabled, _acl_included), **_overrides) if not _public : self.set_header ("Vary", "Authorization", False, (_acl, _acl_enabled, _acl_included), **_overrides) self.set_header ("Vary", "Cookie", False, (_acl, _acl_enabled, _acl_included), **_overrides) else : self.delete_header ("Set-Cookie", (_acl, _acl_enabled, _acl_included), **_overrides) if _vary is not None : for _vary in _vary : self.set_header ("Vary", _vary, False, (_acl, _acl_enabled, _acl_included), **_overrides) def force_caching_control (self, _max_age = 3600, _public = True, _no_cache = False, _must_revalidate = False, _immutable = None, _acl = None, _force = False, _store_max_age = None, _header = None, **_overrides) : _private = not _public if _immutable is None : _immutable = not _no_cache and not _must_revalidate if _max_age is not None : _max_age = statement_enforce_int (_max_age) if _store_max_age is not None : _store_max_age = statement_enforce_int (_store_max_age) _public = statement_enforce_bool (_public) _private = statement_enforce_bool (_private) _no_cache = statement_enforce_bool (_no_cache) _must_revalidate = statement_enforce_bool (_must_revalidate) _immutable = statement_enforce_bool (_immutable) _acl_enabled = self._acl.variable_bool ("$http_force_caching_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_caching_excluded_variable", True) .negate () if not _force else None self.set_header ("Cache-Control" if _header is None else _header, statement_join (", ", ( statement_choose_if (_public, "public"), statement_choose_if (_private, "private"), statement_choose_if (_no_cache, "no-cache"), statement_choose_if (_must_revalidate, "must-revalidate"), statement_choose_if (_immutable, "immutable"), statement_choose_if (_max_age, statement_format ("max-age=%d", _max_age)), statement_choose_if (_store_max_age, statement_format ("s-maxage=%d", _store_max_age)), # statement_choose_if (_store_max_age, statement_choose_if (_must_revalidate, statement_format ("proxy-revalidate"))), )), False, (_acl, _acl_enabled, _acl_included), **_overrides) if _header is None : _expire_age = _max_age if _store_max_age is not None : _expire_age = statement_choose_max (_expire_age, _store_max_age) self.force_caching_maxage (_expire_age, (_acl, _acl_enabled, _acl_included), **_overrides) def force_caching_no (self, _acl = None, _force = False, _header = None, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_caching_enabled_variable", True) .negate () if not _force else None _acl_included = self._acl.variable_bool ("$http_force_caching_excluded_variable", True) .negate () if not _force else None #! self.set_header ("Cache-Control" if _header is None else _header, "no-cache, no-store, must-revalidate", False, (_acl, _acl_enabled, _acl_included), **_overrides) self.set_header ("Cache-Control" if _header is None else _header, "no-store, max-age=0", False, (_acl, _acl_enabled, _acl_included), **_overrides) #! self.force_caching_maxage (0, (_acl, _acl_enabled, _acl_included), **_overrides) def force_caching_maxage (self, _max_age, _acl, **_overrides) : if _max_age is not None : self.set_header ("Last-Modified", statement_format ("%%[date(-%d),http_date()]", _max_age), False, _acl, **_overrides) self.set_header ("Expires", statement_format ("%%[date(%d),http_date()]", _max_age), False, _acl, **_overrides) self.set_header ("Date", statement_format ("%%[date(),http_date()]"), False, _acl, **_overrides) self.set_header ("Age", 0, False, _acl, **_overrides) else : self.delete_header ("Last-Modified", _acl, **_overrides) self.delete_header ("Expires", _acl, **_overrides) self.delete_header ("Date", _acl, **_overrides) self.delete_header ("Age", _acl, **_overrides) self.delete_header ("Pragma", _acl, **_overrides) def drop_cookies (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_drop_cookies_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_drop_cookies_excluded_variable", True) .negate () if not _force else None self.delete_header ("Set-Cookie", (_acl, _acl_enabled, _acl_included), **_overrides) def force_cors (self, _origin = "origin", _methods = ["GET"], _headers = None, _max_age = 3600, _credentials = False, _acl = None, _force = False, **_overrides) : self.force_cors_unset (_acl, _force, **_overrides) self.force_cors_set (_origin, _methods, _headers, _max_age, _credentials, _acl, _force, **_overrides) self.force_cors_vary (_acl, _force, **_overrides) def force_cors_unset (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None self.delete_header ("Access-Control-Allow-Origin", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Allow-Methods", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Allow-Headers", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Expose-Headers", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Allow-Credentials", (_acl, _acl_enabled, _acl_included), **_overrides) self.delete_header ("Access-Control-Max-Age", (_acl, _acl_enabled, _acl_included), **_overrides) def force_cors_set (self, _origin = "origin", _methods = ["GET"], _headers = None, _max_age = 3600, _credentials = False, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None _acl_allowed = self._acl.variable_bool ("$http_force_cors_allowed_variable", True) if not _force else None _acl_origin = self._acl.variable_bool ("$http_force_cors_origin_present_variable", True) if not _force else None if _origin == "origin" : _origin = self._samples.variable ("$http_force_cors_origin_variable") .statement_format () if _origin is not None : self.set_header ("Access-Control-Allow-Origin", _origin, False, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed), **_overrides) if _methods is not None : self.set_header ("Access-Control-Allow-Methods", ", ".join (_methods), False, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed), **_overrides) if _headers is not None : self.set_header ("Access-Control-Allow-Headers", ", ".join (_headers), False, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed), **_overrides) if _credentials is True : self.set_header ("Access-Control-Allow-Credentials", "true", False, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed), **_overrides) elif _credentials is False or _credentials is None : pass else : raise_error ("b00395cd", _credentials) if _max_age is not None : self.set_header ("Access-Control-Max-Age", statement_enforce_int (_max_age), False, (_acl, _acl_enabled, _acl_included, _acl_origin, _acl_allowed), **_overrides) def force_cors_vary (self, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_force_cors_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_force_cors_excluded_variable", True) .negate () if not _force else None _acl_origin = self._acl.variable_bool ("$http_force_cors_origin_present_variable", True) if not _force else None self.append_header ("Vary", "Origin", (_acl, _acl_enabled, _acl_included, _acl_origin), **_overrides) self.append_header ("Vary", "Access-Control-Request-Method", (_acl, _acl_enabled, _acl_included, _acl_origin), **_overrides) self.append_header ("Vary", "Access-Control-Request-Headers", (_acl, _acl_enabled, _acl_included, _acl_origin), **_overrides) def capture (self, _sample, _acl = None, **_overrides) : _index = self._context._declare_response_capture (**_overrides) _rule_condition = self._context._condition_if (_acl) _rule = ("capture", _sample, "id", _index) self._declare_http_rule_0 (_rule, _rule_condition, **_overrides) return _index def capture_header (self, _header, _transforms = None, _acl = None, _index = None, **_overrides) : _sample = self._samples.response_header (_header, _transforms, _index) return self.capture (_sample, _acl, **_overrides) def capture_defaults (self, _acl = None, **_overrides) : self.capture_protocol (_acl, **_overrides) self.capture_caching (_acl, **_overrides) self.capture_cookies (_acl, **_overrides) def capture_protocol (self, _acl = None, **_overrides) : self.capture_header ("Location", "base64", _acl, **_overrides) self.capture_header ("Content-Type", "base64", _acl, **_overrides) self.capture_header ("Content-Encoding", "base64", _acl, **_overrides) self.capture_header ("Content-Length", "base64", _acl, **_overrides) self.capture_header ("Content-Disposition", "base64", _acl, **_overrides) def capture_caching (self, _acl = None, **_overrides) : self.capture_header ("Cache-Control", "base64", _acl, **_overrides) self.capture_header ("Last-Modified", "base64", _acl, **_overrides) self.capture_header ("Expires", "base64", _acl, **_overrides) self.capture_header ("Date", "base64", _acl, **_overrides) self.capture_header ("ETag", "base64", _acl, **_overrides) self.capture_header ("Vary", "base64", _acl, **_overrides) self.capture_header ("Age", "base64", _acl, **_overrides) self.capture_header ("Pragma", "base64", _acl, **_overrides) def capture_cookies (self, _acl = None, **_overrides) : self.capture_header ("Set-Cookie", "base64", _acl, 1, **_overrides) self.capture_header ("Set-Cookie", "base64", _acl, 2, **_overrides) self.capture_header ("Set-Cookie", "base64", _acl, 3, **_overrides) self.capture_header ("Set-Cookie", "base64", _acl, 4, **_overrides) def variables_defaults (self, _acl = None, **_overrides) : self.variables_protocol (_acl, **_overrides) def variables_protocol (self, _acl = None, **_overrides) : self.set_variable ("$logging_http_variable_location", self._samples.response_header ("Location"), _acl, **_overrides) self.set_variable ("$logging_http_variable_content_type", self._samples.response_header ("Content-Type"), _acl, **_overrides) self.set_variable ("$logging_http_variable_content_encoding", self._samples.response_header ("Content-Encoding"), _acl, **_overrides) self.set_variable ("$logging_http_variable_content_length", self._samples.response_header ("Content-Length"), _acl, **_overrides) self.set_variable ("$logging_http_variable_cache_control", self._samples.response_header ("Cache-Control"), _acl, **_overrides) self.set_variable ("$logging_http_variable_cache_etag", self._samples.response_header ("ETag"), _acl, **_overrides) def authenticate_trigger (self, _credentials, _acl = None, **_overrides) : _acl_authenticated = self._acl.variable_exists ("$http_authenticated_variable") self.delete_header ("$http_authenticated_header", _acl, **_overrides) self.set_cookie ("$http_authenticated_cookie", statement_format ("%%[%s]", self._samples.variable ("$http_authenticated_variable")), "/", "$http_authenticated_cookie_max_age", True, True, True, (_acl, _acl_authenticated), **_overrides) # FIXME: Make this configurable! if False : self.set_header ("$http_authenticated_header", statement_format ("%%[%s]", self._samples.variable ("$http_authenticated_variable")), False, (_acl, _acl_authenticated), **_overrides) def set_debug_headers (self, _counters = False, _acl = None, _force = False, **_overrides) : _acl_enabled = self._acl.variable_bool ("$http_debug_enabled_variable", True) if not _force else None _acl_included = self._acl.variable_bool ("$http_debug_excluded_variable", True) .negate () if not _force else None self.set_header ("$logging_http_header_action", statement_format ("%%[%s]", self._samples.variable ("$logging_http_variable_action")), False, (_acl, _acl_enabled, _acl_included), **_overrides) self.set_header ("$http_debug_timestamp_header", "%[date(),http_date()]", False, (_acl, _acl_enabled, _acl_included), **_overrides) self.append_header ("$http_debug_frontend_header", "%f", (_acl, _acl_enabled, _acl_included), **_overrides) self.append_header ("$http_debug_backend_header", "%b", (_acl, _acl_enabled, _acl_included), **_overrides) if _counters : self.append_header ("$http_debug_counters_header", "conn-cur=%[sc0_conn_cur()], conn-cnt=%[sc0_conn_cnt()], conn-rate=%[sc0_conn_rate()], sess-cnt=%[sc0_sess_cnt()], sess-rate=%[sc0_sess_rate()], req-cnt=%[sc0_http_req_cnt()], req-rate=%[sc0_http_req_rate()], err-cnt=%[sc0_http_err_cnt()], err-rate=%[sc0_http_err_rate()], in-total-kb=%[sc0_kbytes_in()], in-rate-b=%[sc0_bytes_in_rate()], out-total-kb=%[sc0_kbytes_out()], out-rate-b=%[sc0_bytes_out_rate()]", (_acl, _acl_enabled, _acl_included), **_overrides) def delete_debug_headers (self, _acl = None, **_overrides) : self.delete_header ("$logging_http_header_action", _acl, **_overrides) self.delete_header ("$http_debug_timestamp_header", _acl, **_overrides) self.delete_header ("$http_debug_frontend_header", _acl, **_overrides) self.delete_header ("$http_debug_backend_header", _acl, **_overrides) self.delete_header ("$http_debug_counters_header", _acl, **_overrides) def set_content_security_policy (self, _directives, _report_only = False, _acl = None, **_overrides) : _policy = [] for _directive in _directives : if isinstance (_directive, tuple) or isinstance (_directive, list) : _directive = statement_join (" ", _directive) _policy.append (_directive) _policy = statement_join ("; ", tuple (_policy)) if _report_only : self.set_header ("Content-Security-Policy-Report-Only", _policy, _acl = _acl, **_overrides) else : self.set_header ("Content-Security-Policy", _policy, _acl = _acl, **_overrides) def set_referrer_policy (self, _policy, _acl = None, **_overrides) : self.set_header ("Referrer-Policy", _policy, _acl = _acl, **_overrides) <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _fe.requests.set_header_from_sample ("agent_hash", _fe.samples.agent_hash ()) _fe.requests.set_header_from_sample ("agent_regsub", _fe.samples.agent_regsub ("^.* id-([0-9a-f]+) .*$", "\\1")) _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> import sys import time from errors import * fallback = object () no_fallback = object () class Parameters (object) : def __init__ (self, _super, _overrides, _defaults) : object.__setattr__ (self, "_super", _super) object.__setattr__ (self, "_defaults", _defaults) object.__setattr__ (self, "_parameters", dict ()) object.__setattr__ (self, "_get_fallback_enabled", fallback) object.__setattr__ (self, "_get_fallback_disabled", no_fallback) self._set (parameters_timestamp = time.strftime ("%Y-%m-%d-%H-%M-%S", time.gmtime ())) self._set (**_overrides) def _fork (self, **_overrides) : return Parameters (self, _overrides, None) def _set (self, **_overrides) : for _parameter, _value in _overrides.iteritems () : self.__setattr__ (_parameter, _value) def _get_and_expand (self, _parameter, _default = fallback) : _value = self._get (_parameter, _default) _value = self._expand (_value) return _value def _get (self, _parameter, _default = fallback, _self = fallback) : try : return self._get_0 (_parameter, _default, _self) except Exception as _error : print >> sys.stderr, "[ee] failed resolving parameter `%r`" % (_parameter,) raise def _get_0 (self, _parameter, _default, _self) : if _parameter.startswith ("_") : raise_error ("8b5c846b", _parameter) if _self is fallback : _self = self if _parameter in self._parameters : _value = self._parameters[_parameter] elif self._super is not None : _value = self._super._get_0 (_parameter, no_fallback, _self) if _value is no_fallback : _value = fallback else : _value = fallback if _value is fallback : if _default is not fallback : _value = _default elif self._defaults is not None and _parameter in self._defaults : _value = self._defaults[_parameter] elif self._super is not None : _value = self._super._get_0 (_parameter, fallback, _self) if _value is fallback : raise_error ("c652aa6d", _parameter) elif _value is no_fallback : return _value else : return _self._expand_0 (_value) def _expand (self, _value) : try : return self._expand_0 (_value) except Exception as _error : print >> sys.stderr, "[ee] failed expanding parameter `%r`" % (_value,) raise def _expand_0 (self, _value) : if isinstance (_value, basestring) : return _value elif isinstance (_value, int) : return _value elif isinstance (_value, tuple) : _value = [self._expand_0 (_value) for _value in _value] _value = tuple (_value) return _value elif _value is None : return _value elif callable (_value) : _value = _value (self) return self._expand_0 (_value) else : raise_error ("873a2ceb", _value) def __getattr__ (self, _parameter) : if _parameter.startswith ("_") : raise_error ("8b5c846b", _parameter) return self._get (_parameter) def __setattr__ (self, _parameter, _value) : if _parameter.startswith ("_") : raise_error ("8b5c846b", _parameter) if _parameter in self._parameters : raise_error ("7db0955d", _parameter) else : self._parameters[_parameter] = _value <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-d244e23f3e50cc6182e450d7e6551deb method(),upper -m str -i eq -- 'GET' acl acl-8efd2993b14d7316ac2f903fed7bb3ac res.fhdr_cnt('X-HA-Hardened'),bool,not -m bool acl acl-dbaf316a86669df8911f5b91102e8aa0 ssl_fc() -m bool acl acl-10ac02033e9cdf71bdaf9f7ecc6e64b1 status() -m int eq -- 200 acl acl-16439216621255f1e0a66f4c49e1aa81 status() -m int eq -- 200 acl acl-f34ae54cb337610afa4910c1bac7bbac status() -m int eq -- 200 acl acl-f34ae54cb337610afa4910c1bac7bbac status() -m int eq -- 201 acl acl-f34ae54cb337610afa4910c1bac7bbac status() -m int eq -- 202 acl acl-10ac02033e9cdf71bdaf9f7ecc6e64b1 status() -m int eq -- 204 acl acl-f34ae54cb337610afa4910c1bac7bbac status() -m int eq -- 204 acl acl-10ac02033e9cdf71bdaf9f7ecc6e64b1 status() -m int eq -- 304 acl acl-16439216621255f1e0a66f4c49e1aa81 status() -m int eq -- 304 acl acl-766136fb89c18a529ae828035871887d var('txn.http_harden_enabled'),bool -m bool acl acl-987ae99ba6da32008839067c993ad497 var('txn.http_harden_excluded'),bool -m bool acl acl-f8de46cff6c1207cdcc8beacca736001 var('txn.http_ranges_allowed'),bool -m bool acl acl-a5ce4c4d95c7c2b129ce65034af2ce3b var('txn.logging_http_method') -m str eq -- 'GET' acl acl-a5ce4c4d95c7c2b129ce65034af2ce3b var('txn.logging_http_method') -m str eq -- 'HEAD' acl acl-129daa7ff8911a10a9f9372f07d30810 var('txn.logging_http_method') -m str eq -- 'POST' acl acl-129daa7ff8911a10a9f9372f07d30810 var('txn.logging_http_method') -m str eq -- 'PUT' #---- HTTP Request Rules http-request set-var(txn.http_harden_enabled) bool(true) http-request deny if !acl-d244e23f3e50cc6182e450d7e6551deb acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "User-Agent" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "Referer" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "Accept-Encoding" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "Accept-Language" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "Accept-Charset" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "Authorization" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 http-request del-header "Range" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 !acl-f8de46cff6c1207cdcc8beacca736001 http-request del-header "If-Range" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 !acl-f8de46cff6c1207cdcc8beacca736001 #---- HTTP Response Rules http-response deny if !acl-10ac02033e9cdf71bdaf9f7ecc6e64b1 acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response deny if acl-a5ce4c4d95c7c2b129ce65034af2ce3b !acl-16439216621255f1e0a66f4c49e1aa81 acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response deny if acl-129daa7ff8911a10a9f9372f07d30810 !acl-f34ae54cb337610afa4910c1bac7bbac acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "Content-Security-Policy" "upgrade-insecure-requests" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac acl-dbaf316a86669df8911f5b91102e8aa0 http-response set-header "Referrer-Policy" "strict-origin-when-cross-origin" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "X-Frame-Options" "SAMEORIGIN" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "X-Content-Type-Options" "nosniff" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "X-XSS-Protection" "1; mode=block" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "Feature-Policy" "accelerometer 'none'; ambient-light-sensor 'none'; autoplay 'none'; camera 'none'; display-capture 'none'; document-domain 'none'; encrypted-media 'none'; fullscreen 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; midi 'none'; payment 'none'; picture-in-picture 'none'; publickey-credentials-get 'none'; sync-xhr 'none'; usb 'none'; xr-spatial-tracking 'none'" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac acl-dbaf316a86669df8911f5b91102e8aa0 http-response set-header "Cross-Origin-Opener-Policy" "same-origin" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "Cross-Origin-Resource-Policy" "same-origin" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "Cross-Origin-Embedder-Policy" "unsafe-none" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response del-header "Via" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response del-header "Server" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response del-header "X-Powered-By" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac http-response set-header "Accept-Ranges" "none" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac !acl-f8de46cff6c1207cdcc8beacca736001 http-response set-header "Strict-Transport-Security" "max-age=504576000" if acl-766136fb89c18a529ae828035871887d !acl-987ae99ba6da32008839067c993ad497 acl-8efd2993b14d7316ac2f903fed7bb3ac acl-dbaf316a86669df8911f5b91102e8aa0 #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> import csv import json import sys import ipaddr def load (_blocks_path, _countries_path) : _blocks = _load_csv (_blocks_path) _countries = _load_csv (_countries_path) _countries_map = {} for _country in _countries : _key = _country["geoname_id"] if _key in _countries_map : raise Exception (("e139c9ff", _key)) _value = (_country["continent_code"], _country["country_iso_code"], _country["country_name"]) _countries_map[_key] = _value _blocks_map = {} for _block in _blocks : _key = _block["network"] if _key in _blocks_map : raise Exception (("d9afa5d6", _key)) _country = _block["geoname_id"] if _country == "" : _country = None if _country is not None : if _country not in _countries_map : raise Exception (("83d60991", _country)) _continent, _country_code, _country_name = _countries_map[_country] if _continent == "" : _continent = None if _country_code == "" : _country_code = None if _country_name == "" : _country_name = None else : _continent = None _country_code = None _country_name = None _blocks_map[_key] = { "network" : _key, "continent" : _continent, "country_code" : _country_code, "country_name" : _country_name, } return _blocks_map def _load_csv (_path) : _header = None _records = [] with open (_path, "rb") as _stream : _stream = csv.reader (_stream, dialect = "excel", strict = True) for _row in _stream : if _header is None : _header = _row else : if len (_header) != len (_row) : raise Exception ("8ff3b9bb") _record = {_key : _value for _key, _value in zip (_header, _row)} _records.append (_record) return _records def export_json (_blocks_path, _countries_path) : _output_stream = sys.stdout _blocks = load (_blocks_path, _countries_path) json.dump (_blocks, _output_stream, ensure_ascii = True, indent = 4, separators = (",", " : "), sort_keys = True) def export_map (_blocks_path, _countries_path) : _output_stream = sys.stdout _blocks = load (_blocks_path, _countries_path) _lines = [] for _block in _blocks.values () : _country_code = _block["country_code"] if _country_code is None : _country_code = "00" _line = "%-20s %2s" % (_block["network"], _country_code) _lines.append (_line) _lines.sort () for _line in _lines : _output_stream.write (_line) _output_stream.write ("\n") if __name__ == "__main__" : if sys.argv[1] == "json" : export_json (*sys.argv[2:]) elif sys.argv[1] == "map" : export_map (*sys.argv[2:]) else : raise Exception (("ebc9e156", sys.argv[1])) <file_sep> import sys from errors import * class Scroll (object) : def __init__ (self, _indent = 0) : self._contents = list () self._indent = _indent def is_empty (self) : return len (self._contents) == 0 def include_normal_line (self, _order, _indent, _contents) : return self.include_normal_line_with_comment (_order, _indent, _contents, None) def include_normal_line_with_comment (self, _order, _indent, _contents, _comment) : if isinstance (_contents, list) : if len (_contents) == 0 : return elif len (_contents) == 1 : _contents = _contents[0] self._contents.append ((_order, _indent, _contents, _comment)) def include_scroll_lines (self, _order, _indent, _scroll, _recurse) : for _line_order, _line_indent, _line_contents, _line_comment in _scroll._contents : if _line_order is None : _line_order = _order if _line_indent is not None : _line_indent += _indent else : _line_indent = _indent _line_indent += _scroll._indent if isinstance (_line_contents, basestring) or isinstance (_line_contents, tuple) : self._contents.append ((_line_order, _line_indent, _line_contents, _line_comment)) elif isinstance (_line_contents, ScrollPart) : self._contents.append ((_line_order, _line_indent, _line_contents, _line_comment)) elif isinstance (_line_contents, Scroll) : if _line_comment is not None : raise_error ("f497f272") if _recurse : self.include_scroll_lines (_line_order, _line_indent, _line_contents, True) else : self._contents.append ((_line_order, _line_indent, _line_contents, None)) else : raise_error ("a602a2e8", _line_contents) def include_comment_line (self, _order, _indent, _contents) : self._contents.append ((_order, _indent, ScrollCommentLine (_contents), None)) def include_empty_line (self, _order, _indent, _count = 1) : self._contents.append ((_order, _indent, ScrollEmptyLine (_count), None)) def output_stdout (self) : self.output (sys.stdout) def output (self, _stream, _indent = 0) : if not isinstance (_stream, ScrollOutputer) : _stream = ScrollOutputer (_stream) _stream_should_be_closed = True else : _stream_should_be_closed = False _contents = sorted (self._contents, key = lambda _contents : _contents[0] if _contents[0] is not None else 1 << 16) for _order, _indent_0, _contents, _comment in _contents : self._output_contents (_order, _indent_0 + _indent + self._indent, _contents, _comment, _stream) if _stream_should_be_closed : _stream.output_done () def _output_contents (self, _order, _indent, _contents, _comment, _stream) : if isinstance (_contents, basestring) : _stream.output_marker (_indent, 0, "## ~~ %s" % _order) if _comment is not None : _stream.output_line_with_comment (_indent, _contents, _comment) else : _stream.output_line (_indent, _contents) elif isinstance (_contents, tuple) : _contents = self._format_tokens (_contents) self._output_contents (_order, _indent, _contents, _comment, _stream) elif isinstance (_contents, ScrollPart) : if _comment is not None : raise_error ("0ab3e07c") _contents.output (_stream, _indent) elif isinstance (_contents, Scroll) : if _comment is not None : raise_error ("0ab3e07c") _stream.output_marker (_indent, +1, "## >> Scroll %s" % _order) _contents.output (_stream, _indent) _stream.output_marker (_indent, -1, "## <<") elif isinstance (_contents, list) : _stream.output_marker (_indent, +1, "## >> List %s" % _order) for _contents in _contents : self._output_contents (_order, _indent, _contents, _comment, _stream) _stream.output_marker (_indent, -1, "## <<") else : raise_error ("1fe1b0e1", _contents) def _format_tokens (self, _tokens) : if isinstance (_tokens, basestring) : return _tokens elif isinstance (_tokens, int) : _tokens = str (_tokens) return _tokens elif isinstance (_tokens, tuple) : _tokens = [self._format_tokens (_tokens) for _tokens in _tokens] _tokens = " ".join (_tokens) return _tokens else : raise_error ("4ca0c09d", _tokens) class ScrollPart (object) : def __init__ (self) : pass def output (self, _stream, _indent) : raise_error ("0d8d2498") class ScrollCommentLine (ScrollPart) : def __init__ (self, _contents) : ScrollPart.__init__ (self) self._contents = _contents def output (self, _stream, _indent) : _stream.output_comment (_indent, self._contents) class ScrollEmptyLine (ScrollPart) : def __init__ (self, _count = 1) : ScrollPart.__init__ (self) self._count = _count def output (self, _stream, _indent) : _stream.output_empty (self._count) class ScrollOutputer (object) : def __init__ (self, _stream) : self._stream = _stream self._just_opened = True self._pending_empty = 1 self._opened = True self._adjust_indent = 0 self._last_line_comment = None def output_empty (self, _count = 1) : if not self._opened : raise_error ("f75bc7b0") self._last_line_comment = None self._pending_empty = max (self._pending_empty, _count) def output_comment (self, _indent, _comment) : if not isinstance (_comment, basestring) : raise_error ("1cc717b6", _comment) if not _comment.startswith ("#") : _comment = "# " + _comment self._last_line_comment = None self.output_empty () self.output_line (_indent, _comment) def output_line_with_comment (self, _indent, _line, _comment) : if _comment != self._last_line_comment : if _comment is not None : self.output_comment (_indent, _comment) self._last_line_comment = _comment self.output_line (_indent, _line) def output_line (self, _indent, _line) : if not isinstance (_line, basestring) : raise_error ("0512b71a", _line) if not self._opened : raise_error ("fbce7fc3") if self._just_opened : self._stream.write ("\n") self._pending_empty = 0 self._just_opened = False elif self._pending_empty > 0 : self._stream.write ("\n" * self._pending_empty) self._pending_empty = 0 self._stream.write (" " * (self._adjust_indent + _indent)) self._stream.write (_line) self._stream.write ("\n") def output_marker (self, _indent, _adjust_indent, _line) : if False : if _adjust_indent < 0 : self._adjust_indent += _adjust_indent self.output_line (_indent, _line) if _adjust_indent > 0 : self._adjust_indent += _adjust_indent def output_done (self) : if not self._just_opened : self._stream.write ("\n") self._opened = False <file_sep> from errors import * from tools import * from builders_core import * class HaHttpSampleBuilder (HaBuilder) : def __init__ (self, _context, _parameters) : HaBuilder.__init__ (self, _context, _parameters) def client_ip (self, _method = None, _transforms = None) : if _method is None : _method = self._parameters._get_and_expand ("samples_client_ip_method") if _method == "src" : return self._context.sample_0 ("src", None, _transforms) elif _method == "X-Forwarded-For" : return self._context.sample_0 ("req.hdr", ("$logging_http_header_forwarded_for", 1), _transforms) else : raise_error ("fd58dd1e", _method) def frontend_port (self, _transforms = None) : return self._context.sample_0 ("dst_port", None, _transforms) def forwarded_host (self, _transforms = None, _from_logging = False) : if _from_logging : return self._context.sample_0 ("var", ("$logging_http_variable_forwarded_host",), _transforms) else : return self._context.sample_0 ("req.hdr", ("$logging_http_header_forwarded_host", 1), _transforms) def forwarded_for (self, _transforms = None, _from_logging = False) : if _from_logging : return self._context.sample_0 ("var", ("$logging_http_variable_forwarded_for",), _transforms) else : return self._context.sample_0 ("req.hdr", ("$logging_http_header_forwarded_for", 1), _transforms) def forwarded_proto (self, _transforms = None, _from_logging = False) : if _from_logging : return self._context.sample_0 ("var", ("$logging_http_variable_forwarded_proto",), _transforms) else : return self._context.sample_0 ("req.hdr", ("$logging_http_header_forwarded_proto", 1), _transforms) def forwarded_port (self, _transforms = None, _from_logging = False) : if _from_logging : return self._context.sample_0 ("var", ("$logging_http_variable_forwarded_port",), _transforms) else : return self._context.sample_0 ("req.hdr", ("$logging_http_header_forwarded_port", 1), _transforms) def host (self, _transforms = None) : if _transforms is None : _transforms = ("host_only", ("ltrim", "."), ("rtrim", ".")) return self._context.sample_0 ("req.fhdr", ("Host", -1), _transforms) def path (self, _transforms = None) : return self._context.sample_0 ("path", None, _transforms) def query (self, _transforms = None) : return self._context.sample_0 ("query", None, _transforms) def query_exists (self, _expected = True) : return self._context.sample_0 ("query", None, (("length", "bool") if _expected else ("length", "bool", "not"))) def query_parameter (self, _parameter, _transforms = None) : return self._context.sample_0 ("url_param", (_parameter,), _transforms) def request_method (self, _transforms = None) : if _transforms is None : _transforms = ("upper",) return self._context.sample_0 ("method", None, _transforms) def response_status (self, _transforms = None) : return self._context.sample_0 ("status", None, _transforms) def request_header (self, _header, _transforms = None, _index = None) : if _index is None : _index = -1 return self._context.sample_0 ("req.fhdr", (_header, _index), _transforms) def response_header (self, _header, _transforms = None, _index = None) : if _index is None : _index = -1 return self._context.sample_0 ("res.fhdr", (_header, _index), _transforms) def request_cookie (self, _cookie, _transforms = None) : return self._context.sample_0 ("req.cook", (_cookie,), _transforms) def response_cookie (self, _cookie, _transforms = None) : return self._context.sample_0 ("res.cook", (_cookie,), _transforms) def request_header_exists (self, _header, _expected = True) : return self._context.sample_0 ("req.fhdr_cnt", (_header,), ("bool" if _expected else ("bool", "not"))) def response_header_exists (self, _header, _expected = True) : return self._context.sample_0 ("res.fhdr_cnt", (_header,), ("bool" if _expected else ("bool", "not"))) def request_cookie_exists (self, _cookie, _expected = True) : return self._context.sample_0 ("req.cook_cnt", (_cookie,), ("bool" if _expected else ("bool", "not"))) def response_cookie_exists (self, _cookie, _expected = True) : return self._context.sample_0 ("res.cook_cnt", (_cookie,), ("bool" if _expected else ("bool", "not"))) def variable (self, _variable, _transforms = None) : return self._context.sample_0 ("var", (_variable,), _transforms) def variable_bool (self, _variable, _expected = True) : return self._context.sample_0 ("var", (_variable,), ("bool" if _expected else ("bool", "not"))) def via_tls (self, _expected = True, _method = None) : if _method is None : _method = self._parameters._get_and_expand ("samples_via_tls_method") if _method == "ssl_fc" : return self._context.sample_0 ("ssl_fc", None, (None if _expected else "not")) elif _method == "dst_port_443" : return self._context.sample_0 ("dst_port", None, (("xor", 443), "bool", ("not" if _expected else None))) elif _method == "X-Forwarded-Port-443" : return self._context.sample_0 ("req.hdr", ("$logging_http_header_forwarded_port", 1), (("xor", 443), "bool", ("not" if _expected else None))) else : raise_error ("fd58dd1e", self) def tls_client_certificate (self) : return self._context.sample_0 ("ssl_c_sha1", None, "hex") def tls_client_certificate_issuer_cn (self) : return self._context.sample_0 ("ssl_c_i_dn", ("CN",), None) def tls_client_certificate_subject_cn (self) : return self._context.sample_0 ("ssl_c_s_dn", ("CN",), None) def tls_session_sni_exists (self, _expected = True) : return self._context.sample_0 ("ssl_fc_has_sni", None, (None if _expected else "not")) def tls_session_sni (self, _transforms = None) : return self._context.sample_0 ("ssl_fc_sni", None, _transforms) def authenticated (self, _credentials, _expected = True) : return self._context.sample_0 ("http_auth", (_credentials,), ("bool" if _expected else ("bool", "not"))) def authenticated_group (self, _credentials, _transforms = None) : return self._context.sample_0 ("http_auth_group", (_credentials,), _transforms) def backend_active (self, _backend, _expected = True) : return self._context.sample_0 ("nbsrv", (_backend,), ("bool" if _expected else ("bool", "not"))) def geoip_country_extracted (self, _method = None) : return self.client_ip (_method, (("map_ip", "$geoip_map"),)) def geoip_country_captured (self) : return self.variable ("$logging_geoip_country_variable") def variable_map_string_to_string (self, _variable, _map, _transforms = None) : if _transforms is None : _transforms = () return self._context.sample_0 ("var", (_variable,), (("map", _map),) + _transforms) def variable_map_string_to_integer (self, _variable, _map, _transforms = None) : if _transforms is None : _transforms = () return self._context.sample_0 ("var", (_variable,), (("map_int", _map),) + _transforms) def variable_map_ip_to_string (self, _variable, _map, _transforms = None) : if _transforms is None : _transforms = () return self._context.sample_0 ("var", (_variable,), (("map_ip", _map),) + _transforms) def variable_map_ip_to_integer (self, _variable, _map, _transforms = None) : if _transforms is None : _transforms = () return self._context.sample_0 ("var", (_variable,), (("map_ip_int", _map),) + _transforms) def uuid_v4 (self, _transforms = None) : return self._context.sample_0 ("uuid", ("4",), _transforms) def uuid_v4_no_dashes (self) : return self._context.sample_0 ("uuid", ("4",), (("regsub", "-", "", "g"),)) def client_ip_hash (self, _method = None) : return self.client_ip (_method, (("digest", "md5"), "hex", "lower")) def agent_hash (self) : return self.request_header ("User-Agent", (("digest", "md5"), "hex", "lower")) def agent_regsub (self, _pattern, _substitutions, _flags = None) : return self.request_header ("User-Agent", (("regsub", _pattern, _substitutions, _flags),)) <file_sep> from errors import * from tools import * from tools import __default__ class HaBuilder (object) : def __init__ (self, _context, _parameters) : self._context = _context self._parameters = _parameters def _value_or_parameters_get_and_expand (self, _value, _parameter, _default = __default__, parameters = None, overrides = None) : if _value is not None : return _value else : return self._parameters_get_and_expand (_parameter, _default, parameters, overrides) def _parameters_get_and_expand (self, _parameter, _default = __default__, parameters = None, overrides = None) : _parameters, _overrides = self._resolve_parameters_overrides (parameters, overrides) if _overrides is not None and _parameter in _overrides : return _overrides[_parameter] _default = _default if _default is not __default__ else self._parameters._get_fallback_enabled return _parameters._get_and_expand (_parameter, _default) def _parameters_get (self, _parameter, _default = __default__, parameters = None, overrides = None) : _parameters, _overrides = self._resolve_parameters_overrides (parameters, overrides) if _overrides is not None and _parameter in _overrides : return _overrides[_parameter] _default = _default if _default is not __default__ else self._parameters._get_fallback_enabled return self._parameters._get (_parameter, _default) def _parameters_expand (self, _parameter, overrides = None) : _parameters, _overrides = self._resolve_parameters_overrides (parameters, overrides) if _overrides is not None and _parameter in _overrides : return _overrides[_parameter] return self._parameters._expand (_parameter) def _resolve_parameters_overrides (self, _parameters, _overrides) : if _parameters is not None : _parameters = parameters else : _parameters = self._parameters return _parameters, _overrides def _one_or_many (self, _value) : if isinstance (_value, tuple) or isinstance (_value, list) : return _value else : return (_value,) <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' bind 'ipv4@0.0.0.0:443' ssl crt '/etc/haproxy/tls/default.pem' crt-list '/etc/haproxy/tls/default.conf' ca-file /etc/haproxy/tls/ca.pem verify optional #---- ACL acl acl-bfe00a394d220de7bce1709a40bc753f ssl_c_sha1(),hex -m str -i eq -- '874a47fdf56abfb59402779564976f48' acl acl-bfe00a394d220de7bce1709a40bc753f ssl_c_sha1(),hex -m str -i eq -- 'bc98855760c47e3643053790edd856cd' #---- HTTP Request Rules http-request deny deny_status 403 if !acl-bfe00a394d220de7bce1709a40bc753f #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> from builders_acl import * from builders_samples import * from builders_rules import * from builders_frontends import * from builders_backends import * from builders_routes import * <file_sep> from core import haproxy from core import parameters from core import overrides import tools from tools import parameters_get <file_sep> from tools import * from declares_servers import * def declare_tcp_frontend (_configuration) : declare_tcp_frontend_connections (_configuration) declare_tcp_frontend_timeouts (_configuration) declare_tcp_frontend_logging (_configuration) declare_tcp_frontend_stick (_configuration) def declare_tcp_backend (_configuration) : declare_tcp_backend_connections (_configuration) declare_tcp_backend_check (_configuration) declare_tcp_backend_server_defaults (_configuration) declare_tcp_backend_server_timeouts (_configuration) def declare_defaults_tcp (_configuration) : _configuration.declare_group ( "TCP", # FIXME: ... ) def declare_tcp_frontend_connections (_configuration) : _configuration.declare_group ( "Protocol", ("mode", "tcp"), statement_choose_if ("$?frontend_enabled", "enabled", "disabled"), order = 2000 + 100, ) _configuration.declare_group ( "Connections", ("maxconn", "$+frontend_max_connections_active_count"), ("backlog", "$+frontend_max_connections_backlog_count"), enabled_if = "$?frontend_connections_configure", order = 2000 + 100, ) def declare_tcp_frontend_timeouts (_configuration) : _configuration.declare_group ( "Timeouts", enabled_if = "$?frontend_timeouts_configure", order = 2000 + 101, ) def declare_tcp_frontend_logging (_configuration) : _configuration.declare_group ( "Logging", ("option", "tcplog"), statement_choose_if_non_null ("$logging_tcp_format", ("log-format", "$\"logging_tcp_format")), enabled_if = "$?frontend_logging_configure", order = 7000 + 400, ) def declare_tcp_frontend_stick (_configuration) : # FIXME: Make this configurable! _configuration.declare_group ( "Stick tables", ("stick-table", "type", "ip", "size", 1024 * 1024, "expire", "3600s", "store", ",".join (( "conn_cur", "conn_cnt", "conn_rate(60s)", "sess_cnt", "sess_rate(60s)", "bytes_in_cnt", "bytes_in_rate(60s)", "bytes_out_cnt", "bytes_out_rate(60s)", )) ), statement_choose_if ("$?frontend_tcp_stick_track", ("tcp-request", "connection", "track-sc0", statement_choose_match ("$frontend_tcp_stick_source", ("src", "src"), ) ), ), enabled_if = "$?frontend_stick_configure", order = 5000 + 290, ) def declare_tcp_backend_connections (_configuration) : _configuration.declare_group ( "Protocol", ("mode", "tcp"), statement_choose_if ("$?backend_enabled", "enabled", "disabled"), ) _configuration.declare_group ( "Connections", # FIXME: Extract this into common function! statement_choose_match ("$backend_balance", ("round-robin", ("balance", "roundrobin")), ("first", ("balance", "first")), (None, None)), enabled_if = "$?backend_connections_configure", ) def declare_tcp_backend_check (_configuration) : # FIXME: ... pass def declare_tcp_backend_server_defaults (_configuration) : declare_backend_server_defaults (_configuration, [ # FIXME: ... ]) def declare_tcp_backend_server_timeouts (_configuration) : declare_backend_server_timeouts (_configuration, [ # FIXME: ... ]) <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _be = _ha.http_backends.basic (_frontend = _fe) _operators = _ha.credentials_create ("operators", "example.com") _operators.declare_user ("operator", "zeregigojacuyixu") _fe.requests.authenticate ( _operators, _acl = _fe.acls.host ("private.example.com"), ) _ha.output_stdout () <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- ACL acl acl-ea05648d97377dcad8074252498487ef src() -m ip -- '10.0.0.0/8' acl acl-ea05648d97377dcad8074252498487ef src() -m ip -- '192.168.0.0/16' #---- HTTP Request Rules http-request deny deny_status 403 if !acl-ea05648d97377dcad8074252498487ef #---- Routes use_backend http-backend backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> defaults #---- Protocol mode tcp disabled #---- Connections maxconn 4096 backlog 1024 rate-limit sessions 16384 balance roundrobin retries 4 #---- Connections TCP-Keep-Alive option clitcpka option srvtcpka #---- Connections splicing option splice-request option splice-response no option splice-auto #---- Timeouts timeout server 60s timeout server-fin 6s timeout client 30s timeout client-fin 6s timeout tunnel 180s timeout connect 6s timeout queue 30s timeout check 6s timeout tarpit 30s #---- Servers fullconn 16 default-server minconn 8 default-server maxconn 32 default-server maxqueue 128 default-server inter 60s default-server fastinter 2s default-server downinter 20s default-server rise 8 default-server fall 4 default-server on-error fastinter default-server error-limit 4 #---- HTTP http-reuse safe http-check disable-on-404 http-check send-state option http-keep-alive timeout http-request 30s timeout http-keep-alive 60s unique-id-format "%[req.hdr(X-HA-Request-Id)]" #---- HTTP compression compression algo gzip compression type 'text/html' 'text/css' 'application/javascript' 'text/javascript' 'application/xml' 'text/xml' 'application/xhtml+xml' 'application/rss+xml' 'application/atom+xml' 'application/json' 'text/json' 'text/plain' 'text/csv' 'text/tab-separated-values' 'image/svg+xml' 'image/vnd.microsoft.icon' 'image/x-icon' 'font/collection' 'font/otf' 'application/font-otf' 'application/x-font-otf' 'application/x-font-opentype' 'font/ttf' 'application/font-ttf' 'application/x-font-ttf' 'application/x-font-truetype' 'font/sfnt' 'application/font-sfnt' 'application/x-font-sfnt' 'font/woff' 'application/font-woff' 'application/x-font-woff' 'font/woff2' 'application/font-woff2' 'application/x-font-woff2' 'font/eot' 'application/font-eot' 'application/x-font-eot' 'application/vnd.ms-fontobject' #---- Logging log global option log-separate-errors option log-health-checks no option checkcache no option dontlognull #---- Stats option contstats option socket-stats #---- Error pages errorfile 200 '/etc/haproxy/errors/http/monitor.http' errorfile 400 '/etc/haproxy/errors/http/400.http' errorfile 401 '/etc/haproxy/errors/http/401.http' errorfile 403 '/etc/haproxy/errors/http/403.http' errorfile 404 '/etc/haproxy/errors/http/404.http' errorfile 405 '/etc/haproxy/errors/http/405.http' errorfile 408 '/etc/haproxy/errors/http/408.http' errorfile 410 '/etc/haproxy/errors/http/410.http' errorfile 429 '/etc/haproxy/errors/http/429.http' errorfile 500 '/etc/haproxy/errors/http/500.http' errorfile 501 '/etc/haproxy/errors/http/501.http' errorfile 502 '/etc/haproxy/errors/http/502.http' errorfile 503 '/etc/haproxy/errors/http/503.http' errorfile 504 '/etc/haproxy/errors/http/504.http' #---- State load-server-state-from-file global <file_sep> frontend 'http' #---- Protocol mode http enabled #---- Bind bind 'ipv4@0.0.0.0:80' #---- HTTP Request Rules http-request set-header "X-Country" "%[src(),map_ip('/etc/haproxy/maps/geoip.txt')]" http-request set-var(txn.logging_geoip_country) req.fhdr('X-Country',-1) http-request capture req.fhdr('X-Country',-1),base64 id 0 #---- Routes use_backend http-backend #---- Captures for requests declare capture request len 1024 backend 'http-backend' #---- Protocol mode http enabled #---- Servers server 'default' 'ipv4@127.0.0.1:8080' <file_sep> import ha _ha = ha.haproxy ( minimal_configure = True, ) _fe = _ha.http_frontends.basic () _be_flask = _ha.http_backends.basic ( _identifier = "http-flask", _endpoint = "ipv4@127.0.0.1:9090", ) _be_static = _ha.http_backends.basic ( _identifier = "http-static", _endpoint = "ipv4@127.0.0.1:9091", ) _be_media = _ha.http_backends.basic ( _identifier = "http-media", _endpoint = "ipv4@127.0.0.1:9092", ) _fe.routes.route_path_prefix (_be_static, ("/assets/", "/public/")) _fe.routes.route_path_prefix (_be_media, "/media/") _fe.routes.route (_be_flask) _ha.output_stdout ()
50d0ed7133eae917bb4e6becc09fbde661dd6dcc
[ "Python", "HAProxy" ]
56
Python
cipriancraciun/haproxy-configurator
4e2f10e98c751cbdb4fcff266ecd253e83938d26
8aba54354124bdbdfb70a6ede84d5b7b11cee691
refs/heads/master
<file_sep># Seminar Diverse NodeMCU
f1cc38c120bb6d3d22d653d0794e3ab457600b9f
[ "Markdown" ]
1
Markdown
honda750/Seminar
25bc1941ad6df34b2e5e5b642e5268577dd00d48
e8592f0ef8ed4a3c118005c5fcb5606846f9954f
refs/heads/master
<repo_name>JimYangZhao/My-Portfolio_Page-React<file_sep>/src/resumeData.js let resumeData = { "imagebaseurl":"https://JimYangZhao.github.io/", "name": "<NAME>(Jim)", "role": "Full Stack Engineer | Front End Specialist ", "linkedinId":"https://www.linkedin.com/in/yang-zhao-11a75015b/", "roleDescription": "Computer Science graduate with a demonstrated history of working in the technology industry. Skilled in Spring Boot, Node.js, React, DevOps technologies, and AWS. Strong advocate for TDD and CI&CD implementation. ", "socialLinks":[ { "name":"linkedin", "url":"https://www.linkedin.com/in/yang-zhao-11a75015b/", "className":"fa fa-linkedin" }, { "name":"github", "url":"https://github.com/JimYangZhao", "className":"fa fa-github" }, ], "aboutme":"Computer Science graduate with a demonstrated history of working in the technology industry. Skilled in Spring Boot, Node.js, React, DevOps technologies, and AWS. Strong advocate for TDD and CI&CD implementation.", "address":"Canada, NL, St. John's, <EMAIL>", "education":[ { "UniversityName":"CA, Memorial University", "specialization":"Computer Science", "MonthOfPassing":"May", "YearOfPassing":"2020", "Achievements":"Bachelor of Science, Computer Science" }, ], "work":[ { "CompanyName":"Heardgi Website Design", "specialization": "Communicating with clients and translate client need into business requirements for feature development", "MonthOfLeaving":"April", "YearOfLeaving":"2016 to Present", }, { "CompanyName":"JAC", "specialization":"Delivered high quality E-commerce web applications based on business requirement using WordPress", "MonthOfLeaving":"Sept", "YearOfLeaving":"2020 to Dec 2020", }, { "CompanyName":"NLCC Service Group Corp.", "specialization":"Successfully led a full stack project to deliver a modern web application to clients of NLCC Service Group.", "MonthOfLeaving":"Jan", "YearOfLeaving":"2019 to Dec 2019", }, { "CompanyName":"FAW-VOLKSWAGEN", "specialization":"Responsible for oversight of the IT infrastructure, provisioning, planning, installation and operation for FAW-VOLKSWAGEN IT Department.", "MonthOfLeaving":"April", "YearOfLeaving":"2016 to August 2016", }, { "CompanyName":"Memorial University", "specialization":"Responsible for installation and maintenance of communication devices on campus.", "MonthOfLeaving":"Dec.", "YearOfLeaving":"2015 to Sept. of 2019", } ], "skillsDescription":"HTML5, CSS3, Bootstrap, JQuery, PHP. JAVA, Spring Boot, Node.js, React, DevOps technologies, and AWS. Strong advocate for TDD and CI&CD implementation. ", "portfolio":[ { "name":"NL Bakery E-shop", "description":"St. John’s local bakery E-shop.", "imgurl":"images/portfolio/WeChat-Screenshot_20200513213724-800x387.png" }, { "name":"Chinese community", "description":"St. John’s biggest Chinese community service/rental website.", "imgurl":"images/portfolio/nlcc-800x387.png", }, { "name":"Chinese restaurant", "description":"St. John’s very popular Chinese restaurant.", "imgurl":"images/portfolio/citylight-800x390.png" }, { "name":"Industry website", "description":"China, Intelligent Power Technology Co.,Ltd., industry website.", "imgurl":"images/portfolio/Gardermoen-800x394.png" } ], "testimonials":[ { "description":"The very important thing you should have is patience.", "name":"<NAME>" }, { "description":"If you get up in the morning and think the future is going to be better, it is a bright day. Otherwise, it’s not.", "name":"<NAME>" } ] } export default resumeData<file_sep>/build/precache-manifest.a0799548cefe0ce20b8fa76bc73fbb37.js self.__precacheManifest = [ { "revision": "4f2ebaff382f8f7da43d", "url": "/My-Portfolio_Page-React/static/css/main.2ba997e0.chunk.css" }, { "revision": "4f2ebaff382f8f7da43d", "url": "/My-Portfolio_Page-React/static/js/main.4f2ebaff.chunk.js" }, { "revision": "63fb5b41de279ed09cdd", "url": "/My-Portfolio_Page-React/static/js/1.63fb5b41.chunk.js" }, { "revision": "76a7b1504ea2dda084f9", "url": "/My-Portfolio_Page-React/static/js/runtime~main.76a7b150.js" }, { "revision": "81398b2307da88dff0c2901099d38e2f", "url": "/My-Portfolio_Page-React/index.html" } ];
c534f44077c1764e2e5162b79e704443a5ffb965
[ "JavaScript" ]
2
JavaScript
JimYangZhao/My-Portfolio_Page-React
c871f71783b0dd3483ae32741fec4aa432ae95c7
fa7c4b7ea80b865f4056a6490ff09794b0b52c97
refs/heads/master
<repo_name>frumpleswift/modowa-db<file_sep>/sync.sql --################################# --##Test sync script to create a modowa portal user ant test package --################################# create user portal identified by portal; grant dba to portal; create or replace procedure portal.test_modowa as begin owa_util.print_cgi_env; end; /
5292241d88d14d449f91efa7049a89cad7d3def2
[ "SQL" ]
1
SQL
frumpleswift/modowa-db
6d868a800a3912ac5677325290b15b435c5e950e
e6420e6ddd143d6c662705ac3d09aca8c961b5d0
refs/heads/master
<repo_name>carlziess/phpgeo_extension<file_sep>/tests/004.phpt --TEST-- Check geo_get_neighbors/geo_get_adjacent --SKIPIF-- <?php if (!extension_loaded("geo")) print "skip"; ?> --FILE-- <?php $hash = 'xp4ge1b'; $r1 = geo_get_neighbors($hash); $r2 = geo_get_neighbors($hash); $r3 = geo_get_neighbors($hash); $r4 = geo_get_neighbors($hash); $a1 = geo_get_adjacent($hash, 0); $a2 = geo_get_adjacent($hash, 1); $a3 = geo_get_adjacent($hash, 2); $a4 = geo_get_adjacent($hash, 3); var_export($r1); echo "\n"; var_export($r2); echo "\n"; var_export($r3); echo "\n"; var_export($r4); echo "\n"; var_export($a1); echo "\n"; var_export($a2); echo "\n"; var_export($a3); echo "\n"; var_export($a4); echo "\n"; ?> --EXPECT-- array ( 'north' => 'xp4ge40', 'east' => 'xp4ge1c', 'west' => 'xp4gdcz', 'south' => 'xp4ge18', 'north_east' => 'xp4ge41', 'south_east' => 'xp4ge19', 'north_west' => 'xp4gdfp', 'south_west' => 'xp4gdcx', ) array ( 'north' => 'xp4ge40', 'east' => 'xp4ge1c', 'west' => 'xp4gdcz', 'south' => 'xp4ge18', 'north_east' => 'xp4ge41', 'south_east' => 'xp4ge19', 'north_west' => 'xp4gdfp', 'south_west' => 'xp4gdcx', ) array ( 'north' => 'xp4ge40', 'east' => 'xp4ge1c', 'west' => 'xp4gdcz', 'south' => 'xp4ge18', 'north_east' => 'xp4ge41', 'south_east' => 'xp4ge19', 'north_west' => 'xp4gdfp', 'south_west' => 'xp4gdcx', ) array ( 'north' => 'xp4ge40', 'east' => 'xp4ge1c', 'west' => 'xp4gdcz', 'south' => 'xp4ge18', 'north_east' => 'xp4ge41', 'south_east' => 'xp4ge19', 'north_west' => 'xp4gdfp', 'south_west' => 'xp4gdcx', ) 'xp4ge40' 'xp4ge1c' 'xp4gdcz' 'xp4ge18' <file_sep>/tests/005.phpt --TEST-- Check geo_simple_distance/geo_distance --SKIPIF-- <?php if (!extension_loaded("geo")) print "skip"; ?> --FILE-- <?php var_export(geo_simple_distance(30.635957,104.011712,30.576722,104.071445)); echo "\n"; var_export(geo_distance(30.635957,104.011712,30.576722,104.071445)); echo "\n"; ?> --EXPECT-- 6839.2073302854624 8731.2457741010312 <file_sep>/config.m4 dnl $Id$ dnl config.m4 for extension geo dnl Comments in this file start with the string 'dnl'. dnl Remove where necessary. This file will not work dnl without editing. dnl If your extension references something external, use with: dnl PHP_ARG_WITH(geo, for geo support, dnl Make sure that the comment is aligned: dnl [ --with-geo Include geo support]) dnl Otherwise use enable: PHP_ARG_ENABLE(geo, whether to enable geo support, dnl Make sure that the comment is aligned: [ --enable-geo Enable geo support]) if test "$PHP_GEO" != "no"; then dnl Write more examples of tests here... dnl # --with-geo -> check with-path dnl SEARCH_PATH="/usr/local /usr" # you might want to change this dnl SEARCH_FOR="/include/geo.h" # you most likely want to change this dnl if test -r $PHP_GEO/$SEARCH_FOR; then # path given as parameter dnl GEO_DIR=$PHP_GEO dnl else # search default path list dnl AC_MSG_CHECKING([for geo files in default path]) dnl for i in $SEARCH_PATH ; do dnl if test -r $i/$SEARCH_FOR; then dnl GEO_DIR=$i dnl AC_MSG_RESULT(found in $i) dnl fi dnl done dnl fi dnl dnl if test -z "$GEO_DIR"; then dnl AC_MSG_RESULT([not found]) dnl AC_MSG_ERROR([Please reinstall the geo distribution]) dnl fi dnl # --with-geo -> add include path dnl PHP_ADD_INCLUDE($GEO_DIR/include) dnl # --with-geo -> check for lib and symbol presence dnl LIBNAME=geo # you may want to change this dnl LIBSYMBOL=geo # you most likely want to change this dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL, dnl [ dnl PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $GEO_DIR/lib, GEO_SHARED_LIBADD) dnl AC_DEFINE(HAVE_GEOLIB,1,[ ]) dnl ],[ dnl AC_MSG_ERROR([wrong geo lib version or lib not found]) dnl ],[ dnl -L$GEO_DIR/lib -lm dnl ]) dnl PHP_SUBST(GEO_SHARED_LIBADD) PHP_NEW_EXTENSION(geo, geo.c geo_lib.c, $ext_shared) fi <file_sep>/geo_lib.c /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | <EMAIL> so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: carlziess <<EMAIL>> | +----------------------------------------------------------------------+ */ #include <ctype.h> #include <string.h> #include <stddef.h> #include <stdlib.h> #include <stdbool.h> #include <assert.h> #include "geo_lib.h" #include <stdio.h> #include <string.h> #include <math.h> #define MAX_HASH_LENGTH 22 #define PI 3.141592653 #define dutorad(X) ((X)/180*PI) #define radtodu(X) ((X)/PI*180) #define EARTH_RADIUS 6378137 double radian(double d) { return d * PI / 180.0; } #define REFINE_RANGE(range, bits, offset) \ if (((bits) & (offset)) == (offset)) \ (range)->min = ((range)->max + (range)->min) / 2.0; \ else \ (range)->max = ((range)->max + (range)->min) / 2.0; #define SET_BIT(bits, mid, range, value, offset) \ mid = ((range)->max + (range)->min) / 2.0; \ if ((value) >= mid) { \ (range)->min = mid; \ (bits) |= (0x1 << (offset)); \ } else { \ (range)->max = mid; \ (bits) |= (0x0 << (offset)); \ } static const char BASE32_ENCODE_TABLE[33] = "0123456789bcdefghjkmnpqrstuvwxyz"; static const char BASE32_DECODE_TABLE[44] = { /* 0 */ 0, /* 1 */ 1, /* 2 */ 2, /* 3 */ 3, /* 4 */ 4, /* 5 */ 5, /* 6 */ 6, /* 7 */ 7, /* 8 */ 8, /* 9 */ 9, /* : */ -1, /* ; */ -1, /* < */ -1, /* = */ -1, /* > */ -1, /* ? */ -1, /* @ */ -1, /* A */ -1, /* B */ 10, /* C */ 11, /* D */ 12, /* E */ 13, /* F */ 14, /* G */ 15, /* H */ 16, /* I */ -1, /* J */ 17, /* K */ 18, /* L */ -1, /* M */ 19, /* N */ 20, /* O */ -1, /* P */ 21, /* Q */ 22, /* R */ 23, /* S */ 24, /* T */ 25, /* U */ 26, /* V */ 27, /* W */ 28, /* X */ 29, /* Y */ 30, /* Z */ 31 }; static const char NEIGHBORS_TABLE[8][33] = { "p0r21436x8zb9dcf5h7kjnmqesgutwvy", /* NORTH EVEN */ "bc01fg45238967deuvhjyznpkmstqrwx", /* NORTH ODD */ "bc01fg45238967deuvhjyznpkmstqrwx", /* EAST EVEN */ "p0r21436x8zb9dcf5h7kjnmqesgutwvy", /* EAST ODD */ "238967debc01fg45kmstqrwxuvhjyznp", /* WEST EVEN */ "14365h7k9dcfesgujnmqp0r2twvyx8zb", /* WEST ODD */ "14365h7k9dcfesgujnmqp0r2twvyx8zb", /* SOUTH EVEN */ "238967debc01fg45kmstqrwxuvhjyznp" /* SOUTH ODD */ }; static const char BORDERS_TABLE[8][9] = { "prxz", /* NORTH EVEN */ "bcfguvyz", /* NORTH ODD */ "bcfguvyz", /* EAST EVEN */ "prxz", /* EAST ODD */ "0145hjnp", /* WEST EVEN */ "028b", /* WEST ODD */ "028b", /* SOUTH EVEN */ "0145hjnp" /* SOUTH ODD */ }; bool GEO_verify_hash(const char *hash) { const char *p; unsigned char c; p = hash; while (*p != '\0') { c = toupper(*p++); if (c < 0x30) return false; c -= 0x30; if (c > 43) return false; if (BASE32_DECODE_TABLE[c] == -1) return false; } return true; } GEO_area* GEO_decode(const char *hash) { const char *p; unsigned char c; char bits; GEO_area *area; GEO_range *range1, *range2, *range_tmp; area = (GEO_area *)emalloc(sizeof(GEO_area)); if (area == NULL) return NULL; area->latitude.max = 90; area->latitude.min = -90; area->longitude.max = 180; area->longitude.min = -180; range1 = &area->longitude; range2 = &area->latitude; p = hash; while (*p != '\0') { c = toupper(*p++); if (c < 0x30) { efree(area); return NULL; } c -= 0x30; if (c > 43) { efree(area); return NULL; } bits = BASE32_DECODE_TABLE[c]; if (bits == -1) { efree(area); return NULL; } REFINE_RANGE(range1, bits, 0x10); REFINE_RANGE(range2, bits, 0x08); REFINE_RANGE(range1, bits, 0x04); REFINE_RANGE(range2, bits, 0x02); REFINE_RANGE(range1, bits, 0x01); range_tmp = range1; range1 = range2; range2 = range_tmp; } return area; } char* GEO_encode(double lat, double lon, unsigned int len) { unsigned int i; char *hash; unsigned char bits = 0; double mid; GEO_range lat_range = { 90, -90 }; GEO_range lon_range = { 180, -180 }; double val1, val2, val_tmp; GEO_range *range1, *range2, *range_tmp; assert(lat >= -90.0); assert(lat <= 90.0); assert(lon >= -180.0); assert(lon <= 180.0); assert(len <= MAX_HASH_LENGTH); hash = (char *)emalloc(sizeof(char) * (len + 1)); if (hash == NULL) return NULL; val1 = lon; range1 = &lon_range; val2 = lat; range2 = &lat_range; for (i=0; i < len; i++) { bits = 0; SET_BIT(bits, mid, range1, val1, 4); SET_BIT(bits, mid, range2, val2, 3); SET_BIT(bits, mid, range1, val1, 2); SET_BIT(bits, mid, range2, val2, 1); SET_BIT(bits, mid, range1, val1, 0); hash[i] = BASE32_ENCODE_TABLE[bits]; val_tmp = val1; val1 = val2; val2 = val_tmp; range_tmp = range1; range1 = range2; range2 = range_tmp; } hash[len] = '\0'; return hash; } void GEO_free_area(GEO_area *area) { efree(area); } GEO_neighbors* GEO_get_neighbors(const char* hash) { GEO_neighbors *neighbors; neighbors = (GEO_neighbors*)emalloc(sizeof(GEO_neighbors)); if (neighbors == NULL) return NULL; neighbors->north = GEO_get_adjacent(hash, GEO_NORTH); neighbors->east = GEO_get_adjacent(hash, GEO_EAST); neighbors->west = GEO_get_adjacent(hash, GEO_WEST); neighbors->south = GEO_get_adjacent(hash, GEO_SOUTH); neighbors->north_east = GEO_get_adjacent(neighbors->north, GEO_EAST); neighbors->north_west = GEO_get_adjacent(neighbors->north, GEO_WEST); neighbors->south_east = GEO_get_adjacent(neighbors->south, GEO_EAST); neighbors->south_west = GEO_get_adjacent(neighbors->south, GEO_WEST); return neighbors; } char* GEO_get_adjacent(const char* hash, GEO_direction dir) { int len, idx; const char *border_table, *neighbor_table; char *base, *refined_base, *ptr, last; assert(hash != NULL); len = strlen(hash); last = tolower(hash[len - 1]); idx = dir * 2 + (len % 2); border_table = BORDERS_TABLE[idx]; base = (char *)emalloc(sizeof(char) * (len + 1)); if (base == NULL) return NULL; memset(base, '\0', sizeof(char) * (len + 1)); strncpy(base, hash, len - 1); if (strchr(border_table, last) != NULL) { refined_base = GEO_get_adjacent(base, dir); if (refined_base == NULL) { efree(base); return NULL; } strncpy(base, refined_base, strlen(refined_base)); efree(refined_base); } neighbor_table = NEIGHBORS_TABLE[idx]; ptr = strchr(neighbor_table, last); if (ptr == NULL) { efree(base); return NULL; } idx = (int)(ptr - neighbor_table); len = strlen(base); base[len] = BASE32_ENCODE_TABLE[idx]; return base; } void GEO_free_neighbors(GEO_neighbors *neighbors) { efree(neighbors->north); efree(neighbors->east); efree(neighbors->west); efree(neighbors->south); efree(neighbors->north_east); efree(neighbors->south_east); efree(neighbors->north_west); efree(neighbors->south_west); efree(neighbors); } double GEO_simple_distance(double lat1,double lng1,double lat2,double lng2) { double dx,dy,b,lx,ly; dx = lat1 - lat2; dy = lng1 - lng2; b = (lng1 + lng2) / 2.0; lx = dutorad(dx) * EARTH_RADIUS * cos( dutorad(b) ); ly = dutorad(dy) * EARTH_RADIUS; return sqrt(lx*lx+ly*ly); } double GEO_distance(double lat1, double lng1, double lat2, double lng2) { double radLat1,radLat2,a,b,dst; radLat1 = radian(lat1); radLat2 = radian(lat2); a = radLat1 - radLat2; b = radian(lng1) - radian(lng2); dst = 2 * asin((sqrt(pow(sin(a / 2), 2) + cos(radLat1) * cos(radLat2) * pow(sin(b / 2), 2) ))); dst = dst * EARTH_RADIUS; return dst; } <file_sep>/geo.c /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | <EMAIL> so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: carlziess <<EMAIL>> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "geo.h" #include "geo_lib.h" const MAX_HASH_LENGTH = 22; /* If you declare any globals in php_geo.h uncomment this: ZEND_DECLARE_MODULE_GLOBALS(geo) */ /* True global resources - no need for thread safety here */ static int le_geo; /* {{{ geo_functions[] * * Every user visible function must have an entry in geo_functions[]. */ const zend_function_entry geo_functions[] = { PHP_FE(confirm_geo_compiled, NULL) /* For testing, remove later. */ PHP_FE(geo_verify_hash, NULL) PHP_FE(geo_encode, NULL) PHP_FE(geo_decode, NULL) PHP_FE(geo_get_neighbors, NULL) PHP_FE(geo_get_adjacent, NULL) PHP_FE(geo_distance, NULL) PHP_FE(geo_simple_distance, NULL) PHP_FE_END /* Must be the last line in geo_functions[] */ }; /* }}} */ /* {{{ geo_module_entry */ zend_module_entry geo_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "geo", geo_functions, PHP_MINIT(geo), PHP_MSHUTDOWN(geo), PHP_RINIT(geo), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(geo), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(geo), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_GEO ZEND_GET_MODULE(geo) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("geo.global_value", "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_geo_globals, geo_globals) STD_PHP_INI_ENTRY("geo.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_geo_globals, geo_globals) PHP_INI_END() */ /* }}} */ /* {{{ php_geo_init_globals */ /* Uncomment this function if you have INI entries static void php_geo_init_globals(zend_geo_globals *geo_globals) { geo_globals->global_value = 0; geo_globals->global_string = NULL; } */ /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(geo) { /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(geo) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(geo) { return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(geo) { return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(geo) { php_info_print_table_start(); php_info_print_table_header(2, "geo support", "enabled"); php_info_print_table_row(2, "functions", "geo_simple_distance,geo_distance,geo_encode,geo_decode,geo_verify_hash,geo_get_neighbors"); php_info_print_table_row(2, "author", PHP_GEO_AUTHOR); php_info_print_table_row(2, "version", PHP_GEO_VERSION); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ /* Remove the following function when you have succesfully modified config.m4 so that your module can be compiled into PHP, it exists only for testing purposes. */ /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_geo_compiled(string arg) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(confirm_geo_compiled) { char *arg = NULL; int arg_len, len; char *strg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "geo", arg); RETURN_STRINGL(strg, len, 0); } /* }}} */ /* The previous line is meant for vim and emacs, so it can correctly fold and unfold functions in source code. See the corresponding marks just before function definition, where the functions purpose is also documented. Please follow this convention for the convenience of others editing your code. */ /* {{{ proto bool geo_verify_hash(string hash) ; */ PHP_FUNCTION(geo_verify_hash) { char *hash = NULL; int argc = ZEND_NUM_ARGS(); int hash_len = 0; if (zend_parse_parameters(argc TSRMLS_CC, "s", &hash, &hash_len) == FAILURE) { RETURN_FALSE; } if(hash_len > 0 && GEO_verify_hash(hash)) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto string geo_encode(double latitude, double longitude, long length) ; */ PHP_FUNCTION(geo_encode) { int argc = ZEND_NUM_ARGS(); long length; double latitude; double longitude; if (zend_parse_parameters(argc TSRMLS_CC, "ddl", &latitude, &longitude, &length) == FAILURE) { RETURN_FALSE; } // check the coordinates if(latitude < -90.0 || latitude > 90.0 || longitude < -180.0 || longitude > 180.0) { RETURN_FALSE; } // check the length if(length < 1 || length > MAX_HASH_LENGTH) { RETURN_FALSE; } char * hash = GEO_encode(latitude, longitude, length); if(hash == NULL) { RETURN_FALSE; } RETURN_STRINGL(hash, strlen(hash), 0); } /* }}} */ /* {{{ proto array geo_decode(string hash) ; */ PHP_FUNCTION(geo_decode) { char *hash = NULL; int argc = ZEND_NUM_ARGS(); int hash_len = 0; if (zend_parse_parameters(argc TSRMLS_CC, "s", &hash, &hash_len) == FAILURE) { RETURN_FALSE; } if(hash_len == 0) { RETURN_FALSE; } GEO_area * area = GEO_decode(hash); if(area == NULL) { RETURN_FALSE; } array_init(return_value); add_assoc_double(return_value, "lat", (area->latitude.max + area->latitude.min) / 2.0); add_assoc_double(return_value, "lng", (area->longitude.max + area->longitude.min) / 2.0); add_assoc_double(return_value, "north", area->latitude.max); add_assoc_double(return_value, "south", area->latitude.min); add_assoc_double(return_value, "east", area->longitude.max); add_assoc_double(return_value, "west", area->longitude.min); GEO_free_area(area); } /* }}} */ /* {{{ proto mixed geo_get_neighbors(string hash) ; */ PHP_FUNCTION(geo_get_neighbors) { char *hash = NULL; int argc = ZEND_NUM_ARGS(); int hash_len = 0; if (zend_parse_parameters(argc TSRMLS_CC, "s", &hash, &hash_len) == FAILURE) { RETURN_FALSE; } if(hash_len == 0) { RETURN_FALSE; } GEO_neighbors * neighbors = GEO_get_neighbors(hash); if(neighbors == NULL) { RETURN_FALSE; } #define ADD_ASSOC_STRINGL(return_value, neighbors, name) \ add_assoc_stringl((return_value), #name, neighbors->name, strlen(neighbors->name), 0) array_init(return_value); ADD_ASSOC_STRINGL(return_value, neighbors, north); ADD_ASSOC_STRINGL(return_value, neighbors, east); ADD_ASSOC_STRINGL(return_value, neighbors, west); ADD_ASSOC_STRINGL(return_value, neighbors, south); ADD_ASSOC_STRINGL(return_value, neighbors, north_east); ADD_ASSOC_STRINGL(return_value, neighbors, south_east); ADD_ASSOC_STRINGL(return_value, neighbors, north_west); ADD_ASSOC_STRINGL(return_value, neighbors, south_west); //GEO_free_neighbors(neighbors); efree(neighbors); } /* }}} */ /* {{{ proto string geo_get_adjacent(string hash, long direction) ; */ PHP_FUNCTION(geo_get_adjacent) { char *hash = NULL; int argc = ZEND_NUM_ARGS(); int hash_len; long direction; if (zend_parse_parameters(argc TSRMLS_CC, "sl", &hash, &hash_len, &direction) == FAILURE) { RETURN_FALSE; } if(direction < GEO_NORTH || direction > GEO_SOUTH) { RETURN_FALSE; } char * _hash = GEO_get_adjacent(hash, direction); if(_hash == NULL) { RETURN_FALSE; } RETURN_STRINGL(_hash, strlen(_hash), 0); } /* }}} */ /* {{{ proto string geo_simple_distance(long lat1, long lng1, long lat2, long lng2) ; */ PHP_FUNCTION(geo_simple_distance) { int argc = ZEND_NUM_ARGS(); double lat1,lng1,lat2,lng2; if (zend_parse_parameters(argc TSRMLS_CC, "dddd", &lat1, &lng1, &lat2, &lng2) == FAILURE){ RETURN_FALSE; } RETURN_DOUBLE(GEO_simple_distance(lat1, lng1, lat2, lng2)); } /* }}} */ /* {{{ proto string geo_distance(long lat1, long lng1, long lat2, long lng2) ; */ PHP_FUNCTION(geo_distance) { int argc = ZEND_NUM_ARGS(); double lat1,lng1,lat2,lng2; if (zend_parse_parameters(argc TSRMLS_CC, "dddd", &lat1, &lng1, &lat2, &lng2) == FAILURE){ RETURN_FALSE; } RETURN_DOUBLE(GEO_distance(lat1, lng1, lat2, lng2)); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ <file_sep>/README.md PHP-Geo-Extentsion ======= <file_sep>/config.w32 // $Id$ // vim:ft=javascript // If your extension references something external, use ARG_WITH // ARG_WITH("geo", "for geo support", "no"); // Otherwise, use ARG_ENABLE // ARG_ENABLE("geo", "enable geo support", "no"); if (PHP_GEOHASH != "no") { EXTENSION("geo", "geo.c"); } <file_sep>/geo_lib.h /* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | <EMAIL> so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: carlziess <<EMAIL>> | +----------------------------------------------------------------------+ */ #ifndef _LIB_GEO_H_ #define _LIB_GEO_H_ #include <stdbool.h> #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #if defined(__cplusplus) extern "C" { #endif typedef enum { GEO_NORTH = 0, GEO_EAST, GEO_WEST, GEO_SOUTH } GEO_direction; typedef struct { double max; double min; } GEO_range; typedef struct { GEO_range latitude; GEO_range longitude; } GEO_area; typedef struct { char* north; char* east; char* west; char* south; char* north_east; char* south_east; char* north_west; char* south_west; } GEO_neighbors; bool GEO_verify_hash(const char *hash); char* GEO_encode(double latitude, double longitude, unsigned int hash_length); GEO_area* GEO_decode(const char* hash); GEO_neighbors* GEO_get_neighbors(const char *hash); void GEO_free_neighbors(GEO_neighbors *neighbors); char* GEO_get_adjacent(const char* hash, GEO_direction dir); void GEO_free_area(GEO_area *area); double GEO_simple_distance(double lat1, double lng1, double lat2, double lng2); double GEO_distance(double lat1, double lng1, double lat2, double lng2); #if defined(__cplusplus) } #endif #endif <file_sep>/tests/003.phpt --TEST-- Check geo_verify_hash --SKIPIF-- <?php if (!extension_loaded("geo")) print "skip"; ?> --FILE-- <?php $a = array( 'xp4ge1b', 'xp4ge1', 'xp4ge', 'xp4g', 'xp4' ); foreach($a as $v) { var_export(geo_verify_hash($v)); echo "\n"; } ?> --EXPECT-- true true true true true <file_sep>/tests/002.phpt --TEST-- Check geo_encode / geo_decode --SKIPIF-- <?php if (!extension_loaded("geo")) print "skip"; ?> --FILE-- <?php $lat = 40; $lng = 139; $r1 = geo_encode($lat, $lng, 7); $r2 = geo_encode($lat, $lng, 6); $r3 = geo_encode($lat, $lng, 5); $r4 = geo_encode($lat, $lng, 4); $r5 = geo_encode($lat, $lng, 3); $d1 = geo_decode($r1); $d2 = geo_decode($r2); $d3 = geo_decode($r3); $d4 = geo_decode($r4); $d5 = geo_decode($r5); var_export($r1); echo "\n"; var_export($r2); echo "\n"; var_export($r3); echo "\n"; var_export($r4); echo "\n"; var_export($r5); echo "\n"; var_export($d1); echo "\n"; var_export($d2); echo "\n"; var_export($d3); echo "\n"; var_export($d4); echo "\n"; var_export($d5); echo "\n"; ?> --EXPECT-- 'xp4ge1b' 'xp4ge1' 'xp4ge' 'xp4g' 'xp4' array ( 'lat' => 40.000534057617188, 'lng' => 138.99971008300781, 'north' => 40.001220703125, 'south' => 39.999847412109375, 'east' => 139.00039672851562, 'west' => 138.9990234375, ) array ( 'lat' => 39.99847412109375, 'lng' => 139.0045166015625, 'north' => 40.001220703125, 'south' => 39.9957275390625, 'east' => 139.010009765625, 'west' => 138.9990234375, ) array ( 'lat' => 40.01220703125, 'lng' => 139.02099609375, 'north' => 40.0341796875, 'south' => 39.990234375, 'east' => 139.04296875, 'west' => 138.9990234375, ) array ( 'lat' => 39.990234375, 'lng' => 139.04296875, 'north' => 40.078125, 'south' => 39.90234375, 'east' => 139.21875, 'west' => 138.8671875, ) array ( 'lat' => 40.078125, 'lng' => 138.515625, 'north' => 40.78125, 'south' => 39.375, 'east' => 139.21875, 'west' => 137.8125, )
83b5fdbbb88f0e4885e37a57d0225bbd5e33a84c
[ "C", "Markdown", "JavaScript", "PHP", "M4" ]
10
C
carlziess/phpgeo_extension
d958830bd19883058375147b89e09ab96648b45a
df6bd0abc445e24d33e10aa222b92a1f74fbb0dd
refs/heads/master
<repo_name>OpenMandrivaAssociation/texlive-progress<file_sep>/texlive-progress.spec Name: texlive-progress Version: 19519 Release: 2 Summary: Creates an overview of a document's state Group: Publishing URL: http://www.ctan.org/tex-archive/macros/latex/contrib/progress License: LPPL Source0: http://mirrors.ctan.org/systems/texlive/tlnet/archive/progress.r%{version}.tar.xz Source1: http://mirrors.ctan.org/systems/texlive/tlnet/archive/progress.doc.r%{version}.tar.xz BuildArch: noarch BuildRequires: texlive-tlpkg Requires(pre): texlive-tlpkg Requires(post): texlive-kpathsea %description Progress is a package which. when compiling TeX and LaTeX documents, generates a HTML file showing an overview of a document's state (of how finished it is). The report is sent to file \ProgressReportName, which is by default the \jobname with the date appended (but is user-modifiable). %post %{_sbindir}/texlive.post %postun if [ $1 -eq 0 ]; then %{_sbindir}/texlive.post fi #----------------------------------------------------------------------- %files %{_texmfdistdir}/tex/latex/progress/progress.sty %doc %{_texmfdistdir}/doc/latex/progress/README %doc %{_texmfdistdir}/doc/latex/progress/progress.pdf %doc %{_texmfdistdir}/doc/latex/progress/progress.tex %doc %{_texmfdistdir}/doc/latex/progress/progress20030701.html #----------------------------------------------------------------------- %prep %autosetup -p1 -c -a1 %build %install mkdir -p %{buildroot}%{_texmfdistdir} cp -fpar tex doc %{buildroot}%{_texmfdistdir} <file_sep>/.abf.yml sources: progress.doc.r19519.tar.xz: 4ef65708a522bcaaf38825721d6d383b056859de progress.r19519.tar.xz: 465170aece912b7b6d12667f1bbd809dbfa28412
2c16fb9cd4524b9fc4dbfdc284b9450889835473
[ "RPM Spec", "YAML" ]
2
RPM Spec
OpenMandrivaAssociation/texlive-progress
f03f8f3a3b89ba0baf41d70ccbd6048f0c8460c3
f66d307f05eb8a081891e6005f3f5784a342ded6
refs/heads/master
<repo_name>chenkezhao/sms-wiretap<file_sep>/SMSWiretapService/src/com/ckz/sms/viewer/BroadcastWin.java package com.ckz.sms.viewer; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import com.ckz.sms.entity.SMS; /** * 使用单例模式,只允许弹一个窗体出来显示内容,不论被调用了多少次 */ public class BroadcastWin { private JFrame frame; private JPanel panel; private JScrollPane jScrPan; //TextArea是一个显示纯文本的多行区域 private JTextArea textArea; //单例模式,只允许一个实例存在 private static BroadcastWin window = new BroadcastWin(); private BroadcastWin(){//初始化窗体操作 frame = new JFrame(); //关闭X,退出程序(默认隐藏窗口) //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("短信窃听内容"); //窗口显示位置 Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); frame.setLocation((displaySize.width - frameSize.width) / 2,(displaySize.height - frameSize.height) / 4); frame.setSize(600,400); panel = new JPanel(); textArea = new JTextArea(); panel.setLayout(new GridLayout()); //当TextArea里的内容过长时生成滚动条 jScrPan = new JScrollPane(); } /** * 提供外部获取实例接口 */ public static BroadcastWin getWindow(){ return window; } /** * 根据短信集合,组装显示窃听的短信内容 * @param smss */ public void packageSmsShow(List<SMS> smss){ textArea.setText(""); int size = smss.size(); for(int i=size-1;i>=0;i--){ SMS sms = smss.get(size-i-1); textArea.append("序号:"+(i+1)); textArea.append("\r\n"); textArea.append("号码:"+sms.getAddress()); textArea.append("\r\n"); String type = sms.getType()==1?"来信":"发信"; textArea.append("状态:"+type); textArea.append("\t"); textArea.append(sms.getDate()); textArea.append("\r\n"); textArea.append("内容:"+sms.getBody()); textArea.append("\r\n"); textArea.append("-----------------------------\r\n\r\n"); } //执行完textArea.append("message")后,刷新textArea内容 textArea.repaint(); jScrPan.setViewportView(textArea); panel.add(jScrPan); frame.add(panel); //显示窗体 frame.setVisible(true); System.out.println("加载成功,开始显示....."); } } <file_sep>/SMSWiretapService/src/com/ckz/sms/servlet/MultiDownloadFileServlet.java package com.ckz.sms.servlet; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; /** * 多线程断点下载案例 * @author Administrator * */ public class MultiDownloadFileServlet { private static int threadCount = 3; private static int runingThread = 3;//正在运行的线程个数 /** * @param args */ public static void main(String[] args) { try { //1.连接服务器,获取文件长度。然后在本地创建一个大小跟服务器文件一样大的临时文件 String path="http://169.254.9.148:8080/xx.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); switch (code) { case 200: //服务器返回数据长度,实际是文件的长度 int length = conn.getContentLength(); System.out.println("文件总长度:"+length); //在客户端本地创建出来一个大小跟服务器文件一样大的临时文件 RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd"); //指定创建这个文件的长度 raf.setLength(length); raf.close(); //假设启用三个线程去下载资源 //平均每个线程下载的文件大小,即下载的长度 int blockSize = length / threadCount; for(int threadId=1;threadId<=threadCount;threadId++){ //每个线程下载开始的位置 int startIndex = (threadId-1)*blockSize; int endIndex = (threadId*blockSize)-1; if(threadId==threadCount)//判断是否为最后一个线程 endIndex=length; System.out.println("线程:"+threadId+"下载:"+startIndex+"--->"+endIndex); //开启子线程下载 new DownloadThread(threadId, startIndex, endIndex, path).start(); } break; default: System.out.println("服务器错误."); break; } } catch (Exception e) { e.printStackTrace(); } } /** * 类 * 下载文件的子线程,每一个线程下载对应位置的文件 */ public static class DownloadThread extends Thread{ private int threadId; private int startIndex; private int endIndex; private String path; public DownloadThread(int threadId, int startIndex, int endIndex, String path) { this.threadId = threadId; this.startIndex = startIndex; this.endIndex = endIndex; this.path = path; } @Override public void run() { try { //检查是否存在记录下载长度的文件,如果存在读取这个文件的长度 File tempFile = new File(threadId+".txt"); if(tempFile.exists() && tempFile.length()>0){ FileInputStream fis = new FileInputStream(tempFile); byte[] temp = new byte[1024]; int leng = fis.read(temp); int downloadLen = Integer.parseInt(new String(temp, 0, leng)); startIndex = downloadLen;//修改下载的真实的开始位置 fis.close(); } System.out.println("线程真实下载:"+threadId+"下载:"+startIndex+"--->"+endIndex); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); //重要:请求服务器下载部分的文件,指定文件的位置 conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); System.out.println("code:"+code); InputStream is = conn.getInputStream();//已经设置了指定的位置,返回对应的是当前文件的输入流 RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd"); //随机写文件的时候,从那个文件开始写 raf.seek(startIndex);//定位文件 int len=0; byte[] buffer = new byte[1024]; int total=0;//已经下载数据的长度 while ((len=is.read(buffer))!=-1) { RandomAccessFile file = new RandomAccessFile(threadId+".txt","rwd");//作用:记录当前线程下载数据的长度 raf.write(buffer, 0, len); total+=len; //System.out.println("线程"+threadId+"total:"+total); file.write(String.valueOf(total+startIndex).getBytes());//记录下载的位置 file.close(); } is.close(); raf.close(); System.out.println("线程"+threadId+"下载完毕."); } catch (Exception e) { e.printStackTrace(); }finally{ threadFinish(); } } /** * 所有线程完毕调用的方法 */ private synchronized void threadFinish() { runingThread--; if(runingThread==0){//所有线程已经执行完毕 for(int i=1;i<=threadCount;i++){ File deleteFile = new File(i+".txt"); deleteFile.delete();//当线程下载完毕后,清除下载的记录 } System.out.println("文件下载完毕,删除所有下载记录."); } } } } <file_sep>/SMSWiretapService/src/com/ckz/sms/entity/SMS.java package com.ckz.sms.entity; /** * 短信内容字段 * * @author Administrator * */ public class SMS { /** * 号码 */ private String address; /** * 日期 */ private String date; /** * 类型,发 0|收 1 */ private Integer type; /** * 内容 */ private String body; /** * @return the address */ public String getAddress() { return address; } /** * @param address * the address to set */ public void setAddress(String address) { this.address = address; } /** * @return the date */ public String getDate() { return date; } /** * @param date * the date to set */ public void setDate(String date) { this.date = date; } /** * @return the type */ public Integer getType() { return type; } /** * @param type * the type to set */ public void setType(Integer type) { this.type = type; } /** * @return the body */ public String getBody() { return body; } /** * @param body * the body to set */ public void setBody(String body) { this.body = body; } }
2454b92f12302e517c2290b2ac6f2c136298c4c4
[ "Java" ]
3
Java
chenkezhao/sms-wiretap
ddeaed94f49695f88f07ea0bf02e314674d7e05a
8f5a6b9653c9ad176e5e85bbfa334e98f3325d12
refs/heads/main
<file_sep>An Optical Character Recognition system for Devanagari characters
a5b444fc00bd8f56377ef4ad3b32aede8cbc9ec8
[ "Markdown" ]
1
Markdown
carnifex-cmd/OCR-for-Devanagari
a818d8d3e926c8b0748e796c0f49e1b777824aa0
f4869fb52631dec493c3605d4e93c8bd67edba9a
refs/heads/master
<repo_name>a-woodworth/ls_projects<file_sep>/lesson_3/exercises_hard1/question2_hard1.rb # Question 2 # What is the result of the last line in the code below? # greetings = { a: 'hi' } # informal_greeting = greetings[:a] # informal_greeting << ' there' # puts informal_greeting # => "hi there" # puts greetings p "The result will be: {:a=>'hi there'}. Because informal_greeting equals greetings, they now reference the same object." p "Then, informal_greeting was altered permanently by adding 'there' to the array." p "The greetings variable now is also changed so you get {:a=>'hi there'}." <file_sep>/lesson_2/loan_messages.yml en: welcome: "Welcome to the Loan Calculator." usage: "Use this calculator for mortgage, auto, or other fixed loan types." enter_loan_amount: "Please enter the total loan amount: " value_confirmation: "You entered: " loan_error: "Invalid data. Please enter a valid amount." enter_apr: "Please enter the interest rate per year." interest_free: "Congrats on your interest free loan!" apr_error: "Please enter a valid interest rate." monthly_rate: "Based on this, your monthly interest rate is: " keep_calculating: "Do you want to perform another calculation?" years_greeting: "How quickly do you want to pay back your loan?" enter_years: "Please enter a number for the loan duration in years." years_error: "Please enter a valid number." payment: "Your monthly payment will be " instructions: "Select --> Y to calculate again. Q to quit." new_calculation: "OK...starting a new calculation." instructions_help: "Hmmm...I'm not sure what to do." goodbye: "Thank you for using the loan calculator. Goodbye!" <file_sep>/lesson_3/exercises_medium2/question6_medium2.rb # Question 6 # One day Spot was playing with the Munster family's home computer and he wrote a small program to mess with their demographic data: munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } def mess_with_demographics(demo_hash) demo_hash.values.each do |family_member| family_member["age"] += 42 family_member["gender"] = "other" end end # After writing this method, he typed the following...and before Grandpa could stop him, he hit the Enter key with his tail: puts "Here's the original hash data." p munsters mess_with_demographics(munsters) puts "Here's the munsters hash now after this destructive method altered the data." p munsters # Did the family's data get ransacked, or did the mischief only mangle a local copy of the original hash? (why?) puts "Answer: That sneaky Spot messed with their original data and replaced it permanently with the revised values." ## Way to fix: # munsters = { # "Herman" => { "age" => 32, "gender" => "male" }, # "Lily" => { "age" => 30, "gender" => "female" }, # "Grandpa" => { "age" => 402, "gender" => "male" }, # "Eddie" => { "age" => 10, "gender" => "male" }, # "Marilyn" => { "age" => 23, "gender" => "female"} # } # def mess_with_demographics(demo_hash) # safe_hash = Marshal.load(Marshal.dump(demo_hash)) # safe_hash.values.each do |family_member| # family_member["age"] += 42 # family_member["gender"] = "other" # end # safe_hash # end # altered_hash = mess_with_demographics(munsters) # munsters # => {"Herman"=>{"age"=>32, "gender"=>"male"}, "Lily"=>{"age"=>30, "gender"=>"female"}, "Grandpa"=>{"age"=>402, "gender"=>"male"}, "Eddie"=>{"age"=>10, "gender"=>"male"}, "Marilyn"=>{"age"=>23, "gender"=>"female"}} # altered_hash # => {"Herman"=>{"age"=>74, "gender"=>"other"}, "Lily"=>{"age"=>72, "gender"=>"other"}, "Grandpa"=>{"age"=>444, "gender"=>"other"}, "Eddie"=>{"age"=>52, "gender"=>"other"}, "Marilyn"=>{"age"=>65, "gender"=>"other"}} <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_2.rb # How does count treat the block's return value? How can we find out? # ['ant', 'bat', 'caterpillar'].count do |str| # str.length < 4 # end result = ['ant', 'bat', 'caterpillar'].count do |str| str.length < 4 end p result #=> 2 # Answer: # In a block, count returns the number of elements yielding a true value. In this case, there are two # strings in the array with a length that's less than 4. <file_sep>/lesson_5_advanced_collections/exercise_3.rb # For each of these collection objects demonstrate how you would reference the letter 'g'. # arr1 = ['a', 'b', ['c', ['d', 'e', 'f', 'g']]] # arr2 = [{first: ['a', 'b', 'c'], second: ['d', 'e', 'f']}, {third: ['g', 'h', 'i']}] # arr3 = [['abc'], ['def'], {third: ['ghi']}] # hsh1 = {'a' => ['d', 'e'], 'b' => ['f', 'g'], 'c' => ['h', 'i']} # hsh2 = {first: {'d' => 3}, second: {'e' => 2, 'f' => 1}, third: {'g' => 0 arr1 = ['a', 'b', ['c', ['d', 'e', 'f', 'g']]] # Answer: arr1[2][1][3] # ------------------------------------------------------ # irb(main):001:0> arr1 = ['a', 'b', ['c', ['d', 'e', 'f', 'g']]] # => ["a", "b", ["c", ["d", "e", "f", "g"]]] # irb(main):002:0> arr1[2] # => ["c", ["d", "e", "f", "g"]] # irb(main):003:0> arr1[2][1] # => ["d", "e", "f", "g"] # irb(main):004:0> arr1[2][1][3] # => "g" arr2 = [{first: ['a', 'b', 'c'], second: ['d', 'e', 'f']}, {third: ['g', 'h', 'i']}] # Answer: arr2[1][:third][0] # ------------------------------------------------------ # irb(main):001:0> arr2 = [{first: ['a', 'b', 'c'], second: ['d', 'e', 'f']}, {third: ['g', 'h', 'i']}] # => [{:first=>["a", "b", "c"], :second=>["d", "e", "f"]}, {:third=>["g", "h", "i"]}] # irb(main):002:0> arr2[1] # => {:third=>["g", "h", "i"]} # irb(main):003:0> arr2[1][:third] # => ["g", "h", "i"] # irb(main):004:0> arr2[1][:third][0] # => "g" arr3 = [['abc'], ['def'], {third: ['ghi']}] # Answer: arr3[2][:third][0][0] # ------------------------------------------------------ # irb(main):001:0> arr3 = [['abc'], ['def'], {third: ['ghi']}] # => [["abc"], ["def"], {:third=>["ghi"]}] # irb(main):002:0> arr3[2] # => {:third=>["ghi"]} # irb(main):003:0> arr3[2][:third] # => ["ghi"] # irb(main):004:0> arr3[2][:third][0] # => "ghi" # irb(main):005:0> arr3[2][:third][0][0] # => "g" hsh1 = {'a' => ['d', 'e'], 'b' => ['f', 'g'], 'c' => ['h', 'i']} # Answer: hsh1['b'][1] # ------------------------------------------------------ # irb(main):001:0> hsh1 = {'a' => ['d', 'e'], 'b' => ['f', 'g'], 'c' => ['h', 'i']} # => {"a"=>["d", "e"], "b"=>["f", "g"], "c"=>["h", "i"]} # irb(main):002:0> hsh1['b'] # => ["f", "g"] # irb(main):003:0> hsh1['b'][1] # => "g" hsh2 = {first: {'d' => 3}, second: {'e' => 2, 'f' => 1}, third: {'g' => 0}} # Answer: hsh2[:third].key(0) # ------------------------------------------------------ # irb(main):001:0> hsh2 = {first: {'d' => 3}, second: {'e' => 2, 'f' => 1}, third: {'g' => 0}} # => {:first=>{"d"=>3}, :second=>{"e"=>2, "f"=>1}, :third=>{"g"=>0}} # irb(main):002:0> hsh2[:third] # => {"g"=>0} # irb(main):003:0> hsh2[:third].key(0) # => "g" <file_sep>/lesson_3/exercises_medium1/question5_medium1.rb # Question 5 # Alan wrote the following method, which was intended to show all of the factors of the input number: # def factors(number) # dividend = number # divisors = [] # begin # divisors << number / dividend if number % dividend == 0 # dividend -= 1 # end until dividend == 0 # divisors # end # Alyssa noticed that this will fail if you call this with an input of 0 or a negative number and asked Alan to change the loop. How can you change the loop construct (instead of using begin/end/until) to make this work? Note that we're not looking to find the factors for 0 or negative numbers, but we just want to handle it gracefully instead of raising an exception or going into an infinite loop. def factors(number) dividend = number divisors = [] while dividend > 0 do divisors << number / dividend if number % dividend == 0 dividend -= 1 end divisors end # Bonus 1 # What is the purpose of the number % dividend == 0 ? puts "Do not want any remainders." # Bonus 2 # What is the purpose of the second-to-last line in the method (the divisors before the method's end)? puts "This is the actual return value of the method. Otherwise will be nil." <file_sep>/oop_book/section_4/exercise_7.rb # Create a class 'Student' with attributes name and grade. Do NOT make the grade getter public, # so joe.grade will raise an error. Create a better_grade_than? method, that you can call # like so... # puts "Well done!" if joe.better_grade_than?(bob) class Student def initialize(name, grade) @name = name @grade = grade end def better_grade_than?(other_student) grade > other_student.grade end protected def grade @grade end end joe = Student.new('Joe', 70) bob = Student.new('Bob', 65) puts "Well done!" if joe.better_grade_than?(bob) <file_sep>/lesson_4_collections/Additional_Practice/exercise_2.rb # Add up all of the ages from the Munster family hash: ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237} # My Solution total = ages.values.inject(:+) p total # => 6174 # Alternate Solution total_ages = 0 ages.each { |_, age| total_ages += age } p total_ages <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_9.rb # What is the return value of map? Why? { a: 'ant', b: 'bear'}.map do |key, value| if value.size > 3 value end end # Answer: # => [nil, "bear"] # The return value of map is an array, which is the collection type that map always returns. Here # we get a nil for the first value because our if condition only evaluates to true when the length # is greater than 3. 'bear' is greater than 3 but 'ant' is not so the condition will evaluate to # false and value won't be returned. When none of the condition in an if statement is evaluated, # then the if statement returns nil. <file_sep>/lesson_3/exercises_medium1/question8_medium1.rb # Question 8 # In another example we used some built-in string methods to change the case of a string. A notably missing method is something provided in Rails, but not in Ruby itself...titleize! This method in Ruby on Rails creates a string that has each word capitalized as it would be in a title. # Write your own version of the rails titleize implementation. def titalize(string) new_string = string.split(' ') new_string.each do |word| word.capitalize! end new_string.join(' ') end p titalize("how now brown cow") #== "How Now Brown Cow" p titalize("Little red Corvette") #== "Little Red Corvette" <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_3.rb # What is the return value of reject? Why? # [1, 2, 3].reject do |num| # puts num # end # Answer: # => [1, 2, 3] # Reject returns a new array containing items where the block's value is "falsey". In this example, # by using puts num, you'll always return nil as puts always returns nil. So, because the return value # was false or nil, the element is selected and returned. <file_sep>/lesson_2/calculator.rb # Build a command line calculator program that does the following: # asks for two numbers # asks for the type of operation to perform: add, subtract, multiply or divide # displays the result require 'yaml' MESSAGES = YAML.load_file('calculator_messages.yml') # LANGUAGE = 'en' LANGUAGE = 'es' def messages(message, lang = 'en') MESSAGES[lang][message] end def prompt(message) puts "=> #{message}" end def integer?(input) input.to_i.to_s == input end def float?(input) input.to_f.to_s == input end def number?(input) integer?(input) || float?(input) end def selection_to_message(sel) case sel when '1' prompt(messages('add', LANGUAGE)) when '2' prompt(messages('subtract', LANGUAGE)) when '3' prompt(messages('multiply', LANGUAGE)) when '4' prompt(messages('divide', LANGUAGE)) end end prompt(messages('welcome', LANGUAGE)) name = '' loop do name = gets.chomp break unless name.empty? prompt(messages('valid_name', LANGUAGE)) end prompt(messages('greeting_part1', LANGUAGE) + name + messages('greeting_part2', LANGUAGE)) loop do # main loop first_number = '' loop do prompt(messages('valid_first_number', LANGUAGE)) first_number = gets.chomp break if number?(first_number) prompt(messages('number_error', LANGUAGE)) end second_number = '' loop do prompt(messages('valid_second_number', LANGUAGE)) second_number = gets.chomp break if number?(second_number) prompt(messages('number_error', LANGUAGE)) end prompt(messages('selection_instructions_1', LANGUAGE)) prompt(messages('selection_instructions_2', LANGUAGE)) prompt(messages('selection_instructions_3', LANGUAGE)) prompt(messages('selection_instructions_4', LANGUAGE)) prompt(messages('selection_instructions_5', LANGUAGE)) selection = '' loop do selection = gets.chomp break if %w(1 2 3 4).include?(selection) prompt(messages('valid_selection', LANGUAGE)) end prompt(selection_to_message(selection)) result = case selection when '1' first_number.to_f + second_number.to_f when '2' first_number.to_f - second_number.to_f when '3' first_number.to_f * second_number.to_f when '4' first_number.to_f / second_number.to_f end prompt(messages('result', LANGUAGE) + result.to_s) prompt(messages('keep_calculating', LANGUAGE)) answer = gets.chomp break unless answer.downcase.start_with?('y') end prompt(messages('goodbye', LANGUAGE)) <file_sep>/lesson_3/exercises_easy3.rb # Question 1 # Show an easier way to write this array: # flintstones = ["Fred", "Barney", "Wilma", "Betty", "BamBam", "Pebbles"] puts "Question 1: Answer" puts "flintstones = %w(<NAME> Wilma Betty BamBam Pebbles)" # Question 2 # How can we add the family pet "Dino" to our usual array: # flintstones = %w(<NAME> Wilma Betty BamBam Pebbles) puts "--------------------------------------" puts "Question 2: Answer" puts "flintstones << 'Dino'" # Question 3 # In the previous exercise we added Dino to our array like this: # flintstones = %w(<NAME> Wilma Betty BamBam Pebbles) # flintstones << "Dino" # We could have used either Array#concat or Array#push to add Dino to the family. # How can we add multiple items to our array? (Dino and Hoppy) puts "--------------------------------------" puts "Question 3: Answer" puts "flintstones.concat(%w(Dino Hoppy)) or flintstones.push('Dino').push('Hoppy')" # Question 4 # Shorten this sentence: # advice = "Few things in life are as important as house training your pet dinosaur." # ...remove everything starting from "house". # Review the String#slice! documentation, and use that method to make the return value "Few things in life are as important as ". But leave the advice variable as "house training your pet dinosaur.". # As a bonus, what happens if you use the String#slice method instead? puts "--------------------------------------" puts "Question 4: Answer" puts "advice.slice!(0, advice.index('house'))" puts "Bonus: if you use .slice instead of .slice!, the advice string will not mutate." # Question 5 # Write a one-liner to count the number of lower-case 't' characters in the following string: # statement = "The Flintstones Rock!" puts "--------------------------------------" puts "Question 5: Answer" puts "statement.count 't'" # Question 6 # Back in the stone age (before CSS) we used spaces to align things on the screen. If we had a 40 character wide table of Flintstone family members, how could we easily center that title above the table with spaces? # title = "Flintstone Family Members" puts "--------------------------------------" puts "Question 6: Answer" puts "title.center(40)" <file_sep>/oop_book/section_4/exercise_2.rb # Add a class variable to your superclass that can keep track of the number of objects created that inherit from the superclass. Create a method to print out the value of this class variable as well. class Vehicle attr_accessor :color attr_reader :year, :model @@number_of_vehicles = 0 def initialize(year, model, color) @year = year @model = model @color = color @current_speed = 0 @@number_of_vehicles += 1 end def self.gas_mileage(gallons, miles) puts "#{miles / gallons} miles per gallon of gas" end def self.number_of_vehicles @@number_of_vehicles end def speed_up(number) @current_speed += number puts "You push the gas and accelerate #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake an decelerate #{number} mph." end def current_speed puts "You are now going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Let's park this bad boy!" end def spray_paint(color) self.color = color puts "Your new #{color} paint job looks great!" end def to_s "This vehicle is a #{color} #{year} #{model}." end end class MyCar < Vehicle NUMBER_OF_DOORS = 4 def to_s "This car is a #{color} #{year} #{model}." end end class MyTruck < Vehicle NUMBER_OF_DOORS = 2 def to_s "This truck is a #{color} #{year} #{model}." end end car = MyCar.new('2016', 'Toyota Prius', 'blue') car2 = MyCar.new('2014', 'Chevy Impala', 'silver') truck = MyTruck.new('2016', 'Chevy Silverado', 'black') puts car puts car2 puts truck puts Vehicle.number_of_vehicles <file_sep>/lesson_3/exercises_medium3/question4_medium3.rb # Question 4 # To drive that last one home...let's turn the tables and have the string show a modified output, while the array thwarts the method's efforts to modify the caller's version of it. # def tricky_method_two(a_string_param, an_array_param) # a_string_param.gsub!('pumpkins', 'rutabaga') # an_array_param = ['pumpkins', 'rutabaga'] # end # my_string = "pumpkins" # my_array = ["pumpkins"] # tricky_method_two(my_string, my_array) # puts "My string looks like this now: #{my_string}" # puts "My array looks like this now: #{my_array}" p "My string looks like this now: rutabaga" p "My array looks like this now: ['pumpkins']" p "Note to remember here: With the Array#= assignment, our literal ['pumpkins', 'rutabaga'] array IS a new object, and we are setting the internal array variable equal to that new array literal object." <file_sep>/oop_book/section_2/exercise_2.rb # Add an accessor method to your MyCar class to change and view the color of your car. Then # add an accessor method that allows you to view, but not modify, the year of your car. class MyCar attr_accessor :color attr_reader :year def initialize(year, model, color) @year = year @model = model @color = color @current_speed = 0 end def speed_up(number) @current_speed += number puts "You push the gas and accelerate #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake an decelerate #{number} mph." end def current_speed puts "You are now going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Let's park this bad boy!" end end chevy = MyCar.new(2016, '<NAME>', 'black') puts chevy.color puts '---------------' chevy.color = 'red' puts chevy.color puts chevy.year <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_10.rb # What is the block's return value in the following code? Why? [1, 2, 3].map do |num| if num > 1 puts num else num end end # Answer: # => [1, nil, nil] # For the first element, the if condition evaluates to false which means num is the block's return value # for the iteration. For the rest of the elements in the array, num > 1 evaluates to true, which means # puts num is the last statement evaluated, which in turn, means that the block's return value is nil # for those iterations (because puts always returns nil). <file_sep>/lesson_2/pseudocode.rb # For example, write out pseudo-code (both casual and formal) that does the following: # 1. a method that returns the sum of two integers # 2. a method that takes an array of strings, and returns a string that is all those strings concatenated together # 3. a method that takes an array of integers, and returns a new array with every other element # 1. # START # add two numbers and print total # END # def sum(num1, num2) # sum = num1 + num2 # end # p sum(20, 5) # 2. # START # GET multiple strings (array of strings) # add together and print (return) 1 string # END # def concat_string(array) # concat_string = array.join(' ') # end # p concat_string(['hello', 'world', 'hi']) # 3. # START # GET multiple numbers (array of integers) # return every other one -- [0 no, 1 yes, 2 no, 3 yes, etc] # PRINT array with new numbers # END # def every_other_one(array) # array.select.with_index { |_, i| i.odd? } # end # p every_other_one([0, 1, 2, 3, 4, 5]) # p every_other_one([2, 4, 6, 8, 10, 12]) <file_sep>/oop_book/section_2/exercise_3.rb # You want to create a nice interface that allows you to accurately describe the action # you want your program to perform. Create a method called spray_paint that can be # called on an object and will modify the color of the car. class MyCar attr_accessor :color attr_reader :year def initialize(year, model, color) @year = year @model = model @color = color @current_speed = 0 end def speed_up(number) @current_speed += number puts "You push the gas and accelerate #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake an decelerate #{number} mph." end def current_speed puts "You are now going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Let's park this bad boy!" end def spray_paint(color) self.color = color puts "Your new #{color} paint job looks great!" end end chevy = MyCar.new(2016, '<NAME>', 'black') puts chevy.color puts '---------------' chevy.spray_paint('yellow') puts chevy.color <file_sep>/lesson_3/exercises_hard1/question1_hard1.rb # Question 1 # What do you expect to happen when the greeting variable is referenced in the last line of the code below? # if false # greeting = “hello world” # end # p greeting p "Expect greeting to be nil. There's no method being called." <file_sep>/oop_lesson_2/classes_and_objects/exercise_5.rb # Continuing with our Person class definition, what does the below print out? # bob = Person.new("<NAME>") # puts "The person's name is: #{bob}" class Person attr_accessor :first_name, :last_name def initialize(full_name) parse_full_name(full_name) end def name "#{first_name} #{last_name}".strip end def name=(full_name) parse_full_name(full_name) end def to_s # Last change -- add a to_s method name end private def parse_full_name(full_name) parts = full_name.split self.first_name = parts.first self.last_name = parts.size > 1 ? parts.last : '' end end bob = Person.new("<NAME>") puts "The person's name is: #{bob}" # puts "The person's name is: #<Person:0x007f9441832d40>" bob will be the object since this is string interpolation. # Concatenation being used: # bob = Person.new("<NAME>") # puts "The person's name is: " + bob.name <file_sep>/lesson_3/exercises_hard1/question3_hard1.rb # def mess_with_vars(one, two, three) # one = two # two = three # three = one # end # one = "one" # p one.object_id # two = "two" # p two.object_id # three = "three" # p three.object_id # mess_with_vars(one, two, three) # puts "one is: #{one}" # puts "two is: #{two}" # puts "three is: #{three}" p "Answer: Section A" p "one is: one" p "two is: two" p "three is: three" p "---------------------------" # def mess_with_vars(one, two, three) # one = "two" # two = "three" # three = "one" # end # one = "one" # two = "two" # three = "three" # mess_with_vars(one, two, three) # puts "one is: #{one}" # puts "two is: #{two}" # puts "three is: #{three}" p "Answer: Section B" p "one is: one" p "two is: two" p "three is: three" p "---------------------------" # def mess_with_vars(one, two, three) # one.gsub!("one","two") # two.gsub!("two","three") # three.gsub!("three","one") # end # one = "one" # two = "two" # three = "three" # mess_with_vars(one, two, three) # puts "one is: #{one}" # puts "two is: #{two}" # puts "three is: #{three}" p "Answer: Section C" p "one is: two" p "two is: three" p "three is: one" <file_sep>/lesson_3/exercises_easy1.rb # Question 1 # What would you expect the code below to print out? # numbers = [1, 2, 2, 3] # numbers.uniq # puts numbers puts "Question 1: Answer" puts "Expect to see: 1 2 2 3" # Question 2 # Describe the difference between ! and ? in Ruby. And explain what would happen in the following scenarios: puts "--------------------------------------" puts "Question 2: Answers" # what is != and where should you use it? puts "!= means 'not equal' and you would use it in conditional statements." # put ! before something, like !user_name puts "An exclamation point before something means 'not' so here it means not user_name." # put ! after something, like words.uniq! puts "An exclamation point after something might indicate a destructive action, be Ruby syntax (like .uniq! here), or it could just be part of the name." # put ? before something puts "? : would be ternary operator for if...else." # put ? after something puts "A question mark after something might be Ruby syntax or just part of the name." # put !! before something, like !!user_name puts "Double exclamation points will turn something into its boolean equivalent." # Question 3 # Replace the word "important" with "urgent" in this string: # advice = "Few things in life are as important as house training your pet dinosaur." puts "--------------------------------------" puts "Question 3: Answer" puts "advice.gsub!(/important/, 'urgent')" # Question 4 # The Ruby Array class has several methods for removing items from the array. Two of them have very similar names. Let's see how they differ: # numbers = [1, 2, 3, 4, 5] # What does the follow method calls do (assume we reset numbers to the original array between method calls)? puts "--------------------------------------" puts "Question 4: Answers" puts "numbers.delete_at(1) => [1, 3, 4, 5]" puts "This will delete the number at index 1 in the array. The number 2 from the array in this example." puts "numbers.delete(1) => [2, 3, 4, 5]" puts "This will delete the number 1 in the array." # Question 5 # Programmatically determine if 42 lies between 10 and 100. # hint: Use Ruby's range object in your solution. puts "--------------------------------------" puts "Question 5: Answer" puts "(10..100).cover?(42)" # Question 6 # Starting with the string: # famous_words = "seven years ago..." # show two different ways to put the expected "Four score and " in front of it. puts "--------------------------------------" puts "Question 6: Answers" puts '"Four score and " << famous_words' puts "famous_words.prepend('Four score and ')" # Question 7 # Fun with gsub: # def add_eight(number) # number + 8 # end # number = 2 # how_deep = "number" # 5.times { how_deep.gsub!("number", "add_eight(number)") } # p how_deep # This gives us a string that looks like a "recursive" method call: # "add_eight(add_eight(add_eight(add_eight(add_eight(number)))))" # If we take advantage of Ruby's Kernel#eval method to have it execute this string as if it were a "recursive" method call # eval(how_deep) # what will be the result? puts "--------------------------------------" puts "Question 7: Answer" puts 42 # Question 8 # If we build an array like this: # flintstones = ["Fred", "Wilma"] # flintstones << ["Barney", "Betty"] # flintstones << ["BamBam", "Pebbles"] # We will end up with this "nested" array: # ["Fred", "Wilma", ["Barney", "Betty"], ["BamBam", "Pebbles"]] # Make this into an un-nested array. puts "--------------------------------------" puts "Question 8: Answer" puts "flintstones.flatten!" # Question 9 # Given the hash below # flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 } # Turn this into an array containing only two elements: Barney's name and Barney's number puts "--------------------------------------" puts "Question 9: Answer" puts "flintstones.assoc('Barney')" # Question 10 # Given the array below # flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"] # Turn this array into a hash where the names are the keys and the values are the positions in the array. puts "--------------------------------------" puts "Question 10: Answer" puts 'flintstones_hash = {} flintstones.each_with_index do |name, index| flintstones_hash[name] = index end p flintstones_hash {"Fred"=>0, "Barney"=>1, "Wilma"=>2, "Betty"=>3, "Pebbles"=>4, "BamBam"=>5}' <file_sep>/lesson_3/exercises_medium2/question5_medium2.rb # Question 5 # What is the output of the following code? # answer = 42 # def mess_with_it(some_number) # some_number += 8 # end # new_answer = mess_with_it(answer) # p answer - 8 puts "Answer = 34. The output for new_answer is not being called here. If it were, new_answer would be 50." <file_sep>/oop_book/section_1/exercise_2.rb # What is a module? What is its purpose? How do we use them with our classes? Create a module for the class you created in exercise 1 and include it properly. puts "Module Definition:" puts "A module is a collection of behaviors that is useable in other classes via mixins. A module is 'mixed in' to a class using the reserved word 'include'. Modules are another way to achieve polymorphism in Ruby." puts '' puts "Module Purpose:" puts "A module lets you group reusable code into one place. You use modules in your classes by using the include reserved word, followed by the module name. Modules are also used as a namespace." puts '' module Meow end class CatPeople include Meow end fluffy = CatPeople.new <file_sep>/lesson_3/exercises_medium1/question3_medium1.rb # Question 3 # The result of the following statement will be an error: # puts "the value of 40 + 2 is " + (40 + 2) # Why is this and what are two possible ways to fix this? puts "You get the error 'TypeError: no implicit conversion of Fixnum into String' because (40 + 2) is an integer and is trying to be turned into a string." puts "----------------------------------------------------------" puts "First way to fix: make the equation a string with '.to_s'." puts "'the value of 40 + 2 is ' + (40 + 2).to_s" puts "----------------------------------------------------------" puts "Second way to fix: use string interpolation." # puts "the value of 40 + 2 is #{40 + 2}" <file_sep>/lesson_4_collections/Additional_Practice/exercise_8.rb # What happens when we modify an array while we are iterating over it? What would be output by this code? # numbers = [1, 2, 3, 4] # numbers.each do |number| # p number # numbers.shift(1) # end # Answer: # 1 # 3 # => [3, 4] # As you iterate over the array, you are mutating it (shift) so you end up dropping the first two values. # The removal of the first item in the first pass changes the value found for the second pass. # numbers = [1, 2, 3, 4] # numbers.each do |number| # p number # numbers.pop(1) # end # Answer: # 1 # 2 # => [1, 2] # As you iterate over the array, you are dropping the last two values (pop). You are shortening the array # with each pass. <file_sep>/oop_book/section_3/exercise_3.rb # When running the following code... # class Person # attr_reader :name # def initialize(name) # @name = name # end # end # bob = Person.new("Steve") # bob.name = "Bob" # We get the following error... # test.rb:9:in `<main>': undefined method `name=' for # #<Person:0x007fef41838a28 @name="Steve"> (NoMethodError) # Why do we get this error and how to we fix it? puts "You get this error because attr_reader only lets you get the name. It's a getter method." puts "To fix this error, you need to change it to attr_accessor or attr_writer so you can set the name." puts "You need a setter method which either one of these will do in this case." puts "However, attr_writer will not let you get the name--it's not a getter method." class Person attr_accessor :name def initialize(name) @name = name end end bob = Person.new("Steve") bob.name = "Bob" puts bob.name # Using attr_writer will not let you get the name so it would throw an error here. # exercise_3.rb:35:in `<main>': undefined method `name' for #<Person:0x007fdd6b833678 @name="Bob"> (NoMethodError) <file_sep>/lesson_5_advanced_collections/exercise_10.rb # Given the following data structure and without modifying the original array, use the map method # to return a new array identical in structure to the original but where the value of each integer # is incremented by 1. # [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] original = [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] new_array = original.map do |hsh| incremented_hash = {} hsh.each do |key, value| incremented_hash[key] = value + 1 end incremented_hash end p original p new_array # [{:a=>1}, {:b=>2, :c=>3}, {:d=>4, :e=>5, :f=>6}] # [{:a=>2}, {:b=>3, :c=>4}, {:d=>5, :e=>6, :f=>7}] <file_sep>/lesson_2/rock_paper_scissors.rb # Build a Rock Paper Scissors game. The game flow should go like this: the user makes a choice, # the computer makes a choice, the winner is displayed. VALID_CHOICES = %w(rock paper scissors lizard spock) INSTRUCTIONS = "Choose one: r = rock, p = paper, s = scissors, l = lizard, k = spock." RULES = <<-MSG RULES OF THE GAME: --------------------- * Scissors cuts Paper * Paper covers Rock * Rock crushes Lizard * Lizard poisons Spock * Spock smashes Scissors * Scissors decapitates Lizard * Lizard eats Paper * Paper disproves Spock * Spock vaporizes Rock * Rock crushes Scissors MSG BEATS = { 'rock' => %w(scissors lizard), 'paper' => %w(rock spock), 'scissors' => %w(paper lizard), 'lizard' => %w(spock paper), 'spock' => %w(scissors rock) } WINNING_SCORE = 5 def prompt(message) puts "=> #{message}" end def win?(first, second) BEATS[first].include?(second) end def player_picks(letter) case letter when 'r' then 'rock' when 'p' then 'paper' when 's' then 'scissors' when 'l' then 'lizard' when 'k' then 'spock' end end def display_results(player, computer) if win?(player, computer) prompt("You won a point.") elsif win?(computer, player) prompt("Computer won a point.") else prompt("It's a tie! No points given.") end end def clear_screen system('clear') || system('cls') end prompt("Welcome to Rock, Paper, Scissors, Lizard, Spock Game.") prompt('') prompt(RULES) prompt('') prompt("------------------------------------------------") prompt("The winner of each round gets a point.") prompt("#{WINNING_SCORE} points wins the game! Let's play!") prompt("------------------------------------------------") prompt('') loop do player_score = 0 computer_score = 0 prompt(INSTRUCTIONS) loop do choice = '' loop do choice = gets.chomp.downcase choice = player_picks(choice) if VALID_CHOICES.include?(choice) break else prompt("That's not a valid choice.") end end clear_screen computer_choice = VALID_CHOICES.sample prompt("You chose: #{choice}. The computer chose: #{computer_choice}.") display_results(choice, computer_choice) if win?(choice, computer_choice) player_score += 1 elsif win?(computer_choice, choice) computer_score += 1 end prompt('') prompt("------------------------------------------------") prompt('') prompt("Your score: #{player_score}.") prompt("The computer's score: #{computer_score}.") prompt('') prompt("------------------------------------------------") prompt('') prompt(INSTRUCTIONS) break if player_score >= WINNING_SCORE || computer_score >= WINNING_SCORE end if player_score == WINNING_SCORE prompt('') prompt("------------------------------------------------") prompt("| |") prompt("| YOU WON THE GAME :) |") prompt("| |") prompt("------------------------------------------------") prompt('') elsif computer_score == WINNING_SCORE prompt('') prompt("------------------------------------------------") prompt("| |") prompt("| YOU LOST THE GAME :( |") prompt("| |") prompt("------------------------------------------------") prompt('') end prompt("Select --> Y to play again. Q to quit.") answer = gets.chomp if answer.downcase.start_with?('q') break elsif answer.downcase.start_with?('y') clear_screen prompt("OK...starting a new game.") else prompt("Hmmm...I'm not sure what to do.") break end end prompt("Thanks for playing! Goodbye.") <file_sep>/lesson_3/exercises_medium1/question6_medium1.rb # Question 6 # Alyssa was asked to write an implementation of a rolling buffer. Elements are added to the rolling buffer and if the buffer becomes full, then new elements that are added will displace the oldest elements in the buffer. # She wrote two implementations saying, "Take your pick. Do you like << or + for modifying the buffer?". Is there a difference between the two, other than what operator she chose to use to add an element to the buffer? # def rolling_buffer1(buffer, max_buffer_size, new_element) # buffer << new_element # buffer.shift if buffer.size >= max_buffer_size # buffer # end # p rolling_buffer1(buffer, max_buffer_size, new_element) # def rolling_buffer2(input_array, max_buffer_size, new_element) # buffer = input_array + [new_element] # buffer.shift if buffer.size >= max_buffer_size # buffer # end # p rolling_buffer2(buffer, max_buffer_size, new_element) puts "Yes there is a difference between the two methods though the return value is the same." puts "rolling_buffer1 will modify the buffer array permanently with the new_element upon its completion." puts "rolling_buffer2 leaves the input_array alone, creating the new 'buffer' variable in the method where the new_element gets added." <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_6.rb # What is the return value of the following statement? Why? # ['ant', 'bear', 'caterpillar'].pop.size # Answer: # => 11 # Pop removes the last element from this array. Then, size evaluates the return value of the popped element. # So, in this case, the string 'caterpillar' is 11 characters long. <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_4.rb # What is the return value of each_with_object? Why? # ['ant', 'bear', 'cat'].each_with_object({}) do |value, hash| # hash[value[0]] = value # end # Answer: # => {"a"=>"ant", "b"=>"bear", "c"=>"cat"} # Each with object iterates the given block for each element with an arbitrary object given, and # returns the initially given object. # In this example, the object was modified within the block and now contains 3 key-value pairs. <file_sep>/lesson_4/twentyone.rb # Make a basic 52-card deck Twenty-One game SUITS = %w(club diamond heart spade).freeze VALUES = %w(Ace 2 3 4 5 6 7 8 9 10 Jack Queen King).freeze # Set max-values to constants so they could be changed later (41, 51 game, etc.) GAME_MAX = 21 DEALER_MAX = 17 WINNING_SCORE = 5 def initialize_deck SUITS.product(VALUES).shuffle end def start_game(deck, player, dealer) 2.times do deal_card(deck, player) deal_card(deck, dealer) end end def deal_card(deck, player) player << deck.shift end def total(cards) values = cards.map { |card| card[1] } sum = 0 values.each do |value| sum += if value == 'Ace' 11 elsif value.to_i == 0 # Jack, Queen, King 10 else value.to_i end end # Correct for multiple Aces values.count { |value| value == 'Ace' }.times do sum -= 10 if sum > 21 end sum end def display_cards(cards) cards.map { |_suit, value| value }.join(', ') end def blackjack?(cards) total(cards) == GAME_MAX end def busted?(cards) total(cards) > GAME_MAX end def compare_cards(dealer, player) player_total = total(player) dealer_total = total(dealer) if player_total > GAME_MAX :player_busted elsif dealer_total > GAME_MAX :dealer_busted elsif dealer_total < player_total :player elsif dealer_total > player_total :dealer else :tie end end def display_compare_cards(dealer, player) result = compare_cards(dealer, player) case result when :player_busted prompt("You busted. Dealer wins!") when :dealer_busted prompt("Dealer busted. Player wins!") when :player prompt("You win!") when :dealer prompt("Dealer wins!") when :tie prompt("It's a tie!") end end def score_game(winner, score) if winner == :player || winner == :dealer_busted score[:player] += 1 elsif winner == :dealer || winner == :player_busted score[:dealer] += 1 end end def display_score(score) score.each_pair do |key, value| puts "#{key.capitalize} => #{value}" end end def play_again? prompt('') prompt("Select --> Y to play again. Q to quit.") answer = gets.chomp if answer.downcase.start_with?('q') prompt("Thanks for playing Twenty-One! Goodbye.") exit elsif answer.downcase.start_with?('y') clear_screen prompt("OK...starting a new game.") return else prompt("Hmmm...I'm not sure what to do.") prompt("Thanks for playing Twenty-One! Goodbye.") exit end end def prompt(message) puts "=> #{message}" end def clear_screen system('clear') || system('cls') end prompt("Welcome to Twenty-One.") prompt("For each round the winner gets a point.") prompt("First one to #{WINNING_SCORE} wins!") sleep(2.5) loop do score = { player: 0, dealer: 0 } loop do # Initialize deck and players deck = initialize_deck players_hand = [] dealers_hand = [] start_game(deck, players_hand, dealers_hand) prompt('') prompt("The dealer shows: #{dealers_hand[0][1]}.") prompt("---------------------------------------------") prompt("You have: #{display_cards(players_hand)}.") prompt("Your current total is #{total(players_hand)}.") prompt('') if blackjack?(players_hand) prompt("Blackjack!") prompt('') prompt("Dealer has: #{display_cards(dealers_hand)}.") prompt('') display_compare_cards(dealers_hand, players_hand) score_game(compare_cards(dealers_hand, players_hand), score) display_score(score) score[:player] == WINNING_SCORE ? break : next end loop do # Player's turn player_turn = nil loop do prompt("Select 'h' to Hit and get another card.") prompt("Choose 's' to Stay with your current total.") player_turn = gets.chomp.downcase break if ['h', 's'].include?(player_turn) prompt "Sorry, must enter 'h' or 's'." end if player_turn.start_with?('h') clear_screen deal_card(deck, players_hand) prompt("You chose to hit!") prompt('') prompt("You have: #{display_cards(players_hand)}.") prompt("Your current total is #{total(players_hand)}.") prompt('') end break if player_turn.start_with?('s') || busted?(players_hand) end if busted?(players_hand) display_compare_cards(dealers_hand, players_hand) score_game(compare_cards(dealers_hand, players_hand), score) display_score(score) if score.values.include?(WINNING_SCORE) break else next end else prompt("You've chosen to stay with #{total(players_hand)}.") prompt('') end prompt("Dealer turn...") loop do break if busted?(dealers_hand) || total(dealers_hand) >= DEALER_MAX prompt("The dealer hits.") deal_card(deck, dealers_hand) prompt("Dealer has: #{display_cards(dealers_hand)}.") prompt('') sleep(2) end dealer_total = total(dealers_hand) if busted?(dealers_hand) prompt("Dealer's current total is: #{dealer_total}.") else prompt("Dealer stays at #{dealer_total}.") end # rubocop:disable LineLength prompt('') prompt("----------------------------------------------------") prompt("Dealer has #{display_cards(dealers_hand)}, for a total of: #{dealer_total}.") prompt("Player has #{display_cards(players_hand)}, for a total of: #{total(players_hand)}.") prompt("----------------------------------------------------") prompt('') # rubocop:enable LineLength display_compare_cards(dealers_hand, players_hand) score_game(compare_cards(dealers_hand, players_hand), score) display_score(score) sleep(5) clear_screen break if score.values.include?(WINNING_SCORE) end if score[:player] == WINNING_SCORE prompt("You won the game!") else prompt("The dealer won!") end play_again? end <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_5.rb # What does shift do in the following code? How can we find out? hash = { a: 'ant', b: 'bear'} hash.shift # Answer: # Hash shift removes a key-value pair from hsh and returns it as the two-item array -- [:a, "ant"] in # this example -- or the hash's default value if the hash is empty -- nil. <file_sep>/lesson_3/exercises_medium1/question4_medium1.rb # Question 4 # What happens when we modify an array while we are iterating over it? What would be output by this code? # numbers = [1, 2, 3, 4] # numbers.each do |number| # p number # numbers.shift(1) # end # numbers = [1, 2, 3, 4] # numbers.each_with_index do |number, index| # p "#{index} #{numbers.inspect} #{number}" # numbers.shift(1) # end puts "Iterates through array so puts first number(1 here). Then shift will remove the first item from the array. This alters the array. The loop counter used by #each is compared against the current length of the array rather than its original length, making 3 the next number to print." puts " The output is: 1 3 " # What would be output by this code? # numbers = [1, 2, 3, 4] # numbers.each do |number| # p number # numbers.pop(1) # end puts "Iterates through array so puts first number 1. Then pop will remove the last item from the array--4. 2 prints next while 3 gets popped off the array so there are no more numbers to cycle through here." puts " 1 2 " <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_8.rb # How does take work? Is it destructive? How can we find out? arr = [1, 2, 3, 4, 5] arr.take(2) # Answer: # => [1, 2] # Array#take selects the specified number of elements (2 for this example) from an array. # It is not destructive. # irb(main):001:0> arr = [1, 2, 3, 4, 5] # => [1, 2, 3, 4, 5] # irb(main):002:0> arr.take(2) # => [1, 2] # irb(main):003:0> arr # => [1, 2, 3, 4, 5] # irb(main):004:0> <file_sep>/lesson_2/loan_calculator.rb # Build a mortgage calculator. You'll need three pieces of information: # 1) the loan amount, 2) the Annual Percentage Rate (APR), 3) the loan duration require 'yaml' MESSAGES = YAML.load_file('loan_messages.yml') LANGUAGE = 'en' def messages(message, lang = 'en') MESSAGES[lang][message] end def prompt(message) puts "=> #{message}" end def to_float(number_string) Float(number_string) rescue ArgumentError nil end def validate_loan(loan_amount) loan_amount_as_float = to_float(loan_amount) if loan_amount_as_float && loan_amount.to_f > 0 loan_amount.to_f.to_s else # For letters/words prompt(messages('loan_error', LANGUAGE)) end loan_amount_as_float end def validate_apr(apr) apr_as_float = to_float(apr) if apr_as_float prompt(messages('interest_free', LANGUAGE)) unless apr_as_float > 0.0 else prompt(messages('apr_error', LANGUAGE)) end apr_as_float end def validate_years(years) years_to_float = to_float(years) if years_to_float && years.to_f > 0 years.to_f.to_s else prompt(messages('years_error', LANGUAGE)) end end def clear_screen system('clear') || system('cls') end prompt(messages('welcome', LANGUAGE)) prompt(messages('usage', LANGUAGE)) loop do loan_amount = '' apr = '' years = '' loop do # Ask user for loan amount prompt(messages('enter_loan_amount', LANGUAGE)) loan_amount = gets.chomp loan_amount.delete!('$,') # If added, remove $ and , from value validate_loan(loan_amount) break if loan_amount.to_f > 0 end prompt(messages('value_confirmation', LANGUAGE) + format('$%.2f', loan_amount)) loop do # Ask user for Annual Percentage Rate prompt(messages('enter_apr', LANGUAGE)) apr = gets.chomp apr.delete!('%') # If added, remove % from value validate_apr(apr) break if apr.to_f > 0 || apr.eql?('0') || apr.eql?('0.0') end prompt(messages('value_confirmation', LANGUAGE) + apr + '%.') prompt(messages('years_greeting', LANGUAGE)) loop do # Ask user for number of years (loan duration) prompt(messages('enter_years', LANGUAGE)) years = gets.chomp validate_years(years) break if years.to_f > 0 end prompt(messages('value_confirmation', LANGUAGE) + years + ' years.') annual_rate = apr.to_f / 100 monthly_rate = annual_rate / 12 months = years.to_f * 12 calculated_payment = if annual_rate == 0 loan_amount.to_f / months else (monthly_rate * loan_amount.to_f) / (1 - ((1 + monthly_rate)**-months)) end prompt(messages('payment', LANGUAGE) + format('$%.2f', calculated_payment)) prompt(messages('instructions', LANGUAGE)) answer = gets.chomp if answer.downcase.start_with?('q') break elsif answer.downcase.start_with?('y') prompt(messages('new_calculation', LANGUAGE)) clear_screen else prompt(messages('instructions_help', LANGUAGE)) break end end prompt(messages('goodbye', LANGUAGE)) <file_sep>/oop_lesson_2/inheritance/exercise_2.rb # Let's create a few more methods for our Dog class. # class Dog # def speak # 'bark!' # end # def swim # 'swimming!' # end # def run # 'running!' # end # def jump # 'jumping!' # end # def fetch # 'fetching!' # end # end # Create a new class called Cat, which can do everything a dog can, except swim or fetch. Assume the methods do the exact same thing. Hint: don't just copy and paste all methods in Dog into Cat; try to come up with some class hierarchy. class Pet def run 'running!' end def jump 'jumping!' end end class Dog < Pet def speak 'bark!' end def swim 'swimming!' end def fetch 'fetching!' end end class Bulldog < Dog def swim "can't swim!" end end class Cat < Pet def speak 'meow!' end end hammy = Pet.new puts hammy.run puts hammy.jump fido = Dog.new puts fido.speak puts fido.fetch puts fido.swim puts fido.run puts fido.jump bud = Bulldog.new puts bud.speak puts bud.swim socks = Cat.new puts socks.speak puts socks.run puts socks.jump puts socks.fetch # Should generate no method error here <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_1.rb # What is the return value of the select method below? Why? [1, 2, 3].select do |num| num > 5 'hi' end # Answer: # => [1, 2, 3] # Select uses the truthiness of the block's return value. Because the return value of 'hi' on line 5 in this example is a truthy value, it will return the original array. # If you removed 'hi', you'd get an empty array because there are no numbers greater than 5. # => [] <file_sep>/oop_book/section_1/exercise_1.rb # How do we create an object in Ruby? Give an example of the creation of an object. class CatPeople end fluffy = CatPeople.new <file_sep>/lesson_3/exercises_easy2.rb # Question 1 # In this hash of people and their age, # ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } # see if there is an age present for "Spot". # Bonus: What are two other hash methods that would work just as well for this solution? puts "Question 1: Answers" puts "ages.key?('Spot')" puts "ages.include?('Spot')" puts "ages.member?('Spot')" # Question 2 # Add up all of the ages from our current Munster family hash: # ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } puts "--------------------------------------" puts "Question 2: Answer" puts "ages.values.reduce(:+)" # Question 3 # In the age hash: # ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } # throw out the really old people (age 100 or older). puts "--------------------------------------" puts "Question 3: Answer" puts "My solution => ages.reject! {|key, value| value > 100}" puts "Exercise solution => ages.keep_if { |_, age| age < 100 }" # Question 4 # Starting with this string: # munsters_description = "The Munsters are creepy in a good way." # Convert the string in the following ways (code will be executed on original munsters_description above): puts "--------------------------------------" puts "Question 4: Answers" # "The munsters are creepy in a good way." puts "munsters_description.capitalize!" # "tHE mUNSTERS ARE CREEPY IN A GOOD WAY." puts "munsters_description.swapcase!" # "the munsters are creepy in a good way." puts "munsters_description.downcase!" # "THE MUNSTERS ARE CREEPY IN A GOOD WAY." puts "munsters_description.upcase!" # Question 5 # We have most of the Munster family in our age hash: # ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10 } # add ages for Marilyn and Spot to the existing hash # additional_ages = { "Marilyn" => 22, "Spot" => 237 } puts "--------------------------------------" puts "Question 5: Answer" puts "ages.merge!(additional_ages)" # Question 6 # Pick out the minimum age from our current Munster family hash: # ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } puts "--------------------------------------" puts "Question 6: Answer" puts "ages.values.min" # Question 7 # See if the name "Dino" appears in the string below: # advice = "Few things in life are as important as house training your pet dinosaur." puts "--------------------------------------" puts "Question 7: Answer" puts "advice.match('Dino')" # Question 8 # In the array: # flintstones = %w(<NAME> Wilma Betty BamBam Pebbles) # Find the index of the first name that starts with "Be" puts "--------------------------------------" puts "Question 8: Answer" puts "flintstones.index { |name| name[0, 2] == 'Be' }" # Question 9 # Using array#map!, shorten each of these names to just 3 characters: # flintstones = %w(<NAME> BamBam Pebbles) puts "--------------------------------------" puts "Question 9: Answer" puts "flintstones.map! do |name|" puts " name[0, 3]" puts "end" # Question 10 # Again, shorten each of these names to just 3 characters -- but this time do it all on one line: # flintstones = %w(<NAME> <NAME> BamBam Pebbles) puts "--------------------------------------" puts "Question 10: Answer" puts "flintstones.map! { |name| name[0, 3] }" <file_sep>/oop_lesson_2/inheritance/exercise_4.rb # What is the method lookup path and how is it important? puts "The method lookup path is the order in which Ruby will traverse the class hierarchy to look for methods to invoke." puts "For example, if you have a Bulldog object called bud and you call: bud.swim. Ruby will first look for a method called swim in the Bulldog class, then traverse up the chain of super-classes; it will invoke the first method called swim and stop its traversal." puts "Use the .ancestors class method to see the lookup path (i.e. Bulldog.ancestors)." class Pet def run 'running!' end def jump 'jumping!' end end class Dog < Pet def speak 'bark!' end def swim 'swimming!' end def fetch 'fetching!' end end class Bulldog < Dog def swim "can't swim!" end end class Cat < Pet def speak 'meow!' end end puts "------------------" p Bulldog.ancestors <file_sep>/lesson_4_collections/Exercises_Methods_and_Sorting/exercise_7.rb # What is the block's return value in the following code? How is it determined? [1, 2, 3].any? do |num| puts num num.odd? end # Answer: # => true # The return value of the block is determined by the return value of the last experession within the block. # In this case, the last statement evaluated is num.odd? which returns a boolean. In this example, # the block's return value will be a boolean since Fixnum#odd? can only return true or false. <file_sep>/lesson_4_collections/Nested_Collections/exercise_3.rb # Given this code, what would be the final values of a and b? Try to work it out without running the code. a = 2 b = [5, 8] arr = [a, b] arr[0] += 2 arr[1][0] -= a # Answer: # The value of a is still 2 since it was never modified. The a value in arr was changed because arr[0] += 2 # added 2 to that value making it 4. The value of b was modified because it is an array and the value # at index 0 was changed -- arr[1][0] -= a or 5 - 2. # irb(main):001:0> a = 2 # => 2 # irb(main):002:0> b = [5, 8] # => [5, 8] # irb(main):003:0> arr = [a, b] # => [2, [5, 8]] # irb(main):004:0> # irb(main):005:0* arr[0] += 2 # => 4 # irb(main):006:0> arr[1][0] -= a # => 3 # irb(main):007:0> a # => 2 # irb(main):008:0> b # => [3, 8] # irb(main):009:0> arr # => [4, [3, 8]] <file_sep>/oop_book/section_4/exercise_8.rb # Given the following code... # bob = Person.new # bob.hi # And the corresponding error message... # NoMethodError: private method `hi' called for #<Person:0x007ff61dbb79f0> # from (irb):8 # from /usr/local/rvm/rubies/ruby-2.0.0-rc2/bin/irb:16:in `<main>' # What is the problem and how would you go about fixing it? # Problem ==> hi is a private method in the Person class, and it's trying to be called outside the class. # Fixing this issue class Person def public_hi hi end private def hi puts "hi" end end bob = Person.new bob.public_hi
394209c49b6fcb2562f4d2e66325d1c0cf5df91d
[ "Ruby", "YAML" ]
46
Ruby
a-woodworth/ls_projects
b02bf4917a6797475468c06408eaf974ace81cf7
f887368079fbc2f44ea3f25378c99583027359e1
refs/heads/master
<file_sep># conversor-de-moedas Uma pequena aplicação para conversão de moedas <file_sep> <?php $servername = "localhost"; $username = "id2877829_convert"; $password = "<PASSWORD>"; $dbname = "id2877829_conversordemoedas"; // Criando conexão $conn = new mysqli($servername, $username, $password,$dbname); // Checando a conexão if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //consultando taxas das moedas no banco de dados $sql = "SELECT jsonTaxas, dataAtualizacao FROM taxaMoedas"; $result = $conn->query($sql); // verificando se algum resultado foi encontrado if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { if($row["dataAtualizacao"] < date("Y-m-d H:i:s",strtotime('-30 minutes'))){ // consultando api das taxas $json =file_get_contents('https://openexchangerates.org/api/latest.json?app_id=fd73872f21184dd9b888597a236f6eda'); //montando query para atualização das taxas no banco $sql = "UPDATE taxaMoedas SET jsonTaxas='$json',dataAtualizacao='" . date("Y-m-d H:i:s") . "' WHERE id=1"; //executando a query para atualização do banco de dados if($conn->query($sql) === TRUE) { echo json_decode($json); }else{ echo "erro"; } }else{ echo $row["jsonTaxas"]; } } }else{ echo "nenhuma resultado encontrado"; } ?>
be464cda291f34f825bbae3b14236c2d6ee317c7
[ "Markdown", "PHP" ]
2
Markdown
samirfreitas/conversor-de-moedas
ed2aa01a9075e4b4e22d426cb539a18d463d49f1
7cdda7a2bb51b557958777021d2ed3321891aa0a
refs/heads/master
<file_sep># DP 此项目为解析一个气象文件,封装成对象并存入数据库
37e8fabfe9ef8f19e0d0c91e1236e2ebde6275db
[ "Markdown" ]
1
Markdown
JzlLx/DP
e2e73ad41661ecf7196830a3d20d7dea39570411
698090eb897cfd1b9b3c2ba8d7f2d79ba0645ca4
refs/heads/master
<file_sep># single-page-web-applications-with-angularjs [Edit on StackBlitz ⚡️](https://stackblitz.com/edit/single-page-web-applications-with-angularjs)
24aaf4a192dc96f69c8d968f9cbd05d761eff5fa
[ "Markdown" ]
1
Markdown
a13dd1234/single-page-web-applications-with-angularjs
7b76ec0eb3e18a7a5a2c1790f8c664dc34227ceb
601ad64ce58840a9ecbac1620007bdb81cc0a929
refs/heads/master
<repo_name>Ashish-Arya-CS/Movie-Recommender-System<file_sep>/README.md # Movie-Recommender-System A recommender system, or a recommendation system, is a subclass of information filtering system that seeks to predict the "rating" or "preference" a user would give to an item. They are primarily used in commercial applications.I have tried to build such models via two approach.First one using cosine similarity and the other one using SVD algorithm available in scikit learn.
6816495e2b19c5ba742c10979ef8962bf9f14424
[ "Markdown" ]
1
Markdown
Ashish-Arya-CS/Movie-Recommender-System
2dce2532cc97c6213bc7f74474d5fe5752acd775
d1d138442684db8960b135e52608e1a72b1ebdf9
refs/heads/main
<file_sep>-- EXERCÍCIO 13: -- Saber quantas pessoas tem o mesmo MiddleName agrupadas por o Middlename. SELECT MiddleName, COUNT(MiddleName) AS "TOTAL" FROM Person.Person GROUP BY MiddleName -- EXERCÍCIO 14: -- Saber em média qual a quantidade que cada produto é vendido na loja. SELECT ProductID, AVG(OrderQty) AS MEDIA FROM Sales.SalesOrderDetail GROUP BY ProductID -- EXERCÍCIO 15: /* Saber qual foram as 10 vendas que no total tiveram os maiores valores de venda por produto do maior valor para o menor. */ SELECT TOP 10 ProductID, SUM(LineTotal) AS "VENDA TOTAL" FROM Sales.SalesOrderDetail GROUP BY ProductID ORDER BY [VENDA TOTAL] DESC -- EXERCÍCIO 16: /* Saber quantos produtos e qual a quantidade média de produtos temos cadastrados nas nossas ordens de serviço, agrupados por ProductId. */ SELECT ProductID, COUNT(ProductID) AS CONTAGEM, AVG(OrderQty) AS MEDIA FROM Production.WorkOrder GROUP BY ProductID -- EXERCÍCIO 17: /* Identificar as províncias com o maior número de cadastros no nosso sistema, então é preciso encontrar quais províncias estão registradas no banco de dados mais que 1000 vezes. */ SELECT StateProvinceID, COUNT(StateProvinceID) AS TOTAL FROM Person.Address GROUP BY StateProvinceID HAVING COUNT(StateProvinceID) > 1000 -- EXERCÍCIO 18: -- Os gerentes querem saber quais produtos não estão trazendo em média no mínimo 1 milhão em total de vendas SELECT ProductID, AVG(LineTotal) AS TOTAL FROM Sales.SalesOrderDetail GROUP BY ProductID HAVING AVG(LineTotal) < 1000000<file_sep>-- Exercício 6: -- Quantos produtos temos cadastrados em nossa tabela de produtos. SELECT COUNT(*) FROM Production.Product; -- Exercício 7: -- Quantos tamanhos de produtos temos cadastrados em nossa tabela. SELECT COUNT(Size) FROM Production.Product; -- Exercício 8: -- Quantos tamanhos diferentes de produtos eu tenho cadastrado em nossa tabela. SELECT COUNT(DISTINCT Size) FROM Production.Product; -- Exercício 9: /* Obter o ProductId dos 10 produtos mais caros cadastrados no sistema, listando do mais caro para o mais barato. */ SELECT TOP 10 ProductID FROM Production.Product ORDER BY ListPrice desc -- Exercício 9: -- Obter o nome e número do produto dos produtos que tem o ProductId entre 1~4 SELECT TOP 4 Name, ProductNumber FROM Production.Product ORDER BY ProductID asc<file_sep>-- EXERCÍCIO 28: /* 1. Criar uma tabela nova. 2. Inserir uma linha de dados nessa tabela. 3. Inserir 3 linhas de dados de uma vez. 4. Criar uma segunda tabela. 5. Inserir uma linha nessa nova tabela. 6. Copiar os dados da segunda tabela para a primeira. */ CREATE TABLE PrimeiraTabela ( IdPrimeiraTabela INT PRIMARY KEY, NomePrimeiraTabela VARCHAR(50) NOT NULL, DataCriacao DATETIME DEFAULT GETDATE() ) SELECT * FROM PrimeiraTabela INSERT INTO PrimeiraTabela(IdPrimeiraTabela, NomePrimeiraTabela) VALUES (1, '<NAME>') INSERT INTO PrimeiraTabela (IdPrimeiraTabela, NomePrimeiraTabela) VALUES (2, '<NAME>'), (3, '<NAME>'), (4, '<NAME>'); CREATE TABLE SegundaTabela( IdSegundaTabela INT PRIMARY KEY, NomeSegundaTabela VARCHAR(50) NOT NULL ) SELECT * FROM SegundaTabela INSERT INTO SegundaTabela(IdSegundaTabela, NomeSegundaTabela) VALUES (5, '<NAME>') INSERT INTO PrimeiraTabela (IdPrimeiraTabela, NomePrimeiraTabela) SELECT IdSegundaTabela, NomeSegundaTabela FROM SegundaTabela<file_sep>-- OUTER JOIN ou LEFT JOIN -- Descobrir quais pessoas têm um cartão de crédito registrado. SELECT * FROM Person.Person PP INNER JOIN Sales.PersonCreditCard SPCC ON PP.BusinessEntityID = SPCC.BusinessEntityID -- INNER JOIN: 19.118 SELECT * FROM Person.Person PP LEFT JOIN Sales.PersonCreditCard SPCC ON PP.BusinessEntityID = SPCC.BusinessEntityID -- LEFT JOIN: 19.972 -- LEFT JOIN - INNER JOIN = 19.972 - 19.118 = 854 SELECT * FROM Person.Person PP LEFT JOIN Sales.PersonCreditCard SPCC ON PP.BusinessEntityID = SPCC.BusinessEntityID WHERE SPCC.BusinessEntityID IS NULL -- UNION: Combina dois ou mais resultados de um SELECT em um resultado apenas removendo os dados duplicados -- Exemplo 1: SELECT [ProductID], [Name], [ProductNumber] FROM Production.Product WHERE Name LIKE '%Chain%' UNION SELECT [ProductID], [Name], [ProductNumber] FROM Production.Product WHERE Name LIKE '%Decal%' -- Exemplo 2: SELECT FirstName, Title, MiddleName FROM Person.Person WHERE Title LIKE 'Mr.' UNION SELECT FirstName, Title, MiddleName FROM Person.Person WHERE MiddleName LIKE 'A' -- SELF JOIN: É obrigatório o uso de alias. -- Todos os clientes que moram na mesma região. SELECT A.ContactName, A.Region, B.ContactName, B.Region FROM Customers A, Customers B WHERE A.Region = B.Region -- Encontrar nome e data de contratação de todos os funcionários que foram contratados no mesmo ano SELECT A.FirstName, A.HireDate, B.FirstName, B.HireDate FROM Employees A, Employees B WHERE DATEPART(YEAR, A.HireDate) = DATEPART(YEAR, B.HireDate)<file_sep># Fundamentos SQL <img align="right" alt="png" src="https://st.depositphotos.com/1029663/1293/i/600/depositphotos_12931298-stock-photo-sql-coding.jpg" height="300" width="300"> <br> ⠀⠀⠀⠀Repositório destinado a amazenar os códigos dos conceitos e dos exercícios, por mim praticados, do básico ao avançado para consulta e criação de banco de dados por meio de SQL, além disso por aqui você também encontra os backups das bases de dados utilizadas. Todas as práticas aqui postadas foram realizadas no SQL Server Management Studio. ### Pode entrar, só não repara a bagunça!!😁 <file_sep>-- CREATE TABLE: Criação de Tabelas CREATE DATABASE YouTube; USE YouTube CREATE TABLE Canal ( IdCanal INT PRIMARY KEY, Nome VARCHAR(150) NOT NULL, ContagemInscritos INT DEFAULT 0, DataCriacao DATETIME NOT NULL ); SELECT * FROM Canal CREATE TABLE Video ( IdVideo INT PRIMARY KEY, Nome VARCHAR(150) NOT NULL, Visualizacoes INT DEFAULT 0, Likes INT DEFAULT 0, Dislikes INT DEFAULT 0, Duracao INT NOT NULL, IdCanal INT FOREIGN KEY REFERENCES Canal(IdCanal) ); SELECT * FROM Video -- INSERT INTO: Inserir dados em uma tabela ou criar uma tabela a partir de uma tabela existente CREATE TABLE Aula ( Id INT PRIMARY KEY, Nome VARCHAR(200) ) SELECT * FROM Aula INSERT INTO Aula (Id, Nome) VALUES (1, 'Aula 1'); INSERT INTO Aula (Id, Nome) VALUES (2, 'Aula 2'), (3, 'Aula 3'), (4, 'Aula 4'), (5, 'Aula 5'); -- CRIAR UMA TABELA A PARTIR DE UMA TABELA EXISTENTE SELECT * INTO tabelaNova FROM Aula SELECT * FROM tabelaNova<file_sep>-- EXERCÍCIO 24: SELECT BusinessEntityID, CreditCardID FROM Sales.PersonCreditCard WHERE ModifiedDate BETWEEN '2014-01-01 00:00:00.000' AND '2014-31-12 00:00:00.000' UNION SELECT BusinessEntityID, CreditCardID FROM Sales.PersonCreditCard WHERE ModifiedDate BETWEEN '2012-01-01 00:00:00.000' AND '2012-31-12 00:00:00.000' -- EXERCÍCIO 25: -- Saber, na tabela Detalhe do Pedido, quais produtos têm o mesmo percentual de desconto. SELECT A.ProductID, A.Discount, B.ProductID, B.Discount FROM [Order Details] A, [Order Details] B WHERE A.Discount = B.Discount<file_sep>-- EXERCICIO 29: -- Altere o nome de duas linhas diferentes. SELECT * FROM PrimeiraTabela UPDATE PrimeiraTabela SET NomePrimeiraTabela = 'EDITADO' WHERE IdPrimeiraTabela = 5 OR IdPrimeiraTabela = 3 -- EXERCÍCIO 30: /* Criar uma tabela nova com 3 colunas e depois: 1. Alterar o tipo de uma coluna. 2. Renomear o nome de uma coluna. 3. Renomear o nome da tabela criada. */ CREATE TABLE CanalYouTube ( IdCanal INT PRIMARY KEY, NomeCanal VARCHAR(50) NOT NULL UNIQUE, DescricaoCanal VARCHAR(200), DataCriacao DATETIME DEFAULT GETDATE(), Premium BIT DEFAULT 0, Inscritos INT DEFAULT 0, Likes INT DEFAULT 0, Dislikes INT DEFAULT 0 ) SELECT * FROM CanalYouTube ALTER TABLE CanalYouTube ALTER COLUMN DescricaoCanal VARCHAR(300) EXEC SP_RENAME 'CanalYouTube.Inscritos', 'InscritosCanal', 'COLUMN' EXEC SP_RENAME 'CanalYouTube', 'PerfilCanalYouTube' SELECT * FROM PerfilCanalYouTube -- EXERCÍCIO 31: -- Criar 2 tabelas novas e 1 restrição para cada tabela. USE YouTube CREATE TABLE EstadosBrasileiros( Id INT PRIMARY KEY, Nome VARCHAR(50) NOT NULL, Sigla VARCHAR(2) CHECK (LEN(Sigla) = 2) ) INSERT INTO EstadosBrasileiros VALUES (1, 'São Paulo', 'SP') SELECT * FROM EstadosBrasileiros CREATE TABLE DisciplinasFaculdade( Id INT PRIMARY KEY, Nome VARCHAR(100) NOT NULL, CargaHoraria INT NOT NULL CHECK (CargaHoraria >= 45 AND CargaHoraria <= 60), Professor VARCHAR(50) NOT NULL ) INSERT INTO DisciplinasFaculdade VALUES (1, 'Lógica de Programação', 60, '<NAME>') SELECT * FROM DisciplinasFaculdade<file_sep>-- UPDATE: Alterar linhas SELECT * FROM Aula UPDATE Aula SET Nome = 'Aulas - Essas linhas foram alteradas sem utilizar o WHERE' UPDATE Aula SET Nome = 'Aula 1 - Essa linha foi alterada usando o WHERE' WHERE Id = 1 -- DELETE: Deletar algum dado da tabela SELECT * FROM Aula DELETE FROM Aula WHERE ID = 4 -- ALTER TABLE: Adicionar, remover ou alterar uma coluna; Alterar valores padrões para uma coluna; Adicionar ou remover restrições de colunas; Renomear tabelas e colunas. CREATE TABLE YouTubeAlterado ( Id INT PRIMARY KEY, Nome VARCHAR(150) NOT NULL UNIQUE, Categoria VARCHAR(200) NOT NULL, DataCriacao DATETIME NOT NULL DEFAULT GETDATE() ) SELECT * FROM YouTubeAlterado -- ADICIONAR COLUNA ALTER TABLE YouTubeAlterado ADD Ativo BIT -- ALTERAR O TIPO DE UMA COLUNA ALTER TABLE YouTubeAlterado ALTER COLUMN Categoria VARCHAR(300) NOT NULL -- ALTERAR O NOME DE UMA COLUNA -- DEVE RODAR UMA PROCEDURE ESPECÍFICA PARA ISSO: -- EXEC sp_RENAME 'nomeTabela.nomeColunaAtual', 'nomeColunaNova', 'COLUMN' EXEC sp_RENAME 'YouTubeAlterado.Nome', 'nomeCanal', 'COLUMN' -- ALTERAR O NOME DA TABELA -- DEVE RODAR UMA PROCEDURE ESPEFÍCICA PARA ISSO: -- EXEC sp_RENAME 'NomeTabelaAtual', 'nomeTabelaNova' EXEC SP_RENAME 'YouTubeAlterado', 'YouTubeComNovoNome' SELECT * FROM YouTubeComNovoNome<file_sep>-- CRIAR UM BANCO DE DADOS: CREATE DATABASE DATABASE_TEST_2 -- DELETAR UM BANCO DE DADOS: DROP DATABASE DATABASE_TEST_2 -- SERVIDOR DO CURSO: -- .\SQLEXPRESS -- RESTAURAR UM BANCO DE DADOS: -- Botão direito DATABASE --> RESTORE DATABASE --> DEVICE --> ... --> ADD --> LOCALIZAR ARQUIVO DE RESTAURAÇÃO DISPONIBILIZADO PELO WINDOWS PARA TESTES(ANEXADO NESTE REPOSITÓRIO) - AdventureWorks2017 --> OK --> OK --> OK<file_sep>-- BETWEEN: Usado para encontrar valor entre um valor mínimo e um valor máximo. SELECT * FROM Production.Product WHERE ListPrice BETWEEN 1000 AND 1500; SELECT * FROM Production.Product WHERE ListPrice NOT BETWEEN 1000 AND 1500; SELECT * FROM HumanResources.Employee WHERE HireDate BETWEEN '2009/01/01' AND '2010/01/01' ORDER BY HireDate ASC -- IN: Verificar se um valor corresponde com qualquer valor passado na lista de valores. SELECT * FROM Person.Person WHERE BusinessEntityID IN (2, 7, 13) SELECT * FROM Person.Person WHERE BusinessEntityID NOT IN (2, 7, 13) -- LIKE: Busca uma informação parcial -- Conhece o início do nome SELECT * FROM Person.Person WHERE FirstName LIKE 'ovi%' -- Conhece o fim do nome SELECT * FROM Person.Person WHERE FirstName LIKE '%to' -- Conhece o meio do nome SELECT * FROM Person.Person WHERE FirstName LIKE '%essa%' -- Substituição de apenas 1 caractere SELECT * FROM Person.Person WHERE FirstName LIKE '%ro_'<file_sep>-- DROP TABLE /* DROP TABLE nomeTabela */ CREATE TABLE TabelaASerExcluida ( Id INT PRIMARY KEY, Descricao VARCHAR(50) ) SELECT * FROM TabelaASerExcluida -- EXCLUI TODA A TABELA DROP TABLE TabelaASerExcluida CREATE TABLE TabelaComDadosASeremExcluidos ( Id INT PRIMARY KEY, Descricao VARCHAR(50) ) SELECT * FROM TabelaComDadosASeremExcluidos INSERT INTO TabelaComDadosASeremExcluidos VALUES (1, 'Linha 1'), (2, 'Linha 2'); -- EXCLUI OS REGISTROS DE UMA TABELA TRUNCATE TABLE TabelaComDadosASeremExcluidos -- CHECK CONSTRAINT: Criar restrições de valores que podem ser inseridos em uma coluna na criação de uma tabela. CREATE TABLE CarteiraMotorista ( Id INT NOT NULL, Nome VARCHAR(255) NOT NULL, Idade INT CHECK (Idade >= 18) ); SELECT * FROM CarteiraMotorista INSERT INTO CarteiraMotorista VALUES (1, '<NAME>', 65) -- NOT NULL CONSTRAINT /* CREATE TABLE NomeTabela( coluna1 tipoDeDado NOT NULL, coluna2 tipoDeDado NOT NULL ) */ -- UNIQUE CONSTRAINT CREATE TABLE CarteiraDeMotorista( Id INT PRIMARY KEY, NomeCondutor VARCHAR(50) NOT NULL UNIQUE, Idade INT CHECK (Idade >= 18), CodigoCNH INT NOT NULL UNIQUE ) INSERT INTO CarteiraDeMotorista (Id, NomeCondutor, Idade, CodigoCNH) VALUES (1, '<NAME>', 45, 987654321), (2, '<NAME>', 42, 123456789); SELECT * FROM CarteiraDeMotorista -- VIEWS: CREATE VIEW [Pessoas Simplificado] AS SELECT FirstName, MiddleName, LastName FROM Person.Person WHERE Title = 'Ms.' SELECT * FROM [Pessoas Simplificado]<file_sep>-- MANIPULAÇÃO DE STRING -- CONCATENAR SELECT FirstName, LastName, CONCAT(FirstName, ' ' ,LastName) AS NOME_E_SOBRENOME FROM Person.Person -- MAIÚSCULAS E MINÚSCULAS SELECT FirstName, UPPER(FirstName) AS MAIÚSCULA FROM Person.Person SELECT FirstName, LOWER(FirstName) AS MINÚSCULA FROM Person.Person -- TAMANHO SELECT FirstName, LEN(FirstName) AS TAMANHO FROM Person.Person -- SUBSTRING SELECT FirstName, SUBSTRING(FirstName, 1, 3) AS REMOVENDO -- Começando do índice 1 e pegando 3 letras FROM Person.Person -- REPLACE SELECT ProductNumber, REPLACE(ProductNumber, '-', '#') AS SUBSTITUIR FROM Production.Product -----------------------------------------------//------------------------------------------------------------------ -- OPERAÇÕES MATEMÁTICAS -- SOMA SELECT UnitPrice, (UnitPrice + UnitPrice) AS SOMA FROM Sales.SalesOrderDetail -- SUBTRAÇÃO SELECT UnitPrice, (UnitPrice - UnitPrice) AS SUBTRAÇÃO FROM Sales.SalesOrderDetail -- MULTIPLICAÇÃO SELECT UnitPrice, (UnitPrice * UnitPrice) AS MULTIPLICAÇÃO FROM Sales.SalesOrderDetail -- DIVISÃO SELECT UnitPrice, (UnitPrice / UnitPrice) AS DIVISÃO FROM Sales.SalesOrderDetail -- MÉDIA SELECT AVG(UnitPrice) AS MÉDIA FROM Sales.SalesOrderDetail -- SOMA SELECT SUM(UnitPrice) AS SOMA FROM Sales.SalesOrderDetail -- MAIOR VALOR SELECT MAX(UnitPrice) AS MAIOR FROM Sales.SalesOrderDetail -- MENOR VALOR SELECT MIN(UnitPrice) AS MENOR FROM Sales.SalesOrderDetail -- PRECISÃO DECIMAL SELECT LineTotal, ROUND(LineTotal, 2) AS ARREDONDAMENTO FROM Sales.SalesOrderDetail -- RAIZ QUADRADA SELECT LineTotal, SQRT(LineTotal) AS RAIZ_QUADRADA FROM Sales.SalesOrderDetail<file_sep>-- EXERCÍCIO 26: -- Encontre os endereços que estão no Estado de 'Alberta'. Pode trazer todas as informações. SELECT * FROM Person.Address WHERE StateProvinceID IN ( SELECT StateProvinceID FROM Person.StateProvince WHERE Name = 'Alberta' ) SELECT * FROM Person.Address PA INNER JOIN Person.StateProvince PSP ON PA.StateProvinceID = PSP.StateProvinceID WHERE PSP.Name = 'Alberta' -- EXERCÍCIO 27: -- Encontrar qualquer tabela no banco que possua colunas com datas, e extrair mês e ano dessa coluna. -- Total de Produtos que começaram a ser vendidos, agrupados por ano. SELECT COUNT(Name) AS Total_Produtos, DATEPART(YEAR, SellStartDate) Ano_Inicio FROM Production.Product GROUP BY DATEPART(YEAR, SellStartDate) ORDER BY Ano_Inicio -- Total de Produtos que começaram a ser vendidos, agrupados por mês. SELECT COUNT(Name) AS Total_Produtos, DATEPART(MONTH, SellStartDate) Mes_Inicio FROM Production.Product GROUP BY DATEPART(MONTH, SellStartDate) ORDER BY Mes_Inicio<file_sep>-- GROUP BY: Divide o resultado da pesquisa em grupos. SELECT SpecialOfferID, SUM(UnitPrice) AS "SOMA" FROM Sales.SalesOrderDetail GROUP BY SpecialOfferID -- Quanto de cada produto foi vendido até hoje? SELECT ProductID, COUNT(ProductID) AS "CONTAGEM" FROM Sales.SalesOrderDetail GROUP BY ProductID -- Quantos nomes de cada nome temos cadastrados em nosso banco de dados? SELECT FirstName, COUNT(FirstName) AS "QUANTIDADE" FROM Person.Person GROUP BY FirstName -- Na tabela Production.Product, saber a média de preço para os produtos que são prata. SELECT Color, AVG(ListPrice) AS MEDIA FROM Production.Product WHERE Color = 'Silver' GROUP BY Color -- HAVING: Usado em junção com o group by para filtrar resultados de um agrupamento ('um WHERE para dados agrupados'). -- Diferença entre WHERE e HAVING: O HAVING é aplicado depois que os dados foram agrupados, e o WHERE é aplicado antes dos dados serem agrupados. -- Dizer quais nomes no sistema tem uma ocorrência maior que 10 vezes. SELECT FirstName, COUNT(FirstName) AS "OCORRENCIA" FROM Person.Person GROUP BY FirstName HAVING COUNT(FirstName) > 10 -- Saber quais produtos que no total de vendas estão entre 162k a 500k. SELECT ProductID, SUM(LineTotal) AS TOTAL FROM Sales.SalesOrderDetail GROUP BY ProductID HAVING SUM(LineTotal) BETWEEN 162000 AND 500000 -- Quais nomes no sistema tem ocorrência maior que 10 vezes, porém somente onde o título é 'Mr.'. SELECT FirstName, COUNT(FirstName) AS TOTAL FROM Person.Person WHERE Title = 'Mr.' GROUP BY FirstName HAVING COUNT(FirstName) > 10<file_sep>-- EXERCÍCIO 19: -- Renomear o FirstName e LastName da tabela Person.Person SELECT TOP 10 FirstName AS PrimeiroNome, LastName AS Sobrenome FROM Person.Person -- EXERCÍCIO 20: -- Renomear ProductNumber da tabela Production.Product SELECT TOP 10 ProductNumber AS CodigoProduto FROM Production.Product -- EXERCÍCIO 21: -- Renomear UnitPrice da tabela Sales.SalesOrderDetail SELECT TOP 10 UnitPrice AS PrecoUnitario FROM Sales.SalesOrderDetail -- EXERCÍCIO 22: /* Trazer as colunas BusinessEntityId, Name, PhoneNumberTypeId, PhoneNumber das colunas PhoneNumberType e PersonPhone */ SELECT Phone.BusinessEntityID, Type.Name, Type.PhoneNumberTypeID, Phone.PhoneNumber FROM Person.PhoneNumberType Type INNER JOIN Person.PersonPhone Phone ON Type.PhoneNumberTypeID = Phone.PhoneNumberTypeID -- EXERCÍCIO 23: /* Trazer as colunas AddressId, City, StateProvinceId, Name StateProvince e Address */ SELECT PA.AddressID, PA.City, PSP.StateProvinceID, PSP.Name FROM Person.StateProvince PSP INNER JOIN Person.Address PA ON PSP.StateProvinceID = PA.StateProvinceID<file_sep>/* Apartir daqui, outro banco de dados foi utilizado para realizar as querys, o arquivo para restauração do banco de dados se encontra neste repositório com o nome de NORTHWIND.bak */ -- SUBQUERY ou SUBSELECT -- Relatório de todos os produtos cadastrados que têm preço de venda acima da média. SELECT * FROM Production.Product WHERE ListPrice > ( SELECT AVG(ListPrice) FROM Production.Product ) -- Nome dos funcionários que têm o cargo de 'Design Engineer' SELECT FirstName FROM Person.Person WHERE BusinessEntityID IN ( SELECT BusinessEntityID FROM HumanResources.Employee WHERE JobTitle = 'Design Engineer' ) SELECT PP.FirstName FROM Person.Person PP INNER JOIN HumanResources.Employee HRE ON PP.BusinessEntityID = HRE.BusinessEntityID WHERE HRE.JobTitle = 'Design Engineer' -- DATEPART SELECT SalesOrderID, DATEPART(MONTH, OrderDate) AS Mês FROM Sales.SalesOrderHeader SELECT SalesOrderID, DATEPART(DAY, OrderDate) AS Dia FROM Sales.SalesOrderHeader SELECT SalesOrderID, DATEPART(YEAR, OrderDate) AS Ano FROM Sales.SalesOrderHeader -- Média de vencimentos por mês SELECT AVG(TotalDue) AS Media, DATEPART(MONTH, OrderDate) AS Mes FROM Sales.SalesOrderHeader GROUP BY DATEPART(MONTH, OrderDate) ORDER BY Mes -- Média de vencimentos por ano SELECT AVG(TotalDue) AS Media, DATEPART(YEAR, OrderDate) AS Ano FROM Sales.SalesOrderHeader GROUP BY DATEPART(YEAR, OrderDate) ORDER BY Ano -- Média de vencimentos por dia SELECT AVG(TotalDue) AS Media, DATEPART(DAY, OrderDate) AS Dia FROM Sales.SalesOrderHeader GROUP BY DATEPART(DAY, OrderDate) ORDER BY Dia<file_sep>-- AS: Nomear uma coluna ou uma consulta. SELECT TOP 10 ListPrice AS PREÇO FROM Production.Product SELECT TOP 10 ListPrice AS "PREÇO DO PRODUTO" FROM Production.Product SELECT TOP 10 AVG(ListPrice) AS "MÉDIA DE PREÇO" FROM Production.Product -- INNER JOIN: Une informações de diferentes tabelas -- Trazer as seguintes colunas: BusinessEntityId, FirstName, LastName, EmailAddress SELECT Person.BusinessEntityID, Person.FirstName, Person.LastName, Email.EmailAddress FROM Person.Person Person INNER JOIN Person.EmailAddress Email ON Email.BusinessEntityID = Person.BusinessEntityID -- Nome dos produtos e as informações de suas subcategorias SELECT Product.Name, SubCategory.Name, Product.ListPrice FROM Production.Product Product INNER JOIN Production.ProductSubcategory SubCategory ON Product.ProductSubcategoryID = SubCategory.ProductSubcategoryID -- Juntar todas as colunas SELECT * FROM Person.BusinessEntityAddress BEA INNER JOIN Person.Address PA ON BEA.AddressID = PA.AddressID <file_sep>-- EXERCICIO 1: -- A Equipe de Marketing precisa fazer uma pesquisa sobre nomes mais comuns de seus clientes e precisa -- do nome e sobrenome de todos os clientes que estão cadastrados no sistema. SELECT FirstName, LastName FROM Person.Person; -- EXERCICIO 2: -- Quantos sobrenomes únicos temos em nossa tabela Person.Person? SELECT DISTINCT LastName FROM Person.Person; -- EXERCICIO 3: /* A Equipe de Produção de produtos precisa do nome de todas as peças que pesam mais de 500Kg, mas não mais que 700kg, para inspeção. */ SELECT Name FROM Production.Product WHERE Weight > 500 AND Weight < 700 -- EXERCICIO 4: /* FOi pedido pelo marketing uma relação de todos os empregados que são casados e são assalariados. */ SELECT * FROM HumanResources.Employee WHERE MaritalStatus = 'M' AND SalariedFlag = 1 -- EXERCICIO 5: /* Um usuário chamado <NAME> está devendo um pagamento, consiga o email dele para que possamos enviar uma cobrança! */ SELECT * FROM Person.Person WHERE FirstName = 'Peter' AND LastName = 'Krebs'; SELECT EmailAddress FROM Person.EmailAddress WHERE BusinessEntityID = 26;<file_sep>-- SELECT: Selciona uma ou mais colunas desejadas da tabela: SELECT * FROM Person.Person; SELECT Title FROM Person.Person; SELECT * FROM Person.EmailAddress; -- DISTINCT: Usado quando se deseja omitir dados duplicados. SELECT FirstName FROM Person.Person; -- 19.972 registros SELECT DISTINCT FirstName FROM Person.Person; -- 1.018 registros -- WHERE: Condição para busca /* SELECT coluna1, coluna2, coluna_N FROM tabela WHERE condicao */ /* OPERADOR - DESCRIÇÃO = IGUAL > MAIOR QUE < MENOR QUE >= MAIOR OU IGUAL QUE <= MENOR OU IGUAL QUE <> DIFERENTE DE AND OPERADOR LÓGICO E OR OPERADOR LÓGICO OU */ SELECT * FROM Person.Person WHERE LastName = 'Miller' AND FirstName = 'Anna'; SELECT * From Production.Product WHERE Color = 'blue' or Color = 'black'; SELECT * FROM Production.Product WHERE ListPrice > 1500 AND ListPrice < 5000 SELECT * FROM Production.Product WHERE Color <> 'Red'<file_sep>-- COUNT: Retorna o número de linhas de acordo com a condição dada /* SELECT COUNT(*) FROM tabela SELECT COUNT(DISTINCT coluna1) // Conta todos os valores distintos e diferentes de nulo FROM tabela */ SELECT * FROM Person.Person; SELECT COUNT(*) FROM Person.Person; SELECT COUNT(Title) FROM Person.Person; SELECT COUNT(DISTINCT Title) FROM Person.Person; -- TOP: Limita a quantidade retornada de uma consulta. SELECT TOP 10 * FROM Production.Product; -- ORDER BY: Ordena os resultados em ordem crescente ou decrescente. -- Default: asc -- Ordenar por ordem crescente. SELECT * FROM Person.Person ORDER BY FirstName asc -- Ordenar por ordem decrescente. SELECT * FROM Person.Person ORDER BY LastName desc -- Ordenar uma coluna por ordem crescente e outra por ordem decrescente. SELECT * FROM Person.Person ORDER BY FirstName asc, LastName desc SELECT FirstName, LastName FROM Person.Person ORDER BY FirstName asc, LastName desc SELECT FirstName, LastName, MiddleName FROM Person.Person ORDER BY MiddleName asc -- Ordenar por uma coluna que não aparece na consulta (nâo recomendável). SELECT FirstName, LastName FROM Person.Person ORDER BY MiddleName asc<file_sep>-- EXERCÍCIO 10: -- Quantas pessoas temos com o sobrenome que inicia com a letra P? SELECT COUNT(LastName) FROM Person.Person WHERE LastName LIKE 'P%' -- EXERCÍCIO 11: -- Quantos produtos vermelhos têm preço entre 500 e 1000 dólares? SELECT COUNT(*) FROM Production.Product WHERE Color = 'red' AND ListPrice BETWEEN 500 AND 1000 -- EXERCÍCIO 12: -- Quantos produtos cadastrados tem a palavra 'road' no nome deles? SELECT COUNT(Name) FROM Production.Product WHERE Name LIKE '%road%'
dd3790334164fc9d7a8be18e357779a03486f141
[ "Markdown", "SQL" ]
22
Markdown
DaianeCamara/Fundamentos_SQL
c4ab535a3afc84d2d0e98606f0be5b8b0c800743
3d45d29287d7d58c717678db6dea6087dffdb11e
refs/heads/master
<repo_name>remoharsono/py-jne<file_sep>/tests/test_api.py import json import responses import unittest from jne import Jne from jne.constants import (URL_TRACKING, URL_TARIFF, URL_CITY_FROM, URL_CITY_TO, URL_NEARBY) class JneAPITest(unittest.TestCase): def setUp(self): self.api = Jne(api_key='<KEY>', username='TESTAPI') def register_response(self, method, url, body='{}', match_querystring=False, status=200, adding_headers=None, stream=False, content_type='application/json; charset=utf-8'): responses.add(method, url, body, match_querystring, status, adding_headers, stream, content_type) @responses.activate def test_tracking(self): response_body = { "cnote": { "city_name": "CIREBON", }, "detail": [{ "cnote_destination": "CIREBON", "cnote_no": "0113101501682546", }] } airbill = "0113101501682546" self.register_response(responses.POST, URL_TRACKING + airbill, body=json.dumps(response_body)) response = self.api.tracking(airbill=airbill) self.assertEqual(response['cnote']['city_name'], 'CIREBON') self.assertEqual(response['detail'][0]['cnote_destination'], 'CIREBON') self.assertEqual(response['detail'][0]['cnote_no'], '0113101501682546') @responses.activate def test_check_tariff(self): response_body = { "price": [{ "destination_name": "CIREBON", "etd_from": "2", "etd_thru": "3", "origin_name": "JAKARTA", "price": "9000", "service_code": "OKE13", "service_display": "OKE", "times": "D" }, { "destination_name": "CIREBON", "etd_from": "1", "etd_thru": "2", "origin_name": "JAKARTA", "price": "10000", "service_code": "REG13", "service_display": "REG", "times": "D" }, { "destination_name": "CIREBON", "etd_from": None, "etd_thru": None, "origin_name": "JAKARTA", "price": "350000", "service_code": "SPS13", "service_display": "SPS", "times": None }, { "destination_name": "CIREBON", "etd_from": "1", "etd_thru": None, "origin_name": "JAKARTA", "price": "19000", "service_code": "YES13", "service_display": "YES", "times": "D" }] } self.register_response(responses.POST, URL_TARIFF, body=json.dumps(response_body)) response = self.api.check_tariff(city_from='CGK10000', city_to='CBN10000') self.assertEqual(response['price'][0]['destination_name'], 'CIREBON') self.assertEqual(response['price'][0]['origin_name'], 'JAKARTA') self.assertEqual(response['price'][0]['price'], '9000') @responses.activate def test_get_from_code(self): response_body = { "detail": [ { "code": "CGK10000", "label": "JAKARTA" } ] } self.register_response(responses.POST, URL_CITY_FROM + 'jakarta', body=json.dumps(response_body)) response = self.api.get_from_code('jakarta') self.assertEqual(response['detail'][0]['code'], 'CGK10000') self.assertEqual(response['detail'][0]['label'], 'JAKARTA') @responses.activate def test_get_target_code(self): response_body = { 'detail': [ { "code": "CGK10000", "label": "JAKARTA" }, { "code": "CGK10100", "label": "JAKARTA BARAT" }, { "code": "CGK10300", "label": "JAKARTA PUSAT" }, { "code": "CGK10200", "label": "JAKARTA SELATAN" }, { "code": "CGK10500", "label": "JAKARTA TIMUR" }, { "code": "CGK10400", "label": "JAKARTA UTARA" } ] } self.register_response(responses.POST, URL_CITY_TO + 'jakarta', body=json.dumps(response_body)) response = self.api.get_target_code('jakarta') self.assertEqual(response['detail'][0]['code'], 'CGK10000') self.assertEqual(response['detail'][0]['label'], 'JAKARTA') self.assertEqual(response['detail'][1]['code'], 'CGK10100') self.assertEqual(response['detail'][1]['label'], 'JAKARTA BARAT') self.assertEqual(response['detail'][2]['code'], 'CGK10300') self.assertEqual(response['detail'][2]['label'], 'JAKARTA PUSAT') @responses.activate def test_find_nearby(self): # Mock API response response_body = { "places": [ { "custaddr1": "JL CIKINI RAYA NO40 MENTENG JAKARTA PUSAT", "custaddr2": None, "custname": "JNE ASP SEVEL CIKINI", "jarak": " 0.10", "latitude": "-6.19164", "longitude": "106.8385" }, { "custaddr1": "JL <NAME> NO 19-20 JAKARTA PUSAT", "custaddr2": None, "custname": "JNE AGEN 0200033", "jarak": " 0.26", "latitude": "-6.1808", "longitude": "106.8392" } ] } self.register_response(responses.POST, URL_NEARBY, body=json.dumps(response_body)) response = self.api.find_nearby(latitude='-6.1886183', longitude='106.8387325') self.assertEqual(response['places'][0]['custname'], 'JNE ASP SEVEL CIKINI') self.assertEqual(response['places'][0]['jarak'].strip(), '0.10') self.assertEqual(response['places'][1]['custname'], 'JNE AGEN 0200033') self.assertEqual(response['places'][1]['jarak'].strip(), '0.26') <file_sep>/jne/constants.py URL_CITY_FROM = "http://api.jne.co.id:8889/auto/api/list/key/" URL_CITY_TO = "http://api.jne.co.id:8889/auto/api/dest/key/" URL_TARIFF = "http://api.jne.co.id:8889/api/price/list/" URL_TRACKING = "http://api.jne.co.id:8889/api/tracking/list/cnote/" URL_NEARBY = "http://api.jne.co.id:8889/maps/maps_track/map" JNE_HTTP_STATUS_CODE = { 200: 'OK', 304: 'Not Modified', 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 406: 'Not Acceptable', 422: 'Unprocessable Entity', 500: 'Internal Server Error', } <file_sep>/jne/api.py # -*- coding: utf-8 -*- """ jne.api ~~~~~~~~~~~ This module contains functionality for access to JNE API calls, and miscellaneous methods that are useful when dealing with the JNE API """ import json import requests from requests.exceptions import RequestException from .constants import (URL_CITY_FROM, URL_CITY_TO, URL_TARIFF, URL_TRACKING, URL_NEARBY) from .exceptions import JneError, JneAPIError from .utils import pretty_print as pprint class Jne(object): def __init__(self, api_key=None, username=None): """Instantiates an instance of Jne. Takes optional parameters for authentication (see below). :param api_key: Your api key from JNE :param username: Your username from JNE """ self.api_key = api_key self.username = username def _request(self, api_call, method='GET', data={}, params={}): """Internal request method""" method = method.upper() payload = {'api_key': self.api_key, 'username': self.username} try: if method == 'GET': params.update(payload) response = requests.get(api_call, params=params) elif method == 'POST': data.update(payload) response = requests.post(api_call, params=params, data=data) else: raise ValueError("Method '{}' is not supported".format(method)) if response.text == '': raise JneAPIError( message='JNE API returned data that we cannot process.', error_code=422 ) except RequestException as error: raise JneError( message=error.message, error_code=error.errno ) return json.loads(response.text) def get_from_code(self, city, pretty_print=False): """Return dict of JNE origin city code :param city: (required) Name of city that you want to know the code :param pretty_print: (optional True or False) To print the result becomes more readable """ response = self._request(method='POST', api_call=URL_CITY_FROM + str(city)) if pretty_print: return pprint(response) return response def get_target_code(self, city, pretty_print=False): """Return dict of JNE destination city code :param city: (required) Name of city that you want to know the code :param pretty_print: (optional True or False) To print the result becomes more readable """ response = self._request(method='POST', api_call=URL_CITY_TO + str(city)) if pretty_print: return pprint(response) return response def check_tariff(self, city_from, city_to, weight=1, pretty_print=False): """return dict of JNE tariff :param city_from: (required) Origin city code. Ex: "CGK10000" :param city_to: (required) Target city code. Ex: "CBN10000" :param weight: (required) Weight of item. :param pretty_print: (optional True or False) To print the result becomes more readable """ data = {'from': city_from, 'thru': city_to, 'weight': weight} response = self._request(method='POST', api_call=URL_TARIFF, data=data) if pretty_print: return pprint(response) return response def tracking(self, airbill, pretty_print=False): """Return dict of JNE tracking detail :param airbill: (required) Airbill number from JNE :param pretty_print: (optional True or False) To print the result becomes more readable """ response = self._request(method='POST', api_call=URL_TRACKING + str(airbill)) if pretty_print: return pprint(response) return response def find_nearby(self, latitude, longitude, pretty_print=False): """Return dict of JNE nearby based latitude and longitude :param latitude: (required) Latitude :param longitude: (required) Longitude :param pretty_print: (optional True or False) To print the result becomes more readable """ data = {'latitude': latitude, 'longitude': longitude} response = self._request(method='POST', api_call=URL_NEARBY, data=data) if pretty_print: return pprint(response) return response <file_sep>/requirements.txt requests==2.6.0 responses==0.3.0 <file_sep>/jne/utils.py import json def pretty_print(text): """This utils used for print pretty json""" print json.dumps(text, indent=2, sort_keys=True) <file_sep>/jne/exceptions.py from .constants import JNE_HTTP_STATUS_CODE class JneError(Exception): def __init__(self, message, error_code=None): self.error_code = error_code if error_code in JNE_HTTP_STATUS_CODE: message = 'JNE API returned %s (%s), %s' % ( error_code, JNE_HTTP_STATUS_CODE.get(error_code), message ) super(JneError, self).__init__(message) class JneAPIError(JneError): pass <file_sep>/setup.py from setuptools import setup setup( name='py-jne', packages=['jne'], version='0.1.3', description='PyJNE is a tool to simplify the user in using the JNE API such as tracking stuff, check tariffs and others.', license='MIT', author='<NAME>', author_email='<EMAIL>', url='https://github.com/kangfend/py-jne', download_url='https://github.com/kangfend/py-jne/tarball/0.1.3', keywords=['JNE', 'Tracking', 'Courier', 'Indonesia'], install_requires=['requests==2.6.0'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) <file_sep>/jne/__init__.py __author__ = '<NAME> <<EMAIL>>' __version__ = '0.1.2' from .api import Jne # noqa from .exceptions import JneAPIError # noqa <file_sep>/README.md PyJNE ===== PyJNE is a tool to simplify the user in using the API JNE such as tracking stuff, check tariffs and others. Features -------- - Get origin city code - Get destination city code - Check JNE tariffs - Tracking stuff - Find Nearby Installation ------------ Install PyJNE via [pip](http://www.pip-installer.org/) ```bash $ pip install py-jne ``` Usage ----- #### 1. Get origin city code --- ```python >>> from jne import Jne >>> jne = Jne(api_key='d4dedbecf40d6d09f22704342c07d804', username='TESTAPI') >>> jne.get_from_code('jakarta') {u'detail': [{u'code': u'CGK10000', u'label': u'JAKARTA'}]} >>> >>> # Show result with pretty print >>> jne.get_from_code('jakarta', pretty_print=True) { "detail": [ { "code": "CGK10000", "label": "JAKARTA" } ] } >>> ``` #### 2. Get destination city code --- ```python >>> jne.get_target_code('jakarta') [{u'code': u'CGK10000', u'label': u'JAKARTA'}, {u'code': u'CGK10100', u'label': u'JAKARTA BARAT'}, {u'code': u'CGK10300', u'label': u'JAKARTA PUSAT'}, {u'code': u'CGK10200', u'label': u'JAKARTA SELATAN'}, {u'code': u'CGK10500', u'label': u'JAKARTA TIMUR'}, {u'code': u'CGK10400', u'label': u'JAKARTA UTARA'}] >>> >>> # Show result with pretty print >>> jne.get_target_code('Cirebon', pretty_print=True) [ { "code": "CBN10000", "label": "CIREBON" }, { "code": "CBN10006", "label": "CIREBON BARAT,CIREBON" }, { "code": "CBN20408", "label": "CIREBON SELATAN, SUMBER" }, { "code": "CBN20407", "label": "CIREBON UTARA, SUMBER" } ] >>> ``` #### 3. Check tariff --- ```python >>> jne.check_tariff(city_from='CGK10000', city_to='CBN10000', weight=1) {u'price': [{u'service_code': u'OKE13', u'etd_from': u'2', u'price': u'9000', u'origin_name': u'JAKARTA', u'times': u'D', u'service_display': u'OKE', u'etd_thru': u'3', u'destination_name': u'CIREBON'}, {u'service_code': u'REG13', u'etd_from': u'1', u'price': u'10000', u'origin_name': u'JAKARTA', u'times': u'D', u'service_display': u'REG', u'etd_thru': u'2', u'destination_name': u'CIREBON'}, {u'service_code': u'SPS13', u'etd_from': None, u'price': u'350000', u'origin_name': u'JAKARTA', u'times': None, u'service_display': u'SPS', u'etd_thru': None, u'destination_name': u'CIREBON'}, {u'service_code': u'YES13', u'etd_from': u'1', u'price': u'19000', u'origin_name': u'JAKARTA', u'times': u'D', u'service_display': u'YES', u'etd_thru': None, u'destination_name': u'CIREBON'}]} >>> >>> >>> # Show result with pretty print >>> jne.check_tariff(city_from='CGK10000', city_to='CBN10000', weight=1, pretty_print=True) { "price": [ { "destination_name": "CIREBON", "etd_from": "2", "etd_thru": "3", "origin_name": "JAKARTA", "price": "9000", "service_code": "OKE13", "service_display": "OKE", "times": "D" }, { "destination_name": "CIREBON", "etd_from": "1", "etd_thru": "2", "origin_name": "JAKARTA", "price": "10000", "service_code": "REG13", "service_display": "REG", "times": "D" }, { "destination_name": "CIREBON", "etd_from": null, "etd_thru": null, "origin_name": "JAKARTA", "price": "350000", "service_code": "SPS13", "service_display": "SPS", "times": null }, { "destination_name": "CIREBON", "etd_from": "1", "etd_thru": null, "origin_name": "JAKARTA", "price": "19000", "service_code": "YES13", "service_display": "YES", "times": "D" } ] } >>> ``` #### 4. Tracking --- ```python >>> jne.tracking(airbill='0113101501682546') {u'runsheet': [{u'city_name': u'TANGERANG', u'pod_status': u'ON PROCESS', u'drsheet_cnote_no': u'0113101501682546', u'mrsheet_date': u'18-mar-2015 09:55'}], u'ip': u'192.168.2.228', u'detail': [{u'cnote_date': u'14-03-2015 01:29', u'cnote_destination': u'KOSAMBI / SELEMBARAN JATI', u'cnote_shipper_addr3': None, u'cnote_origin': u'JAKARTA', u'cnote_shipper_addr1': u'PUNINAR LOGISTIC JL INSPEKSI', u'cnote_shipper_addr2': u'KIRANA NAGRAK CAKUNG DRAIN', u'cnote_shipper_name': u'LAZADA (ECART WEBPORTAL IND)', u'cnote_receiver_addr3': u' NO. 4 RT 004 / 004 JL. RAYA D', u'cnote_receiver_addr2': u'004 / 004 JL. RAYA DADAP SAWAH', u'cnote_receiver_addr1': u'JL. RAYA DADAP SAWAH NO. 4 RT', u'cnote_shipper_city': u'JAKARTA UTARA', u'cnote_receiver_city': u'KOSAMBI / SELEMBARAN', u'cnote_weight': u'1', u'cnote_no': u'0113101501682546', u'cnote_receiver_name': u'UDI TUKANG IKAN'}], u'cnote': {u'cnote_date': u'2015-03-14', u'cnote_receiver_name': u'<NAME>', u'cnote_pod_receiver': u'UDIN', u'cnote_pod_date': u'18 Mar 2015 13:00', u'pod_status': u'DELIVERED', u'cnote_services_code': u'REG', u'city_name': u'KOSAMBI / SELEMBARAN JATI', u'cnote_no': u'0113101501682546'}, u'manifest': [{u'mfcnote_no': u'0113101501682546', u'city_name': u'JAKARTA', u'manifest_date': u'14-MAR-2015 03:24', u'manifest_code': u'1', u'keterangan': u'Manifested'}, {u'mfcnote_no': u'0113101501682546', u'city_name': u'TANGERANG', u'manifest_date': u'15-MAR-2015 22:43', u'manifest_code': u'3', u'keterangan': u'Received On Destination'}]} >>> >>> # Show result with pretty print >>> jne.tracking(airbill='0113101501682546', pretty_print=True) { "cnote": { "city_name": "KOSAMBI / SELEMBARAN JATI", "cnote_date": "2015-03-14", "cnote_no": "1234567890123456", "cnote_pod_date": "18 Mar 2015 13:00", "cnote_pod_receiver": "UDIN", "cnote_receiver_name": "UDIN", "cnote_services_code": "REG", "pod_status": "DELIVERED" }, "detail": [ { "cnote_date": "14-03-2015 01:29", "cnote_destination": "KOSAMBI / SELEMBARAN JATI", "cnote_no": "1234567890123456", "cnote_origin": "JAKARTA", "cnote_receiver_addr1": "JL. SAHABAT NO. 11", "cnote_receiver_addr2": "RT 003/004", "cnote_receiver_addr3": "", "cnote_receiver_city": "KOSAMBI / SELEMBARAN", "cnote_receiver_name": "UDIN", "cnote_shipper_addr1": "PUNINAR LOGISTIC JL INSPEKSI", "cnote_shipper_addr2": "KIRANA NAGRAK CAKUNG DRAIN", "cnote_shipper_addr3": null, "cnote_shipper_city": "JAKARTA UTARA", "cnote_shipper_name": "SUDRAJAT", "cnote_weight": "1" } ], "ip": "192.168.2.228", "manifest": [ { "city_name": "JAKARTA", "keterangan": "Manifested", "manifest_code": "1", "manifest_date": "14-MAR-2015 03:24", "mfcnote_no": "1234567890123456" }, { "city_name": "TANGERANG", "keterangan": "Received On Destination", "manifest_code": "3", "manifest_date": "15-MAR-2015 22:43", "mfcnote_no": "1234567890123456" } ], "runsheet": [ { "city_name": "TANGERANG", "drsheet_cnote_no": "1234567890123456", "mrsheet_date": "18-mar-2015 09:55", "pod_status": "ON PROCESS" } ] } >>> ``` #### 5. Find Nearby --- ```python >>> jne.find_nearby(latitude='-6.1886183', longitude='106.8387325') {u'places': [{u'custaddr1': u'JL CIKINI RAYA NO40 MENTENG JAKARTA PUSAT', u'custaddr2': None, u'jarak': u' 0.10', u'longitude': u'106.8385', u'custname': u'JNE ASP SEVEL CIKINI', u'latitude': u'-6.19164'}, {u'custaddr1': u'JL KWITANG RAYA NO 19-20 JAKARTA PUSAT', u'custaddr2': None, u'jarak': u' 0.26', u'longitude': u'106.8392', u'custname': u'JNE AGEN 0200033', u'latitude': u'-6.1808'}, {u'custaddr1': u'JL PEMBANGUNAN II NO 4 JAKARTA PUSAT', u'custaddr2': None, u'jarak': u' 0.27', u'longitude': u'106.83951', u'custname': u'JNE AGEN 0200006', u'latitude': u'-6.18073'}, {u'custaddr1': u'GD ALFA GLORIA PERKASA JL PEGANGSAAN TIMUR NO 1 CIKINI JAKARTA', u'custaddr2': None, u'jarak': u' 0.34', u'longitude': u'106.84045', u'custname': u'JNE AGEN 0200044', u'latitude': u'-6.19746'}, {u'custaddr1': u'MALL PLAZA ATRIUM LT 5 NO 8B SENEN JAKARTA PUSAT', u'custaddr2': None, u'jarak': u' 0.48', u'longitude': u'106.84177', u'custname': u'JNE AGEN 0200056', u'latitude': u'-6.17801'}]} >>> >>> # Show result with pretty print >>> jne.find_nearby(latitude='-6.1886183', longitude='106.8387325', pretty_print=True) { "places": [ { "custaddr1": "JL CIKINI RAYA NO40 MENTENG JAKARTA PUSAT", "custaddr2": null, "custname": "<NAME>", "jarak": " 0.10", "latitude": "-6.19164", "longitude": "106.8385" }, { "custaddr1": "JL KWITANG RAYA NO 19-20 JAKARTA PUSAT", "custaddr2": null, "custname": "JNE AGEN 0200033", "jarak": " 0.26", "latitude": "-6.1808", "longitude": "106.8392" }, { "custaddr1": "JL PEMBANGUNAN II NO 4 JAKARTA PUSAT", "custaddr2": null, "custname": "JNE AGEN 0200006", "jarak": " 0.27", "latitude": "-6.18073", "longitude": "106.83951" }, { "custaddr1": "GD ALFA GLORIA PERKASA JL PEGANGSAAN TIMUR NO 1 CIKINI JAKARTA", "custaddr2": null, "custname": "JNE AGEN 0200044", "jarak": " 0.34", "latitude": "-6.19746", "longitude": "106.84045" }, { "custaddr1": "MALL PLAZA ATRIUM LT 5 NO 8B SENEN JAKARTA PUSAT", "custaddr2": null, "custname": "<NAME> 0200056", "jarak": " 0.48", "latitude": "-6.17801", "longitude": "106.84177" } ] } >>> ``` #### Run Test --- ``` python -m unittest discover ``` Credits ------- Thanks to [Widnyana](https://github.com/widnyana), this [script](https://github.com/widnyana/jne) is very useful :)
0f7a6c2cbc2468eab0082b4c9fb33c3e43dc93bd
[ "Markdown", "Text", "Python" ]
9
Markdown
remoharsono/py-jne
b6c02f35ee80240aac06d3c076f12cb2c1e6cdd4
1f5b432dc12519eecec4df99a4cfe4430193c5a4
refs/heads/master
<repo_name>wang-yaxiong/mycncart<file_sep>/catalog/view/theme/default/template/account/register.twig {{ header }} <style> footer{ margin-top:0; } #middle{ margin-top:74px; height:800px; background-image:url(catalog/view/theme/default/image/login-bgm.png); background-repeat:no-repeat; } #mid-left{ float:left; margin-top:40px; margin-left:495px; padding:20px; width:950px; background:rgba(0,0,0,0.3); height:700px; } #mid-register{ padding:10px; background-color:#fffffe; height:660px; } #m-left{ float:left; padding:10px; border-right:solid 1px #E6E6E6; width:60%; background-color:#fffffe; height:640px; } #m-left ul li{ border-bottom: solid 1px #E6E6E6; list-style:none; color:red; font-size:18px; height:40px; text-align: center; } #m-left dl{ background-color: #FFF; width: 473px; height: 52px; margin-left: 40px; border: solid 1px #E6E6E6; position: relative; z-index: 1; } #m-left dl dt{ font-size: 14px; color: #666; width: 106px; padding: 16px 10px 16px 10px; float: left; } #m-left dl dd{ height: 36px; float: left; padding: 8px 0; } #m-left dl dd .text{ font-size: 14px; line-height: 36px; width: 360px; height: 36px; padding: 0; border: none 0; } #m-left .cap-div dl { width: 340px; float: left; } #m-right{ float:right; padding:30px 20px; width:40%; text-align: center; height:640px; } .cap100 { width: 100px !important; } .pwd-div , .tcap-div{ clear:both; } #m-left .pwd-div .pwd{ font-size: 14px; line-height: 36px; width: 260px; height: 36px; padding: 0; border: none 0; } #m-left .xieyi , .bt-div { margin-left: 40px; } .bt-div .submit{ width:473px; height:40px; font-size:20px; } #p-ts{ position:relative; height:33px; z-index:999; width:106px; float:left; left:-120px; top:8px; padding: } img{ margin-top:-36px; } #tmcap{ visibility:hidden; } </style> <div id='middle'> <div id='mid-left' > <div id='mid-register'> <div id='m-left'> <ul><li>注册</li></ul> <form method="post" action="index.php?route=common/register/add"> <dl> <dt>手机号:</dt><dd><input type="text" id = 'tel' name = 'tel' class='text' placeholder='请输入手机号'></dd> <dt id='d-ts'></dt> </dl> <div class='cap-div'> <dl id='ts_cap'> <dt>验证码:</dt><dd><input type="text" id = 'cap' class='text cap100' placeholder='请输入验证码'></dd> </dl> <dt id='p-ts'></dt> <span>{{ captcha }}</span> </div> <div class='tcap-div'> <dl> <dt>手机验证码:</dt> <dd><input type="button" id = 'tcap' class='text' value='获取手机验证码' onclick='checkphone()'></dd> <dd><input type="text" id = 'tmcap' class='text' placeholder='请输入手机验证码'></dd> </dl> </div> <div class='pwd-div'> <dl> <dt>密码:</dt><dd><input type="<PASSWORD>" name = 'password' class='text pwd' placeholder='请输入密码'></dd> </dl> </div> <div class='cpwd-div'> <dl> <dt>确认密码:</dt><dd><input type="password" name = 'qpwd' class='text cpwd' placeholder='请输入确认密码'></dd> </dl> </div> <div class = 'xieyi'> <input type="checkbox" name="xieyi" id='xieyi'><a href="/">《注册协议及隐私政策》</a> </div> <div class='bt-div'> <input type="submit" class='submit' id ='submit' value='注&nbsp;&nbsp;&nbsp;册' disabled> </div> </form> </div> <div id='m-right' > <h6>已有账号,去<a href="index.php?route=/account/login">登录</a></h6> </div> </div> </div> </div> {{ footer }} <script> $("#cap").blur(function (){ var captcha = $("#cap").val(); if( captcha ==''){ $("#p-ts").html("请输入验证码"); $("#p-ts").css("background-color","#ddd549"); $("#p-ts").css("position","relative"); $("#p-ts").css("height","33px"); $("#p-ts").css("line-height","33px"); $("#p-ts").css("left","-120px"); $("#p-ts").css("top","8px"); $("#p-ts").css("z-index","999"); $("#p-ts").css("width","106px"); $("#p-ts").css("padding-left","14px"); return; } }) $("#cap").focus(function (){ $("#p-ts").html(""); $("#p-ts").css("background-color","transparent"); }) function checkphone (){ var phone = $("#tel").val(); var reg = /^1[3|4|5|7|8][0-9]{9}$/; var flag = reg.test(phone); var captcha = $("#cap").val(); if( phone==''){ $("#d-ts").html("<span>请输入手机号</span>"); $("#d-ts").css("background-color","#ddd549"); $("#d-ts").css("position","relative"); $("#d-ts").css("height","33px"); $("#d-ts").css("line-height","0"); $("#d-ts").css("left","230px"); $("#d-ts").css("top","-28px"); return; } if( captcha ==''){ $("#p-ts").html("请输入验证码"); $("#p-ts").css("background-color","#ddd549"); $("#p-ts").css("position","relative"); $("#p-ts").css("height","33px"); $("#p-ts").css("line-height","33px"); $("#p-ts").css("left","-120px"); $("#p-ts").css("top","8px"); $("#p-ts").css("z-index","999"); $("#p-ts").css("width","106px"); $("#p-ts").css("padding-left","14px"); return; } if(!flag){ $("#d-ts").html("<span>格式错误</span>"); $("#d-ts").css("background-color","#ddd549"); $("#d-ts").css("position","relative"); $("#d-ts").css("height","33px"); $("#d-ts").css("line-height","0"); $("#d-ts").css("left","230px"); $("#d-ts").css("top","-28px"); return; } $.post("index.php?route=account/register/checkcap", {captcha:captcha}, function(result){ if(result == 0){ $("#p-ts").html("验证码错误"); $("#p-ts").css("background-color","#ddd549"); $("#p-ts").css("position","relative"); $("#p-ts").css("height","33px"); $("#p-ts").css("line-height","33px"); $("#p-ts").css("left","-120px"); $("#p-ts").css("top","8px"); $("#p-ts").css("z-index","999"); $("#p-ts").css("width","106px"); $("#p-ts").css("padding-left","14px"); return; }else{ $("#tcap").hide(); $("#tmcap").css("visibility","visible"); $("#tmcap").focus(); } } ); } $("#tel").blur(function (){ var phone = $("#tel").val(); var reg = /^1[3|4|5|7|8][0-9]{9}$/; var flag = reg.test(phone); if( phone==''){ $("#d-ts").html("<span>请输入手机号</span>"); $("#d-ts").css("background-color","#ddd549"); $("#d-ts").css("position","relative"); $("#d-ts").css("height","33px"); $("#d-ts").css("line-height","0"); $("#d-ts").css("left","230px"); $("#d-ts").css("top","-28px"); return; } if(!flag){ $("#d-ts").html("<span>格式错误</span>"); $("#d-ts").css("background-color","#ddd549"); $("#d-ts").css("position","relative"); $("#d-ts").css("height","33px"); $("#d-ts").css("line-height","0"); $("#d-ts").css("left","230px"); $("#d-ts").css("top","-28px"); return; } }) $("#tel").focus(function (){ $("#d-ts").html("<span> </span>"); $("#d-ts").css("background-color","transparent"); }) $('#xieyi').click(function (){ var bool =$("#xieyi").is(':checked'); if(bool){ $('#submit').attr('disabled',false); $('#submit').css('background-color','#ff3300'); $('#submit').css('border-radius','3px'); $('#submit').css('border','1px solid #adb2b5' ); }else{ $('#submit').attr('disabled',true); $('#submit').css('background-color','#f4f4f4'); $('#submit').css('border','1px solid #adb2b5' ); } }) $('#submit').click(function (){ }) </script>
358b43364f5e93af3532c45778e5557ab2a4732d
[ "Twig" ]
1
Twig
wang-yaxiong/mycncart
ba64022e408f65abe705b247e57f66a6f9b0d626
82686a04b07529626653c5cde8e119a7da52f485