branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>rmanacmol/AndroidTemplate2<file_sep>/app/src/main/java/com/mobiledev/rpm/androidtemplate2/managers/UserManager.java package com.mobiledev.rpm.androidtemplate2.managers; import com.mobiledev.rpm.androidtemplate2.network.model.Users; import io.realm.Realm; import io.realm.RealmResults; /** * Created by rmanacmol on 2/26/2017. */ public class UserManager { private DBManager dbManager; private Users user; public UserManager(DBManager dbManager) { this.dbManager = dbManager; } public Users getUser() { Realm realm = dbManager.getRealm(); if (user != null) return user; if (realm.where(Users.class).findFirst() != null) { user = realm.where(Users.class).findFirst(); return user; } return null; } public void saveUser(Users user) { Realm realm = dbManager.getRealm(); realm.beginTransaction(); realm.copyToRealmOrUpdate(user); realm.commitTransaction(); this.user = user; } public void deleteUser() { Realm realm = dbManager.getRealm(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<Users> result = realm.where(Users.class).equalTo("id", user.getId()).findAll(); result.deleteAllFromRealm(); } }); this.user = null; } } <file_sep>/app/src/main/java/com/mobiledev/rpm/androidtemplate2/adapter/UserAdapter.java package com.mobiledev.rpm.androidtemplate2.adapter; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mobiledev.rpm.androidtemplate2.BR; import com.mobiledev.rpm.androidtemplate2.R; import com.mobiledev.rpm.androidtemplate2.databinding.ItemRowNameBinding; import com.mobiledev.rpm.androidtemplate2.network.model.Users; import java.util.List; /** * Created by rmanacmol on 2/26/2017. */ public class UserAdapter extends RecyclerView.Adapter<UserAdapter.BindingHolder> { private List<Users> mUser; public UserAdapter(List<Users> mUser) { this.mUser = mUser; } @Override public BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_name, parent, false); BindingHolder holder = new BindingHolder(v); return holder; } @Override public void onBindViewHolder(BindingHolder holder, int position) { final Users users = mUser.get(position); holder.getBinding().setVariable(BR.users, users); holder.getBinding().executePendingBindings(); } @Override public int getItemCount() { return mUser.size(); } public class BindingHolder extends RecyclerView.ViewHolder { private ItemRowNameBinding binding; public BindingHolder(View v) { super(v); binding = DataBindingUtil.bind(v); } public ViewDataBinding getBinding() { return binding; } } } <file_sep>/app/src/main/java/com/mobiledev/rpm/androidtemplate2/ApplicationTemp.java package com.mobiledev.rpm.androidtemplate2; import android.app.Application; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mobiledev.rpm.androidtemplate2.managers.UserManager; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by rmanacmol on 2/26/2017. */ public class ApplicationTemp extends Application{ protected ApplicationComponent mApplicationComponent; @Inject public UserManager userManager; @Override public void onCreate() { super.onCreate(); initAppComponent(); mApplicationComponent.inject(this); } protected void initAppComponent() { mApplicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build(); } public ApplicationComponent getApplicationComponent() { return mApplicationComponent; } } <file_sep>/app/src/main/java/com/mobiledev/rpm/androidtemplate2/managers/DBManager.java package com.mobiledev.rpm.androidtemplate2.managers; import android.content.Context; import com.mobiledev.rpm.androidtemplate2.BuildConfig; import io.realm.Realm; import io.realm.RealmConfiguration; /** * Created by rmanacmol on 30/01/2017. */ public class DBManager { private Context context; private Realm realm; private RealmConfiguration realmConfiguration; public DBManager(Context context) { this.context = context; buildRealmConfiguration(); } protected void buildRealmConfiguration() { Realm.init(context); RealmConfiguration.Builder builder = new RealmConfiguration.Builder(); if (BuildConfig.DEBUG) { builder = builder.deleteRealmIfMigrationNeeded(); } realmConfiguration = builder.build(); } public void openRealm() { realm = Realm.getInstance(realmConfiguration); } public void closeRealm() { if (realm != null) { realm.close(); } realm = null; } public Realm getRealm() { if (realm == null || realm.isClosed()) { openRealm(); } return realm; } } <file_sep>/app/src/main/java/com/mobiledev/rpm/androidtemplate2/ApplicationModule.java package com.mobiledev.rpm.androidtemplate2; /** * Created by rmanacmol on 2/26/2017. */ import android.app.Application; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mobiledev.rpm.androidtemplate2.managers.DBManager; import com.mobiledev.rpm.androidtemplate2.managers.UserManager; import com.mobiledev.rpm.androidtemplate2.network.api.ApiService; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by rmanacmol on 2/26/2017. */ @Module public class ApplicationModule { Application mApplication; public ApplicationModule(Application application) { mApplication = application; } @Provides @Singleton public Application providesApplication() { return mApplication; } @Provides @Singleton public Cache provideOkHttpCache(Application application) { int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(application.getCacheDir(), cacheSize); return cache; } @Provides @Singleton public Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); return gsonBuilder.create(); } @Provides @Singleton public OkHttpClient provideOkHttpClient(Cache cache) { OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES); if (BuildConfig.DEBUG) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(logging); } return httpClient.build(); } @Provides @Singleton public Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) { Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(mApplication.getString(R.string.base_service_url)) .client(okHttpClient) .build(); return retrofit; } @Provides @Singleton public ApiService providesApiService(Retrofit retrofit) { return retrofit.create(ApiService.class); } @Provides @Singleton public DBManager provideDBManager(Application application) { return new DBManager(application); } @Provides @Singleton public UserManager provideUserManager(DBManager dbManager) { return new UserManager(dbManager); } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'realm-android' android { compileSdkVersion 25 buildToolsVersion "25.0.2" dataBinding { enabled = true } defaultConfig { applicationId "com.mobiledev.rpm.androidtemplate2" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } productFlavors { staging { resValue "string", "base_service_url", "https://jsonplaceholder.typicode.com" resValue "string", "base_api_port", "81" versionName = defaultConfig.versionName + " STAGING" } localGenymotion { resValue "string", "base_service_url", "https://jsonplaceholder.typicode.com" resValue "string", "base_api_port", "81" versionName = defaultConfig.versionName + " LOCAL GENYMOTION" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) // Test Libraries testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:2.7.7' testCompile 'org.robolectric:robolectric:3.2.2' testCompile 'org.robolectric:shadows-support-v4:3.2.2' testCompile 'org.robolectric:shadows-multidex:3.2.2' androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) // Android Support Libraries compile 'com.android.support:appcompat-v7:25.1.1' compile 'com.android.support:design:25.1.1' compile 'com.android.support:cardview-v7:25.1.1' compile 'com.android.support:recyclerview-v7:25.1.1' // Dagger 2 compile 'com.google.dagger:dagger:2.9' apt 'com.google.dagger:dagger-compiler:2.9' // GSON compile 'com.google.code.gson:gson:2.8.0' // Retrofit & OkHTTP compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.okhttp3:logging-interceptor:3.6.0' //Rx compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0' compile 'io.reactivex:rxandroid:1.2.1' }
417916c2efe61a79744ffaf9cf94254a18f1f45f
[ "Java", "Gradle" ]
6
Java
rmanacmol/AndroidTemplate2
287f962b8212cf7077f3b6acd575a799b1fec5d4
7044f3fe903f01af50ea46e7b5beb28cb15be72a
refs/heads/master
<repo_name>qdnqn/appmgmt<file_sep>/src/main.js import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import { auth } from './firebase' import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm'; import InstantSearch from 'vue-instantsearch'; import VueChatScroll from 'vue-chat-scroll' import { Datetime } from 'vue-datetime' import '@fortawesome/fontawesome-free/css/all.css' import '@fortawesome/fontawesome-free/js/all.js' import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import 'vue-datetime/dist/vue-datetime.css' Vue.use(BootstrapVue); Vue.use(InstantSearch); Vue.use(require('vue-faker')); Vue.use(VueChatScroll) Vue.use(Datetime) Vue.config.productionTip = false let app auth.onAuthStateChanged((user) => { if (!app) { app = new Vue({ router, store, render: h => h(App) }).$mount('#app') } if (user) { store.dispatch('fetchAdmin', user) } })<file_sep>/src/router/index.js import Vue from 'vue' import VueRouter from 'vue-router' import Dashboard from '../views/Dashboard.vue' import Edit from '../views/Edit.vue' import { auth } from '../firebase' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Dashboard', component: Dashboard, meta: { onlyAuthenticated: true } }, { path: '/view/:id', name: 'Applicant', component: Dashboard, meta: { onlyAuthenticated: true } }, { path: '/edit/:id', name: 'Edit', component: Edit, meta: { onlyAuthenticated: true } }, { path: '/error', name: 'Error', component: () => import('../views/Error.vue') }, { path: '/login', name: 'Login', component: () => import('../views/Login.vue'), meta: { onlyGuest: true } }, ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) // navigation guard to check for logged in users router.beforeEach((to, from, next) => { const onlyAuthenticated = to.matched.some(x => x.meta.onlyAuthenticated) const onlyGuest = to.matched.some(x => x.meta.onlyGuest) if (onlyAuthenticated && !auth.currentUser) { next('/login') } else if(onlyGuest && auth.currentUser) { next('/') } else { next() } }) export default router <file_sep>/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import * as fb from '../firebase' import router from '../router/index' import algoliasearch from 'algoliasearch/lite'; import moment from 'moment' Vue.use(Vuex) fb.applicantsCollection.orderBy('createdOn', 'desc').onSnapshot(snapshot => { let applicantsArray = [] snapshot.forEach(doc => { let applicant = doc.data() applicant.id = doc.id applicant.number = 1; applicantsArray.push(applicant) }) store.commit('setApplicants', applicantsArray) }) const store = new Vuex.Store({ state: { admin: {}, applicantExperience: {}, applicantEducation: {}, applicantMessages: {}, applicants: [], applicant: {}, update: {}, addExp: {}, addEdu: {} }, mutations: { setAdmin(state, val){ state.admin = val }, setApplicantEducation(state, val) { state.applicantEducation = val }, setApplicantExperience(state, val) { state.applicantExperience = val }, setApplicantMessages(state, val){ state.applicantMessages = val }, setApplicants(state, val) { state.applicants = val }, setApplicant(state, val) { state.applicant = val }, setUpdateCompleted(state, val){ state.update = val }, setAddExp(state, val){ state.addExp = val }, setAddEdu(state, val){ state.addEdu = val } }, actions: { async login({ dispatch }, form) { const { user } = await fb.auth.signInWithEmailAndPassword(form.email, form.password) dispatch('fetchAdmin', user) dispatch('fetchApplicants') router.push('/').catch(()=>{}); }, async logout({ dispatch }) { await fb.auth.signOut() store.commit('setApplicants', {}) store.commit('setApplicantEducation', {}) store.commit('setApplicantExperience', {}) store.commit('setApplicantMessages', {}) store.commit('setApplicant', {}) store.commit('setApplicants', {}) router.push('/login') }, async fetchAdmin({ commit }, user) { const admin = await fb.usersCollection.doc(user.uid).get() commit('setAdmin', admin.data()) }, async fetchApplicants({ commit }) { fb.applicantsCollection.orderBy('createdOn', 'desc').onSnapshot(snapshot => { let applicantsArray = [] snapshot.forEach(doc => { let applicant = doc.data() applicant.id = doc.id applicant.number = 1; applicantsArray.push(applicant) }) store.commit('setApplicants', applicantsArray) }) }, async fetchApplicantExperience({ commit }, user) { console.log(user) fb.experienceCollection.where("userId", "==", user).orderBy('createdOn', 'desc').onSnapshot(snapshot => { let experienceArray = [] snapshot.forEach(doc => { let experienceEntry = doc.data() experienceEntry.id = doc.id experienceArray.push(experienceEntry) }) store.commit('setApplicantExperience', experienceArray) }) }, async fetchApplicantEducation({ commit }, user) { fb.educationCollection.where("userId", "==", user).orderBy('createdOn', 'desc').onSnapshot(snapshot => { let educationArray = [] snapshot.forEach(doc => { let educationEntry = doc.data() educationEntry.id = doc.id educationArray.push(educationEntry) }) store.commit('setApplicantEducation', educationArray) }) }, async fetchApplicantMessages({ commit }, userId) { fb.messagesCollection.where("refByUser", "==", userId).orderBy('createdOn', 'desc').onSnapshot(snapshot => { let messagesArray = [] let group = {} snapshot.forEach(doc => { let message = doc.data() message.id = doc.id message.dateGroup = moment.unix(doc.data().createdOn.seconds).format("DDMMYYYY"); messagesArray.unshift(message) }) store.commit('setApplicantMessages', messagesArray) }) }, async fetchApplicant({dispatch}, id) { dispatch('fetchApplicantExperience', id) dispatch('fetchApplicantEducation', id) fb.applicantsCollection.doc(id).onSnapshot(doc => { let applicant = doc.data() applicant.id = doc.id store.commit('setApplicant', applicant) }) }, async viewApplicant({dispatch}, id) { dispatch('fetchApplicantExperience', id) dispatch('fetchApplicantEducation', id) dispatch('fetchApplicantMessages', id) router.push('/view/'+id); }, async findApplicants({dispatch}, query) { var client = algoliasearch("EXLQASWZMZ", "9b1359906139b9b7ba2e76b0dc7f8586"); var index = client.initIndex('applicants'); let applicantsArray = [], i = 0 console.log(query.find) if(query.find == ""){ fb.applicantsCollection.orderBy('createdOn', 'desc').onSnapshot(snapshot => { let applicantsArray = [] snapshot.forEach(doc => { let applicant = doc.data() applicant.id = doc.id applicant.number = 1; applicantsArray.push(applicant) }) store.commit('setApplicants', applicantsArray) }) } else { return index .search(query.find) .then(function(responses) { for(i in responses.hits){ let applicant = responses.hits[i]; applicant.id = applicant.objectID; applicant.number = 1; applicantsArray.push(applicant) } store.commit('setApplicants', applicantsArray) }); } }, async addApplicantExperience({ state }, exp) { await fb.experienceCollection.add({ userId: exp.userId, photo: Vue.faker().image.avatar(), position: exp.position, company: exp.company, startDate: new Date(exp.startDate), endDate: exp.present ? new Date() : new Date(exp.endDate), location: exp.location, present: exp.present, createdOn: new Date() }).then(function() { store.commit('setAddExp', {message: 'Successfully added new experience!', type: "success"}) }); }, async addApplicantEducation({ state }, edu) { await fb.educationCollection.add({ userId: edu.userId, university: edu.university, faculty: edu.faculty, startDate: new Date(edu.startDate), endDate: edu.present ? new Date() : new Date(edu.endDate), present: edu.present, createdOn: new Date() }).then(function() { store.commit('setAddEdu', {message: 'Successfully added new education!', type: "success"}) }); }, async updateApplicant({dispatch}, applicant) { console.log(applicant) fb.applicantsCollection.doc(applicant.id).update({ "firstname": applicant.firstname, "lastname": applicant.lastname, "country": applicant.country, "city": applicant.city, "company": applicant.company, "position": applicant.position }).then(function() { if(typeof applicant.undo == 'undefined') store.commit('setUpdateCompleted', {message: 'Successfully saved changes!', type: "success"}) else store.commit('setUpdateCompleted', {message: 'Save action reversed!', type: "undo"}) }); }, async deleteApplicant({ state }, userId) { fb.messagesCollection.where("refByUser", "==", userId).orderBy('createdOn', 'desc').onSnapshot(snapshot => { snapshot.forEach(doc => { fb.messagesCollection.doc(doc.id).delete() }) }) fb.experienceCollection.where("userId", "==", userId).orderBy('createdOn', 'desc').onSnapshot(snapshot => { snapshot.forEach(doc => { fb.experienceCollection.doc(doc.id).delete() }) }) fb.educationCollection.where("userId", "==", userId).orderBy('createdOn', 'desc').onSnapshot(snapshot => { snapshot.forEach(doc => { fb.educationCollection.doc(doc.id).delete() }) }) fb.applicantsCollection.doc(userId).delete() }, async createApplicant() { await fb.applicantsCollection.add({ firstname: Vue.faker().name.firstName(), lastname: Vue.faker().name.lastName(), photo: Vue.faker().image.avatar(), position: Vue.faker().name.jobTitle(), company: Vue.faker().company.companyName(), country: Vue.faker().address.country(), city: Vue.faker().address.city(), address: Vue.faker().address.streetAddress(), createdOn: new Date(), }) }, async createExperience({ state }, uid) { await fb.experienceCollection.add({ userId: uid.userId, photo: Vue.faker().image.avatar(), position: Vue.faker().name.jobTitle(), company: Vue.faker().company.companyName(), startDate: Vue.faker().date.between('2000-01-01', '2005-12-31'), endDate: Vue.faker().date.between('2005-12-31', '2020-12-31'), location: Vue.faker().address.city(), present: (Math.random() < 0.5) ? true : false, createdOn: new Date() }) }, async createEducation({ state }, uid) { await fb.educationCollection.add({ userId: uid.userId, university: 'University of ' + Vue.faker().address.city(), faculty: 'Department of ' + Vue.faker().name.jobArea(), startDate: Vue.faker().date.between('2000-01-01', '2005-12-31'), endDate: Vue.faker().date.between('2005-12-31', '2020-12-31'), present: (Math.random() < 0.5) ? true : false, createdOn: new Date() }) }, async createMessage({ state }, message) { await fb.messagesCollection.add({ senderId: message.senderId, receiverId: message.receiverId, message: Vue.faker().lorem.paragraph(), refByUser: message.refByUser, createdOn: new Date() }) } }, modules: { } }) export default store<file_sep>/src/firebase.js import * as firebase from 'firebase/app' import 'firebase/auth' import 'firebase/firestore' // firebase init - add your own config here const firebaseConfig = { apiKey: "<KEY>", authDomain: "appmgmt-191ad.firebaseapp.com", databaseURL: "https://appmgmt-191ad.firebaseio.com", projectId: "appmgmt-191ad", storageBucket: "appmgmt-191ad.appspot.com", messagingSenderId: "667870022647", appId: "1:667870022647:web:098e3099249d1c7aa7fcf2" }; firebase.initializeApp(firebaseConfig) // utils const db = firebase.firestore() const auth = firebase.auth() // collection references const usersCollection = db.collection('users') const applicantsCollection = db.collection('applicants') const educationCollection = db.collection('education') const experienceCollection = db.collection('experience') const messagesCollection = db.collection('messages') // export utils/refs export { db, auth, usersCollection, applicantsCollection, educationCollection, experienceCollection, messagesCollection } <file_sep>/README.md # appmgmt Demo web app for applicant management created using vuejs and firebase. ## Firebase structure Firebase realtime db has 5 collections: ``` applicants |- firstname (String) |- lastname (String) |- photo (String) |- address (String) |- city (String) |- country (String) |- city (String) |- company (String) |- position (String) |- createdOn (Timestamp) ``` ``` education |- userId (String) |- university (String) |- faculty (String) |- startDate (Timestamp) |- endDate (Timestamp) |- present (Boolean) |- createdOn (Timestamp) ``` ``` experience |- userId (String) |- company (String) |- position (String) |- location (String) |- photo (String) |- startDate (Timestamp) |- endDate (Timestamp) |- present (Boolean) |- createdOn (Timestamp) ``` ``` messages |- message (String) |- senderId (String) |- receiverId (String) |- refByUser (String) |- createdOn (Timestamp) ``` * Note: refByUser: Added redundant field so app doesn't need to use where query 2x (senderId == userId || receiverId == userId) times when fetching messages because firebase doesn't support OR like clause. When we need to fetch user messages we simply fetch by refByUser (It doesn't matter who sent the message: admin or user). ``` |- email (String) |- firstname (String) |- latname (String) |- photo (String) ``` * Note: Holds admin information. Documents id are identical to UUID in authentication. ## Search Search is implemented using algolia search-as-a-service. Using firebase cloud functions, triggers are set up in the backend to listen for changes on applicant collection (onCreate, onUpdate and onDelete) to replicate data to algolia service using their API. As you type in search bar app is querying algolia service and returning applicants matching search criteria. Note: Web app is currently using trial on algolia (14 days from 08.06.2020). ## Auth Authentication is created by using firebase auth service. ## Database rules & indexes Simple database rules are implemented so only authenticated user (Admin) can write to database. ``` service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read; allow write: if request.auth.uid != null } } } ``` Compound indexes created: ``` experience userId Ascending createdOn Descending education userId Ascending createdOn Descending messages refByUser Ascending createdOn Ascending ``` ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Lints and fixes files ``` npm run lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). <file_sep>/functions/index.js const functions = require('firebase-functions'); const admin = require('firebase-admin'); let Promise = require('promise'); const cors = require('cors')({ origin: true }); const auth = require('basic-auth'); const request = require('request'); const algoliasearch = require('algoliasearch'); admin.initializeApp(); const db = admin.firestore(); exports.addApplicantToAlgolia = functions.firestore.document('applicants/{documentId}') .onCreate((event, context) => { const data = { objectID: context.params.documentId, photo: event.data().photo, position: event.data().position, firstname: event.data().firstname, lastname: event.data().lastname, company: event.data().company, address: event.data().address, city: event.data().city, country: event.data().country }; return addToAlgolia(data, 'applicants') .then(res => console.log('Success: Applicant add to algolia.', res)) .catch(err => console.log('Error: Applicant add to algolia', err)); }); exports.editApplicantOnAlgolia = functions.firestore.document('applicants/{documentId}') .onUpdate((event,context) => { const data = { objectID: context.params.documentId, photo: event.after.data().photo, position: event.after.data().position, firstname: event.after.data().firstname, lastname: event.after.data().lastname, company: event.after.data().company, address: event.after.data().address, city: event.after.data().city, country: event.after.data().country }; return editOnAlgolia(data, 'applicants') .then(res => console.log('Success: Applicant edit on algolia', res)) .catch(err => console.log('Success: Applicant edit on algolia', err)); }); exports.removeApplicantFromAlgolia = functions.firestore.document('applicants/{documentId}') .onDelete((event, context) => { const objectID = context.params.documentId; return removeFromAlgolia(objectID, 'applicants') .then(res => console.log('Success: Applicant remove from algolia', res)) .catch(err => console.log('Success: Applicant remove from algolia', err)); }) function addToAlgolia(object, indexName) { const ALGOLIA_ID = functions.config().algolia.app_id; const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key; const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY); const index = client.initIndex(indexName); return new Promise((resolve, reject) => { index.saveObject(object) .then(res => { console.log('res GOOD', res); resolve(res) }) .catch(err => { console.log('err BAD', err); reject(err) }); }); } function editOnAlgolia(object, indexName) { const ALGOLIA_ID = functions.config().algolia.app_id; const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key; const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY); const index = client.initIndex(indexName); return new Promise((resolve, reject) => { index.saveObject(object) .then(res => { console.log('res GOOD', res); resolve(res) }) .catch(err => { console.log('err BAD', err); reject(err) }); }); } function removeFromAlgolia(objectID, indexName) { const ALGOLIA_ID = functions.config().algolia.app_id; const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key; const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY); const index = client.initIndex(indexName); return new Promise((resolve, reject) => { index.deleteObject(objectID) .then(res => { console.log('res GOOD', res); resolve(res) }) .catch(err => { console.log('err BAD', err); reject(err) }); }); }
da791dc4f4c28d06ad9bfba925cdfe64aa566c78
[ "JavaScript", "Markdown" ]
6
JavaScript
qdnqn/appmgmt
174f54c0d8bd45d64e99ffb38f500436c110ca44
1223373240e589d0370ba5e89269cea03f0f69ad
refs/heads/main
<repo_name>sandwich1234/-portfolio_project<file_sep>/parallax-scroll-image-full-web/src/script.js // $('.p-content01').css({'background-size':'cover'}); // $(window).scroll(function(){ // var scrollPos = $(this).scrollTop(); // $(".p-content01").css({ // 'background-size': 100 + scrollPos + '%' + '' + 10 + scrollPos + '%' // }); // });<file_sep>/js/index.js // JavaScript Document (function() { var curImgId = 1; var numberOfImages = 2; // Change this to the number of background images window.setInterval(function() { $('body').fadeTo('slow', 0, function() { $(this).css('background-image','url(../img/inde_bg' + curImgId +'.png)').fadeTo('slow', 1); }); curImgId = (curImgId + 1) % numberOfImages; }, 5 * 1000); })();<file_sep>/parallax-scroll-image-full-web/README.markdown # parallax scroll image full web A Pen created on CodePen.io. Original URL: [https://codepen.io/nguyenvan/pen/ZwvbEa](https://codepen.io/nguyenvan/pen/ZwvbEa).
04e7777dba9e1a52f1bf8440bf6150a5af782863
[ "JavaScript", "Markdown" ]
3
JavaScript
sandwich1234/-portfolio_project
1faaf2444cbefe68bf9bb748d3cff7809bec1541
e8b2f51334e64a95da795a1d19b3306df77f0573
refs/heads/master
<file_sep>function greeter(person) { return "Hello, " + person; } let user = "<NAME>"; document.body.innerHTML = greeter(user); function greeter2(person: string) { return "Hello, " + person; } let user2 = [0, 1, 2]; document.body.innerHTML = greeter2(user2); //greeter.ts:15:36 - error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.<file_sep># learning-of-ts
bd725a28803e7517b450f83358881270e27767ca
[ "Markdown", "TypeScript" ]
2
TypeScript
TulipLi/learning-of-ts
57406394ffb52c6444441f2b46bdd1d07f94a78a
4164c16afe261c6cd9e711a52f7499dee7ac7c39
refs/heads/master
<repo_name>ArloL/gate<file_sep>/src/Tests/Gate.Builder.Tests/Loader/DoesNotFollowConvention.cs using Owin; namespace DifferentNamespace { public class DoesNotFollowConvention { public static int ConfigurationCalls; public static void Configuration(IAppBuilder builder) { ConfigurationCalls += 1; } } }<file_sep>/src/Main/Gate.Builder/AppBuilder.cs using System; using System.Collections.Generic; using System.Threading; using Gate.Builder.Loader; using Owin; using System.Linq; namespace Gate.Builder { #pragma warning disable 811 using AppAction = Action< // app IDictionary<string, object>, // env Action< // result string, // status IDictionary<string, string[]>, // headers Action< // body Func< // write ArraySegment<byte>, // data Action, // continuation bool>, // buffering Action< // end Exception>, // error CancellationToken>>, // cancel Action<Exception>>; // error public class AppBuilder : IAppBuilder { public static AppDelegate BuildConfiguration() { return BuildConfiguration(default(string)); } public static AppDelegate BuildConfiguration(string startupName) { var startup = new StartupLoader().Load(startupName); return BuildConfiguration(startup); } public static AppDelegate BuildConfiguration(Action<IAppBuilder> startup) { if (startup == null) throw new ArgumentNullException("startup"); var builder = new AppBuilder(); startup(builder); return builder.Materialize(); } readonly IList<Delegate> _stack; readonly IDictionary<string, object> _context; readonly IDictionary<Tuple<Type, Type>, Func<object, object>> _adapters = new Dictionary<Tuple<Type, Type>, Func<object, object>>(); public AppBuilder() { _stack = new List<Delegate>(); _context = new Dictionary<string, object>(); AddAdapter<AppDelegate, AppAction>(Adapters.ToAction); AddAdapter<AppAction, AppDelegate>(Adapters.ToDelegate); AddAdapter<AppDelegate, AppTaskDelegate>(Adapters.ToTaskDelegate); AddAdapter<AppTaskDelegate, AppDelegate>(Adapters.ToDelegate); AddAdapter<AppAction, AppTaskDelegate>(app => Adapters.ToTaskDelegate(Adapters.ToDelegate(app))); AddAdapter<AppTaskDelegate, AppAction>(app => Adapters.ToAction(Adapters.ToDelegate(app))); } public AppBuilder(IDictionary<string, object> context, IDictionary<Tuple<Type, Type>, Func<object, object>> adapters) { _stack = new List<Delegate>(); _context = context; _adapters = adapters; } public IAppBuilder Use<TApp>(Func<TApp, TApp> middleware) { _stack.Add(middleware); return this; } public TApp Build<TApp>(Action<IAppBuilder> fork) { var b = new AppBuilder(); fork(b); return b.Materialize<TApp>(); } public TApp Materialize<TApp>() { var app = (object)NotFound.App(); app = _stack .Reverse() .Aggregate(app, Wrap); return (TApp)Adapt(app, typeof(TApp)); } object Wrap(object app, Delegate middleware) { var middlewareFlavor = middleware.Method.ReturnType; var neededApp = Adapt(app, middlewareFlavor); return middleware.DynamicInvoke(neededApp); } object Adapt(object currentApp, Type neededFlavor) { var currentFlavor = currentApp.GetType(); if (neededFlavor.IsAssignableFrom(currentFlavor)) return currentApp; foreach (var kv in _adapters) { if (neededFlavor.IsAssignableFrom(kv.Key.Item2) && kv.Key.Item1.IsAssignableFrom(currentFlavor)) { return kv.Value.Invoke(currentApp); } } throw new Exception(string.Format("Unable to convert from {0} to {1}", currentFlavor, neededFlavor)); } void AddAdapter<TCurrent, TNeeded>(Func<TCurrent, TNeeded> adapter) { var key = Tuple.Create(typeof(TCurrent), typeof(TNeeded)); if (!_adapters.ContainsKey(key)) _adapters.Add(key, Adapter(adapter)); } Func<object, object> Adapter<TCurrent, TNeeded>(Func<TCurrent, TNeeded> adapter) { return app => adapter((TCurrent)app); } public AppDelegate Build(Action<IAppBuilder> fork) { var b = new AppBuilder(_context, _adapters); fork(b); return b.Materialize<AppDelegate>(); } public AppDelegate Materialize() { return Materialize<AppDelegate>(); } public IAppBuilder AddAdapters<TApp1, TApp2>(Func<TApp1, TApp2> adapter1, Func<TApp2, TApp1> adapter2) { AddAdapter(adapter1); AddAdapter(adapter2); return this; } public IDictionary<string, object> Context { get { return _context; } } } }<file_sep>/src/Hosts/Gate.Hosts.AspNet/AppSingleton.cs using System; using System.Configuration; using Gate.Builder; using Owin; namespace Gate.Hosts.AspNet { public static class AppSingleton { static AppSingleton() { SetFactory(DefaultFactory); } static Func<AppDelegate> _accessor; public static AppDelegate Instance { get { return _accessor(); } set { _accessor = () => value; } } public static void SetFactory(Func<AppDelegate> factory) { var sync = new object(); AppDelegate instance = null; _accessor = () => { lock (sync) { if (instance == null) { instance = factory(); _accessor = () => instance; } return instance; } }; } public static AppDelegate DefaultFactory() { var configurationString = ConfigurationManager.AppSettings["Gate.Startup"]; return AppBuilder.BuildConfiguration(configurationString); } } } <file_sep>/src/Hosts/Gate.Hosts.Firefly/ExecutionContextPerRequest.cs using System; using System.Threading; using Owin; namespace Gate.Hosts.Firefly { public static class ExecutionContextPerRequest { public static AppDelegate Middleware(AppDelegate app) { return (env, result, fault) => { ExecutionContext.SuppressFlow(); ThreadPool.QueueUserWorkItem( _ => { var context = ExecutionContext.Capture(); app( env, WrapResultDelegate(context, result), fault); }, null); ExecutionContext.RestoreFlow(); }; } static ResultDelegate WrapResultDelegate(ExecutionContext context, ResultDelegate result) { return (status, headers, body) => result( status, headers, WrapBodyDelegate(context, body)); } static BodyDelegate WrapBodyDelegate(ExecutionContext context, BodyDelegate body) { return body == null ? (BodyDelegate)null : (write, end, cancellationToken) => ExecutionContext.Run( context.CreateCopy(), _ => body(WrapWriteDelegate(context, write), end, cancellationToken), null); } static Func<ArraySegment<byte>, Action, bool> WrapWriteDelegate(ExecutionContext context, Func<ArraySegment<byte>, Action, bool> write) { return (data, callback) => callback == null ? write(data, null) : write(data, () => ExecutionContext.Run(context.CreateCopy(), _ => callback(), null)); } } } <file_sep>/src/Adapters/Gate.Adapters.Nancy/ResponseStream.cs using System; using System.IO; using System.Threading; namespace Gate.Adapters.Nancy { class ResponseStream : Stream { private Func<ArraySegment<byte>, Action, bool> _write; private Action<Exception> _end; public ResponseStream(Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end) { _write = write; _end = end; } public override void Close() { End(null); } public void End(Exception ex) { _write = (data, callback) => false; Interlocked.Exchange(ref _end, _ => { }).Invoke(ex); } public override void Flush() { _write(default(ArraySegment<byte>), null); } public override void Write(byte[] buffer, int offset, int count) { _write(new ArraySegment<byte>(buffer, offset, count), null); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var result = new WriteAsyncResult { AsyncState = state }; var delayed = _write(new ArraySegment<byte>(buffer, offset, count), () => { result.IsCompleted = true; if (callback != null) { try { callback(result); } catch { } } }); if (!delayed) { result.CompletedSynchronously = true; result.IsCompleted = true; if (callback != null) { try { callback(result); } catch { } } } return result; } public override void EndWrite(IAsyncResult asyncResult) { if (!asyncResult.IsCompleted) { throw new InvalidOperationException("Async write with wait state is not supported"); } } public class WriteAsyncResult : IAsyncResult { public bool IsCompleted { get; set; } public WaitHandle AsyncWaitHandle { get { throw new InvalidOperationException("Async write with wait state is not supported"); } } public object AsyncState { get; set; } public bool CompletedSynchronously { get; set; } } public override void WriteByte(byte value) { Write(new[] { value }, 0, 1); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotImplementedException(); } public override int EndRead(IAsyncResult asyncResult) { throw new NotImplementedException(); } public override int ReadByte() { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanTimeout { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override int ReadTimeout { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override int WriteTimeout { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }<file_sep>/src/Adapters/Gate.Adapters.AspNetWebApi/ResponseHttpStream.cs using System; using System.Threading; using System.Threading.Tasks; namespace Gate.Adapters.AspNetWebApi { class ResponseHttpStream : StreamNotImpl { private readonly Func<ArraySegment<byte>, Action, bool> _write; private Action<Exception> _end; public ResponseHttpStream( Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end) { _write = write; _end = end; } public override void Close() { Interlocked.Exchange(ref _end, error => { }).Invoke(null); } public override bool CanWrite { get { return true; } } public override void Write(byte[] buffer, int offset, int count) { _write(new ArraySegment<byte>(buffer, offset, count), null); } public override void Flush() { _write(default(ArraySegment<byte>), null); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var tcs = new TaskCompletionSource<object>(state); if (callback != null) { tcs.Task.ContinueWith(_ => callback(tcs.Task)).Catch(); } if (!_write(new ArraySegment<byte>(buffer, offset, count), () => tcs.TrySetResult(null))) { tcs.TrySetResult(null); } return tcs.Task; } public override void EndWrite(IAsyncResult asyncResult) { ((Task)asyncResult).Wait(); } } }<file_sep>/src/Hosts/Gate.Hosts.Kayak/GateRequestDelegate.cs using System; using System.Collections.Generic; using System.Text; using System.Linq; using Owin; using Kayak; using Kayak.Http; namespace Gate.Hosts.Kayak { class GateRequestDelegate : IHttpRequestDelegate { AppDelegate appDelegate; IDictionary<string, object> context; public GateRequestDelegate(AppDelegate appDelegate, IDictionary<string, object> context) { this.appDelegate = appDelegate; this.context = context; } public void OnRequest(HttpRequestHead head, IDataProducer body, IHttpResponseDelegate response) { var env = new Dictionary<string, object>(); var request = new RequestEnvironment(env); if (context != null) foreach (var kv in context) env[kv.Key] = kv.Value; if (head.Headers == null) request.Headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); else request.Headers = head.Headers.ToDictionary(kv => kv.Key, kv => new[] { kv.Value }, StringComparer.OrdinalIgnoreCase); request.Method = head.Method ?? ""; request.Path = head.Path ?? ""; request.PathBase = ""; request.QueryString = head.QueryString ?? ""; request.Scheme = "http"; // XXX request.Version = "1.0"; if (body == null) request.BodyDelegate = null; else request.BodyDelegate = (write, end, cancellationToken) => { var d = body.Connect(new DataConsumer( write, end, () => end(null))); cancellationToken.Register(d.Dispose); }; appDelegate(env, HandleResponse(response), HandleError(response)); } ResultDelegate HandleResponse(IHttpResponseDelegate response) { return (status, headers, body) => { if (headers == null) headers = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); if (body != null && !headers.ContainsKey("Content-Length") && !headers.ContainsKey("Transfer-Encoding")) { // disable keep-alive in this case headers["Connection"] = new[] {"close"}; } response.OnResponse(new HttpResponseHead() { Status = status, Headers = headers.ToDictionary(kv => kv.Key, kv => string.Join("\r\n", kv.Value.ToArray()), StringComparer.OrdinalIgnoreCase), }, body == null ? null : new DataProducer(body)); }; } Action<Exception> HandleError(IHttpResponseDelegate response) { return error => { Console.Error.WriteLine("Error from Gate application."); Console.Error.WriteStackTrace(error); response.OnResponse(new HttpResponseHead() { Status = "503 Internal Server Error", Headers = new Dictionary<string, string>() { { "Connection", "close" } } }, null); }; } } } <file_sep>/src/Tests/Gate.Tests/TestClientTests.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using Gate.TestHelpers; using NUnit.Framework; using Owin; namespace Gate.Tests { [TestFixture] public class TestClientTests { [Test] public void ForConfigurationShouldCallWithBuilderAndReturnHttpClient() { var called = 0; var httpClient = TestHttpClient.ForConfiguration(builder => { ++called; }); Assert.That(called, Is.EqualTo(1)); Assert.That(httpClient, Is.Not.Null); } [Test] public void RequestPassesThroughToApplication() { var client = TestHttpClient.ForAppDelegate(NotFound.Call); var result = client.GetAsync("http://localhost/foo?hello=world").Result; Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.NotFound)); Assert.That(client.Calls.Count, Is.EqualTo(1)); Assert.That(client.Calls.Single().ResponseStatus, Is.EqualTo("404 Not Found")); } [Test] public void ResponseBodyIsReturned() { var client = TestHttpClient.ForAppDelegate(ReturnText("Hello world")); var result = client.GetStringAsync("http://localhost/foo?hello=world").Result; Assert.That(result, Is.EqualTo("Hello world")); } [Test] public void ResponseHeadersAreReturned() { var client = TestHttpClient.ForAppDelegate(ReturnText("Hello world")); client.GetStringAsync("http://localhost/foo?hello=world").Wait(); Assert.That(client.Calls.Single().ResponseHeaders["Content-Type"].Single(), Is.EqualTo("text/plain")); Assert.That(client.Calls.Single().HttpResponseMessage.Content.Headers.ContentType.MediaType, Is.EqualTo("text/plain")); Assert.That(client.Calls.Single().ResponseHeaders["X-Server"].Single(), Is.EqualTo("inproc")); Assert.That(client.Calls.Single().HttpResponseMessage.Headers.GetValues("X-Server").Single(), Is.EqualTo("inproc")); } [Test] public void RequestIsAssociatedWithResponse() { var client = TestHttpClient.ForAppDelegate(ReturnText("Hello world")); var responseMessage = client.GetAsync("http://localhost/foo?hello=world").Result; Assert.That(responseMessage.RequestMessage, Is.Not.Null); Assert.That(responseMessage.RequestMessage.RequestUri.Query, Is.EqualTo("?hello=world")); } [Test] public void RequestContentShouldBeSent() { var client = new TestHttpClient(EchoRequestBody()); var requestContent = new StringContent("Hello world", Encoding.UTF8, "text/plain"); var responseMessage = client.PostAsync("http://localhost/", requestContent).Result; var result = responseMessage.Content.ReadAsStringAsync().Result; Assert.That(result, Is.EqualTo("Hello world")); } AppDelegate EchoRequestBody() { return (env, result, fault) => { var callDisposed = (CancellationToken)env["host.CallDisposed"]; var requestHeaders = (IDictionary<string, string[]>)env["owin.RequestHeaders"]; var requestBody = (BodyDelegate)env["owin.RequestBody"]; var responseHeaders = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) { {"Content-Type", requestHeaders["Content-Type"].ToArray()} }; Action<Func<ArraySegment<byte>, Action, bool>> repeatAllData = write => { }; requestBody.Invoke( (data, callback) => { var copy = new byte[data.Count]; Array.Copy(data.Array, data.Offset, copy, 0, data.Count); var priorDelegate = repeatAllData; repeatAllData = write => { priorDelegate(write); write(new ArraySegment<byte>(copy), null); }; return false; }, ex => { if (ex != null) { fault(ex); } else { result.Invoke( "200 OK", responseHeaders, (write, end, cancel) => { repeatAllData(write); end(null); }); } }, callDisposed); }; } AppDelegate ReturnText(string text) { return (env, result, fault) => result( "200 OK", new Dictionary<string, string[]> { {"Content-Type", new[] {"text/plain"}}, {"X-Server", new[] {"inproc"}} }, (write, end, cancel) => { write(new ArraySegment<byte>(Encoding.ASCII.GetBytes(text)), null); end(null); }); } } } <file_sep>/src/Hosts/Gate.Hosts.Manos/Server.cs using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading; using Owin; using Manos.Collections; using Manos.Http; using Manos.IO; namespace Gate.Hosts.Manos { public static class Server { public static IDisposable Create(AppDelegate app, int port) { return Create(app, port, ""); } public static IDisposable Create(AppDelegate app, int port, string path) { app = ErrorPage.Middleware(app); var effectivePath = path; var endpoint = new IPEndPoint(IPAddress.Any, port); var context = Context.Create(); var httpServer = new HttpServer( context, transaction => { var cts = new CancellationTokenSource(); var requestPathBase = effectivePath; if (requestPathBase == "/" || requestPathBase == null) requestPathBase = ""; var requestPath = transaction.Request.Path; if (requestPath.StartsWith(requestPathBase, StringComparison.OrdinalIgnoreCase)) requestPath = requestPath.Substring(requestPathBase.Length); var requestQueryString = RequestQueryString(transaction.Request.QueryData); var requestHeaders = transaction.Request.Headers.Keys.ToDictionary(k => k, k => transaction.Request.Headers[k], StringComparer.OrdinalIgnoreCase); var env = new Dictionary<string, object> { {OwinConstants.Version, "1.0"}, {OwinConstants.RequestMethod, transaction.Request.Method.ToString().Substring(5)}, {OwinConstants.RequestScheme, "http"}, {OwinConstants.RequestPathBase, requestPathBase}, {OwinConstants.RequestPath, requestPath}, {OwinConstants.RequestQueryString, requestQueryString}, {OwinConstants.RequestHeaders, requestHeaders}, {OwinConstants.RequestBody, RequestBody(transaction.Request.PostBody, transaction.Request.ContentEncoding)}, {"Manos.Http.IHttpTransaction", transaction}, {"server.CLIENT_IP", transaction.Request.Socket.RemoteEndpoint.Address.ToString()}, {"System.Threading.CancellationToken", cts.Token} }; app( env, (status, headers, body) => { transaction.Response.StatusCode = int.Parse(status.Substring(0, 3)); foreach (var header in headers) { if (string.Equals(header.Key, "Set-Cookie", StringComparison.OrdinalIgnoreCase)) { // use a header-injection to avoid re-parsing values into Manos HttpCookie structure transaction.Response.SetHeader(header.Key, string.Join("\r\nSet-Cookie: ", header.Value.ToArray())); } else { transaction.Response.SetHeader(header.Key, string.Join(",", header.Value.ToArray())); } } body( (data, callback) => { var duplicate = new byte[data.Count]; Array.Copy(data.Array, data.Offset, duplicate, 0, data.Count); transaction.Response.Write(duplicate); return false; }, ex => transaction.Response.End(), cts.Token); }, ex => { // This should never be called throw new NotImplementedException(); }); }, context.CreateTcpServerSocket(endpoint.AddressFamily), true); httpServer.Listen(endpoint.Address.ToString(), port); var thread = new Thread(context.Start); thread.Start(); return new Disposable(() => { context.Stop(); thread.Join(250); //httpServer.Dispose(); }); } static string RequestQueryString(DataDictionary queryData) { var count = queryData.Count; if (count == 0) return null; var sb = new StringBuilder(); foreach (var key in queryData.Keys) { if (sb.Length != 0) { sb.Append('&'); } UrlEncode(key, sb); sb.Append('='); UrlEncode(queryData.Get(key).UnsafeValue, sb); } return sb.ToString(); } static void UrlEncode(string text, StringBuilder sb) { var bytes = new byte[8]; var count = text.Length; for (var index = 0; index != count; ++index) { var ch = text[index]; if (char.IsLetterOrDigit(ch) || ch == '.' || ch == '-' || ch == '~' || ch == '_') { sb.Append(ch); } else if (ch == ' ') { sb.Append('+'); } else { var byteCount = Encoding.UTF8.GetBytes(text, index, 1, bytes, 0); for (var byteIndex = 0; byteIndex != byteCount; ++byteIndex) { sb.Append('%'); sb.Append("0123456789ABCDEF"[bytes[byteIndex] / 0x10]); sb.Append("0123456789ABCDEF"[bytes[byteIndex] & 0x0f]); } } } } static BodyDelegate RequestBody(string postBody, Encoding encoding) { return (write, end, cancel) => { try { var data = new ArraySegment<byte>(encoding.GetBytes(postBody)); write(data, null); end(null); } catch (Exception ex) { end(ex); } }; } public class Disposable : IDisposable { readonly Action _dispose; public Disposable(Action dispose) { _dispose = dispose; } public void Dispose() { _dispose(); } } } } <file_sep>/src/Main/Gate/RequestStream.cs using System; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Gate.Utils; using Owin; namespace Gate { public class RequestStream : Stream { readonly Spool _spool; Exception _error; public RequestStream() { _spool = new Spool(true); } public void Start(BodyDelegate body, CancellationToken cancel) { body.Invoke(OnWrite, OnEnd, cancel); } bool OnWrite(ArraySegment<byte> data, Action callback) { return _spool.Push(data, callback); } void OnEnd(Exception error) { _error = error; _spool.PushComplete(); } public override void Flush() { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { var retval = new int[1]; _spool.Pull(new ArraySegment<byte>(buffer, offset, count), retval, null); if (retval[0] == 0 && _error != null) { // return error that arrived from request stream source throw new TargetInvocationException(_error); } return retval[0]; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var tcs = new TaskCompletionSource<int>(state); var retval = new int[1]; Action result = () => { if (retval[0] == 0 && _error != null) { // return error that arrived from request stream source tcs.SetException(_error); } else { tcs.SetResult(retval[0]); } }; if (!_spool.Pull(new ArraySegment<byte>(buffer, offset, count), retval, result)) { result.Invoke(); } if (callback != null) { tcs.Task.Then(() => callback(tcs.Task)); } return tcs.Task; } public override int EndRead(IAsyncResult asyncResult) { return ((Task<int>)asyncResult).Result; } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }<file_sep>/src/Main/Gate.Middleware/StaticFiles/StateMachine.cs using System; using System.Collections.Generic; namespace Gate.Middleware.StaticFiles { public class StateMachine<TCommand, TState> where TCommand : struct where TState : struct { private readonly IDictionary<TCommand, Action> handlers = new Dictionary<TCommand, Action>(); private readonly IDictionary<TCommand, TState> transitions = new Dictionary<TCommand, TState>(); public TState State { get; private set; } public void Initialize(TState state) { State = state; } public StateMachine<TCommand, TState> MapTransition(TCommand command, TState state) { transitions[command] = state; return this; } public void On(TCommand command, Action handler) { handlers[command] = handler; } public void Invoke(TCommand command) { if (transitions.ContainsKey(command)) { State = transitions[command]; } if (handlers.ContainsKey(command)) { handlers[command].Invoke(); } } } } <file_sep>/src/Main/Gate.Middleware/StaticFiles/BodyStream.cs using System; using System.Linq; using System.Threading; namespace Gate.Middleware.StaticFiles { public enum BodyStreamCommand { Start, Pause, Stop, Cancel, Resume } public enum BodyStreamState { Ready, Started, Paused, Stopped, Cancelled, Resumed } public class BodyStream { private readonly StateMachine<BodyStreamCommand, BodyStreamState> stateMachine; public Func<ArraySegment<byte>, Action, bool> Write { get; private set; } public Action<Exception> End { get; private set; } public CancellationToken CancellationToken { get; private set; } public BodyStream(Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancellationToken) { stateMachine = new StateMachine<BodyStreamCommand, BodyStreamState>(); stateMachine.Initialize(BodyStreamState.Ready); stateMachine.MapTransition(BodyStreamCommand.Pause, BodyStreamState.Paused); stateMachine.MapTransition(BodyStreamCommand.Start, BodyStreamState.Started); stateMachine.MapTransition(BodyStreamCommand.Cancel, BodyStreamState.Cancelled); stateMachine.MapTransition(BodyStreamCommand.Resume, BodyStreamState.Resumed); stateMachine.MapTransition(BodyStreamCommand.Stop, BodyStreamState.Stopped); Write = write; End = end; CancellationToken = cancellationToken; } public void Start(Action start, Action dispose) { if (start == null) { throw new ArgumentNullException("start", "Missing start action for the BodyStream."); } stateMachine.On(BodyStreamCommand.Start, start); stateMachine.Invoke(BodyStreamCommand.Start); CancellationToken.Register(Cancel); if (dispose != null) { foreach (var command in new[] { BodyStreamCommand.Stop, BodyStreamCommand.Cancel }) { stateMachine.On(command, dispose); } } } public void Finish() { Stop(); End(null); } public void SendBytes(ArraySegment<byte> part, Action continuation, Action complete) { if (!CanSend()) { if (complete != null) { complete.Invoke(); } return; } Action resume = null; Action pause = () => { }; if (continuation != null) { stateMachine.On(BodyStreamCommand.Resume, continuation); resume = Resume; pause = Pause; } // call on-next with back-pressure support if (Write(part, resume)) { pause.Invoke(); } if (complete != null) { complete.Invoke(); } } public void Cancel() { stateMachine.Invoke(BodyStreamCommand.Cancel); } public void Pause() { stateMachine.Invoke(BodyStreamCommand.Pause); } public void Resume() { stateMachine.Invoke(BodyStreamCommand.Resume); } public void Stop() { stateMachine.Invoke(BodyStreamCommand.Stop); } public bool CanSend() { var validStates = new[] { BodyStreamState.Started, BodyStreamState.Resumed }; return validStates.Contains(stateMachine.State); } } } <file_sep>/src/Main/Gate/Request.cs using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Gate.Utils; namespace Gate { using BodyAction = Action<Func<ArraySegment<byte>, Action, bool>, Action<Exception>, Action, CancellationToken>; public class Request : Environment { static readonly char[] CommaSemicolon = new[] { ',', ';' }; public Request(IDictionary<string, object> env) : base(env) { } public IDictionary<string, string> Query { get { var text = QueryString; if (Get<string>("Gate.Request.Query#text") != text || Get<IDictionary<string, string>>("Gate.Request.Query") == null) { this["Gate.Request.Query#text"] = text; this["Gate.Request.Query"] = ParamDictionary.Parse(text); } return Get<IDictionary<string, string>>("Gate.Request.Query"); } } static readonly char[] CookieParamSeparators = new[] { ';', ',' }; public IDictionary<string, string> Cookies { get { var cookies = Get<IDictionary<string, string>>("Gate.Request.Cookies#dictionary"); if (cookies == null) { cookies = new Dictionary<string, string>(StringComparer.Ordinal); Env["Gate.Request.Cookies#dictionary"] = cookies; } var text = Headers.GetHeader("Cookie"); if (Get<string>("Gate.Request.Cookies#text") != text) { cookies.Clear(); foreach (var kv in ParamDictionary.ParseToEnumerable(text, CookieParamSeparators)) { if (!cookies.ContainsKey(kv.Key)) cookies.Add(kv); } Env["Gate.Request.Cookies#text"] = text; } return cookies; } } public bool HasFormData { get { var mediaType = MediaType; return (Method == "POST" && string.IsNullOrEmpty(mediaType)) || mediaType == "application/x-www-form-urlencoded" || mediaType == "multipart/form-data"; } } public bool HasParseableData { get { var mediaType = MediaType; return mediaType == "application/x-www-form-urlencoded" || mediaType == "multipart/form-data"; } } public string ContentType { get { return Headers.GetHeader("Content-Type"); } } public string MediaType { get { var contentType = ContentType; if (contentType == null) return null; var delimiterPos = contentType.IndexOfAny(CommaSemicolon); return delimiterPos < 0 ? contentType : contentType.Substring(0, delimiterPos); } } public Stream OpenInputStream() { var inputStream = new RequestStream(); inputStream.Start(BodyDelegate, CallDisposed); return inputStream; } public Task CopyToStreamAsync(Stream stream, CancellationToken cancel) { var tcs = new TaskCompletionSource<object>(); BodyDelegate.Invoke( (data, callback) => { try { if (data.Array == null) { stream.Flush(); return false; } if (callback == null) { stream.Write(data.Array, data.Offset, data.Count); return false; } var sr = stream.BeginWrite( data.Array, data.Offset, data.Count, ar => { if (ar.CompletedSynchronously) { return; } try { stream.EndWrite(ar); } catch (Exception ex) { tcs.TrySetException(ex); } finally { try { callback(); } catch (Exception ex) { tcs.TrySetException(ex); } } }, null); if (!sr.CompletedSynchronously) { return true; } stream.EndWrite(sr); return false; } catch (Exception ex) { tcs.SetException(ex); return false; } }, ex => { if (ex == null) { tcs.TrySetResult(null); } else { tcs.TrySetException(ex); } }, cancel); return tcs.Task; } public Task<string> ReadTextAsync() { var text = Get<string>("Gate.Request.Text"); var thisInput = BodyDelegate; var lastInput = Get<object>("Gate.Request.Text#input"); var tcs = new TaskCompletionSource<string>(); if (text != null && ReferenceEquals(thisInput, lastInput)) { tcs.SetResult(text); return tcs.Task; } var buffer = new MemoryStream(); //TODO: determine encoding from request content type return CopyToStreamAsync(buffer, CallDisposed) .Then(() => new StreamReader(buffer).ReadToEnd()); } public string ReadText() { return ReadTextAsync().Result; } public Task<IDictionary<string, string>> ReadFormAsync() { if (!HasFormData && !HasParseableData) { var tcs = new TaskCompletionSource<IDictionary<string, string>>(); tcs.SetResult(ParamDictionary.Parse("")); return tcs.Task; } var form = Get<IDictionary<string, string>>("Gate.Request.Form"); var thisInput = Get<object>(OwinConstants.RequestBody); var lastInput = Get<object>("Gate.Request.Form#input"); if (form != null && ReferenceEquals(thisInput, lastInput)) { var tcs = new TaskCompletionSource<IDictionary<string, string>>(); tcs.SetResult(form); return tcs.Task; } return ReadTextAsync().Then(text => { form = ParamDictionary.Parse(text); this["Gate.Request.Form#input"] = thisInput; this["Gate.Request.Form"] = form; return form; }); } public IDictionary<string, string> ReadForm() { return ReadFormAsync().Result; } public string HostWithPort { get { var hostHeader = Headers.GetHeader("Host"); if (!string.IsNullOrWhiteSpace(hostHeader)) { return hostHeader; } var serverName = Get<string>("server.SERVER_NAME"); if (string.IsNullOrWhiteSpace(serverName)) serverName = Get<string>("server.SERVER_ADDRESS"); var serverPort = Get<string>("server.SERVER_PORT"); return serverName + ":" + serverPort; } } public string Host { get { var hostHeader = Headers.GetHeader("Host"); if (!string.IsNullOrWhiteSpace(hostHeader)) { var delimiter = hostHeader.IndexOf(':'); return delimiter < 0 ? hostHeader : hostHeader.Substring(0, delimiter); } var serverName = Get<string>("server.SERVER_NAME"); if (string.IsNullOrWhiteSpace(serverName)) serverName = Get<string>("server.SERVER_ADDRESS"); return serverName; } } } }<file_sep>/src/Tests/Gate.Middleware.Tests/ContentLengthTests.cs using System; using Gate.Middleware; using Gate.TestHelpers; using Owin; using Gate.Builder; using NUnit.Framework; using System.Text; namespace Gate.Middleware.Tests { [TestFixture] public class ContentLengthTests { [Test] public void Content_length_is_added_if_body_is_zero_length() { var result = AppUtils.CallPipe(b => b .UseContentLength() .Simple( "200 OK", headers => { }, write => { })); Assert.That(result.Headers.GetHeader("content-length"), Is.EqualTo("0")); } [Test] public void Content_length_is_added() { var result = AppUtils.CallPipe(b => b .UseContentLength() .Simple( "200 OK", headers => { }, write => { write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("hello "))); write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("world."))); })); Assert.That(result.Headers.GetHeader("content-length"), Is.EqualTo("12")); } [Test] public void Content_length_is_not_changed() { var result = AppUtils.CallPipe(b => b .UseContentLength() .Simple( "200 OK", headers => headers.SetHeader("content-length", "69"), write => { })); Assert.That(result.Headers.GetHeader("content-length"), Is.EqualTo("69")); } [Test] public void Content_length_is_not_added_if_transfer_encoding_is_present() { var result = AppUtils.CallPipe(b => b .UseContentLength() .Simple( "200 OK", headers => headers.SetHeader("transfer-encoding", "chunked"), write => { })); Assert.That(result.Headers.ContainsKey("content-length"), Is.False); } [Test] [Sequential] public void Content_length_is_not_added_if_response_status_should_not_have_a_response_body( [Values( "204 No Content", "205 Reset Content", "304 Not Modified", "100 Continue", "101 Switching Protocols", "112 Whatever" // and all other 1xx statuses... )] string status) { var result = AppUtils.CallPipe(b => b .UseContentLength() .Simple(status, headers => { }, write => { })); Assert.That(result.Headers.ContainsKey("content-length"), Is.False); } } } <file_sep>/src/Samples/Samples.ViaRouting/Startup.cs using System; using System.Collections.Generic; using System.Text; using System.Web.Routing; using Gate; using Gate.Hosts.AspNet; using Gate.Middleware; using Owin; namespace Samples.ViaRouting { public class Startup { public void Configuration(IAppBuilder builder) { var xx = default(ArraySegment<byte>); // routes can be added for each path prefix that should be // mapped to owin RouteTable.Routes.AddOwinRoute("hello"); RouteTable.Routes.AddOwinRoute("world"); // the routes above will be map onto whatever is added to // the IAppBuilder builder that was passed into this method builder.RunDirect((req, res) => { res.ContentType = "text/plain"; res.End("Hello from " + req.PathBase + req.Path); }); // a route may also be added for a given builder method. // this can also be done from global.asax RouteTable.Routes.AddOwinRoute("wilson-async", x => x.UseShowExceptions().UseContentType("text/plain").Run(Wilson.AsyncApp())); // a route may also be added for a given builder method. // this can also be done from global.asax RouteTable.Routes.AddOwinRoute("wilson", x => x.UseShowExceptions().UseContentType("text/plain").Run(Wilson.App())); // a route may also be added for a given app delegate // this can also be done from global.asax RouteTable.Routes.AddOwinRoute("raw", Raw); } void ConfigWilson(IAppBuilder builder) { builder.UseShowExceptions().Run(Wilson.App()); } void Raw(IDictionary<string, object> env, ResultDelegate result, Action<Exception> fault) { result( "200 OK", new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } }, (write, end, cancel) => { write(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello from lowest-level code")), null); end(null); }); } } } <file_sep>/src/Hosts/Gate.Hosts/PipeRequest.cs using System; using System.IO; using System.Threading; namespace Gate.Hosts { class PipeRequest { readonly Stream _stream; readonly Func<ArraySegment<byte>, Action, bool> _write; Action<Exception> _end; readonly CancellationToken _cancellationToken; readonly byte[] _buffer; ArraySegment<byte> _segment; bool _running; public PipeRequest( Stream stream, Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancellationToken) { _stream = stream; _write = write; _end = end; _cancellationToken = cancellationToken; _buffer = new byte[1024]; } public Action Go() { _running = true; try { Loop(0); } catch (Exception ex) { FireError(ex); } return () => _running = false; } void Loop(int mode) { while (_running) { switch (mode) { case 0: { var sr = _stream.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, null); if (!sr.CompletedSynchronously) { return; } _segment = new ArraySegment<byte>(_buffer, 0, _stream.EndRead(sr)); mode = 1; } break; case 1: { if (_segment.Count == 0) { FireComplete(); return; } if (_write(_segment, NextCallback)) { return; } mode = 0; } break; } } } void ReadCallback(IAsyncResult ar) { if (ar.CompletedSynchronously) { return; } try { _segment = new ArraySegment<byte>(_buffer, 0, _stream.EndRead(ar)); Loop(1); } catch (Exception ex) { FireError(ex); } } void NextCallback() { try { Loop(0); } catch (Exception ex) { FireError(ex); } } void FireError(Exception ex) { _running = false; Interlocked.Exchange(ref _end, _ => { }).Invoke(ex); } void FireComplete() { _running = false; Interlocked.Exchange(ref _end, _ => { }).Invoke(null); } } }<file_sep>/src/Main/Gate.Middleware/StaticFiles/FileBody.cs using System; using System.IO; using System.Threading; using Owin; namespace Gate.Middleware.StaticFiles { public class FileBody { private FileStream fileStream; private readonly Tuple<long, long> range; private readonly string path; private BodyStream bodyStream; public FileBody(string path, Tuple<long, long> range) { this.path = path; this.range = range; } public static BodyDelegate Create(string path, Tuple<long, long> range) { return (write, end, cancel) => { var fileBody = new FileBody(path, range); fileBody.Start(write, end, cancel); }; } void Start(Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancellationToken) { bodyStream = new BodyStream(write, end, cancellationToken); Action start = () => { try { var rangeLength = range.Item2 - range.Item1 + 1; SendFile(rangeLength); } catch (Exception ex) { bodyStream.End(ex); } }; Action dispose = () => { if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); fileStream = null; } }; bodyStream.Start(start, dispose); } private void SendFile(long length) { if (bodyStream.CanSend()) { EnsureOpenFileStream(); SendBuffer(length); } } private void EnsureOpenFileStream() { if (fileStream == null || !fileStream.CanRead) { fileStream = File.OpenRead(path); fileStream.Seek(range.Item1, SeekOrigin.Begin); } } private void SendBuffer(long length) { var segmentInfo = ReadNextBuffer(length); var buffer = segmentInfo.Item1; var bytesRead = segmentInfo.Item2; if (bytesRead == 0) { bodyStream.Finish(); return; } length -= bytesRead; Action nextCall = () => SendFile(length); bodyStream.SendBytes(buffer, nextCall, nextCall); } private Tuple<ArraySegment<byte>, long> ReadNextBuffer(long remainingLength) { const long maxBufferSize = 64 * 1024; var bufferSize = remainingLength < maxBufferSize ? remainingLength : maxBufferSize; var part = new byte[bufferSize]; var bytesRead = fileStream.Read(part, 0, (int)bufferSize); return new Tuple<ArraySegment<byte>, long>(new ArraySegment<byte>(part), bytesRead); } } }<file_sep>/src/Main/Gate.Middleware/ContentType.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Owin; namespace Gate.Middleware { /// <summary> /// Sets content type in response if none present /// </summary> public static class ContentType { const string DefaultContentType = "text/html"; public static IAppBuilder UseContentType(this IAppBuilder builder) { return builder.Use(Middleware); } public static IAppBuilder UseContentType(this IAppBuilder builder, string contentType) { return builder.Use(Middleware, contentType); } public static AppDelegate Middleware(AppDelegate app) { return Middleware(app, DefaultContentType); } public static AppDelegate Middleware(AppDelegate app, string contentType) { return (env, result, fault) => app( env, (status, headers, body) => { if (!headers.HasHeader("Content-Type")) { headers.SetHeader("Content-Type", contentType); } result(status, headers, body); }, fault); } } }<file_sep>/src/Hosts/Gate.Hosts.Manos/Workaround.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Owin; namespace Gate.Hosts.Manos { class Workaround { #pragma warning disable 169 ResultDelegate _resultDelegate; Func<int, int> _func2; Func<int, int, int> _func3; #pragma warning restore 169 } } <file_sep>/src/Hosts/Gate.Hosts/Workaround.cs using System; using Owin; namespace Gate.Hosts { class Workaround { #pragma warning disable 169 ResultDelegate _resultDelegate; Func<int, int> _func2; Func<int, int, int> _func3; #pragma warning restore 169 } } <file_sep>/src/Main/Gate.Middleware/ContentLength.cs using System; using System.Linq; using System.Collections.Generic; using System.Threading; using Owin; namespace Gate.Middleware { using Response = Tuple<string, IDictionary<string, string[]>, BodyDelegate>; public static class ContentLength { public static IAppBuilder UseContentLength(this IAppBuilder builder) { return builder.Use<AppDelegate>(Middleware); } public static AppDelegate Middleware(AppDelegate app) { return (env, result, fault) => app( env, (status, headers, body) => { if (IsStatusWithNoNoEntityBody(status) || headers.ContainsKey("Content-Length") || headers.ContainsKey("Transfer-Encoding")) { result(status, headers, body); } else { var token = CancellationToken.None; object obj; if (env.TryGetValue(typeof(CancellationToken).FullName, out obj) && obj is CancellationToken) token = (CancellationToken)obj; var buffer = new DataBuffer(); body( buffer.Add, ex => { buffer.End(ex); headers["Content-Length"] = new[] { buffer.GetCount().ToString() }; result(status, headers, buffer.Body); }, token); } }, fault); } private static bool IsStatusWithNoNoEntityBody(string status) { return status.StartsWith("1") || status.StartsWith("204") || status.StartsWith("205") || status.StartsWith("304"); } class DataBuffer { readonly List<ArraySegment<byte>> _buffers = new List<ArraySegment<byte>>(); ArraySegment<byte> _tail = new ArraySegment<byte>(new byte[2048], 0, 0); Exception _error; public int GetCount() { return _buffers.Aggregate(0, (c, d) => c + d.Count); } public bool Add(ArraySegment<byte> data, Action continuation) { var remaining = data; while (remaining.Count != 0) { if (_tail.Count + _tail.Offset == _tail.Array.Length) { _buffers.Add(_tail); _tail = new ArraySegment<byte>(new byte[4096], 0, 0); } var copyCount = Math.Min(remaining.Count, _tail.Array.Length - _tail.Offset - _tail.Count); Array.Copy(remaining.Array, remaining.Offset, _tail.Array, _tail.Offset + _tail.Count, copyCount); _tail = new ArraySegment<byte>(_tail.Array, _tail.Offset, _tail.Count + copyCount); remaining = new ArraySegment<byte>(remaining.Array, remaining.Offset + copyCount, remaining.Count - copyCount); } return false; } public void End(Exception error) { _buffers.Add(_tail); _error = error; } public void Body( Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancel) { try { foreach (var data in _buffers) { if (cancel.IsCancellationRequested) break; write(data, null); } end(_error); } catch (Exception ex) { end(ex); } } } } } <file_sep>/src/Adapters/Gate.Adapters.AspNetWebApi/RequestHttpContent.cs using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Owin; namespace Gate.Adapters.AspNetWebApi { class RequestHttpContent : HttpContent { readonly BodyDelegate _body; readonly CancellationToken _cancellationToken; public RequestHttpContent(BodyDelegate body, CancellationToken cancellationToken) { _body = body; _cancellationToken = cancellationToken; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { var tcs = new TaskCompletionSource<object>(); _body.Invoke( (data, callback) => { if (data.Count == 0) { stream.Flush(); } else if (callback == null) { stream.Write(data.Array, data.Offset, data.Count); } else { var sr = stream.BeginWrite(data.Array, data.Offset, data.Count, ar => { if (!ar.CompletedSynchronously) { try { stream.EndWrite(ar); } catch { } try { callback.Invoke(); } catch { } } }, null); if (!sr.CompletedSynchronously) { return true; } stream.EndWrite(sr); callback.Invoke(); } return false; }, ex => { if (ex == null) { tcs.TrySetResult(null); } else { tcs.TrySetException(ex); } }, _cancellationToken); return tcs.Task; } protected override bool TryComputeLength(out long length) { length = 0; return false; } } }<file_sep>/src/Main/Gate.Middleware/Chunked.cs using System; using System.Collections.Generic; using Owin; using System.Text; namespace Gate.Middleware { public static class Chunked { public static IAppBuilder UseChunked(this IAppBuilder builder) { return builder.Use<AppDelegate>(Middleware); } static readonly ArraySegment<byte> EndOfChunk = new ArraySegment<byte>(Encoding.ASCII.GetBytes("\r\n")); static readonly ArraySegment<byte> FinalChunk = new ArraySegment<byte>(Encoding.ASCII.GetBytes("0\r\n\r\n")); static readonly byte[] Hex = Encoding.ASCII.GetBytes("0123456789abcdef\r\n"); public static AppDelegate Middleware(AppDelegate app) { return (env, result, fault) => app( env, (status, headers, body) => { if (IsStatusWithNoNoEntityBody(status) || headers.ContainsKey("Content-Length") || headers.ContainsKey("Transfer-Encoding")) { result(status, headers, body); } else { headers["Transfer-Encoding"] = new[] { "chunked" }; result( status, headers, (write, end, cancel) => body( (data, callback) => { if (data.Count == 0) { return write(data, callback); } write(ChunkPrefix((uint)data.Count), null); write(data, null); return write(EndOfChunk, callback); }, ex => { if (ex == null) { write(FinalChunk, null); } end(ex); }, cancel)); } }, fault); } public static ArraySegment<byte> ChunkPrefix(uint dataCount) { var prefixBytes = new[] { Hex[(dataCount >> 28) & 0xf], Hex[(dataCount >> 24) & 0xf], Hex[(dataCount >> 20) & 0xf], Hex[(dataCount >> 16) & 0xf], Hex[(dataCount >> 12) & 0xf], Hex[(dataCount >> 8) & 0xf], Hex[(dataCount >> 4) & 0xf], Hex[(dataCount >> 0) & 0xf], Hex[16], Hex[17], }; var shift = (dataCount & 0xffff0000) == 0 ? 16 : 0; shift += ((dataCount << shift) & 0xff000000) == 0 ? 8 : 0; shift += ((dataCount << shift) & 0xf0000000) == 0 ? 4 : 0; return new ArraySegment<byte>(prefixBytes, shift / 4, 10 - shift / 4); } private static bool IsStatusWithNoNoEntityBody(string status) { return status.StartsWith("1") || status.StartsWith("204") || status.StartsWith("205") || status.StartsWith("304"); } } } <file_sep>/src/Adapters/Gate.Adapters.Nancy/NancyAdapter.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Owin; using Nancy; using Nancy.Bootstrapper; using Nancy.IO; namespace Gate.Adapters.Nancy { public static class NancyAdapter { public static IAppBuilder RunNancy(this IAppBuilder builder) { return builder.Use<AppDelegate>(_ => App()); } public static IAppBuilder RunNancy(this IAppBuilder builder, INancyBootstrapper bootstrapper) { return builder.Use<AppDelegate>(_ => App(bootstrapper)); } public static AppDelegate App() { return App(NancyBootstrapperLocator.Bootstrapper); } public static AppDelegate App(INancyBootstrapper bootstrapper) { bootstrapper.Initialise(); var engine = bootstrapper.GetEngine(); return (env, result, fault) => { Action<Exception> onError = ex => { fault(ex); }; var owinRequestMethod = Get<string>(env, OwinConstants.RequestMethod); var owinRequestScheme = Get<string>(env, OwinConstants.RequestScheme); var owinRequestHeaders = Get<IDictionary<string, string[]>>(env, OwinConstants.RequestHeaders); var owinRequestPathBase = Get<string>(env, OwinConstants.RequestPathBase); var owinRequestPath = Get<string>(env, OwinConstants.RequestPath); var owinRequestQueryString = Get<string>(env, OwinConstants.RequestQueryString); var owinRequestBody = Get<BodyDelegate>(env, OwinConstants.RequestBody, EmptyBody); var cancellationToken = Get(env, typeof(CancellationToken).FullName, CancellationToken.None); var serverClientIp = Get<string>(env, "server.CLIENT_IP"); var callDisposing = Get<CancellationToken>(env, "host.CallDisposing"); var url = new Url { Scheme = owinRequestScheme, HostName = GetHeader(owinRequestHeaders, "Host"), Port = null, BasePath = owinRequestPathBase, Path = owinRequestPath, Query = owinRequestQueryString, }; var body = new RequestStream(ExpectedLength(owinRequestHeaders), false); owinRequestBody.Invoke( OnRequestData(body, onError), readError => { if (readError != null) { onError(readError); return; } body.Position = 0; var nancyRequest = new Request(owinRequestMethod, url, body, owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable<string>)kv.Value, StringComparer.OrdinalIgnoreCase), serverClientIp); engine.HandleRequest( nancyRequest, context => { callDisposing.Register(() => { context.Dispose(); }); var nancyResponse = context.Response; var status = String.Format("{0} {1}", (int)nancyResponse.StatusCode, nancyResponse.StatusCode); var headers = nancyResponse.Headers.ToDictionary(kv => kv.Key, kv => new[] { kv.Value }, StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrWhiteSpace(nancyResponse.ContentType)) { headers["Content-Type"] = new[] { nancyResponse.ContentType }; } if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0) { headers["Set-Cookie"] = nancyResponse.Cookies.Select(cookie => cookie.ToString()).ToArray(); } result( status, headers, (write, end, cancel) => { using (var stream = new ResponseStream(write, end)) { try { nancyResponse.Contents(stream); } catch (Exception ex) { stream.End(ex); } } }); }, onError); }, cancellationToken); }; } static T Get<T>(IDictionary<string, object> env, string key) { object value; return env.TryGetValue(key, out value) && value is T ? (T)value : default(T); } static T Get<T>(IDictionary<string, object> env, string key, T defaultValue) { object value; return env.TryGetValue(key, out value) && value is T ? (T)value : defaultValue; } static string GetHeader(IDictionary<string, string[]> headers, string key) { string[] value; return headers.TryGetValue(key, out value) && value != null ? string.Join(",", value.ToArray()) : null; } static long ExpectedLength(IDictionary<string, string[]> headers) { var header = GetHeader(headers, "Content-Length"); if (string.IsNullOrWhiteSpace(header)) return 0; int contentLength; return int.TryParse(header, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength) ? contentLength : 0; } static void EmptyBody(Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancellationToken) { end(null); } static Func<ArraySegment<byte>, Action, bool> OnRequestData(Stream body, Action<Exception> fault) { return (data, callback) => { try { if (data.Count != 0) { body.Write(data.Array, data.Offset, data.Count); } return false; } catch (Exception ex) { fault(ex); return false; } }; } } } <file_sep>/src/Main/Gate.Builder/Adapters.cs using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Owin; namespace Gate.Builder { using ResultTuple = Tuple<string, IDictionary<String, string[]>, BodyDelegate>; #pragma warning disable 811 using AppAction = Action< // app IDictionary<string, object>, // env Action< // result string, // status IDictionary<string, string[]>, // headers Action< // body Func< // write ArraySegment<byte>, // data Action, // continuation bool>, // buffering Action< // end Exception>, // error CancellationToken>>, // cancel Action<Exception>>; // error using BodyAction = Action< // body Func< // write ArraySegment<byte>, // data Action, // continuation bool>, // buffering Action< // end Exception>, // error CancellationToken>; //cancel public static class Adapters { public static AppAction ToAction(AppDelegate app) { return (env, result, fault) => { var revert = Replace<BodyAction, BodyDelegate>(env, ToDelegate); app( env, (status, headers, body) => { revert(); result(status, headers, ToAction(body)); }, ex => { revert(); fault(ex); }); }; } public static AppDelegate ToDelegate(AppAction app) { return (env, result, fault) => { var revert = Replace<BodyDelegate, BodyAction>(env, ToAction); app( env, (status, headers, body) => { revert(); result(status, headers, ToDelegate(body)); }, ex => { revert(); fault(ex); }); }; } static Action Replace<TFrom, TTo>(IDictionary<string, object> env, Func<TFrom, TTo> adapt) { object body; if (env.TryGetValue(OwinConstants.RequestBody, out body) && body is TFrom) { env[OwinConstants.RequestBody] = adapt((TFrom)body); return () => env[OwinConstants.RequestBody] = body; } return () => { }; } public static BodyAction ToAction(BodyDelegate body) { return (write, end, cancel) => body(write, end, cancel); } public static BodyDelegate ToDelegate(BodyAction body) { return (write, end, cancel) => body(write, end, cancel); } public static AppTaskDelegate ToTaskDelegate(AppDelegate app) { return env => { var tcs = new TaskCompletionSource<ResultTuple>(); app( env, (status, headers, body) => tcs.SetResult(new ResultTuple(status, headers, body)), tcs.SetException); return tcs.Task; }; } public static AppDelegate ToDelegate(AppTaskDelegate app) { return (env, result, fault) => { var task = app(env); task.ContinueWith( t => result(t.Result.Item1, t.Result.Item2, t.Result.Item3), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion); task.ContinueWith( t => fault(t.Exception), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted); }; } } } <file_sep>/src/Tests/Gate.Builder.Tests/Startup.cs  using Owin; namespace Gate.Builder.Tests { public class Startup { public static void Configuration(IAppBuilder builder) { ++ConfigurationCalls; } public static int ConfigurationCalls { get; set; } } }<file_sep>/src/Tests/Gate.Middleware.Tests/StaticFiles/FileServerTests.cs using System; using System.IO; using Gate.Middleware.StaticFiles; using Gate.Middleware.Utils; using Gate.TestHelpers; using NUnit.Framework; namespace Gate.Middleware.Tests.StaticFiles { [TestFixture] public class FileServerTests { string root; FileServer fileServer; [SetUp] public void Setup() { root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public"); fileServer = new FileServer(root); } [Test] public void FileServer_serves_files() { var result = AppUtils.Call(fileServer.Invoke, "/kayak.png"); Assert.That(result.Status, Is.EqualTo("200 OK")); } [Test] public void FileServer_returns_404_on_missing_file() { var result = AppUtils.Call(fileServer.Invoke, "/scripts/horses.js"); Assert.That(result.Status, Is.EqualTo("404 Not Found")); } [Test] public void FileServer_sets_LastModified_header() { var fileInfo = new FileInfo(Path.Combine(root, "kayak.png")); var result = AppUtils.Call(fileServer.Invoke, "/kayak.png"); Assert.That(result.Headers.GetHeader("Last-Modified"), Is.EqualTo(fileInfo.LastWriteTimeUtc.ToHttpDateString())); } [Test] public void FileServer_does_not_decode_request_path() { var result = AppUtils.Call(fileServer.Invoke, "/%6B%61%79%61%6B%2E%70%6E%67"); // kayak.png, url encoded Assert.That(result.Status, Is.EqualTo("404 Not Found")); } [Test] public void FileServer_returns_403_on_directory_traversal_attempt() { var result = AppUtils.Call(fileServer.Invoke, "/../ccinfo.txt"); Assert.That(result.Status, Is.EqualTo("403 Forbidden")); } [Test] public void FileServer_returns_correct_byte_range_in_body() { var result = AppUtils.CallPipe(b => b.Run(fileServer.Invoke), FakeHostRequest.GetRequest("/test.txt", req => req.Headers.SetHeader("Range", "bytes=22-33"))); Assert.That(result.Status, Is.EqualTo("206 Partial Content")); Assert.That(result.Headers.GetHeader("Content-Length"), Is.EqualTo("12")); Assert.That(result.Headers.GetHeader("Content-Range"), Is.EqualTo("bytes 22-33/193")); Assert.That(result.BodyText, Is.EqualTo("-*- test -*-")); } [Test] public void FileServer_returns_error_for_unsatisfiable_byte_range() { var result = AppUtils.CallPipe(b => b.Run(fileServer.Invoke), FakeHostRequest.GetRequest("/test.txt", req => req.Headers.SetHeader("Range", "bytes=1234-5678"))); Assert.That(result.Status, Is.EqualTo("416 Requested Range Not Satisfiable")); Assert.That(result.Headers.GetHeader("Content-Range"), Is.EqualTo("bytes */193")); } } } <file_sep>/src/Tests/Gate.Tests/EnvironmentTests.cs using System; using System.Collections.Generic; using System.Net; using Owin; using NUnit.Framework; namespace Gate.Tests { [TestFixture] public class EnvironmentTests { [Test] public void Version_property_provide_access_to_environment() { var env = new Dictionary<string, object> { { "owin.Version", "1.0" } }; var environment = new Environment(env); Assert.That(environment.Version, Is.EqualTo("1.0")); } [Test] public void Environment_access_is_not_buffered_or_cached() { var environment = new Environment() { { "owin.Version", "1.0" } }; Assert.That(environment.Version, Is.EqualTo("1.0")); environment["owin.Version"] = "1.1"; Assert.That(environment.Version, Is.EqualTo("1.1")); environment["owin.Version"] = null; Assert.That(environment.Version, Is.Null); environment.Remove("owin.Version"); Assert.That(environment.Version, Is.Null); } [Test] public void All_environment_variables_from_spec_are_available_as_typed_properties() { var headers = new Dictionary<string, string[]>(); BodyDelegate body = (a, b, c) => { }; var env = new Dictionary<string, object> { {OwinConstants.RequestMethod, "GET"}, {OwinConstants.RequestPath, "/foo"}, {OwinConstants.RequestHeaders, headers}, {OwinConstants.RequestBody, body}, {OwinConstants.RequestPathBase, "/my-app"}, {OwinConstants.RequestQueryString, "hello=world"}, {OwinConstants.RequestScheme, "https"}, {OwinConstants.Version, "1.0"}, }; var environment = new Environment(env); Assert.That(environment.Method, Is.EqualTo("GET")); Assert.That(environment.Path, Is.EqualTo("/foo")); Assert.That(environment.Headers, Is.SameAs(headers)); Assert.That(environment.BodyDelegate, Is.SameAs(body)); Assert.That(environment.PathBase, Is.EqualTo("/my-app")); Assert.That(environment.QueryString, Is.EqualTo("hello=world")); Assert.That(environment.Scheme, Is.EqualTo("https")); Assert.That(environment.Version, Is.EqualTo("1.0")); } [Test] public void Environment_properties_may_be_used_to_initialize_env_dictionary() { var headers = Headers.New(); BodyDelegate body = (a,b,c)=> { }; var environment = new Environment() { Method = "GET", Path = "/foo", Headers = headers, BodyDelegate = body, PathBase = "/my-app", QueryString = "hello=world", Scheme = "https", Version = "1.0" }; IDictionary<string, object> env = environment; Assert.That(environment.Method, Is.EqualTo("GET")); Assert.That(environment.Path, Is.EqualTo("/foo")); Assert.That(environment.Headers, Is.SameAs(headers)); Assert.That(environment.BodyDelegate, Is.SameAs(body)); Assert.That(environment.PathBase, Is.EqualTo("/my-app")); Assert.That(environment.QueryString, Is.EqualTo("hello=world")); Assert.That(environment.Scheme, Is.EqualTo("https")); Assert.That(environment.Version, Is.EqualTo("1.0")); Assert.That(env["owin.RequestMethod"], Is.EqualTo("GET")); Assert.That(env["owin.RequestPath"], Is.EqualTo("/foo")); Assert.That(env["owin.RequestHeaders"], Is.SameAs(headers)); Assert.That(env["owin.RequestBody"], Is.SameAs(body)); Assert.That(env["owin.RequestPathBase"], Is.EqualTo("/my-app")); Assert.That(env["owin.RequestQueryString"], Is.EqualTo("hello=world")); Assert.That(env["owin.RequestScheme"], Is.EqualTo("https")); Assert.That(env["owin.Version"], Is.EqualTo("1.0")); } } }<file_sep>/src/Main/Gate.Middleware/Cascade.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Owin; namespace Gate.Middleware { public static class Cascade { public static IAppBuilder RunCascade(this IAppBuilder builder, params AppDelegate[] apps) { return builder.Run(App, apps); } public static IAppBuilder RunCascade(this IAppBuilder builder, params Action<IAppBuilder>[] apps) { return builder.Run(App, apps.Select(builder.Build<AppDelegate>)); } public static IAppBuilder UseCascade(this IAppBuilder builder, params AppDelegate[] apps) { return builder.Use(Middleware, apps); } public static IAppBuilder UseCascade(this IAppBuilder builder, params Action<IAppBuilder>[] apps) { return builder.Use(Middleware, apps.Select(builder.Build<AppDelegate>)); } public static AppDelegate App(IEnumerable<AppDelegate> apps) { return Middleware(null, apps); } public static AppDelegate App(AppDelegate app0) { return Middleware(null, new[] { app0 }); } public static AppDelegate App(AppDelegate app0, AppDelegate app1) { return Middleware(null, new[] { app0, app1 }); } public static AppDelegate App(AppDelegate app0, AppDelegate app1, AppDelegate app2) { return Middleware(null, new[] { app0, app1, app2 }); } public static AppDelegate Middleware(AppDelegate app, AppDelegate app0) { return Middleware(app, new[] { app0 }); } public static AppDelegate Middleware(AppDelegate app, AppDelegate app0, AppDelegate app1) { return Middleware(app, new[] { app0, app1 }); } public static AppDelegate Middleware(AppDelegate app, AppDelegate app0, AppDelegate app1, AppDelegate app2) { return Middleware(app, new[] { app0, app1, app2 }); } public static AppDelegate Middleware(AppDelegate app, IEnumerable<AppDelegate> apps) { // sequence to attempt is {apps[0], apps[n], app} // or {apps[0], apps[n]} if app is null apps = (apps ?? new AppDelegate[0]).Concat(new[] { app ?? NotFound.Call }).ToArray(); // the first non-404 result will the the one to take effect // any subsequent apps are not called return (env, result, fault) => { var iter = apps.GetEnumerator(); iter.MoveNext(); Action loop = () => { }; loop = () => { var threadId = Thread.CurrentThread.ManagedThreadId; for (var hot = true; hot; ) { hot = false; iter.Current.Invoke( env, (status, headers, body) => { try { if (status.StartsWith("404") && iter.MoveNext()) { // ReSharper disable AccessToModifiedClosure if (threadId == Thread.CurrentThread.ManagedThreadId) { hot = true; } else { loop(); } // ReSharper restore AccessToModifiedClosure } else { result(status, headers, body); } } catch (Exception ex) { fault(ex); } }, fault); } threadId = 0; }; loop(); }; } } }<file_sep>/src/Main/Gate/ResponseStream.cs using System; using System.IO; namespace Gate { public class ResponseStream : Stream { readonly Response _response; public ResponseStream(Response response) { _response = response; } public override void Flush() { _response.Flush(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { _response.Write(ToArraySegment(buffer, offset, count)); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return _response.BeginWrite(ToArraySegment(buffer, offset, count), callback, state); } public override void EndWrite(IAsyncResult asyncResult) { _response.EndWrite(asyncResult); } static ArraySegment<byte> ToArraySegment(byte[] buffer, int offset, int count) { return buffer == null ? default(ArraySegment<byte>) : new ArraySegment<byte>(buffer, offset, count); } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }<file_sep>/src/Tests/Gate.Hosts.Manos.Tests/Startup.cs using System; using System.Collections.Generic; using System.Text; using Owin; namespace Gate.Hosts.Manos.Tests { public static class Startup { public static void Custom(IAppBuilder builder) { builder.Use<AppDelegate>(App); } static AppDelegate App(AppDelegate arg) { return (env, result, fault) => result("200 OK", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) { { "Content-Type", new[] { "text/plain" } } }, (write, end, cancel) => { var bytes = Encoding.Default.GetBytes("This is a custom page"); write(new ArraySegment<byte>(bytes), null); end(null); }); } } } <file_sep>/src/Main/Gate/Response.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Owin; using Gate.Utils; namespace Gate { public class Response { ResultDelegate _result; int _autostart; readonly Object _onStartSync = new object(); Action _onStart = () => { }; Func<ArraySegment<byte>, Action, bool> _responseWrite; Action<Exception> _responseEnd; CancellationToken _responseCancellationToken = CancellationToken.None; Stream _outputStream; public Response(ResultDelegate result) : this(result, "200 OK") { } public Response(ResultDelegate result, string status) : this(result, status, new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)) { } public Response(ResultDelegate result, string status, IDictionary<string, string[]> headers) { _result = result; _responseWrite = EarlyResponseWrite; _responseEnd = EarlyResponseEnd; Status = status; Headers = headers; Encoding = Encoding.UTF8; } public Response(ResultDelegate result, int statusCode) : this(result, statusCode, new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)) { } public Response(ResultDelegate result, int statusCode, IDictionary<string, string[]> headers) { _result = result; _responseWrite = EarlyResponseWrite; _responseEnd = EarlyResponseEnd; StatusCode = statusCode; Headers = headers; Encoding = Encoding.UTF8; } int _statusCode; string _reasonPhrase; public string Status { get { var reasonPhrase = ReasonPhrase; return string.IsNullOrEmpty(reasonPhrase) ? StatusCode.ToString(CultureInfo.InvariantCulture) : StatusCode.ToString(CultureInfo.InvariantCulture) + " " + reasonPhrase; } set { if (value.Length < 3 || (value.Length >= 4 && value[3] != ' ')) { throw new ArgumentException("Status must be a string with 3 digit statuscode, a space, and a reason phrase"); } _statusCode = int.Parse(value.Substring(0, 3)); _reasonPhrase = value.Length < 4 ? null : value.Substring(4); } } public int StatusCode { get { return _statusCode; } set { if (_statusCode != value) { _statusCode = value; _reasonPhrase = null; } } } public string ReasonPhrase { get { if (string.IsNullOrEmpty(_reasonPhrase)) { switch (_statusCode) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 226: return "IM Used"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 306: return "Reserved"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-URI Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 418: return "I'm a Teapot"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 426: return "Upgrade Required"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "HTTP Version Not Supported"; case 506: return "Variant Also Negotiates"; case 507: return "Insufficient Storage"; case 510: return "Not Extended"; default: return null; } } return _reasonPhrase; } set { _reasonPhrase = value; } } public IDictionary<string, string[]> Headers { get; set; } public Encoding Encoding { get; set; } public bool Buffer { get; set; } public string GetHeader(string name) { var values = GetHeaders(name); if (values == null) { return null; } switch (values.Length) { case 0: return string.Empty; case 1: return values[0]; default: return string.Join(",", values); } } public string[] GetHeaders(string name) { string[] existingValues; return Headers.TryGetValue(name, out existingValues) ? existingValues : null; } public Response SetHeader(string name, string value) { if (string.IsNullOrWhiteSpace(value)) Headers.Remove(value); else Headers[name] = new[] { value }; return this; } public Response SetCookie(string key, string value) { Headers.AddHeader("Set-Cookie", Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(value) + "; path=/"); return this; } public Response SetCookie(string key, Cookie cookie) { var domainHasValue = !string.IsNullOrEmpty(cookie.Domain); var pathHasValue = !string.IsNullOrEmpty(cookie.Path); var expiresHasValue = cookie.Expires.HasValue; var setCookieValue = string.Concat( Uri.EscapeDataString(key), "=", Uri.EscapeDataString(cookie.Value ?? ""), //TODO: concat complex value type with '&'? !domainHasValue ? null : "; domain=", !domainHasValue ? null : cookie.Domain, !pathHasValue ? null : "; path=", !pathHasValue ? null : cookie.Path, !expiresHasValue ? null : "; expires=", !expiresHasValue ? null : cookie.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ") + "GMT", !cookie.Secure ? null : "; secure", !cookie.HttpOnly ? null : "; HttpOnly" ); Headers.AddHeader("Set-Cookie", setCookieValue); return this; } public Response DeleteCookie(string key) { Func<string, bool> predicate = value => value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase); var deleteCookies = new[] { Uri.EscapeDataString(key) + "=; expires=Thu, 01-Jan-1970 00:00:00 GMT" }; var existingValues = Headers.GetHeaders("Set-Cookie"); if (existingValues == null) { Headers["Set-Cookie"] = deleteCookies; return this; } Headers["Set-Cookie"] = existingValues.Where(value => !predicate(value)).Concat(deleteCookies).ToArray(); return this; } public Response DeleteCookie(string key, Cookie cookie) { var domainHasValue = !string.IsNullOrEmpty(cookie.Domain); var pathHasValue = !string.IsNullOrEmpty(cookie.Path); Func<string, bool> rejectPredicate; if (domainHasValue) { rejectPredicate = value => value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase) && value.IndexOf("domain=" + cookie.Domain, StringComparison.InvariantCultureIgnoreCase) != -1; } else if (pathHasValue) { rejectPredicate = value => value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase) && value.IndexOf("path=" + cookie.Path, StringComparison.InvariantCultureIgnoreCase) != -1; } else { rejectPredicate = value => value.StartsWith(key + "=", StringComparison.InvariantCultureIgnoreCase); } var existingValues = Headers.GetHeaders("Set-Cookie"); if (existingValues != null) { Headers["Set-Cookie"] = existingValues.Where(value => !rejectPredicate(value)).ToArray(); } return SetCookie(key, new Cookie { Path = cookie.Path, Domain = cookie.Domain, Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), }); } public class Cookie { public Cookie() { Path = "/"; } public Cookie(string value) { Path = "/"; Value = value; } public string Value { get; set; } public string Domain { get; set; } public string Path { get; set; } public DateTime? Expires { get; set; } public bool Secure { get; set; } public bool HttpOnly { get; set; } } public string ContentType { get { return GetHeader("Content-Type"); } set { SetHeader("Content-Type", value); } } public Response Start() { _autostart = 1; Interlocked.Exchange(ref _result, ResultCalledAlready).Invoke(Status, Headers, ResponseBody); return this; } public Response Start(string status) { if (!string.IsNullOrWhiteSpace(status)) Status = status; return Start(); } public Response Start(string status, IEnumerable<KeyValuePair<string, string[]>> headers) { if (headers != null) { foreach (var header in headers) { Headers[header.Key] = header.Value; } } return Start(status); } public void Start(string status, IEnumerable<KeyValuePair<string, string>> headers) { var actualHeaders = headers.Select(kv => new KeyValuePair<string, string[]>(kv.Key, new[] { kv.Value })); Start(status, actualHeaders); } public void Start(Action continuation) { OnStart(continuation); Start(); } public void Start(string status, Action continuation) { OnStart(continuation); Start(status); } public Stream OutputStream { get { if (_outputStream == null) { Interlocked.Exchange(ref _outputStream, new ResponseStream(this)); } return _outputStream; } } public bool Write(string text) { // this could be more efficient if it spooled the immutable strings instead... var data = Encoding.GetBytes(text); return Write(new ArraySegment<byte>(data)); } public bool Write(string format, params object[] args) { return Write(string.Format(format, args)); } public bool Write(ArraySegment<byte> data) { return _responseWrite(data, null); } public bool Write(ArraySegment<byte> data, Action callback) { return _responseWrite(data, callback); } public Task WriteAsync(ArraySegment<byte> data) { var tcs = new TaskCompletionSource<object>(); if (!_responseWrite(data, () => tcs.SetResult(null))) tcs.SetResult(null); return tcs.Task; } public IAsyncResult BeginWrite(ArraySegment<byte> data, AsyncCallback callback, object state) { var tcs = new TaskCompletionSource<object>(state); if (!_responseWrite(data, () => tcs.SetResult(null))) tcs.SetResult(null); tcs.Task.ContinueWith(t => callback(t)); return tcs.Task; } public void EndWrite(IAsyncResult result) { ((Task)result).Wait(); } public bool Flush() { return Write(default(ArraySegment<byte>)); } public bool Flush(Action callback) { return Write(default(ArraySegment<byte>), callback); } public Task FlushAsync() { return WriteAsync(default(ArraySegment<byte>)); } public IAsyncResult BeginFlush(AsyncCallback callback, object state) { return BeginWrite(default(ArraySegment<byte>), callback, state); } public void EndFlush(IAsyncResult result) { EndWrite(result); } public void End() { OnEnd(null); } public void End(string text) { Write(text); OnEnd(null); } public void End(ArraySegment<byte> data) { Write(data); OnEnd(null); } public void Error(Exception error) { OnEnd(error); } void ResponseBody( Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancellationToken) { _responseWrite = write; _responseEnd = end; _responseCancellationToken = cancellationToken; lock (_onStartSync) { Interlocked.Exchange(ref _onStart, null).Invoke(); } } static readonly ResultDelegate ResultCalledAlready = (_, __, ___) => { throw new InvalidOperationException("Start must only be called once on a Response and it must be called before Write or End"); }; void Autostart() { if (Interlocked.Increment(ref _autostart) == 1) { Start(); } } void OnStart(Action notify) { lock (_onStartSync) { if (_onStart != null) { var prior = _onStart; _onStart = () => { prior.Invoke(); CallNotify(notify); }; return; } } CallNotify(notify); } void OnEnd(Exception error) { Interlocked.Exchange(ref _responseEnd, _ => { }).Invoke(error); } void CallNotify(Action notify) { try { notify.Invoke(); } catch (Exception ex) { Error(ex); } } bool EarlyResponseWrite(ArraySegment<byte> data, Action callback) { var copy = data; if (copy.Count != 0) { copy = new ArraySegment<byte>(new byte[data.Count], 0, data.Count); Array.Copy(data.Array, data.Offset, copy.Array, 0, data.Count); } OnStart( () => { var willCallback = _responseWrite(copy, callback); if (callback != null && willCallback == false) { callback.Invoke(); } }); if (!Buffer || data.Array == null) { Autostart(); } return true; } void EarlyResponseEnd(Exception ex) { OnStart(() => OnEnd(ex)); Autostart(); } } }<file_sep>/src/Main/Gate.Middleware/StaticFiles/FileServer.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Gate.Middleware.Utils; using Owin; namespace Gate.Middleware.StaticFiles { public class FileServer { private const string OK = "200 OK"; private const string PartialContent = "206 Partial Content"; private const string NotFound = "404 Not Found"; private const string Forbidden = "403 Forbidden"; private const string RequestedRangeNotSatisfiable = "416 Requested Range Not Satisfiable"; private readonly string root; private string pathInfo; private Tuple<long, long> range; // Note: Path should be exposed when implementing Sendfile middleware. private string path; public FileServer(string root) { this.root = root; } public void Invoke(IDictionary<string, object> env, ResultDelegate result, Action<Exception> fault) { pathInfo = env[OwinConstants.RequestPath].ToString(); if (pathInfo.StartsWith("/")) { pathInfo = pathInfo.Substring(1); } if (pathInfo.Contains("..")) { Fail(Forbidden, "Forbidden").Invoke(env, result, fault); return; } path = Path.Combine(root ?? string.Empty, pathInfo); if (!File.Exists(path)) { Fail(NotFound, "File not found: " + pathInfo).Invoke(env, result, fault); return; } try { Serve(env).Invoke(env, result, fault); } catch (UnauthorizedAccessException) { Fail(Forbidden, "Forbidden").Invoke(env, result, fault); } } private static AppDelegate Fail(string status, string body, IDictionary<string, string[]> headers = null) { return (env, res, err) => res( status, Headers.New(headers) .SetHeader("Content-Type", "text/plain") .SetHeader("Content-Length", body.Length.ToString()) .SetHeader("X-Cascade", "pass"), TextBody.Create(body, Encoding.UTF8) ); } private AppDelegate Serve(IDictionary<string, object> environment) { var fileInfo = new FileInfo(path); var size = fileInfo.Length; string status; var headers = Headers.New() .SetHeader("Last-Modified", fileInfo.LastWriteTimeUtc.ToHttpDateString()) .SetHeader("Content-Type", Mime.MimeType(fileInfo.Extension, "text/plain")); if (!RangeHeader.IsValid(environment)) { status = OK; range = new Tuple<long, long>(0, size - 1); } else { var ranges = RangeHeader.Parse(environment, size); if (ranges == null) { // Unsatisfiable. Return error and file size. return Fail(RequestedRangeNotSatisfiable, "Byte range unsatisfiable", Headers.New().SetHeader("Content-Range", "bytes */" + size)); } if (ranges.Count() > 1) { // TODO: Support multiple byte ranges. status = OK; range = new Tuple<long, long>(0, size - 1); } else { // Partial content range = ranges.First(); status = PartialContent; headers.SetHeader("Content-Range", "bytes " + range.Item1 + "-" + range.Item2 + "/" + size); size = range.Item2 - range.Item1 + 1; } } headers.SetHeader("Content-Length", size.ToString()); return (env, res, err) => { try { res(status, headers, FileBody.Create(path, range)); } catch (Exception ex) { err(ex); } }; } } }<file_sep>/src/Samples/Sample.Nancy/DefaultPage.cs using Gate; using Owin; namespace Sample.Nancy { public static class DefaultPage { public static IAppBuilder RunDefaultPage(this IAppBuilder builder) { return builder.Run(App); } public static AppDelegate App() { return (env, result, fault) => { var request = new Request(env); var response = new Response(result); if (request.Path == "/") { response.Status = "200 OK"; response.ContentType = "text/html"; response.Start(() => { response.Write("<h1>Sample.App</h1>"); response.Write("<p><a href='{0}/wilson/'>Wilson</a></p>", request.PathBase); response.Write("<p><a href='{0}/wilsonasync/'>Wilson (async)</a></p>", request.PathBase); response.Write("<p><a href='{0}/nancy/'>Nancy</a></p>", request.PathBase); response.Write("<p><a href='{0}/fileupload'>File Upload</a></p>", request.PathBase); response.End(); }); } else { NotFound.Call(env, result, fault); } }; } } }<file_sep>/src/Adapters/Gate.Adapters.AspNetWebApi/Workaround.cs using Owin; namespace Gate.Adapters.AspNetWebApi { static class Workaround { #pragma warning disable 169 static ResultDelegate _resultDelegate; #pragma warning restore 169 } } <file_sep>/src/Tests/Gate.TestHelpers/TestHttpClient.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.Remoting.Contexts; using System.Threading; using System.Threading.Tasks; using Gate.Builder; using Owin; namespace Gate.TestHelpers { public class TestHttpClient : HttpClient { readonly AppDelegateMessageHandler _handler; public TestHttpClient(AppDelegate app) : this(new AppDelegateMessageHandler(app)) { } TestHttpClient(AppDelegateMessageHandler handler) : base(handler) { _handler = handler; } public AppDelegate App { get { return _handler.App; } } public IList<Call> Calls { get { return _handler.Calls; } } public class Call { public HttpRequestMessage HttpRequestMessage { get; set; } public HttpResponseMessage HttpResponseMessage { get; set; } public IDictionary<string, object> Environment { get; set; } public string ResponseStatus { get; set; } public IDictionary<string, string[]> ResponseHeaders { get; set; } public BodyDelegate ResponseBody { get; set; } public Exception Exception { get; set; } } /// <summary> /// Create an HttpClient that can be used to test an app. /// </summary> /// <param name="configuration">Delegate called to build the app being tested</param> /// <returns></returns> public static TestHttpClient ForConfiguration(Action<IAppBuilder> configuration) { return ForAppDelegate(AppBuilder.BuildConfiguration(configuration)); } /// <summary> /// Create an HttpClient that can be used to test an app. /// </summary> /// <param name="app">Delegate that will be called by the HttpClient</param> /// <returns></returns> public static TestHttpClient ForAppDelegate(AppDelegate app) { return new TestHttpClient(app); } class AppDelegateMessageHandler : HttpMessageHandler { public AppDelegateMessageHandler(AppDelegate app) { App = app; Calls = new List<Call>(); } public IList<Call> Calls { get; private set; } public AppDelegate App { get; private set; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var call = new Call { HttpRequestMessage = request, Environment = new Dictionary<string, object> { {OwinConstants.Version, "1.0"}, {OwinConstants.RequestMethod, request.Method.ToString()}, {OwinConstants.RequestScheme, request.RequestUri.Scheme}, {OwinConstants.RequestPathBase, ""}, {OwinConstants.RequestPath, request.RequestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped)}, {OwinConstants.RequestQueryString, request.RequestUri.GetComponents(UriComponents.Path, UriFormat.UriEscaped)}, {OwinConstants.RequestHeaders, RequestHeaders(request)}, {OwinConstants.RequestBody, MakeRequestBody(request)}, {"host.CallDisposed", cancellationToken}, {"System.Net.Http.HttpRequestMessage", request}, } }; Calls.Add(call); var tcs = new TaskCompletionSource<HttpResponseMessage>(); App( call.Environment, (status, headers, body) => { call.ResponseStatus = status; call.ResponseHeaders = headers; call.ResponseBody = body; var response = MakeResponseMessage(status, headers, body); response.RequestMessage = request; call.HttpResponseMessage = response; tcs.TrySetResult(response); }, ex => { call.Exception = ex; tcs.TrySetException(ex); }); return tcs.Task; } static IDictionary<string, string[]> RequestHeaders(HttpRequestMessage request) { IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers = request.Headers; if (request.Content != null) headers = headers.Concat(request.Content.Headers); var requestHeaders = headers.ToDictionary(kv => kv.Key, kv => kv.Value.ToArray(), StringComparer.OrdinalIgnoreCase); return requestHeaders; } static BodyDelegate MakeRequestBody(HttpRequestMessage request) { if (request.Content == null) { return (write, end, cancel) => end(null); } return (write, end, cancel) => { var task = request.Content.CopyToAsync(new BodyDelegateStream(write, cancel)); if (task.IsFaulted) { end(task.Exception); } else if (task.IsCompleted) { end(null); } else { task.ContinueWith(t => { end(t.IsFaulted ? t.Exception : null); }, cancel); } }; } static HttpResponseMessage MakeResponseMessage(string status, IDictionary<string, string[]> headers, BodyDelegate body) { var httpStatusCode = (HttpStatusCode)int.Parse(status.Substring(0, 3)); var response = new HttpResponseMessage(httpStatusCode); //response. if (body != null) { response.Content = MakeResponseContent(body); } foreach (var header in headers) { if (!response.Headers.TryAddWithoutValidation(header.Key, header.Value)) { if (response.Content == null) { response.Content = MakeResponseContent((write, end, cancel) => end(null)); } response.Content.Headers.TryAddWithoutValidation(header.Key, header.Value); } } return response; } static HttpContent MakeResponseContent(BodyDelegate body) { return new BodyDelegateHttpContent(body); } class BodyDelegateHttpContent : HttpContent { readonly BodyDelegate _body; public BodyDelegateHttpContent(BodyDelegate body) { _body = body; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { var tcs = new TaskCompletionSource<object>(); _body.Invoke( (data, callback) => { if (data == default(ArraySegment<byte>)) { stream.Flush(); } else { stream.Write(data.Array, data.Offset, data.Count); } return false; }, ex => { if (ex == null) { tcs.TrySetResult(null); } else { tcs.TrySetException(ex); } }, CancellationToken.None); return tcs.Task; } protected override bool TryComputeLength(out long length) { length = 0; return false; } } class BodyDelegateStream : Stream { readonly Func<ArraySegment<byte>, Action, bool> _write; readonly CancellationToken _cancellationToken; public BodyDelegateStream(Func<ArraySegment<byte>, Action, bool> write, CancellationToken cancellationToken) { _write = write; _cancellationToken = cancellationToken; } public override void Flush() { _write(new ArraySegment<byte>(), null); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { _write(new ArraySegment<byte>(buffer, offset, count), null); } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } } } } <file_sep>/src/Hosts/Gate.Hosts/PipeResponse.cs using System; using System.IO; using System.Threading; using Owin; namespace Gate.Hosts { class PipeResponse { Stream _stream; readonly Action<Exception> _error; readonly Action _complete; public PipeResponse(Stream stream, Action<Exception> error, Action complete) { _stream = stream; _error = error; _complete = complete; } public void Go(BodyDelegate body) { body(OnWrite, OnEnd, CancellationToken); } bool OnWrite(ArraySegment<byte> data, Action continuation) { try { if (_stream != null) { if (data.Count == 0) { _stream.Flush(); } else if (continuation == null) { _stream.Write(data.Array, data.Offset, data.Count); } else { var sr = _stream.BeginWrite(data.Array, data.Offset, data.Count, ar => { if (!ar.CompletedSynchronously) { try { _stream.EndWrite(ar); } catch { } try { continuation.Invoke(); } catch { } } }, null); if (!sr.CompletedSynchronously) { return true; } _stream.EndWrite(sr); continuation.Invoke(); } } } catch (Exception ex) { OnEnd(ex); } return false; } bool OnFlush(Action continuation) { try { if (_stream != null) { _stream.Flush(); } } catch (Exception ex) { OnEnd(ex); } return false; } void OnEnd(Exception exception) { if (_stream != null) { _stream = null; if (exception == null) _complete(); else _error(exception); } } protected CancellationToken CancellationToken { get; set; } } }<file_sep>/src/Adapters/Gate.Adapters.AspNetWebApi/WebApiAdapter.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Dispatcher; using Owin; namespace Gate.Adapters.AspNetWebApi { public static class WebApiAdapter { public static IAppBuilder RunHttpServer(this IAppBuilder builder) { return builder.Use<AppDelegate>(_ => App()); } public static IAppBuilder RunHttpServer(this IAppBuilder builder, HttpControllerDispatcher dispatcher) { return builder.Use<AppDelegate>(_ => App(dispatcher)); } public static IAppBuilder RunHttpServer(this IAppBuilder builder, HttpConfiguration configuration) { return builder.Use<AppDelegate>(_ => App(configuration)); } public static IAppBuilder RunHttpServer(this IAppBuilder builder, HttpConfiguration configuration, HttpMessageHandler dispatcher) { return builder.Use<AppDelegate>(_ => App(configuration, dispatcher)); } public static IAppBuilder RunHttpServer(this IAppBuilder builder, HttpServer server) { return builder.Use<AppDelegate>(_ => App(server)); } public static AppDelegate App() { return App(new HttpServer()); } public static AppDelegate App(HttpConfiguration configuration) { return App(new HttpServer(configuration)); } public static AppDelegate App(HttpConfiguration configuration, HttpMessageHandler dispatcher) { return App(new HttpServer(configuration, dispatcher)); } public static AppDelegate App(HttpControllerDispatcher dispatcher) { return App(new HttpServer(dispatcher)); } public static AppDelegate App(HttpServer server) { var invoker = new HttpMessageInvoker(server); return (env, result, fault) => { var owinRequestMethod = Get<string>(env, "owin.RequestMethod"); var owinRequestPath = Get<string>(env, "owin.RequestPath"); var owinRequestPathBase = Get<string>(env, "owin.RequestPathBase"); var owinRequestQueryString = Get<string>(env, "owin.RequestQueryString"); var owinRequestHeaders = Get<IDictionary<string, IEnumerable<string>>>(env, "owin.RequestHeaders"); var owinRequestBody = Get<BodyDelegate>(env, "owin.RequestBody"); var owinRequestScheme = Get<string>(env, "owin.RequestScheme"); var cancellationToken = Get<CancellationToken>(env, "System.Threading.CancellationToken"); var uriBuilder = new UriBuilder(owinRequestScheme, "localhost") { Path = owinRequestPathBase + owinRequestPath, Query = owinRequestQueryString }; var request = new HttpRequestMessage(new HttpMethod(owinRequestMethod), uriBuilder.Uri) { Content = new RequestHttpContent(owinRequestBody, cancellationToken) }; if (owinRequestHeaders != null) { foreach (var kv in owinRequestHeaders) { foreach (var value in kv.Value) { if (kv.Key.StartsWith("content", StringComparison.InvariantCultureIgnoreCase)) { request.Content.Headers.Add(kv.Key, value); } else { request.Headers.Add(kv.Key, value); } } } } invoker.SendAsync(request, cancellationToken) .Then(response => { var status = (int)response.StatusCode + " " + response.ReasonPhrase; IEnumerable<KeyValuePair<string, IEnumerable<string>>> headersEnumerable = response.Headers; if (response.Content != null) headersEnumerable = headersEnumerable.Concat(response.Content.Headers); var headers = headersEnumerable.ToDictionary( kv => kv.Key, kv => kv.Value.ToArray(), StringComparer.InvariantCultureIgnoreCase); result(status, headers, ResponseBody(response.Content)); }) .Catch(fault); }; } private static T Get<T>(IDictionary<string, object> env, string name) { object value; return env.TryGetValue(name, out value) && value is T ? (T)value : default(T); } private static BodyDelegate ResponseBody(HttpContent content) { if (content == null) { return (write, end, cancel) => end(null); } return (write, end, cancel) => { try { var stream = new ResponseHttpStream(write, end); content.CopyToAsync(stream) .Then(() => { stream.Close(); end(null); }) .Catch(ex => { stream.Close(); end(ex); }); } catch (Exception ex) { end(ex); } }; } } } <file_sep>/src/Hosts/Gate.Hosts/ErrorPage.cs using System; using System.Collections.Generic; using System.Text; using Owin; namespace Gate.Hosts { static class ErrorPage { static readonly ArraySegment<byte> Body = new ArraySegment<byte>(Encoding.UTF8.GetBytes(@" <!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML 2.0//EN""> <html><head> <title>500 Internal Server Error</title> </head><body> <h1>Internal Server Error</h1> <p>The requested URL was not found on this server.</p> </body></html> ")); static readonly Dictionary<string, string[]> ResponseHeaders = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) { { "Content-Type", new[] { "text/html" } } }; public static AppDelegate Middleware(AppDelegate app) { return Middleware(app, ex => { }); } public static AppDelegate Middleware(AppDelegate app, Action<Exception> logError) { return (env, result, fault) => { Action<Exception> onError = ex => { logError(ex); result( "500 Internal Server Error", ResponseHeaders, (write, end, cancel) => { try { write(Body, null); end(null); } catch (Exception error) { end(error); } }); }; try { app( env, (status, headers, body) => { // errors send from inside the body are // logged, but not passed to the host. it's too // late to change the status or send an error page. onError = logError; result( status, headers, (write, end, cancel) => body( write, ex => { if (ex != null) { logError(ex); } end(ex); }, cancel)); }, ex => onError(ex)); } catch (Exception ex) { onError(ex); } }; } } } <file_sep>/src/Main/Gate.Middleware/StaticFiles/TextBody.cs using System; using System.Text; using System.Threading; using Owin; namespace Gate.Middleware.StaticFiles { public class TextBody { private readonly string text; private readonly Encoding encoding; private BodyStream bodyStream; public TextBody(string text, Encoding encoding) { this.text = text; this.encoding = encoding; } public static BodyDelegate Create(string text, Encoding encoding) { return (write, end, cancel) => { var textBody = new TextBody(text, encoding); textBody.Start(write, end, cancel); }; } public void Start(Func<ArraySegment<byte>, Action, bool> write, Action<Exception> end, CancellationToken cancellationToken) { bodyStream = new BodyStream(write, end, cancellationToken); Action start = () => { try { if (bodyStream.CanSend()) { var bytes = encoding.GetBytes(text); var segment = new ArraySegment<byte>(bytes); // Not buffered. bodyStream.SendBytes(segment, null, null); bodyStream.Finish(); } } catch (Exception ex) { bodyStream.End(ex); } }; bodyStream.Start(start, null); } } }<file_sep>/src/Tests/Gate.Middleware.Tests/StaticTests.cs using System; using System.IO; using Gate.Builder; using Gate.TestHelpers; using NUnit.Framework; namespace Gate.Middleware.Tests { [TestFixture] public class StaticTests { [Test] public void Static_serves_files_from_default_location() { var result = AppUtils.CallPipe(b => b.UseStatic(), FakeHostRequest.GetRequest("/kayak.png")); Assert.That(result.Status, Is.EqualTo("200 OK")); } [Test] public void Static_serves_files_from_provided_location() { var root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public"); var result = AppUtils.CallPipe(b => b.UseStatic(root), FakeHostRequest.GetRequest("/kayak.png")); Assert.That(result.Status, Is.EqualTo("200 OK")); } [Test] public void Static_serves_files_from_provided_whitelist() { var root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public"); var result = AppUtils.CallPipe(b => b.UseStatic(root, new[] {"/scripts/lib.js"}), FakeHostRequest.GetRequest("/scripts/lib.js")); Assert.That(result.Status, Is.EqualTo("200 OK")); } [Test] public void Static_returns_404_for_request_to_file_not_in_provided_whitelist() { var root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public"); var result = AppUtils.CallPipe(b => b.UseStatic(root, new[] { "/scripts/lib.js" }), FakeHostRequest.GetRequest("/kayak.png")); Assert.That(result.Status, Is.EqualTo("404 Not Found")); } [Test] public void Static_calls_down_the_chain_if_URL_root_is_unknown() { var app = new FakeApp("200 OK", "Hello World"); app.Headers.SetHeader("Content-Type", "text/plain"); var config = AppBuilder.BuildConfiguration(b => b.UseStatic().Run(app.AppDelegate)); var host = new FakeHost(config); var response = host.GET("/johnson/and/johnson"); Assert.That(response.Status, Is.EqualTo("200 OK")); Assert.That(response.BodyText, Is.EqualTo("Hello World")); Assert.That(app.AppDelegateInvoked, Is.True); } [Test] public void Static_returns_404_on_missing_file() { var result = AppUtils.CallPipe(b => b.UseStatic(), FakeHostRequest.GetRequest("/scripts/penicillin.js")); Assert.That(result.Status, Is.EqualTo("404 Not Found")); } } }<file_sep>/src/Hosts/Gate.Hosts.HttpListener/Workaround.cs using Owin; namespace Gate.Hosts.HttpListener { class Workaround { #pragma warning disable 169 ResultDelegate _resultDelegate; #pragma warning restore 169 } } <file_sep>/src/Tests/Gate.Middleware.Tests/ChunkedTests.cs using System; using System.Collections.Generic; using Gate.Builder; using Gate.TestHelpers; using NUnit.Framework; using System.Text; namespace Gate.Middleware.Tests { [TestFixture] public class ChunkedTests { [Test] public void ChunkPrefixHasCorrectResults() { AssertChunkPrefix(Chunked.ChunkPrefix(1), "1\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(15), "f\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x10), "10\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x80), "80\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0xff), "ff\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x10), "10\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x100), "100\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x1000), "1000\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x10000), "10000\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x100000), "100000\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x1000000), "1000000\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0x10000000), "10000000\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0), "0\r\n"); AssertChunkPrefix(Chunked.ChunkPrefix(0xffffffff), "ffffffff\r\n"); } static void AssertChunkPrefix(ArraySegment<byte> data, string expected) { Assert.That(Encoding.ASCII.GetString(data.Array, data.Offset, data.Count), Is.EqualTo(expected)); } [Test] public void Does_not_encode_if_content_length_present() { var app = AppUtils.Simple( "200 OK", h => h .SetHeader("Content-Length", "12") .SetHeader("Content-Type", "text/plain"), write => { write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("hello "))); write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("world."))); }); var response = AppUtils.Call(AppBuilder.BuildConfiguration(b => b .UseChunked() .Run(app))); Assert.That(response.Headers.ContainsKey("transfer-encoding"), Is.False); Assert.That(response.BodyText, Is.EqualTo("hello world.")); } [Test] public void Does_not_encode_if_transfer_encoding_is_present() { var app = AppUtils.Simple( "200 OK", h => h .SetHeader("transfer-encoding", "girl") .SetHeader("Content-Type", "text/plain"), write => { write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("hello "))); write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("world."))); }); var response = AppUtils.Call(AppBuilder.BuildConfiguration(b => b .UseChunked() .Run(app))); Assert.That(response.Headers.GetHeader("Transfer-Encoding"), Is.EqualTo("girl")); Assert.That(response.BodyText, Is.EqualTo("hello world.")); } [Test] public void Encodes_if_content_length_is_not_present() { var app = AppUtils.Simple( "200 OK", h => h .SetHeader("Content-Type", "text/plain"), write => { write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("hello "))); write(new ArraySegment<byte>(Encoding.ASCII.GetBytes("world."))); }); var response = AppUtils.Call(AppBuilder.BuildConfiguration(b => b .UseChunked() .Run(app))); Assert.That(response.BodyText, Is.EqualTo("6\r\nhello \r\n6\r\nworld.\r\n0\r\n\r\n")); Assert.That(response.Headers.GetHeader("Transfer-Encoding"), Is.EqualTo("chunked")); } } } <file_sep>/src/Tests/Gate.Hosts.Manos.Tests/ServerTests.cs using System; using System.IO; using System.Net; using System.Text; using System.Threading; using Gate.Middleware; using Owin; using NUnit.Framework; namespace Gate.Hosts.Manos.Tests { [TestFixture] public class ServerTests { [Test] public void ServerCanBeCreatedAndDisposed() { var server = Server.Create((env, result, fault) => { throw new NotImplementedException(); }, 9089, ""); server.Dispose(); } [Test] public void ServerWillRespondToRequests() { using (Server.Create(Wilson.App(), 19090)) { var request = (HttpWebRequest)WebRequest.Create("http://localhost:19090"); using (var response = (HttpWebResponse)request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { var text = reader.ReadToEnd(); Assert.That(text, Is.StringContaining("hello world")); } } } } [Test] public void ExceptionsWillReturnStatus500() { using (Server.Create(Wilson.App(), 9091)) { var request = (HttpWebRequest)WebRequest.Create("http://localhost:9091/?flip=crash"); var exception = Assert.Throws<WebException>(() => request.GetResponse().Close()); var response = (HttpWebResponse)exception.Response; Assert.That((int)response.StatusCode, Is.EqualTo(500)); } } [Test] public void RequestsMayHavePostBody() { var requestData = new MemoryStream(); AppDelegate app = (env, result, fault) => { var body = (BodyDelegate)env[OwinConstants.RequestBody]; body((data, callback) => { requestData.Write(data.Array, data.Offset, data.Count); return false; }, ex => Wilson.App().Invoke(env, result, fault), CancellationToken.None); }; using (Server.Create(app, 19092)) { var request = (HttpWebRequest)WebRequest.Create("http://localhost:19092/"); request.Method = "POST"; using (var requestStream = request.GetRequestStream()) { var bytes = Encoding.Default.GetBytes("This is a test"); requestStream.Write(bytes, 0, bytes.Length); } request.GetResponse().Close(); var requestText = Encoding.Default.GetString(requestData.ToArray()); Assert.That(requestText, Is.EqualTo("This is a test")); } } } } <file_sep>/src/Tests/Gate.Builder.Tests/Loader/MultiConfigs.cs using Owin; namespace Gate.Builder.Tests.Loader { public class MultiConfigs { public static int FooCalls; public static void Foo(IAppBuilder builder) { FooCalls += 1; } public static int BarCalls; public static void Bar(IAppBuilder builder) { BarCalls += 1; } public static int ConfigurationCalls; public static void Configuration(IAppBuilder builder) { ConfigurationCalls += 1; } } }<file_sep>/src/Hosts/Gate.Hosts.AspNet/RouteCollectionExtensions.cs using System; using System.Web.Routing; using Gate.Builder; using Owin; namespace Gate.Hosts.AspNet { public static class RouteCollectionExtensions { public static void AddOwinRoute(this RouteCollection routes, string path) { routes.Add(new OwinRoute(path, null)); } public static void AddOwinRoute(this RouteCollection routes, string path, AppDelegate app) { routes.Add(new OwinRoute(path, app)); } public static void AddOwinRoute(this RouteCollection routes, string path, Action<IAppBuilder> configuration) { var app = AppBuilder.BuildConfiguration(configuration); routes.Add(new OwinRoute(path, app)); } public static void AddOwinRoute(this RouteCollection routes, string path, IAppBuilder builder, Action<IAppBuilder> configuration) { var app = builder.Build<AppDelegate>(configuration); routes.Add(new OwinRoute(path, app)); } } } <file_sep>/src/Tests/Gate.Middleware.Tests/StaticFiles/BodyStreamTests.cs using System; using System.Text; using System.Threading; using Gate.Middleware.StaticFiles; using NUnit.Framework; namespace Gate.Middleware.Tests.StaticFiles { [TestFixture] public class BodyStreamTests { [Test] public void BodyStream_calls_on_data_delegate() { var called = false; Func<ArraySegment<byte>, Action, bool> next = (data, callback) => { called = true; return false; }; var bodyStream = new BodyStream(next, null, CancellationToken.None); bodyStream.Start(() => { }, null); var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes("dada")); bodyStream.SendBytes(bytes, null, null); Assert.That(called, Is.True); } [Test] public void BodyStream_does_not_send_bytes_while_paused() { var called = false; Func<ArraySegment<byte>, Action, bool> write = (data, callback) => { called = true; return false; }; var bodyStream = new BodyStream(write, null, CancellationToken.None); bodyStream.Start(() => { }, null); bodyStream.Pause(); var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes("dada")); bodyStream.SendBytes(bytes, null, null); Assert.That(called, Is.False); } [Test] public void BodyStream_does_not_send_bytes_while_stopped() { var called = false; Func<ArraySegment<byte>, Action, bool> write = (data, callback) => { called = true; return false; }; var bodyStream = new BodyStream(write, null, CancellationToken.None); bodyStream.Start(() => { }, null); bodyStream.Stop(); var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes("dada")); bodyStream.SendBytes(bytes, null, null); Assert.That(called, Is.False); } [Test] public void BodyStream_calls_completion() { var called = false; var bodyStream = new BodyStream((data, callback) => false, null, CancellationToken.None); bodyStream.Start(() => { }, null); var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes("dada")); bodyStream.SendBytes(bytes, null, () => { called = true; }); Assert.That(called, Is.True); } [Test] public void BodyStream_calls_completion_if_unable_to_send_bytes() { var called = false; var bodyStream = new BodyStream((data, callback) => false, null, CancellationToken.None); bodyStream.Start(() => { }, null); bodyStream.Stop(); var bytes = new ArraySegment<byte>(Encoding.UTF8.GetBytes("dada")); bodyStream.SendBytes(bytes, null, () => { called = true; }); Assert.That(called, Is.True); } [Test] public void BodyStream_calls_dispose_action_when_it_finishes() { var called = false; var bodyStream = new BodyStream((data, callback) => false, _ => { }, CancellationToken.None); bodyStream.Start(() => { }, () => { called = true; }); bodyStream.Finish(); Assert.That(called, Is.True); } } }
cea1f56673e810db3a3f890bd404bfd932616a3f
[ "C#" ]
47
C#
ArloL/gate
f003254f2bf6922e4d378913ef9d75e8f681c003
250e05da3a5f43f3a825e4b5763474b00c6a5a35
refs/heads/main
<file_sep>document.getElementById('memory8GB').addEventListener('click', function(){ setPrice('extra-memory-cost', 0); }); document.getElementById('memory16GB').addEventListener('click', function(){ setPrice('extra-memory-cost', 180); }); document.getElementById('storage256GB').addEventListener('click', function(){ setPrice('extra-storage-cost', 0); }); document.getElementById('storage512GB').addEventListener('click', function(){ setPrice('extra-storage-cost', 100); }); document.getElementById('storage1TB').addEventListener('click', function(){ setPrice('extra-storage-cost', 180); }); document.getElementById('free-delivery').addEventListener('click', function(){ setPrice('delivery-charge', 0); }); document.getElementById('cost-delivery').addEventListener('click', function(){ setPrice('delivery-charge', 20); }); document.getElementById('promo-btn').addEventListener('click', function(){ applyPromoCode(); }); function applyPromoCode(){ const promoText = document.getElementById('promo-text').value; const totalPriceWithOutPromo = parseFloat(document.getElementById('total-price').innerText); let totalPrice = totalPriceWithOutPromo; if (promoText == 'fahim20'){ const discount = totalPriceWithOutPromo * 0.2; totalPrice = totalPriceWithOutPromo - discount; } else if (promoText != 'fahim20'){ document.getElementById('message').innerText = 'Please enter valid code.'; } document.getElementById('total-bill').innerText = totalPrice; } function setPrice(id, price){ document.getElementById(id).innerText = price; total(); } function total(){ const bestPrice = parseInt(document.getElementById('best-price').innerText); const extraMemoryCost = parseInt(document.getElementById('extra-memory-cost').innerText); const extraStorageCost = parseInt(document.getElementById('extra-storage-cost').innerText); const delieryCharge = parseInt(document.getElementById('delivery-charge').innerText); const total = bestPrice + extraMemoryCost + extraStorageCost + delieryCharge; document.getElementById('total-price').innerText = total; document.getElementById('total-bill').innerText = total; }<file_sep># mac-book-pro Simple JavaScript Project. Here i use HTML, Bootstrap and JavaScript. ### Laguage: JavaScript Test Promo Code: **fahim20** <h6><a href='https://fahimahammed.github.io/mac-book-pro/'>Live Site</a></h6>
3c3b7e3fc00fe6b97fe7897a302bb20e2b35f3b0
[ "JavaScript", "Markdown" ]
2
JavaScript
fahimahammed/mac-book-pro
a6db3bcf61f7a34f11b51c4f84a8dfb9b7abd434
e7ade4aed4f29dbec89bc30ac5423ba0d1325c7c
refs/heads/main
<file_sep>#Program calculates geometric characteristics of polygons #Asking how many points will polygon has n = int (input("Enter number of points your polygon would has ")) #Asking coordinates of the points print ("Enter coordinates for every point in counter clockwise order:") #creating empty lists for coordinates x = [] y = [] #filling lists i=0 while i<n: xi = float (input(f"Enter x{i+1}: ")) x.append(xi) yi = float (input(f"Enter y{i+1}: ")) y.append(yi) i=i+1 x.append(x[0]) y.append(y[0]) print () #priinting table of points and coordinates print("Point"+" "*10+"x"+" "*10+"y") print ("-"*30) for i in range(n): print (f"{i+1} {x[i]:16.2f} {y[i]:10.2f}") print () #calculating geometrical characteristics Ax = 0.0 Sx = 0.0 Sy = 0.0 Ix = 0.0 Iy = 0.0 Ixy = 0.0 i=0 for i in range(n): Ax=0.5*(x[i+1]+x[i])*(y[i+1]-y[i])+Ax Sx=(-1/6)*(x[i+1]-x[i])*(y[i+1]**2+y[i]*y[i+1]+y[i]**2)+Sx Sy=(1/6)*(y[i+1]-y[i])*(x[i+1]**2+x[i]*x[i+1]+x[i]**2)+Sy Ix=(-1/12)*(x[i+1]-x[i])*(y[i+1]**3+y[i+1]**2*y[i]+y[i+1]*y[i]**2+y[i]**3)+Ix Iy=(1/12)*(y[i+1]-y[i])*(x[i+1]**3+x[i+1]**2*x[i]+x[i+1]*x[i]**2+x[i]**3)+Iy Ixy=(-1/24)*(y[i+1]-y[i])*((y[i+1]*(3*x[i+1]**2+2*x[i+1]*x[i]+x[i]**2)+y[i]*(3*x[i]**2+2*x[i+1]*x[i]+x[i+1]**2)))+Ixy Xt = Sy/Ax Yt = Sx/Ax Itx = Ix-(Yt**2)*Ax Ity = Iy-(Xt**2)*Ax Itxy =Ixy+Xt*Yt*Ax print ("Geometric characteristics:") print (f"Ax={Ax:3.2f}") print (f"Sx={Sx:3.2f}") print (f"Sy={Sy:3.2f}") print (f"Ix={Ix:3.2f}") print (f"Iy={Iy:3.2f}") print (f"Ixy={Ixy:3.2f}") print (f"Xt={Xt:3.2f}") print (f"Yt={Yt:3.2f}") print (f"Itx={Itx:3.2f}") print (f"Ity={Ity:3.2f}") print (f"Itxy={Itxy:3.2f}")<file_sep># bimaplus3 Files for BIM A+3
6c607ece193442a333435d1c5d705475d246ad2a
[ "Markdown", "Python" ]
2
Python
velokate/bimaplus3
5e167ec64a7b9ea4440cba9ebb05482f59221e05
3a24a1380156f042ffe72634d44f98faa4a602e1
refs/heads/main
<repo_name>codeprentice-org/codeprentice-site-revamped<file_sep>/API/README.md # Codeprentice-Site The new Codeprentice website (currently in development). ## Docker Image Deployment (no Github clone needed) Install and run the image: ```bash docker pull devinleamy/codeprentice-web docker run -p 4200:4200 devinleamy/codeprentice-web ``` ## Project Setup Pretty straight forward just run `npm install` <br/> Make sure you check out the CONTRIBUTING.md file ## Various Commands Run compile and start server: ```bash npm start ``` Run nodemon (after building): ```bash nodemon server.js ``` Build: ```bash npm run-script build ``` Build & Set ENV variables ```npm run-script build DB=YOUR_MONGODB_CONN_STRING ACCESS_TOKEN=ADD_BACKEND_TOKEN npm start ``` <file_sep>/frontend/src/devtools.d.ts declare module 'react-perf-devtool'<file_sep>/API/backend/controllers/user.controller.ts import { Users, UserSchema } from '../models/user.model'; import { Request, Response, NextFunction } from "express"; import { UserType } from "../types/user"; import jwt from "jsonwebtoken"; import { Secret } from "jsonwebtoken"; import { ROLE } from "../enums/role"; import { AxiosResponse } from "axios"; import qs from "qs"; import axios from "axios"; import { Types, Schema } from "mongoose"; //localhost:4200/user/github/login const loginUser = async (req: Request, res: Response, next: NextFunction) => { console.log(process.env.GITHUB_CLIENT_SECRET); // Redirect caller to the GitHub auth web flow with our app credentials res.redirect("https://github.com/login/oauth/authorize?" + qs.stringify({ client_id: process.env.GITHUB_CLIENT_ID, client_secret: process.env.GITHUB_CLIENT_SECRET, scope: "read:org", redirect_uri: "http://localhost:4200/user/github/callback" })) }; const gitHubCallback = async (req: Request, res: Response, next: NextFunction) => { // After successfull auth on GitHub, a code is sent back. We POST it back // to exchange it for an access token const body = { client_id: process.env.GITHUB_CLIENT_ID, client_secret: process.env.GITHUB_CLIENT_SECRET, code: req.query.code // The code we received from GitHub }; const opts = { headers: { accept: 'application/json' } }; axios.post(`https://github.com/login/oauth/access_token`, body, opts) .then((post_res:AxiosResponse) => { console.log(post_res.data); axios.get('https://api.github.com/user', //memberships/orgs/codeprentice-org { headers: { authorization: "token " + post_res.data.access_token, accept: "application/vnd.github.v3+json" } }) .then((r:AxiosResponse) => qs.parse(r.data)) .catch((err:Error) => console.log(err)); }) .catch((err:Error) => res.status(500).json({ message: err.message })); }; // const loginUser = async (req: Request, res: Response, next: NextFunction) => { // // authentication with github api // // adds user to database if they are not there already // // pull user from database // // temporary static user // const userData = req.body.user; // await Users.findOne({email: userData.email}) // .exec() // .then(async (resolve) => { // if (!resolve) { // return res.status(401).json({ // status: 1, // data: "Authentication Failed" // }); // } // const user: UserType = resolve.toObject(); // const token = jwt.sign(user, process.env.JWT_KEY as Secret, { expiresIn: '1h' }); // console.log(`User with email: ${user.email} logged in`); // return res.status(200).json({ // status: 0, // data: { token: token } // }); // }) // .catch(() => { // return res.status(401).json({ // status: 1, // data: "Authentication Failed" // }); // }) // }; // Changes user username give a request body container user: { newUsername: string } // Just for testing const changeUsername = async (req: Request, res: Response, next: NextFunction) => { const user: UserType = req.body.user; const newUsername: string = req.body.newUsername; Users.updateOne({ _id: user._id }, {"$set": { "username": newUsername } }) .exec() .then((resolve) => { console.log(resolve); return res.status(200) .send("Username Successfully Updated"); }) .catch(() => { return res.status(401).json({ status: 1, data: "Failed to Change Username" }); }); }; // Creats a new user given a request body containing user: { email: string, username: string, name: string } // Just for testing const createUser = async (req: Request, res: Response, next: NextFunction) => { req.body._id = Types.ObjectId() const newUser = new Users({...req.body}); await newUser.save() .then((data: any) => res.status(200).send("User was successfully created")) .catch((err: any) => res.status(401).send("Error in creating user")); }; const getUsers = async (req: Request, res: Response, next: NextFunction) => { console.log("getUsers()"); Users.find() .then((results: any[]) => { res.status(200).json(results) }) .catch((err: any) => { console.log("Error in fetching users", err); res.status(404).send(err) }) }; export { loginUser, changeUsername, createUser, gitHubCallback, getUsers } <file_sep>/frontend/src/entities/project.ts import { TimelineItem } from "react-chrono" export type Project = { _id: string; name: string; team: string[], description: string, timeline: TimelineItem[] } <file_sep>/API/backend/models/accessToken.model.ts import { Document, Model, model, Types, Schema, Query } from "mongoose"; const AccessTokenSchema: Schema = new Schema({ _id: Types.ObjectId, userId: String }, {collection: "access_tokens"}); const AccessTokenModel = model("AccessToken", AccessTokenSchema); export { AccessTokenSchema, AccessTokenModel };<file_sep>/API/backend/models/user.model.ts import { model, Types, Schema } from "mongoose"; import { ROLE } from "../enums/role"; export const UserSchema: Schema = new Schema({ _id: { type: Types.ObjectId, required: true }, email: { type: String, required: true }, username: { type: String, required: true }, name: { type: String, required: true }, ROLE: { type: ROLE, required: true }, projects: [{ type: String, required: true }], bio: { type: String, required: true }, github_link: { type: String, }, facebook_link: { type: String, }, linkedin_link: { type: String, }, instagram_link: { type: String, } // The collection in which users will be saved }, { writeConcern: { w: "majority", j: true, wtimeout: 1000, } }); export const Users = model("users", UserSchema);<file_sep>/API/backend/controllers/project.controller.ts import { Request, Response, NextFunction } from "express"; import { Projects, ProjectSchema } from "../models/project.model"; import { UserSchema } from '../models/user.model' import { Types, Schema } from "mongoose"; // Creates a new project give a request body containing project: { name: string } // Just for testing export const createProject = async (req: Request, res: Response, next: NextFunction) => { console.log("Adding project to db"); req.body._id = Types.ObjectId(); const newProject = new Projects({ ...req.body }); newProject.save() .then((res: any) => res.status(200).send("Project Added")) .catch((err: any) => res.status(500).send(err)) }; export const getProjects = (req: Request, res: Response) => { console.log("getProjects()"); Projects.find() .then((results: any[]) => { console.log("Resolved projects") res.status(200).json(results) }) .catch((err: any) => res.status(404).send(err)) } export const getProjectByName = (req: Request, res: Response) => { console.log("getProjectByName() - ", req.params.name); Projects.find({name: req.params.name}) .then((results:any[]) => res.status(200).json(results)) .catch((err: any) => res.status(404).send(err)) } <file_sep>/API/backend/server.ts import express from 'express'; import { Request, Response, NextFunction } from "express"; import { USER_API } from "./routes/user.route"; import { PROJECT_API } from "./routes/project.route"; import { PICTURE_API } from './routes/picture.route'; import bodyParser from 'body-parser' import mongoose from "mongoose"; import cors from "cors"; import path from "path"; import helmet from "helmet"; import rateLimit from "express-rate-limit"; import { validateRequest } from './middleware/validate-request'; require("dotenv").config(); // Set rate limit properties const MINUTES = 15; const limiter = rateLimit({ windowMs: MINUTES * 60 * 1000, // 15 minutes max: 100 // limit each IP to 100 requests per windowMs }); // Connect to database mongoose.connect( process.env.DB as string, { useNewUrlParser: true, useUnifiedTopology: true } ); const database = mongoose.connection; database.on("error", () => console.log("Unable to connect to the database")); database.once("open", () => console.log("Connected to database")); // Express config const app = express(); app.use(helmet()); app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Rate limiting is disabled for testing //app.use(limiter); // Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc) // see https://expressjs.com/en/guide/behind-proxies.html // app.set('trust proxy', 1); // For sending view app.use(express.static(path.join(__dirname, "./static"))); // Config API Routes app.use("/user", validateRequest, USER_API); app.use("/project", validateRequest, PROJECT_API); app.use("/picture", validateRequest, PICTURE_API); // Start Express server const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log(`Server started on port ${PORT}`)); <file_sep>/API/backend/types/user.ts import { ROLE } from "../enums/role"; import { Types } from "mongoose"; export type UserType = { _id: Types.ObjectId; email: string; username: string; name: string; ROLE: ROLE; } export interface UserInt { _id: Types.ObjectId; email: string; username: string; name: string; ROLE: ROLE; }<file_sep>/frontend/src/entities/user.ts export type User = { _id: string; email: string; username: string; name: string; ROLE: string; projects: string[]; bio: string; github_link?: string; facebook_link?: string; linkedin_link?: string; instagram_link?: string; }<file_sep>/frontend/src/components/navbar/github.d.ts declare module 'react-login-github';<file_sep>/API/backend/routes/user.route.ts import express from "express"; import { checkAuth } from "../middleware/check-auth"; import { createUser, loginUser, changeUsername, gitHubCallback, getUsers } from "../controllers/user.controller"; export const USER_API = express.Router(); // logins in user and creates signed JWT USER_API.get("/github/login", loginUser); USER_API.get("/github/callback", gitHubCallback); // Changes user username given a request body containing user: { newUsername: string } USER_API.post("/change_username", checkAuth, changeUsername); // Creates new user given a request body containing user: { email: string, username: string, name: string } USER_API.post("/create_user", createUser); USER_API.get("/", getUsers); <file_sep>/API/backend/middleware/check-role.ts import { Request, Response, NextFunction } from "express"; import { UserType } from "../types/user"; import { ROLE } from "../enums/role"; // Verifies that the user has Admin privilages export const checkRoleAdmin = (req: Request, res: Response, next: NextFunction) => { try { const user: UserType = req.body.user; console.log(user) if (user.ROLE === ROLE.ADMIN) { next(); } else { return res.status(401).json({ status: 1, data: "Authentication Failed" }); } } catch (error) { return res.status(401).json({ status: 1, data: "Authentication Failed" }); } }<file_sep>/API/backend/routes/picture.route.ts import express from "express"; import { Request, Response, NextFunction } from "express"; export const PICTURE_API = express.Router(); // Endpoints to get pictures PICTURE_API.get("/code", (req: Request, res: Response) => { res.sendFile("../static/code.jpg"); }) PICTURE_API.get("/coding", (req: Request, res: Response) => { res.sendFile("../static/coding.jpg"); }) PICTURE_API.get("/dark", (req: Request, res: Response) => { res.sendFile("../static/dark.png"); }) PICTURE_API.get("/githubLogo", (req: Request, res: Response) => { res.sendFile("../static/github_logo.png"); }) PICTURE_API.get("/codeprenticeLogo", (req: Request, res: Response) => { res.sendFile("../static/logo.png"); }) PICTURE_API.get("/:username", (req: Request, res: Response) => { res.sendFile("../static/logo.png"); }) <file_sep>/API/backend/routes/project.route.ts import express from "express"; import { Request, Response, NextFunction } from "express"; import { checkAuth } from "../middleware/check-auth"; import { checkRoleAdmin } from "../middleware/check-role"; import { createProject, getProjects, getProjectByName } from "../controllers/project.controller"; export const PROJECT_API = express.Router(); // Creates a new project given a request body containing project: { name: string } // need to add middleware - checkAuth, checkRoleAdmin, PROJECT_API.post("/create_project", createProject); PROJECT_API.get("/", getProjects); PROJECT_API.get("/:name", getProjectByName); <file_sep>/frontend/src/env/env.ts const API_GET_USER = "" const API_SEND_USER_DETAILS = "" export {}<file_sep>/API/backend/models/project.model.ts import { model, Types, Schema } from "mongoose"; export const ProjectSchema = new Schema({ _id: { type: Types.ObjectId, required: true }, name: { type: String, required: true }, team: [{ type: String, required: true }], description: { type: String, required: true }, timeline: [ { title: { type: String, }, cardTitle: { type: String, }, cardSubtitle: { type: String, }, cardDetailedText: { type: String, } } ] }, { writeConcern: { w: "majority", j: true, wtimeout: 1000, } } ); export const Projects = model("projects", ProjectSchema);<file_sep>/API/backend/middleware/validate-request.ts import { Request, Response, NextFunction } from "express"; import safeCompare from 'safe-compare'; export const validateRequest = (req: Request, res: Response, next: NextFunction) => { console.log("validateRequest()"); let requestToken = req.header('access_token') as string; if (safeCompare(requestToken, process.env.ACCESS_TOKEN as string)) { console.log("Access Granted"); next(); } else { console.log("Access Token invalid"); res.status(400).send("Need access token to get data"); } }<file_sep>/API/backend/enums/role.ts export enum ROLE { ADMIN = "ADMIN", ORG = "ORG", DEV = "DEV" } <file_sep>/API/backend/types/project.ts import { UserType, UserInt } from "./user"; import { Types } from 'mongoose'; export type ProjectType = { _id: Types.ObjectId; name: string; team: Array<UserType>; } export interface ProjectInt { _id: Types.ObjectId; name: string; team: Array<UserType>; }
afdc7d401ce96698df8574dc488499e8498be60a
[ "Markdown", "TypeScript" ]
20
Markdown
codeprentice-org/codeprentice-site-revamped
28c4b1fb797c28017e42bee97b5dc26460ce143c
b8fa190ade7a740a03650949d9aa9ae99409011a
refs/heads/master
<file_sep>// // ArtCollectionViewController.swift // CreativityApp-CSP // // Created by <NAME> on 10/21/19. // Copyright © 2019 CTEC. All rights reserved. // import UIKit public class ArtCollectionViewController : UICollectionViewController { // MARK: Data Members var images : [[String]]! let resuseIdentifier = "artIdentifier" private let sectionInsets = UIEdgeInsets(top: 10.0, left: 2.0, bottom: 10.0, right: 2.0) // MARK: - Life Cycle public override func viewDidLoad() { super.viewDidLoad() loadImages() } private func loadImages() -> Void { let i1 : [String] = ["BenFaerberJavaHaiku", "Java Haiku"] let i2 : [String] = ["BenFaerberMainframeHaiku", "Mainframe Haiku"] let i3 : [String] = ["BenFaerberSwiftHaiku", "Swift Haiku"] let i4 : [String] = ["bobpool", "Bobpool"] let i5 : [String] = ["fastcar", "Fast Car"] let i6 : [String] = ["octocat", "Octokitty"] let i7 : [String] = ["sleeping", "Self Driving Cars"] images = [i1, i2, i3, i4, i5, i6, i7] } // MARK: - Navigation / Layout public override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section : Int) -> Int { if (images != nil) { return images.count // TODO: - fix the return amount } return 0 } // MARK: - CollectionView methods public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let artCell = collectionView.dequeueReusableCell(withReuseIdentifier: resuseIdentifier, for: indexPath) as! ArtCell artCell.backgroundColor = .purple artCell.artImage.image = UIImage.init(named: images[0][indexPath.row]) artCell.artLabel.text = images[1][indexPath.row] return artCell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let availableWidth = view.frame.width - sectionInsets.top let widthPerItem = availableWidth / 4 let size = UIImage.init(named: images[indexPath.row][0])?.size let scale = size!.width / widthPerItem let newWidth = scale * size!.width let newHeight = scale * size!.height return CGSize(width: newWidth, height: newHeight) } // MARK: - Handle Touch @objc private func dismissFullscreenImage(_ sender: UITapGestureRecognizer) { sender.view?.removeFromSuperview() } public override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let imageView = UIImageView(image: UIImage.init(named: images[indexPath.row][0])) imageView.frame = self.view.frame imageView.backgroundColor = .green imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage)) imageView.addGestureRecognizer(tap) self.view.addSubview(imageView) } // Mark: - Handle spacing between compents public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left } } <file_sep>// // ArtCell.swift // CreativityApp-CSP // // Created by <NAME> on 10/21/19. // Copyright © 2019 CTEC. All rights reserved. // import UIKit class ArtCell : UICollectionViewCell { @IBOutlet weak var artImage: UIImageView! @IBOutlet weak var artLabel: UILabel! } <file_sep>// // ViewController.swift // CreativityApp-CSP // // Created by <NAME>/Users/wfae1302/Documents/Creativity/creativity-pm-benfaerber/CreativityApp-CSP/View/DrawingView.swiftber on 10/21/19. // Copyright © 2019 CTEC. All rights reserved. // import UIKit class CreativityViewController : UIViewController { @IBOutlet weak var artPanel: DrawingView! override func viewDidLoad() -> Void { super.viewDidLoad() // Do any additional setup after loading the view. } } <file_sep>// // DrawingView.swift // CreativityApp-CSP // // Created by <NAME> on 10/21/19. // Copyright © 2019 CTEC. All rights reserved. // import UIKit class DrawingView : UIView { // Dont call it bruh public override func draw(_ rect: CGRect) -> Void { createStickFigure().stroke() } private func createStickFigure() -> UIBezierPath { let figure :UIBezierPath = UIBezierPath() UIColor.magenta.setStroke() figure.lineWidth = 3.0 figure.addArc(withCenter: CGPoint(x: 200, y: 200), radius: CGFloat(20), startAngle: CGFloat(0), endAngle: CGFloat(2) * CGFloat.pi, clockwise: true) figure.move(to: CGPoint(x: 200, y: 220)) figure.addLine(to: CGPoint(x:200, y:270)) figure.move(to: CGPoint(x: 180, y: 240)) figure.addLine(to: CGPoint(x:220, y:240)) figure.move(to: CGPoint(x: 200, y: 270)) figure.addLine(to: CGPoint(x:180, y:300)) figure.move(to: CGPoint(x: 200, y: 270)) figure.addLine(to: CGPoint(x:220, y:300)) return figure } private func lotsOfFigures() -> Void { for _ in 0..<5 { let randomX = CGFloat(arc4random() % 300) let randomY = CGFloat(arc4random() % 300) let randomSize = CGFloat(arc4random() % 100) createStickFigure(at: CGPoint(x: randomX, y: randomY), ofSize: randomSize) } } private func makeRandomColor() -> UIColor { let red :CGFloat = CGFloat( Double(arc4random() % 256) / 255.0) let green :CGFloat = CGFloat( Double(arc4random() % 256) / 255.0) let blue :CGFloat = CGFloat( Double(arc4random() % 256) / 255.0) let color = UIColor(red: red, green: green, blue: blue, alpha: CGFloat(1.0)) return color; } private func createStickFigure(at center : CGPoint, ofSize: CGFloat) -> Void { let specialFigure :UIBezierPath = UIBezierPath() specialFigure.addArc(withCenter: center, radius: CGFloat(ofSize), startAngle: CGFloat(0), endAngle: CGFloat(2) * CGFloat.pi, clockwise: true) specialFigure.move(to: CGPoint(x: center.x, y: center.y + CGFloat(ofSize))) specialFigure.addLine(to: CGPoint(x: center.x, y: center.y + (ofSize * 3.5))) specialFigure.move(to: CGPoint(x: center.x - ofSize, y: center.y + (ofSize * 2))) specialFigure.addLine(to: CGPoint(x: center.x + ofSize, y: center.y + (ofSize * 2))) specialFigure.move(to: CGPoint(x: center.x, y: center.y + CGFloat(ofSize * 3.5))) specialFigure.addLine(to: CGPoint(x: center.x - ofSize, y: center.y + (ofSize * 5))) specialFigure.move(to: CGPoint(x: center.x, y: center.y + (ofSize * 5))) specialFigure.addLine(to: CGPoint(x: center.x + ofSize, y: center.y + (ofSize * 5))) makeRandomColor().setStroke() specialFigure.lineWidth = CGFloat(arc4random() % 6 + 1) specialFigure.stroke() } private func drawTurtle() -> Void { let logo = UIBezierPath() UIColor.white.setFill() logo.move(to: CGPoint(x: 50, y: 250)) logo.addLine(to: CGPoint(x: 100, y: 300)) logo.addLine(to: CGPoint(x: 50, y: 350)) logo.close() logo.fill() } private func drawWithImage() -> Void { let bobRoss : UIBezierPath = UIBezierPath() UIColor(patternImage: UIImage(named: "bobpool")!).setFill() UIColor.green.setStroke() bobRoss.lineWidth = 1.4 bobRoss.move(to: CGPoint(x: 150, y: 40)) bobRoss.addLine(to: CGPoint(x: 75, y: 200)) bobRoss.addLine(to: CGPoint(x: 50, y: 200)) bobRoss.addLine(to: CGPoint(x: 0, y: 200)) bobRoss.close() bobRoss.stroke() bobRoss.fill() } private func drawF() { let f = UIBezierPath() UIColor.white.setFill() let scalar = 7 // bottom left corner of f let x = 100 let y = 100 f.move(to: CGPoint(x: x, y: y)) f.addLine(to: CGPoint(x: x, y: y+(20 * scalar))) // 1 f.addLine(to: CGPoint(x: x+(10 * scalar), y: y+(20 * scalar))) // 2 f.addLine(to: CGPoint(x: x+(10 * scalar), y: y+(16 * scalar))) // 3 f.addLine(to: CGPoint(x: x+(4 * scalar), y: y+(16 * scalar))) // 4 f.addLine(to: CGPoint(x: x+(8 * scalar), y: y+(12 * scalar))) // 5 f.addLine(to: CGPoint(x: x+(8 * scalar), y: y+(8 * scalar))) // 6 f.addLine(to: CGPoint(x: x+(4 * scalar), y: y+(8 * scalar))) // 7 f.addLine(to: CGPoint(x: x+(4 * scalar), y: y)) // 8 f.addLine(to: CGPoint(x: x, y: y)) // 9 f.close() f.fill() } }
a46f6a8dd21ca26e9643955cf47e16082a939aa6
[ "Swift" ]
4
Swift
benfaerber/CreativityApp
20f41dc0d826169cf59f8de652b6da0e30562f14
b5a8178a926bc8d2d08935c88d84a074f450ff48
refs/heads/master
<file_sep>package edu.hm.dako.lwtrt; /** * The Class LWTRTAbortException. * * @author Bakomenko * @version 1.0.0 */ public class LWTRTAbortException extends LWTRTException { /** The Constant serialVersionUID. */ private static final long serialVersionUID = -46473630383065913L; /** * Instantiates a new LWTRT Abort exception. * * @param msg the msg */ public LWTRTAbortException(String msg) { super(msg); } /** * Instantiates a new LWTRT Abort exception. * * @param msg the msg * @param e the e */ public LWTRTAbortException(Throwable e) { super(e); } } <file_sep>package edu.hm.dako.lwtrt.udpWrapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.hm.dako.lwtrt.pdu.LWTRTPdu; /** * The Class UdpSocketWrapper. * * Diese Klasse kapselt die Datagram-Sockets und stellt * eine etwas komfortablere Schnittstelle zur Verfuegung, * die ausschliesslich fuer die LWTRT-Schicht dient und nicht * wiederverwendbar programmiert ist. * * Der Mehrwert dieser Klasse im Vergleich zur Standard-DatagramSocket-Klasse * ist die Nutzung eines Objektstroms zur Kommunikation ueber UDP. * * Die Klasse ist also Bestandteil der LWTRT-Schicht. * * @author <NAME> * * @version 2.0.0 */ public class UdpSocketWrapper { private DatagramSocket socket; private static Log log = LogFactory.getLog(UdpSocketWrapper.class); private static final int receiveBufferSize = 1000000; private static final int sendBufferSize = 50000; /** * Konstruktor * @param port UDP-Port, der lokal für das Datagramm-Socket verwendet werden soll */ public UdpSocketWrapper(int port) throws SocketException { socket = new DatagramSocket(port); try { socket.setReceiveBufferSize(receiveBufferSize); socket.setSendBufferSize(sendBufferSize); } catch (SocketException e){ log.debug("Socketfehler: " + e); } } /** * Empfangen einer LWTRT-PDU * * @param lwtrtPdu: Nachricht, die empfangen wurde * @throws IOException */ public synchronized void receive(LWTRTPdu lwtrtPdu) throws IOException { byte[] bytes = new byte[65527]; DatagramPacket packet = new DatagramPacket(bytes, bytes.length); try { socket.receive(packet); } catch (IOException e) { log.error("SEND: " + "Fehler beim Senden einer LWTRT-Pdu"); throw e; } ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); ObjectInputStream ois = new ObjectInputStream(bais); try { lwtrtPdu.clone((LWTRTPdu)ois.readObject()); String remoteAddress = packet.getAddress().toString(); remoteAddress = remoteAddress.substring(1, remoteAddress.length()); lwtrtPdu.setRemoteAddress(remoteAddress); lwtrtPdu.setRemotePort(packet.getPort()); log.debug("" + packet.getPort() + "->" + socket.getLocalPort() + " " + decodeOpid(lwtrtPdu) + "-" + lwtrtPdu.getSequenceNumber()); } catch (ClassNotFoundException e) { log.error("ClassNotFoundException:", e); } } /** * Senden einer LWTRT-PDU * @param lwtrtPdu: Zu sendende PDU * @throws IOException */ public void send(LWTRTPdu lwtrtPdu) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(lwtrtPdu); byte[] bytes = out.toByteArray(); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(lwtrtPdu .getRemoteAddress()), lwtrtPdu.getRemotePort()); log.debug("SEND: " + packet.getAddress() + ":" + packet.getPort() + " " + decodeOpid(lwtrtPdu) + "-" + lwtrtPdu.getSequenceNumber()); try { socket.send(packet); } catch (IOException e) { log.error("SEND: " + "Fehler beim Senden einer LWTRT-Pdu"); throw e; } } /** * Datagram-Socket schliessen */ public void close() { socket.close(); } /** * @return Lokale Adresse */ public String getLocalAddress() { return socket.getLocalAddress().getHostAddress(); } /** * @return lokalen Port */ public int getLocalPort() { return socket.getLocalPort(); } /** * Dekodieren des LWTRT-Operationscodes fuer das Debugging */ private String decodeOpid(LWTRTPdu lwtrtPdu) { switch( lwtrtPdu.getOpId()){ case 1: return "OPID_CONNECT_REQ"; case 2: return "OPID_CONNECT_RSP"; case 3: return "OPID_DISCONNECT_REQ"; case 4: return "OPID_DISCONNECT_RSP"; case 5: return "OPID_DATA_REQ"; case 6: return "OPID_DATA_RSP"; case 7: return "OPID_PING_REQ"; case 8: return "OPID_PING_RSP"; default: return "UNKNOWN"; } } }<file_sep>log4j.rootLogger=WARN, ConsoleAppender log4j.rootLogger=TRACE, RollingFileAppender log4j.appender.ConsoleAppender=org.apache.log4j.ConsoleAppender log4j.appender.ConsoleAppender.layout=org.apache.log4j.PatternLayout log4j.appender.ConsoleAppender.layout.ConversionPattern=%d{ISO8601} %-5p [%t] %c: %m%n log4j.appender.RollingFileAppender=org.apache.log4j.DailyRollingFileAppender log4j.appender.RollingFileAppender.datePattern='.'yyyy-MM-dd_HH-mm log4j.appender.RollingFileAppender.file=logs/echoclient_tracelog.log log4j.appender.RollingFileAppender.layout=org.apache.log4j.PatternLayout log4j.appender.RollingFileAppender.layout.ConversionPattern=%d{ISO8601} %-5p [%t] %c: %m%n<file_sep>package BenchmarkingClient; /** * Klasse TimeCounterThread * * Eigener Thread, der die Laufzeit eines Tests alle 2 Sekunden fuer * eine Ausgabe auf Terminal (Bildschirm) meldet. * * @author Mandl * */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TimeCounterThread extends Thread { private static Log log = LogFactory.getLog(TimeCounterThread.class); private BenchmarkingClientGuiInterface out = null; private boolean running = true; private static int numberOfSeconds = 2; public TimeCounterThread(BenchmarkingClientGuiInterface clientGui) { setName("TimeCounterThread"); this.out = clientGui; } /** * Run-Methode fuer den Thread: * Erzeugt alle n Sekunden einen Zaehler und sendet ihn an die Ausgabe */ public void run() { log.debug(getName() + " gestartet"); //System.out.println(getName() + " gestartet"); out.resetCurrentRunTime(); while (running) { try { Thread.sleep(1000*numberOfSeconds); } catch (InterruptedException e) { log.error("Sleep unterbrochen"); } out.addCurrentRunTime(numberOfSeconds); } } /** * Beenden des Threads */ public void stopThread() { running = false; log.debug(getName() + " gestoppt"); //System.out.println(getName() + " gestoppt"); } }<file_sep>package BenchmarkingClient; /** * Klasse GuiStartData * * Startparameter fuer Lasttest, die nach dem Start des Tests * auf Terminal (Bildschirm) ausgegeben werden sollen. * * @author Mandl * */ public class GuiStartData { long numberOfRequests; // Anzahl geplanter Requests String startTime; // Zeit des Testbeginns public long getNumberOfRequests() { return numberOfRequests; } public void setNumberOfRequests(long numberOfRequests) { this.numberOfRequests = numberOfRequests; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } }<file_sep>package edu.hm.dako.chat.administration; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * @author <NAME> * @author <NAME> * * Administrationsprogramm * * - auslesen des auditLogs -> Pfad angeben? * - Pfad als String einlesen von cmd line * - aufbereiten der Informationen -> Statistik nach clients aufdröseln * - ausgeben -> wo? */ public class Administration { /** * Das sind die benötigten Objektvariablen. */ private BufferedReader bufferedReader; private ListOfClients clients = new ListOfClients(); private int messageCounter = 0; private int logoutCounter = 0; /** * Die Methode dient dazu, dass die Daten aus der Log-Datei in die Kommandozeile eingetragen wird. * @param fileName */ private void loadFile(String fileName) { File file = new File(fileName); if (!file.canRead() || !file.isFile()) System.exit(0); BufferedReader in = null; try { in = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = in.readLine()) != null) { //System.out.println("Gelesene Zeile: " + line); String[] s = line.split("@@"); //Für den Fall, falls wir es brauchen sollten. if(s.length == 6) { String s1 = s[0]; //ClientName String s2 = s[1]; //PDU-Type String s3 = s[2]; //Time-Stamp String s4 = s[3]; //Server-Thread String s5 = s[4]; //Client-Thread String s6 = s[5]; //Message if (s1.equals(clients.getClient(s1).getClientName())) { if (s2.equals("Login-Request")) { clients.getClient(s1).setLoginTimestamp(s3); //Wenn ein Login bereits stattfand, dann wird der TimeStamp überschrieben. } else if (s2.equals("Logout-Request")) { clients.getClient(s1).setLogoutTimestamp(s3); } else if (s2.equals("Chat-Message-Request")) { clients.getClient(s1).setMessageCounter(clients.getClient(s1).getMessageCounter()+1); messageCounter = messageCounter + 1; } else { } } else if (s1 != null) { if (s2.equals("Login-Request")) { ClientStatistic clientNew = new ClientStatistic(); clientNew.setClientName(s1); clientNew.setLoginTimestamp(s3); clients.addClients(clientNew); } else { } } else { } } else if (s.length == 5) { String s1 = s[0]; //ClientName String s2 = s[1]; //PDU-Type String s3 = s[2]; //Time-Stamp String s4 = s[3]; //Server-Thread String s5 = s[4]; //Client-Thread //if (s1.equals(clients.getClient(s1).getClientName())) { if (clients.getClient(s1) != null && s1.equals(clients.getClient(s1).getClientName())) { if (s2.equals("Login-Request")) { clients.getClient(s1).setLoginTimestamp(s3); //Wenn ein Login bereits stattfand, dann wird der TimeStamp überschrieben. } else if (s2.equals("Logout-Request")) { //System.out.println("Lo"); clients.getClient(s1).setLogoutTimestamp(s3); logoutCounter = logoutCounter + 1; } else if (s2.equals("Chat-Message-Request")) { System.out.println("M"); clients.getClient(s1).setMessageCounter(clients.getClient(s1).getMessageCounter()+1); messageCounter = messageCounter + 1; } else { } } else if (s1 != null) { if (s2.equals("Login-Request")) { ClientStatistic clientNew = new ClientStatistic(); clientNew.setClientName(s1); clientNew.setLoginTimestamp(s3); clients.addClients(clientNew); } else { } } else { } } } System.out.println("Anzahl der insgesamt angemeldeten Clients: "+ clients.getListSize()); System.out.println("Anzahl der insgesamt abgemeldeten Clients: "+ logoutCounter); System.out.println("Anzahl der insgesamt gesendeten Textnachrichten: "+ messageCounter); for (int i = 0; i < clients.getListSize(); i++) { System.out.println(clients.getClientsByIndex(i).toString()); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Eine main-Methode zum testen dieser Klasse. * @param args */ public static void main(String[] args) { String fileName = args[0]; Administration a = new Administration(); a.loadFile(fileName); } } <file_sep>package edu.hm.dako.chat.auditlog; import java.io.IOException; /** * @author <NAME> * Eine abstrakte Klasse für unseren AuditLog-Server-Klasse. */ public abstract class AbstractAuditLogServer implements AuditLogServerInterface { /** * Eine start-Methode * @throws IOException */ public abstract void start() throws IOException; /** * Eine stop-Methode * @throws IOException */ public abstract void stop() throws IOException; } <file_sep>package edu.hm.dako.EchoApplication.Basics; import java.io.Serializable; /** * Klasse EchoPDU * * Dient der Uebertragung einer Echo-Nachricht (Request und Response) * * @author Mandl * */ public class EchoPDU implements Serializable { private static final long serialVersionUID = -6172619032079227583L; String clientName; // Name des Client-Threads, der den Request absendet String serverThreadName; // Name des Threads, der den Request im Server bearbeitet boolean lastRequest; // Kennzeichen, ob Client letzte Nachricht sendet. Dieses Kennzeichen // dient dem Server dazu, um festzustellen, ob sich der Client nach der Nachricht beendet private long serverTime; // Zeit in Nanosekunden, die der Server benoetigt. Diese // Zeit wird vom Server vor dem Absenden der Response eingetragen String message; // Echo-Nachricht (eigentliche Nachricht in Textform) public EchoPDU() { clientName = null; serverThreadName = null; message = null; serverTime = 0; lastRequest = false; } public void setClientName(String name) { this.clientName = name; } public void setServerThreadName(String name) { this.serverThreadName = name; } public void setMessage(String msg) { this.message= msg; } public void setServerTime(long time) { this.serverTime = time; } public void setLastRequest (boolean last) { this.lastRequest = last; } public String getClientName() { return(clientName); } public String getServerThreadName() { return(serverThreadName); } public String getMessage() { return(message); } public long getServerTime() { return(serverTime); } public boolean getLastRequest() { return(lastRequest); } } <file_sep>package edu.hm.dako.lwtrt.impl; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import edu.hm.dako.lwtrt.LWTRTAbortException; import edu.hm.dako.lwtrt.LWTRTConnection; import edu.hm.dako.lwtrt.LWTRTService; import edu.hm.dako.lwtrt.LWTRTException; /** * Klasse LWTRTServiceImpl * * @author Bakomenko, Mandl * @version 1.0.0 */ public class LWTRTServiceImpl implements LWTRTService { /** Singleton-Instanz von LWTRTService */ public static LWTRTService INSTANCE = new LWTRTServiceImpl(); /** Liste aller aktiv genutzten Ports */ private Map<Integer, PortHandle> portsInUse = new ConcurrentHashMap<Integer, PortHandle>(); /** * Leerer privater Konstruktor. Es handelt sich hier um * ein Singleton. */ private LWTRTServiceImpl(){} /* * (non-Javadoc) * * @see edu.hm.dako.wise0910.lwtrt.Instance#register(int, int[]) */ @Override public void register(int localPort) throws LWTRTException { if (portsInUse.containsKey(localPort)) { throw new LWTRTException("Port is already in use"); } PortHandle porthandle = new PortHandle(localPort); portsInUse.put(localPort, porthandle); } /* * (non-Javadoc) * * @see edu.hm.dako.wise0910.lwtrt.Instance#unregister() */ @Override public void unregister(int localPort) throws LWTRTException { if (!portsInUse.containsKey(localPort)) { throw new LWTRTException("There is no connection registered for port "+localPort); } else { PortHandle portHandle = portsInUse.get(localPort); portHandle.requestStop(); portsInUse.remove(localPort); } } @Override public LWTRTConnection connect(int localPort, String remoteAddress, int remotePort) throws LWTRTException, LWTRTAbortException { return portsInUse.get(localPort).connect(remoteAddress, remotePort); } @Override public LWTRTConnection accept(int localPort) throws LWTRTException { return portsInUse.get(localPort).accept(); } } <file_sep>package BenchmarkingClient; /** * Konfigurationsparameter fuer Lasttest * * @author Mandl * */ public class GuiInputParameters { int numberOfClients; // Anzahl zu startender Client-Threads int messageLength; // Nachrichtenlaenge int clientThinkTime; // Denkzeit zwischen zwei Requests int numberOfMessages; // Anzahl der Nachrichten pro Client-Thread // Typ der Implementierung ImplementationType implementationType; // Typ der Messung fuer das Messprotokoll MeasurementType measurementType; int remoteServerPort; // UDP- oder TCP-Port des Servers, Default: 50000 String remoteServerAddress; // Server-IP-Adresse, Default: "127.0.0.1" /** * Konstruktor * Belegung der Inputparameter mit Standardwerten */ public GuiInputParameters() { numberOfClients = 500; clientThinkTime = 100; messageLength = 50; numberOfMessages = 100; remoteServerPort = 50000; remoteServerAddress = new String("127.0.0.1"); implementationType = ImplementationType.TCPSingleThreaded; measurementType = MeasurementType.VarMsgLength; } /** * Implementierungsvarianten des Lasttests mit verschiedenen Transportprotokollen * * @author Mandl */ public enum ImplementationType { TCPSingleThreaded(0) { public String toString() { return "Single-threaded TCP"; } }, TCPMultiThreaded(1) { public String toString() { return "Multi-threaded TCP"; } }, UDPSingleThreaded(2) { public String toString() { return "Single-threaded UDP"; } }, UDPMultiThreaded(3) { public String toString() { return "Multi-threaded UDP"; } }, MyMultiThreaded(4) { public String toString() { return "My Multi-threaded Implementation"; } }, LwtrtMultiThreaded(5) { public String toString() { return "Multi-threaded LWTRT"; } }, RmiMultiThreaded(6) { public String toString() { return "Multi-threaded RMI"; } }; private int wert; // Ordnung fuer Enum-Werte private ImplementationType(int wert) { this.wert = wert; } //TODO: mapping des Strings zum Wert fehlt private ImplementationType() { } } /** * Typen von unterstuetzten Messungen * @author Mandl * */ public enum MeasurementType { // Variation der Threadanzahl VarThreads { public String toString() { return "Veraenderung der Threadanzahl"; } }, // Variation der Nachrichtenlaenge VarMsgLength { public String toString() { return "Veraenderung der Nachrichtenlaenge"; } } } public int getNumberOfClients() { return numberOfClients; } public void setNumberOfClients(int numberOfClients) { this.numberOfClients = numberOfClients; } public int getMessageLength() { return messageLength; } public void setMessageLength(int messageLength) { this.messageLength = messageLength; } public void getMessageLength(int numberOfClients) { this.numberOfClients = numberOfClients; } public int getClientThinkTime() { return clientThinkTime; } public void setClientThinkTime(int clientThinkTime) { this.clientThinkTime = clientThinkTime; } public int getNumberOfMessages() { return numberOfMessages; } public void setNumberOfMessages(int numberOfMessages) { this.numberOfMessages = numberOfMessages; } public ImplementationType getImplementationType() { return implementationType; } public void setImplementationType(ImplementationType implementationType) { this.implementationType = implementationType; } public MeasurementType getMeasurementType() { return measurementType; } public void setMeasurementType(MeasurementType measurementType) { this.measurementType = measurementType; } public int getRemoteServerPort() { return remoteServerPort; } public void setRemoteServerPort(int remoteServerPort) { this.remoteServerPort = remoteServerPort; } public String getRemoteServerAddress() { return remoteServerAddress; } public void setRemoteServerAddress(String remoteServerAddress) { this.remoteServerAddress = remoteServerAddress; } }<file_sep>package edu.hm.dako.lwtrt; import edu.hm.dako.lwtrt.LWTRTException; /** * Repraesentiert eine Transportverbindung, ueber die ein Dienstnehmer mit einem Verbindungspartner Daten austauschen kann. * <p> * Die {@link LWTRTConnection} stellt eine gesicherte Verbindung zur Verfuegung. Beim Senden von Daten wird der Empfang * der Daten nach verfolgt. Beim Empfang von Daten wird die Reihenfolge ueberwacht und mehrfach ausgelieferte Daten * erkannt. Ein Verlust einer Nachricht wird ebenfalls erkannt. Die Nachrichten werden ggf. erneut gesendet. * * @author Bakomenko */ public interface LWTRTConnection { /** * Aufgebaute Verbindung wird aktiv abgebaut. * * @throws LWTRTException Allgemeine Fehler die waehrend des aktiven Verbindungsabbaus auftreten */ public void disconnect() throws LWTRTException; /** * Akzeptieren einer eingegangenen Nachricht ueber den Abbau der Verbindung beim passiven Verbindungsabbau. * * @throws LWTRTException Fehler die waehrend des passiven Verbindungsabaus auftreten */ public void acceptDisconnection() throws LWTRTException; /** * Daten an den Verbindungspartner uebertragen. * <p> * Nach dem Senden der Daten wird auf eine Bestaetigung durch den Empfaenger gewartet. Ist die Bestaetigung nicht vor * Ablauf eines Timer eingetroffen, wird der Sendeversuch wiederholt. Nach zwei erfolglosen Wiederholungen wird das * Senden abgebrochen und die Verbindung gilt als abgebaut. * * @param pdu Daten, die zu uebertragen sind * @throws LWTRTException Allgemeiner Fehler die waehrend des Sendenbs auftreten * @throws LWTRTAbortException Zeigt den Abbruch des Sendeversuchts an (nach drei Versuchen) */ public void send(Object pdu) throws LWTRTException, LWTRTAbortException; /** * Daten vom Verbindungspartner empfangen. * <p> * Es wird gewartet, bis Daten vom Verbindungspartner vorliegen. Wurden mehrere Pakete vom Verbindungspartner * gesendet, werden die Daten in der richtigen Reihenfolge (FIFO) an den Dienstnehmer uebergeben. Pakete die mehrmals * empfangen wurden, werden nur einmal an den Dienstnehmer uebergeben. * * @return empfangenes Paket * @throws LWTRTException Fehler die waehrend des Empfangens auftreten */ public Object receive() throws LWTRTException; /** * Durchfuehrung einer Lebendueberwachung eines Partners. * <p> * An den Verbindungspartner wird eine Anfrage (ping) gesendet, die umgehend beantwortet werden muss. Wird auf die * Anfrage nicht vor Ablauf eines Timers geantwortet wird zwei mal versucht die Anfrage zu wiederholen. Ist auch der * dritte Versuch ohne Erfolg (keine Antwort) gilt die Verbindung als abgebaut. * * @throws LWTRTException Allgemeiner Fehler die waehrend der Lebendueberwachung auftreten * @throws LWTRTAbortException Zeigt den Abbruch des Pings an (nach drei Versuchen) */ public void ping() throws LWTRTException, LWTRTAbortException; }
99c07203183579a77314ee06125401e19712435f
[ "Java", "INI" ]
11
Java
ElaMay/chatApplication_WS18
eefcb97fa0c7f6e854ed40db11a6b6e5dc0105e7
04c703147842eb30d3d134913753375037f96c7f
refs/heads/master
<file_sep>package actions import ( "fmt" "html/template" "reflect" "strings" "github.com/gobuffalo/plush" "github.com/gobuffalo/tags" "github.com/gobuffalo/tags/form/bootstrap" "github.com/markbates/inflect" ) // FieldsFor struct helps on the generation of nested fields. type FieldsFor struct { Model interface{} FieldPrefix string FieldName string Field reflect.Value HelperContext plush.HelperContext Options tags.Options } //NewFieldsFor initializes FieldsFor struct and returns it func NewFieldsFor(fieldName string, options tags.Options, help plush.HelperContext) (FieldsFor, error) { nff := FieldsFor{ FieldPrefix: fieldName, FieldName: fieldName, HelperContext: help, Options: options, } if parentPrefix, ok := help.Value("parent").(string); ok { nff.FieldPrefix = strings.Join([]string{parentPrefix, nff.FieldPrefix}, ".") } nff.Model = help.Value("parentModel") if nff.Model == nil { nff.Model = help.Value("f").(*bootstrap.FormFor).Model } rfield := reflect.ValueOf(nff.Model) fbn := reflect.Indirect(rfield) fieldInd := fbn.FieldByName(fieldName) if !fieldInd.IsValid() { return FieldsFor{}, fmt.Errorf("Could not find field %v", nff.FieldPrefix) } nff.Field = fieldInd return nff, nil } //HTML generates the html for a FieldsForStruct func (ff FieldsFor) HTML() (template.HTML, error) { switch ff.Field.Kind() { case reflect.Slice: result := "" for i := 0; i < ff.Field.Len(); i++ { indexIndicator := fmt.Sprintf("[%v]", i) nf, err := NewFieldsFor(ff.FieldName, ff.Options, ff.HelperContext) nf.Field = ff.Field.Index(i) nf.FieldPrefix = ff.FieldPrefix + indexIndicator if err != nil { return "", err } s, err := nf.render() if err != nil { return "", err } result += s } return template.HTML(result), nil case reflect.Map: return "", nil case reflect.Struct: s, err := ff.render() if err != nil { return "", err } return template.HTML(s), nil default: return "", nil } } func (ff FieldsFor) render() (string, error) { el := ff.Field.Interface() form := bootstrap.NewFormFor(el, ff.Options) ctx := ff.HelperContext.Context.New() ctx.Set("parentModel", el) ctx.Set(inflect.CamelizeDownFirst(ff.FieldName)+"Form", form) if formVarName, ok := ff.Options["var"].(string); ok { ctx.Set(formVarName, form) } ctx.Set(inflect.CamelizeDownFirst(ff.FieldName), el) ctx.Set("parent", ff.FieldName) //WARNING: This requires some changes in FormFor to allow customization on the name of the field. form.FieldNameResolver = func(name string) string { return strings.Join([]string{ff.FieldPrefix, name}, ".") } s, err := ff.HelperContext.BlockWith(ctx) if err != nil { return "", err } return s, nil } //FieldsForHelper is the plush helper to use FieldsFor func FieldsForHelper(fieldName string, options tags.Options, help plush.HelperContext) (template.HTML, error) { nff, err := NewFieldsFor(fieldName, options, help) if err != nil { return "", err } return nff.HTML() } <file_sep>package actions import "github.com/gobuffalo/buffalo" // HomeHandler is a default handler to serve up // a home page. func HomeHandler(c buffalo.Context) error { c.Set("car", Car{ Brand: "Lambo", Owner: Owner{ Name: "Antonio", Pets: []Pet{ Pet{Name: "Ringo"}, Pet{Name: "Clocky", Age: 12}, }, }, }) return c.Render(200, r.HTML("index.html")) } func BindHandler(c buffalo.Context) error { var car Car c.Bind(&car) return c.Render(200, r.JSON(car)) } <file_sep>package actions type Car struct { Brand string Color string Owner Owner } type Owner struct { Name string PreferedBook Book Pets []Pet } type Book struct { Name string ISBN string } type Pet struct { Name string Age int }
529995acb641d0ad3e94db3133294a48983d9d73
[ "Go" ]
3
Go
apaganobeleno/app
69359b6c8f6c8abfbcb9a3da3e0631e9529807fe
7707a67261fe2e56966d4962d5521e5573060355
refs/heads/master
<repo_name>vally/meetup<file_sep>/app/src/main/java/entity/EventType.kt package entity enum class EventType{ EVENT, CONFERENCE, MEET_UP, TALK }<file_sep>/app/src/main/java/entity/Event.kt package entity import java.util.* data class Event( val id: String, val type: EventType, val name: String, val speakers: List<Speaker>, val date: Date, val venue: String, val agenda: String, val description: String) <file_sep>/app/src/main/java/MeetupApp.kt import android.app.Application import network.EventAPI import network.EventFromJson class MeetupApp : Application() { override fun onCreate() { super.onCreate() instance = this eventApi = EventFromJson(this) } companion object { private var instance: MeetupApp? = null private var eventApi: EventAPI? = null fun getEventApi(): EventAPI? { return eventApi } } }<file_sep>/app/src/main/java/network/EventFromJson.kt package network import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import entity.Event import entity.EventType import java.io.IOException import java.nio.charset.Charset import java.util.* class EventFromJson(val context: Context) : EventAPI { private val events: List<Event> init { val gson = Gson() val collectionType = object : TypeToken<Collection<Int>>() {}.type events = gson.fromJson(loadJSONFromAsset(), collectionType) } override fun getEvents(): List<Event> { return events } override fun findEvents(name: String): List<Event> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findEvents(date: Date): List<Event> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findEvents(from: Date, to: Date): List<Event> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findEvents(type: EventType): List<Event> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } private fun loadJSONFromAsset(): String { val json: String try { val eventJson = context.getAssets().open("yourfilename.json") val size = eventJson.available() val buffer = ByteArray(size) eventJson.read(buffer) eventJson.close() json = String(buffer, Charset.forName("UTF-8")) } catch (e: IOException) { error(e) } return json } }<file_sep>/app/src/main/java/network/EventAPI.kt package network import entity.Event import entity.EventType import java.util.* interface EventAPI { fun getEvents(): List<Event> fun findEvents(name: String): List<Event> fun findEvents(date: Date): List<Event> fun findEvents(from: Date, to: Date): List<Event> fun findEvents(type: EventType): List<Event> }<file_sep>/README.md # meetup service. A portal for events and meet-ups or any talks. <file_sep>/app/src/main/java/entity/Speaker.kt package entity data class Speaker(val name: String, val position: String)
f5ae02f8b703a7d318b248a6825f28ebc19a385c
[ "Markdown", "Kotlin" ]
7
Kotlin
vally/meetup
119daa49700017de28f7a1d6056f6c766a65d07c
be911137d7c56645a4badbb1ddb3e778d47e432d
refs/heads/master
<file_sep>/** * */ "use strict"; function Timer( counter_element, up_element, down_element, display_element,start_element) { var timerId; var restMin = 0; var counter_element = counter_element; var up_element = up_element; var down_element = down_element; var display_element = display_element; var start_element = start_element; return { modify : function(min) { if ( isNaN(min) || min === undefined ){ min = 0; } restMin = counter_element.val(); if (isNaN(restMin) || restMin === undefined || restMin == ""){ restMin = 0; } var neuer_wert = parseInt(restMin,10) + min; if ( neuer_wert < 0 ){ neuer_wert = 0; } $(counter_element).val(neuer_wert); }, execute: function(){ if ( timerId === undefined ){ // Timer wird das erste Mal gestartet start_element.text("Stop"); var aktueller_wert = counter_element.val(); if (isNaN(aktueller_wert) || aktueller_wert === undefined || aktueller_wert == ""){ aktueller_wert = 0; } countdown2(0,0,aktueller_wert,0); }else{// Timer wird angehalten start_element.text("Start"); clearTimeout(timerId); timerId = undefined; } } }; function countdown(time){ //time brauchen wir später noch var t = time; //Tage berechnen var d = Math.floor(t/(60*60*24)) % 24; // Stunden berechnen var h = Math.floor(t/(60*60)) % 24; // Minuten berechnen // Sekunden durch 60 ergibt Minuten // Minuten gehen von 0-59 //also Modulo 60 rechnen var m = Math.floor(t/60) %60; // Sekunden berechnen var s = t %60; //Zeiten formatieren d = (d > 0) ? d+"d ":""; h = (h < 10) ? "0"+h : h; m = (m < 10) ? "0"+m : m; s = (s < 10) ? "0"+s : s; // Ausgabestring generieren var strZeit =d + h + ":" + m + ":" + s; // Falls der Countdown noch nicht zurückgezählt ist if(time > 0) { //Countdown-Funktion erneut aufrufen //diesmal mit einer Sekunde weniger //timerId = window.setTimeout('countdown('+ --time+',\''+id+'\')',1000); timerId = window.setTimeout(function(){countdown(--time);},1000); } else { //führe eine funktion aus oder refresh die seite //dieser Teil hier wird genau einmal ausgeführt und zwar //wenn die Zeit um ist. strZeit = "Fertig"; } display_element.html(strZeit); } //Helfer Funktion erlaubt Counter auch ohne Timestamp //countdown2(Tage,Stunden,Minuten,Sekunden) function countdown2 (d,h,m,s){ countdown(d*60*60*24+h*60*60+m*60+s); } } <file_sep># exerciser Projekt zur Erstellung einer Übung-Planungs-Hilfe für Gitaristen <file_sep>/** * */ "use strict"; alert ("Hello"); //Using YQL and JSONP $.ajax({ url: "http://query.yahooapis.com/v1/public/yql", // The name of the callback parameter, as specified by the YQL service jsonp: "callback", // Tell jQuery we're expecting JSONP dataType: "jsonp", // Tell YQL what we want and that we want JSON data: { q: "select * from bible.bible where language='en' and bibleref='Luke 11:10'", format: "json" }, // Work with the response success: function( response ) { console.log( response ); // server response } });<file_sep>/** * */ angular.module('myApp', []).controller('uebungCtrl', function($scope) { $scope.name = ''; $scope.typ = ''; $scope.uebungen = [{id:1, name:'Dehnung', typ:"WarmUp" }]; $scope.edit = true; $scope.error = false; $scope.incomplete = false; $scope.editUebung = function(id) { if (id == 'new') { $scope.edit = true; $scope.incomplete = true; $scope.name = ''; $scope.typ = ''; } else { $scope.edit = false; $scope.name = $scope.uebungen[id-1].name; $scope.typ = $scope.uebungen[id-1].typ; } }; $scope.saveUebung = function(){ $scope.uebungen.push({id:2, name:$scope.name, typ:$scope.typ}); }; $scope.$watch('name',function() {$scope.test();}); $scope.$watch('typ',function() {$scope.test();}); $scope.test = function() { $scope.incomplete = false; if ($scope.edit && (!$scope.name.length || !$scope.typ.length )) { $scope.incomplete = true; } } });
7a5af46a9a5308ca04c501173e724a39131106dd
[ "JavaScript", "Markdown" ]
4
JavaScript
fishandscale/exerciser
51f38061bb5d34d1dd77cf82a7a87993ee701621
1b991737935b566d3f40cc51df60551a5dc935e7
refs/heads/master
<file_sep>A small program for the bringup of the AVR on the robosmoker board # Getting The Software Environment Setup I'm using Raspian, which is a quasi-debian. In order to program the AVR, you need a patched version of avrdude. To do this, we just rebuild the avrdude dude package. 1. Enable source repositories `sudo sed -i -E 's/#\s?deb-src/deb-src/' /etc/apt/sources.list` 2. Update package lists `sudo apt-get update` 3. Install needed tools/etc `sudo apt-get install build-essential fakeroot git arduino screen` 4. Get the avrdude build dependencies `sudo apt get build-dep avrdude` 5. Get the avrdude source `apt-get build-dep avrdude` 6. Modify the configure scipt `sed -i -E 's/--enable-doc/--enable-doc --enable-linuxgpio/' debian/rules` 7. Fix debian bug #745034 `sed -i -E 's/HAVE_LINUX_GPIO/HAVE_LINUXGPIO/' pindefs.h` 8. Build it `fakeroot debian/rules binary` 9. Install it: `sudo dpkg -i ../*.deb` 10. Configure for i2c dev Run raspi-config, and under advanced, enable the hw i2c support: `sudo raspi-config` 11. Reboot 10. Build/Flash AVR code `make && sudo make ispload` 12. Interract with AVR from RPI get with `sudo i2cget 1 0x45 <register> c` set with `sudo i2cset 1 0x45 <rigister> <value>` <file_sep>#include <EventManager.h> #include <Wire.h> #include <stdint.h> #define SLAVE_ADDRESS 0x45 EventManager eventManager; boolean pin13State; unsigned long lastToggled; //current status: working // get with i2cget 1 0x45 <register> c // set with i2cset 1 0x45 <rigister> <value> union RegisterFile { struct { volatile uint8_t FanSetSpeed; volatile uint8_t CurrentFanSpeed; volatile uint16_t adc0; volatile uint16_t adc1; volatile uint16_t adc2; volatile uint16_t adc3; } regs; uint8_t bytes[sizeof(regs)]; }; struct Registers { RegisterFile regFile; volatile uint8_t address; static inline bool inBounds(uint8_t addr) { return (addr < sizeof(RegisterFile::regs)); } void write(uint8_t addr, uint8_t data) { if (addr == 0) { regFile.bytes[addr] = data; } } uint8_t read() { if (inBounds(address)) { return regFile.bytes[address]; } return 0; } uint8_t read(uint8_t addr) { if (inBounds(addr)) { return regFile.bytes[addr]; } return 0; } } registers; static void i2cReceiveCallback(int count) { int i = 0; uint8_t address = 0; uint8_t data = 0; while (Wire.available() > 0) { uint8_t d = Wire.read(); if (i == 0) { address = d; } else if (i == 1) { data = d; } i++; } if (i == 1) { //This is a read and the byte is the address. //calling with the c mode seems to cause a request to get issued. registers.address = address; } if (i >= 2) { //This is a write registers.write(address, data); } } static void i2cRequestCallback(void) { Wire.write(registers.read()); } static void blinkListener(int, int eventParam) { pin13State = pin13State ? false : true; digitalWrite(13, pin13State ? HIGH : LOW); lastToggled = millis(); } static void ADCPoller(int, int) { registers.regFile.regs.adc0 = analogRead(A0); registers.regFile.regs.adc1 = analogRead(A1); registers.regFile.regs.adc2 = analogRead(A2); registers.regFile.regs.adc3 = analogRead(A3); } void setup() { Serial.begin(9600); Wire.begin(SLAVE_ADDRESS); Wire.onReceive(i2cReceiveCallback); Wire.onRequest(i2cRequestCallback); pinMode(13, OUTPUT); digitalWrite( 13, HIGH ); pin13State = true; lastToggled = millis(); eventManager.addListener(EventManager::kEventUser0, blinkListener); pinMode(A0, INPUT); pinMode(A1, INPUT); pinMode(A2, INPUT); pinMode(A3, INPUT); eventManager.addListener(EventManager::kEventAnalog0, ADCPoller); Serial.println(F("We're up and running!")); } void loop() { if ((millis() - lastToggled) > 1000) { eventManager.queueEvent(EventManager::kEventUser0, 0); eventManager.queueEvent(EventManager::kEventAnalog0, 0); } eventManager.processEvent(); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * mode: c++ * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */ <file_sep># Makefile fragment made by /home/pi/bin/mkarduino ARDUINO_DIR = /usr/share/arduino ARDMK_DIR = Arduino-Makefile AVR_TOOLS_DIR = /usr AVRDUDE_CONF = ./avrdude_gpio.conf USER_LIB_PATH = libraries TARGET = arduino_bringup ARDUINO_LIBS = EventManager/EventManager Wire BOARDS_TXT = ./boards.txt BOARD_TAG = atmega328_9600_8 ARDUINO_PORT = /dev/ttyUSB0 BOOTLOADER_PATH = $(PWD) BOOTLOADER_FILE = optiboot_atmega328_9600_8.hex ISP_PROG = pi_1 ISP_PORT = /dev/null include Arduino-Makefile/Arduino.mk
fd114c36eeffede51a1638aeceb2e7be9dad828d
[ "Markdown", "Makefile", "C++" ]
3
Markdown
robosmoker/arduino_bringup
17962dc57d9fd36839b9910a63a83d7b494badf6
b10612f04de1ab83caa4c8ce9567edbb4157d556
refs/heads/main
<file_sep>package com.springboot.example.springbootcrud.dao; import com.springboot.example.springbootcrud.entity.Employee; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.persistence.EntityManager; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Base64; import java.util.List; import java.util.Random; @Repository @EnableWebSecurity public class EmployeeDAOHibImpl implements EmployeeDAO{ //entity manager private EntityManager entityManager; public EmployeeDAOHibImpl(EntityManager theEntityManager){ entityManager = theEntityManager; } @Override public List<Employee> getAll() { Session currentSession =entityManager.unwrap(Session.class); Query<Employee> theQuery = currentSession.createQuery("from Employee ", Employee.class); List<Employee> employees = theQuery.getResultList(); return employees; } @Override public int login(Employee employee) { int dataAvailable=0; Session currentSession = entityManager.unwrap(Session.class); //Query<Employee> theQuery = currentSession.createQuery("from Employee as e where e.username=:employeeName and e.password=:employeePassword").setString("employeeName", employee.getUsername()).setString("employeePassword", employee.getPassword()); Query hashedPassword= (currentSession.createQuery("from Employee as e where e.username=:employeeName "). setString("employeeName", employee.getUsername())); Employee stringHashedPassword =(Employee) hashedPassword.uniqueResult(); System.out.println("Login----- hashedPassword---"+stringHashedPassword); if (BCrypt.checkpw(employee.getPassword(), stringHashedPassword.getPassword())) { System.out.println("It matches"); return dataAvailable = 1; } else { System.out.println("It does not match"); return dataAvailable = 0; } } @Override public void addEmp(Employee employee) { Session currentSession = entityManager.unwrap(Session.class); //decoding the encoded password from the frontend byte[] decodedBytes = Base64.getDecoder().decode(employee.getPassword()); String decodedString = new String(decodedBytes); String passwordHash = BCrypt.hashpw(decodedString, BCrypt.gensalt(12)); //setting the decoded password tro the db employee.setPassword(passwordHash); currentSession.saveOrUpdate(employee); currentSession.close(); } @Override public Employee getEmpWithId(Integer id) { Session currentSession = entityManager.unwrap(Session.class); Employee theEmployee = currentSession.get(Employee.class, id); currentSession.close(); return theEmployee; } @Override public void updateEmp(Employee employee) { Session currentSession = entityManager.unwrap(Session.class); currentSession.saveOrUpdate(employee); System.out.println("data migt have updated"); currentSession.close(); } @Override public void deleteEmp(Integer id) { Session currentSession = entityManager.unwrap(Session.class); Query theQuery = currentSession.createQuery("delete from Employee where empId=:id"); theQuery.setParameter("id",id); theQuery.executeUpdate(); } @Override public void addEmpWithCSV(Employee employee) { Session currentSession = entityManager.unwrap(Session.class); String passwordHash = BCrypt.hashpw(employee.getPassword(), BCrypt.gensalt(12)); //setting the decoded password tro the db employee.setPassword(password<PASSWORD>); currentSession.saveOrUpdate(employee); currentSession.close(); } } <file_sep>import React, { Component } from 'react'; import EmployeeService from '../services/EmployeeService'; class LoginComponent extends Component { constructor(props){ super(props) this.state = { username:'', password:'', loginMessage:'' } this.changeUsernameHandler = this.changeUsernameHandler.bind(this); this.changePasswordHandler = this.changePasswordHandler.bind(this); this.loginUser = this.loginUser.bind(this); } //this is for the authentication for the login to get through loginUser=(e)=>{ e.preventDefault(); //setting up the username and password entered in the form to a object to sent to the REST API let user = {username: this.state.username, password: <PASSWORD>} //console.log('user details == ' +JSON.stringify(user)); var canLogin; EmployeeService.loginUserIn(user).then((res)=>{ //setting the @postmapping return value from REST api to canLogin var canLogin = res.data; console.log("login value 2: "+canLogin); //if login value is 1 means that there is a user can that user can now login if(canLogin == 1){ this.setState({loginMessage: 'Login Success'}); this.props.history.push('/AllEmployees'); //if login value is 0 means there is no user as such so the user cannot login }else if(canLogin == 0){ this.setState({loginMessage: 'Login Failed. UserName or Password maybe wrong.'}); this.props.history.push('/Login'); } }); } changeUsernameHandler = (event) => { this.setState({username: event.target.value}); } changePasswordHandler = (event) => { this.setState({password: event.target.value}); } render() { //css part for the login error msg const loginTextMsg={ color: 'red', fontWeight: 'bold', fontSize: '13px' } return ( <div> <div className="container"> <div className="row"> <div className="card col-md-6 offset-md-3 offset-md-3"> <h3 className="text-center">Login</h3> <div className="card-body"> <form> <div className="form-group"> <label>User Name:</label> <input placeholder="<NAME>" name="username" className="form-control" value={this.state.username} onChange={this.changeUsernameHandler}/> </div> <div className="form-group"> <label>Password:</label> <input placeholder="<PASSWORD>" name="<PASSWORD>" className="form-control" type="<PASSWORD>" value={this.state.password} onChange={this.changePasswordHandler}/> </div> <div className="form-group" > <label style={loginTextMsg}>{this.state.loginMessage}</label> </div> <button className="btn btn-primary" onClick={this.loginUser}>Login</button> </form> </div> </div> </div> </div> </div> ); } } export default LoginComponent;<file_sep>package com.springboot.example.springbootcrud.service; import com.springboot.example.springbootcrud.entity.Employee; import net.sf.jasperreports.engine.JRException; import org.springframework.web.multipart.MultipartFile; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; public interface EmployeeService { List<Employee> getAll(); int login(Employee employee); void addEmp(Employee employee); Employee getEmpWithId(Integer id); void updateEmp(Employee employee); void deleteEmp(Integer id); String exportReport(String format) throws IOException, JRException; void saveCSV(MultipartFile file); } <file_sep>package com.springboot.example.springbootcrud.controller; import com.springboot.example.springbootcrud.dao.EmployeeDAO; import com.springboot.example.springbootcrud.entity.Employee; import com.springboot.example.springbootcrud.service.EmployeeService; import com.springboot.example.springbootcrud.util.CSVHelper; import net.sf.jasperreports.engine.JRException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; @CrossOrigin(origins = "http://localhost:3000") @RestController @RequestMapping("/api/v1/") public class EmployeeController { private EmployeeService employeeService; @Autowired public EmployeeController(EmployeeService theEmployeeService){ employeeService = theEmployeeService; } @GetMapping("Employees") public List<Employee> findAll(){ return employeeService.getAll(); } @PostMapping("Login") public int loginId(@RequestBody Employee employee){ int loginVal = employeeService.login(employee); return loginVal; } @PostMapping("AddEmp") public void addEmployee(@RequestBody Employee employee){ employeeService.addEmp(employee); } @GetMapping("EmpId/{empId}") public Employee getEmployeeById(@PathVariable Integer empId){ Employee emp = employeeService.getEmpWithId(empId); return emp; } @PutMapping("UpdateEmp/{empId}") public Employee updateEmployee(@PathVariable Integer empId, @RequestBody Employee employee){ Employee emp = employeeService.getEmpWithId(empId); //System.out.println("emp id" +emp.toString()); emp.setEmpName(employee.getEmpName()); emp.setEmpSalary(employee.getEmpSalary()); emp.setEmpDesignation(employee.getEmpDesignation()); System.out.println("after changes "+emp.toString()); employeeService.updateEmp(emp); return emp; } @DeleteMapping("DeleteEmp/{empId}") public void deleteEmployee(@PathVariable Integer empId){ Employee emp = employeeService.getEmpWithId(empId); employeeService.deleteEmp(empId); } @GetMapping("Report/{format}") public String generateReport(@PathVariable String format) throws IOException, JRException { //System.out.println(format); return employeeService.exportReport(format); } @PostMapping("CSV/upload") public String uploadFile(@RequestParam("file") MultipartFile file){ //System.out.println("Send in file content type " +file.getContentType()); //if (CSVHelper.hasCSVFormat(file)){ try{ employeeService.saveCSV(file); return "File uploaded"; }catch (Exception e){ return "File couldnt be uploaded"; } //} //return "Please upload csv file"; } } <file_sep># Struts-Revamp Please do a node modules intallation for the frontend in the terminal. \ Go to react-springboot folder using `cd` command. Command eg: `cd Frontend- React`. Once inside react-springboot folder run `npm install` to install the node modules. # To Start React application Inside react-springboot folder use command `npm start`. Apllication should start on [http://localhost:3000](http://localhost:3000). <file_sep>package com.springboot.example.springbootcrud.dao; import com.springboot.example.springbootcrud.entity.Employee; import javax.persistence.criteria.CriteriaBuilder; import java.util.List; public interface EmployeeDAO { List<Employee> getAll(); int login(Employee employee); void addEmp(Employee employee); Employee getEmpWithId(Integer id); void updateEmp(Employee employee); void deleteEmp(Integer id); void addEmpWithCSV(Employee employee); } <file_sep>import React, { Component } from 'react'; import EmployeeService from '../services/EmployeeService'; class UpdateEmployeeComponent extends Component { constructor(props){ super(props) this.state = { empId: this.props.match.params.empId, empName:'', empSalary:'', empDesignation:'', } this.changeNameHandler = this.changeNameHandler.bind(this); this.changeSalaryHandler = this.changeSalaryHandler.bind(this); this.changeDesignationHandler = this.changeDesignationHandler.bind(this); this.updateEmp = this.updateEmp.bind(this); } componentDidMount(){ EmployeeService.getEmployeeById(this.state.empId).then( (res) =>{ let employeeData = res.data; this.setState({empName: employeeData.empName, empSalary: employeeData.empSalary, empDesignation: employeeData.empDesignation}); }); } changeNameHandler=(event)=>{ this.setState({empName: event.target.value}); } changeSalaryHandler=(event)=>{ this.setState({empSalary: event.target.value}); } changeDesignationHandler=(event)=>{ this.setState({empDesignation: event.target.value}); } //save button function updateEmp = (e)=>{ e.preventDefault(); let employee = {empName: this.state.empName, empSalary: this.state.empSalary, empDesignation: this.state.empDesignation, }; console.log("Emp object ==> " +JSON.stringify(employee)); EmployeeService.updateEmployee(employee, this.state.empId).then(res=>{ this.props.history.push(`/AllEmployees`); }); } //cancel button function cancel(){ this.props.history.push('/AllEmployees'); } render() { return ( <div> <div className="container"> <div className="row"> <div className="card col-md-6 offset-md-3 offset-md-3"> <h3 className="text-center">Update Employee</h3> <div className="card-body"> <form> <div className="form-group"> <label>Name :</label> <input placeholder="Name" name="empName" className="form-control" value={this.state.empName} onChange={this.changeNameHandler} /> </div> <div className="form-group"> <label>Salary :</label> <input placeholder="Salary" name="empSalary" className="form-control" value={this.state.empSalary} onChange={this.changeSalaryHandler} /> </div> <div className="form-group"> <label>Designation :</label> <input placeholder="Designation" name="empDesignation" className="form-control" value={this.state.empDesignation} onChange={this.changeDesignationHandler} /> </div> <button className="btn btn-success" onClick={this.updateEmp} >Save</button> <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft:"10px"}}>Cancel</button> </form> </div> </div> </div> </div> </div> ); } } export default UpdateEmployeeComponent;<file_sep>import axios from 'axios'; const EMPLOYEE_API_BASE_URL = "http://localhost:8080/api/v1/Employees"; const EMPLOYEE_API_LOGIN_URL = "http://localhost:8080/api/v1/Login"; const EMPLOYEE_API_ADD_URL = "http://localhost:8080/api/v1/AddEmp"; const EMPLOYEE_API_GET_EMPID_URL = "http://localhost:8080/api/v1/EmpId"; const EMPLOYEE_API_UPDATE_URL = "http://localhost:8080/api/v1/UpdateEmp"; const EMPLOYEE_API_DELETE_URL = "http://localhost:8080/api/v1/DeleteEmp"; const EMPLOYEE_API_REPORT_PDF_URL = "http://localhost:8080/api/v1/Report"; const EMPLOYEE_API_CSV_UPLOAD_URL = "http://localhost:8080/api/v1/CSV/upload"; class EmployeeService{ //calling get method to get all employees getEmployees(){ return axios.get(EMPLOYEE_API_BASE_URL); } //calling post method to send the entered details and get the login value from the api loginUserIn(user){ return axios.post(EMPLOYEE_API_LOGIN_URL, user); } //calling post method to add the employee to db addEmployee(employee){ return axios.post(EMPLOYEE_API_ADD_URL, employee); } getEmployeeById(employeeId){ return axios.get(EMPLOYEE_API_GET_EMPID_URL+ '/' +employeeId); } updateEmployee(employee, employeeId){ return axios.put(EMPLOYEE_API_UPDATE_URL+'/'+employeeId, employee); } deleteEmployee(employeeId){ return axios.delete(EMPLOYEE_API_DELETE_URL+'/'+employeeId); } getReport(format){ return axios.get(EMPLOYEE_API_REPORT_PDF_URL+'/'+format); } uploadCSV(file){ return axios.post(EMPLOYEE_API_CSV_UPLOAD_URL, file, { headers: { 'Content-Type': 'multipart/form-data' }}); } } export default new EmployeeService()<file_sep>package com.springboot.example.springbootcrud.util; import com.springboot.example.springbootcrud.entity.Employee; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class CSVHelper { public static String TYPECSV = "text/csv"; public static String TYPEExcelCSVxls = "application/vnd.ms-excel"; public static String TYPEExcelCSVxlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; static String[] HEADERs = {"empName", "empSalary", "empDesignation", "username", "password"}; public static boolean hasCSVFormat(MultipartFile file) { if (!TYPEExcelCSVxls.equals(file.getContentType())) { return false; }else if (!TYPECSV.equals(file.getContentType())){ return false; }else if(!TYPEExcelCSVxlsx.equals(file.getContentType())){ return false; } return true; } public static List<Employee> csvToEmployees(InputStream inputStream) { try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) { List<Employee> employees = new ArrayList<Employee>(); Iterable<CSVRecord> csvRecords = csvParser.getRecords(); for (CSVRecord csvRecord : csvRecords){ Employee employee = new Employee( csvRecord.get("empName"), Integer.parseInt(csvRecord.get("empSalary")), csvRecord.get("empDesignation"), csvRecord.get("username"), csvRecord.get("password") ); employees.add(employee); } return employees; }catch(IOException e){ throw new RuntimeException("fail to parse CSV file: " + e.getMessage()); } } } <file_sep>import React, { Component } from 'react'; class ViewPageComponent extends Component { constructor(props){ super(props) this.state = { } this.goToLogin = this.goToLogin.bind(this); } goToLogin(){ this.props.history.push('/Login'); } render() { return ( <div> <button className="btn btn-primary" onClick={this.goToLogin}>Login</button> </div> ); } } export default ViewPageComponent;
3966cf773989cd5c3cc05ee86e68889cf0ea8020
[ "JavaScript", "Java", "Markdown" ]
10
Java
YomalNimeshka/Struts-Revamp
2974eceaf68d3673631e228cc60a555fb920a9f1
cbeb4fe916b145087745132553196c27d54205a9
refs/heads/master
<file_sep>#!/bin/bash # This script builds some of the other the other tools I use with pyne. # # Run this script from any directory by issuing the command: # $ ./install_tools.sh # After the build finishes run: # $ source ~/.bashrc # first alara sudo apt-get install build-essential libtool automake cd $HOME # clean any earlier install rm alara -rf mkdir alara cd alara git clone https://github.com/svalinn/alara.git cd alara autoreconf -fi mkdir bld cd bld ../configure --prefix=/home/pi/alara make make install # # # now other tools cd $HOME # clean any earlier install rm toolkit -rf mkdir toolkit cd toolkit git clone https://github.com/py1sl/neutron_tools git clone https://github.com/py1sl/pyne_based_tools
948dc78042ccecbf60dc799e5dac6f115eb7b8c2
[ "Shell" ]
1
Shell
py1sl/install_scripts
f83af217f354b6ca0a49fecbf7d31906d61e9968
1fcac2a28f0de42118d3fa2438ac56dfa73171d9
refs/heads/master
<repo_name>JananiVelmurugan/Mapping<file_sep>/One2Many/src/com/janani/onetomany/Employee.java package com.janani.onetomany; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Employee { @Id @GeneratedValue private int empno; private String username; @ManyToOne @JoinColumn(name = "department") private Department department; public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } } <file_sep>/Many2Many/src/Queries.sql CREATE DATABASE relationship_db; CREATE TABLE employee( empno INT, username VARCHAR(20), department VARCHAR(10) ); INSERT INTO employee VALUES(101,'Janani04',10); INSERT INTO employee VALUES(102,'Naresh08',10); INSERT INTO employee VALUES(103,'Suyambu09',10); INSERT INTO employee VALUES(104,'Sairam02',10); INSERT INTO employee VALUES(105,'Sentamil',10); CREATE TABLE department( id INT, NAME VARCHAR(10) ); INSERT INTO department VALUES(10,'Training'); CREATE TABLE person( empid INT, firstname VARCHAR(20), lastname VARCHAR(20) ); INSERT INTO person VALUES(101,'Janani','Velmurugan'); CREATE TABLE course ( id INT, NAME VARCHAR(20), duration INT ); INSERT INTO course VALUES(1,'C',1); INSERT INTO course VALUES(2,'C++',2); INSERT INTO course VALUES(3,'Java',3); CREATE TABLE employee_course ( empno INT, id INT ); INSERT INTO employee_course VALUES(101,3); INSERT INTO employee_course VALUES(101,2); INSERT INTO employee_course VALUES(101,1); INSERT INTO employee_course VALUES(102,3); INSERT INTO employee_course VALUES(102,2); INSERT INTO employee_course VALUES(103,2); INSERT INTO employee_course VALUES(104,1); INSERT INTO employee_course VALUES(105,1); <file_sep>/One2One/src/com/janani/onetoone/Employee.java package com.janani.onetoone; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity public class Employee { private int empno; private String username; private Person personalDetails; @Id @GeneratedValue public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "empno") public Person getPersonalDetails() { return personalDetails; } public void setPersonalDetails(Person personalDetails) { this.personalDetails = personalDetails; } }
66beba5e9a882ded4c48ac5494cfb616c8f2392d
[ "Java", "SQL" ]
3
Java
JananiVelmurugan/Mapping
24b36a246e4f16a8327ecc90e9d70168f48ad06e
ec69143d5c7ce17f41520b245e6eac1af68ffb78
refs/heads/master
<file_sep>let samples = []; let sum = 0, max = 0, mean = 0; let fps = document.getElementById('fps') || createElement(); document.addEventListener('fps', e => { if (e.fps > 120) return; if (samples.length >= 60) { sum -= samples.pop(); } samples.unshift(e.fps) sum += samples[0]; if (samples[0] > max) { max = samples[0]; } let s = (sum/samples.length).toFixed(1) fps.innerText = `${samples[0]}; ${s}; ${max} fps`; }, false); window["FPSMeter"] && FPSMeter.run(); function createElement() { let fps = document.createElement('div'); fps.id = 'fps'; document.body.appendChild(fps); return fps; } <file_sep>export function bind(fn, obj, ...left) { let curried = function(...right) { return fn.call(obj || this, ...left, ...right); }; if (fn.memoize) { curried.memoize = fn.memoize; } return curried; } export function partial(fn, ...left) { return bind(fn, null, ...left); } export function identity(x) { return x; } <file_sep>import * as _ from './util.js'; import {newRectangularLayout} from './rect.js'; const ns = 'http://www.w3.org/2000/svg'; function createRectangularSvgRoot(rows, cols) { let root = document.createElementNS(ns, 'svg'); root.setAttribute('viewBox', `0 0 ${cols} ${rows}`); root.setAttribute('preserveAspectRatio', 'none'); return root; } function createRectangularSvgCell(x, y) { let rect = document.createElementNS(ns, 'rect'); rect.setAttribute('x', x); rect.setAttribute('y', y); rect.setAttribute('width', 1); rect.setAttribute('height', 1); rect.setAttribute('style', 'stroke-width:1px;vector-effect:non-scaling-stroke;'); return rect; } function setSvgCellColor(e, v) { e.style.fill = v; e.style.stroke = v; } export let newRectangularSvg = _.partial(newRectangularLayout, createRectangularSvgRoot, createRectangularSvgCell, setSvgCellColor); <file_sep>version: "2" services: web: image: pierrezemb/gostatic volumes: - .:/srv/http <file_sep>import * as _ from './util.js'; import {newRectangularLayout} from './rect.js'; export let newRectangularGrid = _.partial(newRectangularLayout, createRectangularGridRoot, createRectangularGridCell, setGridCellColor); function createRectangularGridRoot(rows, cols) { let root = document.createElement('div'); root.style.display = 'grid'; root.style.gridTemplateColumns = `repeat(${cols}, 1fr)`; return root; } function createRectangularGridCell() { return document.createElement('div'); } function setGridCellColor(e, v) { e.style.backgroundColor = v; } <file_sep>import * as _ from './util.js'; import {transition} from './transition.js'; import {newRectangularGrid} from './grid.js'; import {newRectangularSvg} from './svg.js'; import {newRectangularCanvas} from './canvas.js'; import {newRectangularTable} from './table.js'; import {rectangularLayoutWithTicks} from './rect.js'; window.options = { w: 130, h: 100 }; let t = 0; let duration = 4000; let layouts = { "rectangular-table": newRectangularTable , "rectangular-canvas": newRectangularCanvas , "rectangular-grid": newRectangularGrid , "rectangular": newRectangularSvg } let columnLabels = d3.scaleQuantize().domain([1, 12]).range(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]); let rowLabels = d3.scaleQuantize().domain([1, 7]).range(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]); let toolbar = {}; let transitions = {}; window.options.init = function() { window.options.compute = _.partial(value, hyperbola(window.options.w/3, window.options.h/2, window.options.w*2/3, window.options.h/2, 400/window.options.w)); window.options.renderers = Object.entries(layouts).map(([id, layout]) => { let [el, render] = layout(window.options.h, window.options.w); render = _.partial(render, d3.interpolateRainbow); document.getElementById(id).innerHTML = ""; document.getElementById(id).appendChild( rectangularLayoutWithTicks( rectangularLayoutWithTicks(el, window.options.h, window.options.w, { yTickCount: 30, xTickCount: 12, tickLength: '4px', }), window.options.h, window.options.w, { gutterLength: '5px', yTickCount: 15, xTickCount: 6, yTickFormat: t => rowLabels(((t - 1) % rowLabels.domain()[1]) + 1), xTickFormat: t => columnLabels(((t - 1) % columnLabels.domain()[1]) + 1) } ) ); if (el.classList) { el.classList.add('heatmap'); } else { el.className = 'heatmap'; } toolbar[id] = document.getElementById(`enable-${id}`); toolbar[id].addEventListener('change', function() { if (this.checked) { let from = transitions[id] ? transitions[id]() : _.partial(window.options.compute, t + 1); transitions[id] = transition(render, d3.easeLinear, duration, from, _.partial(window.options.compute, t)); } else if (transitions[id]) { transitions[id](); } }); return [id, render]; }); } window.options.update = function() { let next = t - 1; let running = false; window.options.renderers.map(([id, render]) => { if (toolbar[id].checked) { running = true; let from = transitions[id] ? transitions[id]() : _.partial(window.options.compute, t); transitions[id] = transition(render, d3.easeLinear, duration, from, _.partial(window.options.compute, next)); } }); if (running) t = next; } window.options.init(); start(); function value(f, t, x, y) { let dx = f(x,y) + t; if (x < window.options.w/2) { return dx + 0.3; } return dx; } function hyperbola(ax, ay, bx, by, scale) { return (x, y) => Math.abs(d(x, y, ax, ay) - d(x, y, bx, by)) * scale; } function d(x1, y1, x2, y2) { let x = x2 - x1; let y = y2 - y1; return Math.sqrt(x * x + y * y); } var loop; function stop() { clearTimeout(loop); } function start() { requestAnimationFrame(window.options.update); loop = setTimeout(start, duration) } <file_sep># heatrect Experimental rectangular heatmaps. <file_sep>import * as _ from './util.js'; import {newLayout, paint} from './common.js'; import {rectangularMemoize} from './rect.js'; export let newRectangularCanvas = _.partial(newRectangularCanvasLayout, setCanvasCellColor); function createRectangularCanvasRoot() { return document.createElement('canvas'); } function newRectangularCanvasLayout(setColor, rows, cols) { let root = newLayout(createRectangularCanvasRoot); let context = root.getContext('2d', {alpha:false}); let forEach = _.partial(forEachCanvasCell, rows, cols); let renderer = _.bind(paint, context, forEach, setColor) renderer.memoize = _.partial(rectangularMemoize, cols); return [ root , renderer ]; } function forEachCanvasCell(rows, cols, apply) { this.save(); this.scale(this.canvas.width/cols, this.canvas.height/rows); for (let y = 0; y < rows; y++) { this.save(); for (let x = 0; x < cols; x++) { apply.call(this, null, x, y); this.translate(1, 0); } this.restore(); this.translate(0, 1); } this.restore(); } function setCanvasCellColor(e, v) { this.fillStyle = v; this.fillRect(0, 0, 1, 1); } <file_sep>export function noop() {} export function newLayout(createRootElement, forEachCell, createCell) { let root = createRootElement.call(this); if (forEachCell) { forEachCell.call(root, (e, x, y) => root.appendChild(createCell.call(root, x, y))); } return root; } export function forEachCell(getCell, rows, cols, apply) { let i = 0; for (let y = 0; y < rows; y++) { for (let x = 0; x < cols; x++) { apply.call(this, getCell.call(this, x, y, i++), x, y); } } } export function paint(forEachCell, update, color, value) { let paintCell = (e, x, y) => update.call(this, e, color.call(this, value.call(this, x, y))); return forEachCell.call(this, paintCell); }
c67cc637e87405509c91f640372aa51105b289c3
[ "JavaScript", "YAML", "Markdown" ]
9
JavaScript
au-phiware/heatrect
11509c0faf20119b2124c4c6f2430bdf54bd92df
c66299ea00ec246f00805e32ce57f91ea767d201
refs/heads/master
<repo_name>treehouse-projects/horse-land<file_sep>/README.md # Horse Land A website built for Treehouse's *Introduction to Web Scraping* course. Site is hosted on GitHub Pages [here](https://treehouse-projects.github.io/horse-land/index.html) The form page can be viewed [here](https://treehouse-projects.github.io/horse-land/form.html)<file_sep>/js/index.js $.getJSON('./data.json', function(data){ $.each(data, function(i, f) { $("ul").append('<li class="card"><img src="' + f.thumbnailUrl + '" alt="' + f.title + '"><p>' + f.title + '</p></div>'); $.cache = f.id; }); });
770dafb5fb9148c9a87635ef8ba6e78706fda5ea
[ "Markdown", "JavaScript" ]
2
Markdown
treehouse-projects/horse-land
d559009a92a8de48ba7f2a62483fbd38060324ce
d1f3b84127ff01c40615ca28e1b28b05c4d7591f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Media; namespace epicture { class MyImage { public string Source { get; set; } public string Id { get; set; } public string Favorite { get; set; } } public class Datum { public string id { get; set; } public string title { get; set; } public string description { get; set; } public string cover { get; set; } public int cover_width { get; set; } public int cover_height { get; set; } public int width { get; set; } public int height { get; set; } public string account_url { get; set; } public int account_id { get; set; } public string privacy { get; set; } public int views { get; set; } public string link { get; set; } public int ups { get; set; } public int downs { get; set; } public int points { get; set; } public int score { get; set; } public bool is_album { get; set; } public string vote { get; set; } public bool favorite { get; set; } public bool nsfw { get; set; } public object section { get; set; } public int comment_count { get; set; } public int favorite_count { get; set; } public string topic { get; set; } public string topic_id { get; set; } public int images_count { get; set; } public object datetime { get; set; } public bool in_gallery { get; set; } public bool in_most_viral { get; set; } public object tags { get; set; } public object images { get; set; } public bool has_sound { get; set; } public bool animated { get; set; } public string type { get; set; } public int size { get; set; } } public class RootObject { public int status { get; set; } public bool success { get; set; } public List<Datum> data { get; set; } } } <file_sep>var searchData= [ ['iapi',['IApi',['../interfaceepicture_1_1_model_1_1_i_api.html',1,'epicture::Model']]], ['imgurapi',['ImgurApi',['../classepicture_1_1_model_1_1_imgur_api.html',1,'epicture::Model']]] ]; <file_sep>using epicture.Model; using Imgur.API.Models; using Imgur.API.Models.Impl; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace epicture { /** * FavoritePage class. * * Controller of the View FavoritePage.Page that contain all of the favorite in the account, also permit to unfav them. * Contain all method that modify the FavoritePage view */ public sealed partial class FavoritePage : Page { /** \brief Model that contain API Information*/ IApi imgurApi; /** * Constructor */ public FavoritePage() { this.InitializeComponent(); } /** * Get information from another page. */ protected override async void OnNavigatedTo(NavigationEventArgs e) { this.imgurApi = e.Parameter as ImgurApi; ImagesLV.ItemsSource = await imgurApi.GetAccountFavorites(); base.OnNavigatedTo(e); } /** * Button (heart icon) that add/remove stuff in favorite. */ private async void AddFavoriteButton_Click(object sender, RoutedEventArgs e) { Button favButton = (sender as Button); await imgurApi.AddFavorites(favButton.Tag.ToString()); if (favButton.Content.ToString() == "\uEB52;") favButton.Content = "\uEB51;"; else favButton.Content = "\uEB52;"; ImagesLV.ItemsSource = await imgurApi.GetAccountFavorites(); } /** * Button on the bottom of the page that change Page into upload page. */ private void UploadButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(UploadPage), imgurApi); } /** * Button on the bottom of the page that change Page into search page. */ private void SearchButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(SearchPage), imgurApi); } /** * Button on the bottom of the page that change Page into my photo page. */ private void PhotoButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(HomePage), imgurApi); } } } <file_sep>var searchData= [ ['epicture',['epicture',['../namespaceepicture.html',1,'']]], ['epicture_5fxamltypeinfo',['epicture_XamlTypeInfo',['../namespaceepicture_1_1epicture___xaml_type_info.html',1,'epicture']]], ['model',['Model',['../namespaceepicture_1_1_model.html',1,'epicture']]] ]; <file_sep>var searchData= [ ['favoritepage',['FavoritePage',['../classepicture_1_1_favorite_page.html',1,'epicture.FavoritePage'],['../classepicture_1_1_favorite_page.html#ae2c1877ec61ad8ccefe6b587fa739e36',1,'epicture.FavoritePage.FavoritePage()']]] ]; <file_sep>using epicture.Model; using System; using System.Diagnostics; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace epicture { /** * MainPage class. * * Controller of the View MainPage.First page of the app that permit connection to the API. * Contain all method that modify the FavoritePage view */ public sealed partial class MainPage : Page { /** \brief Initialisation of the model that contain API Information*/ IApi imgurApi = new ImgurApi(); /** * Constructor */ public MainPage() { this.InitializeComponent(); } /** * Button that connect user to the account */ private async void ConnectButton_Click(object sender, RoutedEventArgs e) { await imgurApi.Connect(); } } } <file_sep>var searchData= [ ['favoritepage',['FavoritePage',['../classepicture_1_1_favorite_page.html',1,'epicture']]] ]; <file_sep>var searchData= [ ['mainpage',['MainPage',['../classepicture_1_1_main_page.html',1,'epicture.MainPage'],['../classepicture_1_1_main_page.html#a7d34f6e8007942c87144e08aef6c4878',1,'epicture.MainPage.MainPage()']]], ['myimage',['MyImage',['../classepicture_1_1_my_image.html',1,'epicture']]] ]; <file_sep>var searchData= [ ['addfavorites',['AddFavorites',['../interfaceepicture_1_1_model_1_1_i_api.html#a0966300815f9129272d91d5edffba327',1,'epicture::Model::IApi']]], ['app',['App',['../classepicture_1_1_app.html#ac385b968cfe8c5cbb76009b068cd5009',1,'epicture::App']]] ]; <file_sep>using epicture.Model; using Imgur.API.Models; using Imgur.API.Models.Impl; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace epicture { /** * SearchPage class. * * Controller of the View SearchPage.Page for searching stuff. * Contain all method that modify the SearchPage view */ public sealed partial class SearchPage : Page { /** \brief Model that contain API Information*/ IApi imgurApi; /** * Constructor */ public SearchPage() { this.InitializeComponent(); } /** * Get information from another page. */ protected override async void OnNavigatedTo(NavigationEventArgs e) { this.imgurApi = e.Parameter as ImgurApi; base.OnNavigatedTo(e); } /** * Button on the bottom of the page that change Page into upload page. */ private void UploadButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(UploadPage), imgurApi); } /** * Button on the bottom of the page that change Page into Favorite page. */ private void FavoriteButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(FavoritePage), imgurApi); } /** * Button on the bottom of the page that change Page into my photo page. */ private void PhotoButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(HomePage), imgurApi); } /** * TextBox that search stuff after input and validation (enter). */ private void SearchTextBox_KeyDown(object sender, KeyRoutedEventArgs e) { if (e != null && e.Key == Windows.System.VirtualKey.Enter) SearchTextBox_QuerySubmitted(sender as SearchBox, null); } /** * button that validate search. */ private async void SearchTextBox_QuerySubmitted(SearchBox sender, SearchBoxQuerySubmittedEventArgs args) { if (SearchTextBox.QueryText != null && SearchTextBox.QueryText != "") ImagesLV.ItemsSource = await imgurApi.GetGalleryBySearch(SearchTextBox.QueryText); } /** * Button (heart icon) that add/remove stuff in favorite. */ private async void AddFavoriteButton_Click(object sender, RoutedEventArgs e) { Button favButton = (Button)sender; if (favButton.Tag != null) await imgurApi.AddFavorites(favButton.Tag.ToString()); if (favButton.Content != null && favButton.Content.ToString() == "\uEB52;") favButton.Content = "\uEB51;"; else favButton.Content = "\uEB52;"; } } } <file_sep>var searchData= [ ['homepage',['HomePage',['../classepicture_1_1_home_page.html',1,'epicture']]] ]; <file_sep>var searchData= [ ['token',['token',['../classepicture_1_1_model_1_1_imgur_api.html#aae546fed3b5ad700a94f2a4fced59bb0',1,'epicture::Model::ImgurApi']]] ]; <file_sep>using Imgur.API.Models; using Imgur.API.Models.Impl; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using System.Net.Http; using epicture.Model; namespace epicture { /** * HomePage class. * * Controller of the View HomePage.Page that contain photo on your account. * Contain all method that modify the HomePage view */ public sealed partial class HomePage : Page { /** \brief Model that contain API Information*/ IApi imgurApi; /** * Constructor */ public HomePage() { this.InitializeComponent(); } /** * Get information from another page. */ protected override async void OnNavigatedTo(NavigationEventArgs e) { this.imgurApi = e.Parameter as ImgurApi; ImagesLV.ItemsSource = await imgurApi.GetAccountImages(); base.OnNavigatedTo(e); } /** * Button on the bottom of the page that change Page into upload page. */ private void UploadButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(UploadPage), imgurApi); } /** * Button on the bottom of the page that change Page into favorite page. */ private void FavoriteButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(FavoritePage), imgurApi); } /** * Button on the bottom of the page that change Page into search page. */ private void SearchButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(SearchPage), imgurApi); } /** * Button (heart icon) that add/remove stuff in favorite. */ private async void AddFavoriteButton_Click(object sender, RoutedEventArgs e) { Button favButton = sender as Button; await imgurApi.AddFavorites(favButton.Tag.ToString()); if (favButton.Content.ToString() == "\uEB52;") favButton.Content = "\uEB51;"; else favButton.Content = "\uEB52;"; } } } <file_sep>using System; using Windows.Storage; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using System; using epicture.Model; namespace epicture { /** * UploadPage class. * * Controller of the View UploadPage.Page for uploading stuff on your account. * Contain all method that modify the UploadPage view */ public sealed partial class UploadPage : Page { /** \brief Model that contain API Information*/ IApi imgurApi; /** \brief Stuff to upload*/ StorageFile file = null; /** \brief title of the stuff*/ string imageName = null; /** \brief description of the stuff*/ string imageDescription = null; /** * Constructor */ public UploadPage() { this.InitializeComponent(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { this.imgurApi = e.Parameter as ImgurApi; base.OnNavigatedTo(e); } /** * Get information from another page. */ private async void ChooseImage_Button_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".gif"); file = await picker.PickSingleFileAsync(); if (file != null) { using (var Stream = await file.OpenAsync(FileAccessMode.Read)) { var result = new BitmapImage(); await result.SetSourceAsync(Stream); ImageToUpload.Source = result; } RemoveButton.Visibility = Visibility.Visible; ChooseImage.Visibility = Visibility.Collapsed; } } /** * Get input of title TextBox. */ private void UploadName_TextBox_TextChanged(object sender, TextChangedEventArgs e) { imageName = Name.Text; } /** * Get input of description TextBox. */ private void UploadDescription_TextBox_TextChanged(object sender, TextChangedEventArgs e) { imageDescription = Description.Text; } /** * Button that submit stuff on your account. */ private async void UploadSubmit_Button_Click(object sender, RoutedEventArgs e) { if (file != null) { await imgurApi.UploadImage(file, imageName, imageDescription); var messageDialog = new MessageDialog(file.Name + " was Uploaded on Imgur"); await messageDialog.ShowAsync(); ChooseImage.Visibility = Visibility.Visible; RemoveButton.Visibility = Visibility.Collapsed; file = null; ImageToUpload.Source = null; imageDescription = null; imageName = null; } else { var messageDialog = new MessageDialog("Choose an image to upload."); await messageDialog.ShowAsync(); } } /** * Button that remove choosen image that permit to chose another image. */ private void RemoveImage_Button_Click(object sender, RoutedEventArgs e) { ChooseImage.Visibility = Visibility.Visible; RemoveButton.Visibility = Visibility.Collapsed; ImageToUpload.Source = null; file = null; } /** * Button on the bottom of the page that change Page into my photo page. */ private void PhotoButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(HomePage), imgurApi); } /** * Button on the bottom of the page that change Page into Favorite page. */ private void FavoriteButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(FavoritePage), imgurApi); } /** * Button on the bottom of the page that change Page into Search page. */ private void SearchButton_Click(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(SearchPage), imgurApi); } } } <file_sep>using Imgur.API; using Imgur.API.Authentication.Impl; using Imgur.API.Endpoints.Impl; using Imgur.API.Enums; using Imgur.API.Models; using Imgur.API.Models.Impl; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace epicture.Model { /** * API used. * * ImgurApi is a child of IApi. * Contain own method to work. * */ class ImgurApi : IApi { /** \brief User of the app*/ ImgurClient client; OAuth2Endpoint oAuth2Endpoint; ImageEndpoint imageEndpoint; AccountEndpoint accountEndpoint; GalleryEndpoint galleryEndpoint; /** \brief Permit access to the user account and the API*/ public static IOAuth2Token token; public static string code { get; set; } /** * Initialise Variable that permit access to the user account. */ public ImgurApi() { this.client = new ImgurClient("76c0f5a4f7e671e", "fd6a836ec1237a2ba383941ca420b2c9bd63922f"); this.oAuth2Endpoint = new OAuth2Endpoint(client); this.client.SetOAuth2Token(token); this.imageEndpoint = new ImageEndpoint(client); this.accountEndpoint = new AccountEndpoint(client); this.galleryEndpoint = new GalleryEndpoint(client); } /** * Get an Image from the Account. * * @param id ID of the image. */ private async Task<IImage> GetImageFromId(string id) { try { var image = await imageEndpoint.GetImageAsync(id); return image; } catch (ImgurException imgurEx) { Debug.Write("An error occurred getting an image from Imgur."); Debug.Write(imgurEx.Message); return null; } } /** * Get all image in the user account. * * @param galleries Contain multiple stuff like image/gif.... */ private async Task<ObservableCollection<MyImage>> GetMyImages(IEnumerable<IGalleryItem> galleries) { ObservableCollection<MyImage> Images = new ObservableCollection<MyImage>(); foreach (GalleryItem gallery in galleries) { var img = new MyImage(); if (gallery.ToString() == "Imgur.API.Models.Impl.GalleryAlbum") { var image = await this.GetImageFromId((gallery as GalleryAlbum).Cover); img.Id = (gallery as GalleryAlbum).Cover; if (image != null) { img.Source = image.Link; if (image.Favorite == true) img.Favorite = "\uEB52;"; else img.Favorite = "\uEB51;"; } } if (gallery.ToString() == "Imgur.API.Models.Impl.GalleryImage") { var image = await this.GetImageFromId((gallery as GalleryImage).Id); img.Id = (gallery as GalleryImage).Id; if (image != null) { img.Source = image.Link; if (image.Favorite == true) img.Favorite = "\uEB52;"; else img.Favorite = "\uEB51;"; } } Images.Add(img); } return Images; } /** * Get the token that give access to the account. * * @param code code to obtain user information. */ public static async Task<bool> GetTokenFromCode(string code) { var imgurApi = new ImgurApi(); if (code != null) token = await imgurApi.oAuth2Endpoint.GetTokenByCodeAsync(code); return true; } async Task IApi.Connect() { var imgurApi = new ImgurApi(); var authorizationUrl = imgurApi.oAuth2Endpoint.GetAuthorizationUrl(OAuth2ResponseType.Code); await Windows.System.Launcher.LaunchUriAsync(new Uri(authorizationUrl)); } async Task IApi.AddFavorites(string img_ID) { await imageEndpoint.FavoriteImageAsync(img_ID); } async Task IApi.UploadImage(Windows.Storage.StorageFile file, string name, string description) { try { IImage image; using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { image = await imageEndpoint.UploadImageStreamAsync(fs.AsStream(), null, name, description); } } catch (ImgurException imgurEx) { Debug.Write("An error occurred uploading an image to Imgur."); Debug.Write(imgurEx.Message); } } async Task<IEnumerable<MyImage>> IApi.GetAccountImages() { var imgIds = await accountEndpoint.GetImageIdsAsync(); ObservableCollection<MyImage> Images = new ObservableCollection<MyImage>(); foreach (var imgId in imgIds) { var img = new MyImage(); var image = await this.GetImageFromId(imgId); img.Source = image.Link; img.Id = imgId; if (image.Favorite == true) img.Favorite = "\uEB52;"; else img.Favorite = "\uEB51;"; Images.Add(img); } return Images; } async Task<IEnumerable<MyImage>> IApi.GetAccountFavorites() { var ret = ""; HttpClient cli = new HttpClient(); cli.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken); HttpResponseMessage response = await cli.GetAsync("https://api.imgur.com/3/account/" + token.AccountUsername + "/favorites"); HttpContent content = response.Content; ret = await content.ReadAsStringAsync(); var images = new List<MyImage>(); if (ret != null) { var img = JsonConvert.DeserializeObject<RootObject>(ret); foreach (var elem in img.data) { if (!elem.is_album) { var ga = new MyImage(); var image = await this.GetImageFromId(elem.id); if (image.Favorite == true) { ga.Favorite = "\uEB52;"; ga.Id = image.Id; ga.Source = image.Link; images.Add(ga); } } } } return images; } async Task<IEnumerable<MyImage>> IApi.GetGalleryBySearch(string query) { return await this.GetMyImages(await this.galleryEndpoint.SearchGalleryAsync(query)); } } } <file_sep>var searchData= [ ['searchpage',['SearchPage',['../classepicture_1_1_search_page.html#a5ca1d903db2a62b599c9da57fe6d07e6',1,'epicture::SearchPage']]] ]; <file_sep>using Imgur.API.Models; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Storage; namespace epicture.Model { /** * Interface of API. * * IApi contain all function that Epicture app need to connect to the wished API. * It also contain method to display content. * */ interface IApi { /** * Get access to your API account. */ Task Connect(); /** * Add stuff as favorite to your API account. * * @param img_ID Contain the ID of th stuff to add. */ Task AddFavorites(string img_ID); /** * Add stuff to your API account. * * @param file Contain the stuff to upload. * @param name Contain the title of the file to upload. * @param description Contain a description of the stuff to upload. */ Task UploadImage(StorageFile file, string name, string description); /** * Get all Favorite in your API account. */ Task<IEnumerable<MyImage>> GetAccountFavorites(); /** * Get all Image in your API account. */ Task<IEnumerable<MyImage>> GetAccountImages(); /** * Search stuff on the API. * * @param query Contain wanted research keywords. */ Task<IEnumerable<MyImage>> GetGalleryBySearch(string query); } } <file_sep>var searchData= [ ['uploadimage',['UploadImage',['../interfaceepicture_1_1_model_1_1_i_api.html#ae7fe093bb7a3734fb215b99cd13a474c',1,'epicture::Model::IApi']]], ['uploadpage',['UploadPage',['../classepicture_1_1_upload_page.html#a11756fcbfb8ab908f8205f2a3708db53',1,'epicture::UploadPage']]] ];
b2ef8e2d82df7732037c17f83c2e6159da47442f
[ "JavaScript", "C#" ]
18
C#
Ervin-Halgand/epicture
4c8b83a9400b14a7140a3ffb3c98b4781bbcecc8
fd0b16fcc94e572992c2cd60dc1103e65d70eea4
refs/heads/master
<file_sep>// // ViewController.swift // PageVCSteps // // Created by Iggy on 4/4/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class ViewController: UIPageViewController { override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self as? UIPageViewControllerDelegate // this sets the background color of the built-in paging dots view.backgroundColor = UIColor.gray // Do any additional setup after loading the view, typically from a nib. setViewControllers([getOne()], direction: .forward, animated: false, completion: nil) } func getOne() -> One { return storyboard!.instantiateViewController(withIdentifier: "One") as! One } func getTwo() -> Two { return storyboard!.instantiateViewController(withIdentifier: "Two") as! Two } func getThree() -> Three { return storyboard!.instantiateViewController(withIdentifier: "Three") as! Three } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var currentPage: Int = 0 func goToPageTwo(){ currentPage = 1 setViewControllers([getTwo()], direction: .forward, animated: false, completion: nil) } func goToPageThree(){ currentPage = 2 setViewControllers([getThree()], direction: .forward, animated: false, completion: nil) } func goToPageOne(){ currentPage = 0 setViewControllers([getOne()], direction: .forward, animated: false, completion: nil) } } extension ViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if viewController is Three { // 2 -> 1 return getTwo() } else if viewController is Two { // 1 -> 0 return getOne() } else { // 0 -> end of the road return nil } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if viewController is One { // 0 -> 1 return getTwo() } else if viewController is Two { // 1 -> 2 return getThree() } else { // 2 -> end of the road return nil } } // Enables pagination dots func presentationCount(for pageViewController: UIPageViewController) -> Int { return 3 }// The number of items reflected in the page indicator. func presentationIndex(for pageViewController: UIPageViewController) -> Int { return currentPage }// The selected item reflected in the page indicator. } enum GotoPage: String { case One = "goToPageOne" case Two = "goToPageTwo" case Three = "goToPageThree" } <file_sep>// // One.swift // PageVCSteps // // Created by Iggy on 4/5/17. // Copyright © 2017 <NAME>. All rights reserved. // import Foundation import UIKit class One: UIViewController { @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. button.addTarget(nil, action: Selector((GotoPage.Two.rawValue)), for: .touchUpInside) } // func getOne() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
9efb1ceaf98bafe566a8920d955e5c5ed51aa63b
[ "Swift" ]
2
Swift
iggym/PageVCSteps
81fd9c1807d2a00b768d892c9a0bdc72ec86e652
c3c224cb8a893ea13bc2ea2296a2521397e1a696
refs/heads/master
<repo_name>rdanieli/tic-tac-toe<file_sep>/README.md # Tic Tac Toe Game Project created to test developer skills ### Getting Started This project were created using Java technology and tested using JUnit Framework. The design decisions were made expecting the software growth in future and using principles of SOLID and DRY. As the input and output is flexible and all is based on the implementation classes, the players is easy to accept more players in the future, the exceptions are properly managed, the software is closed to modification and open to extensions. ### Prerequisites and Installing Java, Maven and an IDE. if you want to generate the jar file simple use: ``` mvn clean package ``` and you will be able to put this program on production. To perform an production run you should use java command line: ``` java -jar tic-tac-toe.jar ``` ### Coding If you want to run directly by the IDE, you can modify the usual game configuration file. Its located into resources folder and named as: ``` game.properties ``` There you can configure the players names, symbols and the playground size. After configuring your should run the Main.java file. <file_sep>/src/main/java/com/metronorm/game/setup/GameSetup.java package com.metronorm.game.setup; import com.metronorm.game.bot.AutoSuggestionPlayed; import com.metronorm.game.domain.Player; import com.metronorm.game.input.ConsoleReaderBoard; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeSet; public class GameSetup { private static final int MAX_SIZE = 10; private static final int MIN_SIZE = 3; private static final int MAX_HUMAN_PLAYERS = 2; private static GameSetup instance; private ResourceBundle resourceBundle = ResourceBundle.getBundle("game"); public static GameSetup getInstance() { if(instance == null) { instance = new GameSetup(); } return instance; } private Player readPlayer(int index){ String symbol = resourceBundle.getString(String.format("player.%s.symbol", index)); checkSymbol(symbol); return new Player(resourceBundle.getString(String.format("player.%s.name", index).trim()), new ConsoleReaderBoard(), symbol); } public Set<Player> getPlayers() { TreeSet<Player> players = new TreeSet<>(); for (int i = 0; i < MAX_HUMAN_PLAYERS; i++) { players.add(readPlayer(i + 1)); } players.add(new Player(resourceBundle.getString("IA.name"), new AutoSuggestionPlayed(), getBotSymbol())); if(players.size() != 3){ throw new IllegalArgumentException("Use different Name and Symbols for domain."); } return players; } public String[][] getBoardGameSize() { Integer size = Integer.valueOf(resourceBundle.getString("playground.size")); if(size < MIN_SIZE || size > MAX_SIZE) { throw new IllegalArgumentException("Board size is available between 3 and 10"); } return new String[size][size]; } private String getBotSymbol() { String symbol = resourceBundle.getString("IA.symbol"); checkSymbol(symbol); return symbol; } private void checkSymbol(String symbol) { if("-".equals(symbol)){ throw new IllegalArgumentException("The Symbol (-) is used to show empty space during the game."); } } } <file_sep>/src/main/java/com/metronorm/game/core/Board.java package com.metronorm.game.core; import com.metronorm.game.domain.Played; import com.metronorm.game.domain.Player; import com.metronorm.game.exceptions.InputIncorrectException; import com.metronorm.game.exceptions.NotAcceptedPlayed; import com.metronorm.game.output.PrintableBoard; import com.metronorm.game.setup.GameSetup; public class Board { private String[][] board; private int remainingPlays = 0; public void insertNewSymbol(Played played, String symbol) { this.board[played.getLine()][played.getColumn()] = symbol; remainingPlays--; } public boolean checkWinner(String symbol) { return checkDiagonals(symbol) || checkLines(symbol) || checkColumns(symbol); } private boolean checkColumns(String symbol) { return checkThroughPath(symbol, PathType.COLUMN); } private boolean checkLines(String symbol) { return checkThroughPath(symbol, PathType.ROW); } private boolean checkThroughPath(String symbol, PathType boardPath) { boolean found = false; for (int i = 0; i < board.length; i++) { found = false; for (int j = 0; j < board.length; j++) { found = symbol.equals(boardPath.getBoardValue(board, i, j)); if (!found) { break; } } if (found) { break; } } return found; } private boolean checkDiagonals(String symbol) { boolean found = false; for (int i = 0; i < board.length; i++) { found = symbol.equals(PathType.DIAGONAL.getBoardValue(board, i, i)); if (!found) { break; } } if (!found) { for (int i = 0; i < board.length; i++) { found = symbol.equals(PathType.DIAGONAL_REVERSE.getBoardValue(board, i, i)); if (!found) { break; } } } return found; } public void print(PrintableBoard printableBoard) { for (String[] column : board) { for (String line : column) { printableBoard.printSingle(line); } printableBoard.breakLine(); } } public Played read(Player player) { Played played = null; do { try { System.out.println(player + " ("+player.getSymbol() + ") your turn:"); played = player.getReader().readInput(board); } catch (InputIncorrectException | NotAcceptedPlayed e) { System.err.println(e.getMessage()); } } while (played == null); return played; } public void initBoard() { board = GameSetup.getInstance().getBoardGameSize(); remainingPlays = board.length * board.length; } public boolean isFull() { return remainingPlays == 0; } } <file_sep>/src/main/resources/game.properties playground.size=3 player.1.name=Pedro player.1.symbol=^ player.2.name=Alfred player.2.symbol=$ IA.symbol=@ IA.name=Bot<file_sep>/src/main/java/com/metronorm/game/bot/AutoSuggestionPlayed.java package com.metronorm.game.bot; import com.metronorm.game.domain.Played; import com.metronorm.game.input.ReadableBoard; public class AutoSuggestionPlayed implements ReadableBoard { @Override public Played readInput(String[][] board) { int rand1; int rand2; Played played = null; while(played == null){ rand1 = (int) (Math.random() * board.length); rand2 = (int) (Math.random() * board.length); if(board[rand1][rand2] == null){ played = new Played(rand1 + 1, rand2 + 1); } } return played; } } <file_sep>/src/main/java/com/metronorm/game/domain/PlayedFactory.java package com.metronorm.game.domain; import com.metronorm.game.exceptions.NotAcceptedPlayed; import com.metronorm.game.input.UserInputData; public class PlayedFactory { public static Played create(UserInputData input){ try { Integer line = Integer.valueOf(input.getData().substring(0, input.getData().indexOf(","))); Integer column = Integer.valueOf(input.getData().substring(input.getData().indexOf(",") + 1)); return new Played(line, column); } catch (NumberFormatException e) { throw new NotAcceptedPlayed("Take it easy, too long value informed :)"); } catch (Exception e) { throw new NotAcceptedPlayed("You're really trying to crash me :("); } } } <file_sep>/src/main/java/com/metronorm/game/domain/Player.java package com.metronorm.game.domain; import com.metronorm.game.input.ReadableBoard; import java.util.Objects; public class Player implements Comparable<Player> { private final String name; private final ReadableBoard reader; private final String symbol; public Player(final String name, final ReadableBoard reader, String symbol){ this.name = name; this.reader = reader; this.symbol = symbol; } public String getName() { return name; } @Override public String toString() { return name; } public ReadableBoard getReader() { return reader; } public String getSymbol() { return symbol; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Player player = (Player) o; return Objects.equals(name, player.name) && Objects.equals(symbol, player.symbol); } @Override public int hashCode() { return Objects.hash(name, symbol); } @Override public int compareTo(Player o) { if(this.name.compareToIgnoreCase(o.getName()) == 0 || this.symbol.compareTo(o.getSymbol()) == 0){ return 0; } else { return 1; } } }
0bc8e632d979835b97c633c0fa2ac79d0d9dadd6
[ "Markdown", "Java", "INI" ]
7
Markdown
rdanieli/tic-tac-toe
6b54e8592ab7cd3d2dd1ebaabbec77af05dc2a31
2824e11fcb2aa02c635fe1d868e27cb33811a81a
refs/heads/master
<file_sep>export default interface WatchlistStockInsert { StockId: number; WatchDate: string; WatchPrice: number; } <file_sep>import knexInitializer from './knex'; import dependencyInjector from './dependency-injector'; export default async () => { const knexConnection = await knexInitializer(); await dependencyInjector({ knexConnection }); };<file_sep>export interface StockPosition { PositionId: number; StockId: number; Quantity: number; BuyDate: Date; BuyPrice: number; }<file_sep>import express from 'express'; import "reflect-metadata"; import { Container } from 'typedi/Container'; import automationInitializer from './initializers/automation-initializer'; import DailyUpdateService from './services/daily-update'; async function startServer() { const app = express(); await require('./initializers').default({ expressApp: app }); app.listen(3000, () => { console.log('Listening on port 3000'); }); } async function dailyUpdate() { await require('./initializers/automation-initializer').default(); const dailyUpdateService = Container.get(DailyUpdateService); console.log("Sending update"); await dailyUpdateService.sendDailyUpdate(); console.log('Exiting'); process.exit(); } const isDailyUpdate = process.argv.find(arg => arg === "daily-update"); if(isDailyUpdate) { dailyUpdate(); } else { startServer(); } <file_sep># Portfolio Tracker I built this to automate keeping track of my stock portfolio. I have a bash script that runs every morning that results in a daily email update so I don't have to check anymore. There is also a client application that can be found here: https://github.com/drod1000/portfolio-tracker-client ## Tech Used * [Express](https://expressjs.com) - Server * [MySQL](https://www.mysql.com) - Database * [Knex](http://knexjs.org) - Query Builder * [typedi](https://www.npmjs.com/package/typedi) - Dependency Injection * [Axios](https://www.npmjs.com/package/axios) - HTTP Client * [Moment.js](https://momentjs.com) - Date Handling ## External APIs * [Sendgrid](https://sendgrid.com) - Email Notification * [World Trading Data](https://www.worldtradingdata.com) - Stock Data ## Available Scripts In the project directory, you can run: ### `npm start dev` Runs the express in development mode. ### `npm start daily-update` Fetches latest data from World Trading Data and sends an email using Sendgrid to the user (me) <file_sep>import { Service, Inject } from 'typedi'; import { StockRepository, StockHistoryRepository, WatchlistStockRepository } from '../db/repositories'; import WorldTradingDataService from './world-trading-data'; import { PostAddWatchlistStockResult, WatchlistStockInsert, PostAddWatchlistStock, StockHistoryInsert } from '../db/dtos'; @Service() class WatchlistStockService { @Inject() private _stockRepository: StockRepository; @Inject() private _stockHistoryRepository: StockHistoryRepository; @Inject() private _watchlistStockRepository: WatchlistStockRepository; @Inject() private _worldTradingDataService: WorldTradingDataService; async getWatchlist() { const rawResult = await this._watchlistStockRepository.getWatchlist(); // Raw returns additional data const [result] = rawResult; return result; } async addWatchlistStock(inputDto: PostAddWatchlistStock): Promise<PostAddWatchlistStockResult> { let stockId: number; let currentPrice: number; const stock = await this._stockRepository.getStockBySymbol(inputDto.StockSymbol); if (stock) { stockId = stock.StockId; currentPrice = await this._stockHistoryRepository.getMostRecentPriceByStockId(stock.StockId); } else { const stockAndHistoryInsertResult = await this._insertStockAndFullHistory(inputDto.StockSymbol); stockId = stockAndHistoryInsertResult.StockId; currentPrice = stockAndHistoryInsertResult.CurrentPrice; } const watchlistStockInsert: WatchlistStockInsert = { StockId: stockId, WatchDate: inputDto.WatchDate.toString(), WatchPrice: inputDto.WatchPrice }; const watchlistStockInsertResult = await this._watchlistStockRepository.insertWatchlistStock(watchlistStockInsert); const result: PostAddWatchlistStockResult = { WatchlistStockId: watchlistStockInsertResult[0], StockSymbol: inputDto.StockSymbol, WatchDate: inputDto.WatchDate, WatchPrice: inputDto.WatchPrice, CurrentPrice: currentPrice }; return new Promise(resolve => resolve(result)); } private async _insertStockAndFullHistory(stockSymbol: string): Promise<any> { const stockHistory = await this._worldTradingDataService.getFullHistoryBySymbol(stockSymbol); const stockInsertResult = await this._stockRepository.insertStock(stockSymbol); const stockHistoryInsert: StockHistoryInsert[] = Object.keys(stockHistory).map(date => { return { StockId: stockInsertResult[0], RecordDate: date, OpenPrice: stockHistory[date].open, ClosePrice: stockHistory[date].close }; }); await this._stockHistoryRepository.insertStockHistory(stockHistoryInsert); const result = { StockId: stockInsertResult[0], CurrentPrice: stockHistoryInsert[stockHistoryInsert.length - 1 ].ClosePrice } return new Promise(resolve => resolve(result)); } } export default WatchlistStockService;<file_sep>export default interface PostAddWatchlistStock { StockSymbol: string; WatchDate: Date; WatchPrice: number; } <file_sep>export default interface StockPositionInsert { StockId: number; Quantity: number; BuyDate: string; BuyPrice: number; } <file_sep>import { Container } from 'typedi'; import { StockRepository, StockHistoryRepository, StockPositionRepository, WatchlistStockRepository } from '../db/repositories'; export default ({ knexConnection }) => { Container.set("knex.connection", knexConnection); }<file_sep>import { Router, Request, Response } from 'express'; import { Container } from 'typedi'; import WatchlistStockService from '../../services/watchlist-stock'; const router = Router(); export default (app) => { app.use('/watchlist', router); router.get('/', (req, res) => { const watchlistStockService: WatchlistStockService = Container.get(WatchlistStockService); watchlistStockService.getWatchlist() .then(watchlist => res.status(200).send(watchlist)) .catch(error => { res.status(400).send({ message: `Something went wrong: ${error}` }); }); }); // TODO: Add async middleware to make this more readable router.post('/', (req: Request, res: Response) => { const watchlistStockService: WatchlistStockService = Container.get(WatchlistStockService); watchlistStockService.addWatchlistStock(req.body) .then(addResult => res.status(201).send(addResult)) .catch(error => { res.status(400).send({ message: `Something went wrong: ${error}` }); }); }); };<file_sep>import StockRepository from './stock'; import StockHistoryRepository from './stock-history'; import StockPositionRepository from './stock-position'; import WatchlistStockRepository from './watchlist-stock'; import StockSaleRepository from './stock-sale'; export { StockRepository, StockHistoryRepository, StockPositionRepository, WatchlistStockRepository, StockSaleRepository } <file_sep>import { Router, Request, Response } from 'express'; import { Container } from 'typedi'; import StockHistoryService from '../../services/stock-history'; const router = Router(); export default (app: Router) => { app.use('/stock', router); // TODO: Move this to a job router.get('/refresh-all', (req: Request, res: Response) => { const stockHistoryService: StockHistoryService = Container.get(StockHistoryService); stockHistoryService.refreshAll() .then(result => { res.status(200).send({ message: "Success!" }); }) .catch(error => { res.status(400).send({ message: `Something went wrong: ${error}` }); }); }); }<file_sep>import { Router, Request, Response } from 'express'; import { Container } from 'typedi'; import StockPositionService from '../../services/stock-position'; const router = Router(); export default (app: Router) => { app.use('/positions', router); router.get('/', (req: Request, res: Response) => { const stockPositionService: StockPositionService = Container.get(StockPositionService); stockPositionService.getAllStockPositions() .then(positions => res.status(200).send(positions)) .catch(error => { res.status(400).send({ message: `Something went wrong: ${error}` }); }); }); // TODO: Add async middleware to make this more readable router.post('/', (req: Request, res: Response) => { const stockPositionService: StockPositionService = Container.get(StockPositionService); stockPositionService.addStockPosition(req.body) .then(addResult => res.status(201).send(addResult)) .catch(error => { res.status(400).send({ message: `Something went wrong: ${error}` }); }); }); router.post('/close', (req: Request, res: Response) => { const stockPositionService: StockPositionService = Container.get(StockPositionService); stockPositionService.closePosition(req.body) .then(closeResult => res.status(200).send(closeResult)) .catch(error => { res.status(400).send({ message: `Something went wrong: ${error}` }); }); }); };<file_sep>import { Service, Inject } from 'typedi'; import moment from 'moment'; import StockHistoryService from './stock-history'; import StockPositionService from './stock-position'; import WatchlistStockService from './watchlist-stock'; import SendgridService from './sendgrid'; @Service() class DailyUpdateService { @Inject() private _stockHistoryService: StockHistoryService; @Inject() private _stockPositionService: StockPositionService; @Inject() private _watchlistStockService: WatchlistStockService; @Inject() private _sendgridService: SendgridService; async sendDailyUpdate() { await this._stockHistoryService.refreshAll(); const emailDate = moment().format('MMM D YYYY'); const positions = await this._stockPositionService.getAllStockPositions(); const watchlist = await this._watchlistStockService.getWatchlist(); const templateData = { "EmailDate": emailDate, "Positions": positions, "Watchlist": watchlist }; const result = await this._sendgridService.sendTemplateMessage('d-4bc9d2c2900f47f2a87a4004829bece4', templateData); return result; } } export default DailyUpdateService;<file_sep> exports.up = function(knex) { return knex.schema.alterTable('StockPosition', function(table) { table.dropColumn('SellDate'); table.dropColumn('SellPrice'); }); }; exports.down = function(knex) { return knex.schema.alterTable('StockPosition', function(table) { table.date('SellDate'); table.decimal('SellPrice'); }); }; <file_sep> exports.up = function(knex) { return knex.schema.createTable('WatchlistStock', function(table) { table.increments('WatchlistStockId'); table.integer('StockId').notNullable().unsigned(); table.foreign('StockId').references('Stock.StockId'); table.date('WatchDate').notNullable(); table.decimal('WatchPrice').notNullable(); }); }; exports.down = function(knex) { return knex.schema.dropTable('WatchlistStock'); };<file_sep>export interface StockHistory { StockHistoryId: number; StockId: number; RecordDate: Date; OpenPrice: number; ClosePrice: number; }<file_sep>import PostAddStockPositionResult from './post-add-stock-position-result'; import PostAddStockPosition from './post-add-stock-position'; import PostAddWatchlistStockResult from './post-add-watchlist-stock-result'; import PostAddWatchlistStock from './post-add-watchlist-stock'; import StockHistoryInsert from './stock-history-insert'; import StockPositionInsert from './stock-position-insert'; import WatchlistStockInsert from './watchlist-stock-insert'; import StockHistoryRefresh from './stock-history-refresh'; import PostClosePosition from './post-close-position'; import PostClosePositionResult from './post-close-position-result'; import StockSaleInsert from './stock-sale-insert'; export { PostAddStockPositionResult, PostAddStockPosition, PostAddWatchlistStockResult, PostAddWatchlistStock, StockHistoryInsert, StockPositionInsert, WatchlistStockInsert, StockHistoryRefresh, PostClosePosition, PostClosePositionResult, StockSaleInsert }<file_sep>export interface StockSale { StockSaleId: number; StockId: number; PositionId: number; Quantity: number; SellDate: Date; SellPrice: number; } <file_sep>export default interface PostClosePosition { PositionId: number; Quantity: number; SellDate: Date; SellPrice: number; } <file_sep>export default interface StockHistoryRefresh { StockId: number; StockSymbol: string; RecordDate: Date; } <file_sep>import expressInitializer from './express'; import knexInitializer from './knex'; import dependencyInjector from './dependency-injector'; export default async ({ expressApp }) => { const knexConnection = await knexInitializer(); await dependencyInjector({ knexConnection }); await expressInitializer({ app: expressApp }); };<file_sep>export default interface StockHistoryInsert { StockId: number; RecordDate: string; OpenPrice: number; ClosePrice: number; } <file_sep>export default interface PostAddWatchlistStockResult { WatchlistStockId: number; StockSymbol: string; WatchDate: Date; WatchPrice: number; CurrentPrice: number; } <file_sep>import { Service, Inject } from 'typedi'; import { StockRepository, StockHistoryRepository, StockPositionRepository, StockSaleRepository } from '../db/repositories'; import WorldTradingDataService from './world-trading-data'; import { PostAddStockPositionResult, PostAddStockPosition, StockHistoryInsert, StockPositionInsert, PostClosePosition, PostClosePositionResult, StockSaleInsert } from '../db/dtos'; @Service() class StockPositionService { @Inject() private _stockRepository: StockRepository; @Inject() private _stockHistoryRepository: StockHistoryRepository; @Inject() private _stockPositionRepository: StockPositionRepository; @Inject() private _stockSaleRepository: StockSaleRepository; @Inject() private _worldTradingDataService: WorldTradingDataService; async getAllStockPositions() { const rawResult = await this._stockPositionRepository.getAllStockPositions(); // Raw returns additional data const [result] = rawResult; return result.filter(p => p.Quantity > 0); } async addStockPosition(inputDto: PostAddStockPosition): Promise<PostAddStockPositionResult> { let stockId: number; let currentPrice: number; const stock = await this._stockRepository.getStockBySymbol(inputDto.StockSymbol); if (stock) { stockId = stock.StockId; currentPrice = await this._stockHistoryRepository.getMostRecentPriceByStockId(stock.StockId); } else { const stockAndHistoryInsertResult = await this._insertStockAndFullHistory(inputDto.StockSymbol); stockId = stockAndHistoryInsertResult.StockId; currentPrice = stockAndHistoryInsertResult.CurrentPrice; } const stockPositionInsert: StockPositionInsert = { StockId: stockId, Quantity: inputDto.Quantity, BuyDate: inputDto.BuyDate.toString(), BuyPrice: inputDto.BuyPrice }; const stockPositionInsertResult = await this._stockPositionRepository.insertStockPosition(stockPositionInsert); const result: PostAddStockPositionResult = { PositionId: stockPositionInsertResult[0], StockSymbol: inputDto.StockSymbol, Quantity: inputDto.Quantity, BuyDate: inputDto.BuyDate, BuyPrice: inputDto.BuyPrice, CurrentPrice: currentPrice }; return new Promise(resolve => resolve(result)); } async closePosition(inputDto: PostClosePosition): Promise<PostClosePositionResult> { const stockPosition = await this._stockPositionRepository.getStockPositionByPositionId(inputDto.PositionId); const newQuantity = stockPosition.Quantity - inputDto.Quantity; if (newQuantity < 0) { const rejection = Promise.reject("Sale quantity cannot be greater than position quantity."); return rejection; } const stockSaleInsert: StockSaleInsert = { StockId: stockPosition.StockId, PositionId: stockPosition.PositionId, Quantity: inputDto.Quantity, SellDate: inputDto.SellDate.toString(), SellPrice: inputDto.SellPrice }; await this._stockSaleRepository.insertStockSale(stockSaleInsert); const result: PostClosePositionResult = { PositionId: stockPosition.PositionId, Quantity: newQuantity }; return new Promise(resolve => resolve(result)); } private async _insertStockAndFullHistory(stockSymbol: string): Promise<any> { const stockHistory = await this._worldTradingDataService.getFullHistoryBySymbol(stockSymbol); const stockInsertResult = await this._stockRepository.insertStock(stockSymbol); const stockHistoryInsert: StockHistoryInsert[] = Object.keys(stockHistory).map(date => { return { StockId: stockInsertResult[0], RecordDate: date, OpenPrice: stockHistory[date].open, ClosePrice: stockHistory[date].close }; }); await this._stockHistoryRepository.insertStockHistory(stockHistoryInsert); const result = { StockId: stockInsertResult[0], CurrentPrice: stockHistoryInsert[stockHistoryInsert.length - 1 ].ClosePrice } return new Promise(resolve => resolve(result)); } } export default StockPositionService;<file_sep> exports.up = function(knex) { return knex.schema.createTable('StockPosition', function(table) { table.increments('PositionId'); table.integer('StockId').notNullable().unsigned(); table.foreign('StockId').references('Stock.StockId'); table.decimal('Quantity').notNullable(); table.date('BuyDate').notNullable(); table.decimal('BuyPrice').notNullable(); table.date('SellDate'); table.decimal('SellPrice'); }); }; exports.down = function(knex) { return knex.schema.dropTable('StockPosition'); }; <file_sep> exports.up = function(knex) { return knex.schema.createTable('StockSale', function(table) { table.increments('StockSaleId'); table.integer('StockId').notNullable().unsigned(); table.foreign('StockId').references('Stock.StockId'); table.integer('PositionId').notNullable().unsigned(); table.foreign('PositionId').references('StockPosition.PositionId'); table.decimal('Quantity').notNullable(); table.date('SellDate').notNullable(); table.decimal('SellPrice').notNullable(); }); }; exports.down = function(knex) { return knex.schema.dropTable('StockSale'); }; <file_sep>export default interface PostClosePositionResult { PositionId: number; Quantity: number; } <file_sep>import { Service, Inject } from 'typedi'; import WatchlistStockInsert from '../dtos/watchlist-stock-insert'; @Service() class WatchlistStockRepository { constructor( @Inject('knex.connection') private _knex ) { } async insertWatchlistStock(dto: WatchlistStockInsert) { const result = this._knex('WatchlistStock').insert(dto); return result; } async getWatchlist() { const result = this._knex.raw( ` SELECT ws.WatchlistStockId, ws.WatchDate, ws.WatchPrice, s.StockSymbol, sh.RecordDate, sh.ClosePrice as CurrentPrice FROM WatchlistStock ws INNER JOIN Stock s ON ws.StockId=s.StockId INNER JOIN ( SELECT oh.StockId, oh.RecordDate, oh.ClosePrice FROM StockHistory oh LEFT JOIN StockHistory nh ON oh.StockId=nh.StockId AND oh.RecordDate < nh.RecordDate WHERE nh.RecordDate IS NULL ) sh ON ws.StockId=sh.StockId; ` ); return result; } } export default WatchlistStockRepository;<file_sep>import { Service, Inject } from 'typedi'; @Service() class StockRepository { constructor( @Inject('knex.connection') private _knex ) { } async insertStock(stockSymbol: string) { const result = this._knex('Stock').insert({ StockSymbol: stockSymbol}); return result; } async getAllStocks() { const result = this._knex.select().from('Stock'); return result; } async getAllStocksWithMostRecentHistory() { const result = this._knex.raw( ` SELECT s.StockId, s.StockSymbol, sh.RecordDate FROM Stock s INNER JOIN ( SELECT oh.StockId, oh.RecordDate FROM StockHistory oh LEFT JOIN StockHistory nh ON oh.StockId=nh.StockId AND oh.RecordDate < nh.RecordDate WHERE nh.RecordDate IS NULL ) sh ON s.StockId=sh.StockId` ); return result; } async getStockBySymbol(stockSymbol: string){ const result = this._knex('Stock').where('StockSymbol', stockSymbol).first(); return result; } } export default StockRepository;<file_sep>import { Service, Inject } from 'typedi'; import StockPositionInsert from '../dtos/stock-position-insert'; @Service() class StockPositionRepository { constructor( @Inject('knex.connection') private _knex ) { } async insertStockPosition(dto: StockPositionInsert) { const result = this._knex('StockPosition').insert(dto); return result; } async getAllStockPositions() { const result = this._knex.raw( ` SELECT sp.PositionId, IF(qs.QuantitySold IS NULL, sp.Quantity, sp.Quantity-qs.QuantitySold) AS Quantity, sp.BuyDate, sp.BuyPrice, s.StockSymbol, sh.RecordDate, sh.ClosePrice AS CurrentPrice FROM StockPosition sp INNER JOIN Stock s ON sp.StockId=s.StockId INNER JOIN ( SELECT oh.StockId, oh.RecordDate, oh.ClosePrice FROM StockHistory oh LEFT JOIN StockHistory nh ON oh.StockId=nh.StockId AND oh.RecordDate < nh.RecordDate WHERE nh.RecordDate IS NULL ) sh ON sp.StockId=sh.StockId LEFT JOIN ( SELECT PositionId, SUM(Quantity) AS QuantitySold FROM StockSale GROUP BY PositionId ) qs ON sp.PositionId=qs.PositionId ` ); return result; } async getStockPositionByPositionId(positionId: number) { const result = this._knex('StockPosition') .where('PositionId', positionId) .first(); return result; } } export default StockPositionRepository;<file_sep> exports.up = function(knex) { return knex.schema.createTable('Stock', function(table) { table.increments('StockId'); table.string('StockSymbol', 16); }); }; exports.down = function(knex) { return knex.schema.dropTable('Stock'); }; <file_sep>import axios from 'axios'; import chunk from 'lodash/chunk'; import reduce from 'lodash/reduce'; import moment from 'moment'; import { Service } from 'typedi'; require('dotenv').config(); @Service() class WorldTradingDataService { private _urlPrefix: string; private _apiToken: string; private _startDate: string; constructor() { this._urlPrefix = 'https://api.worldtradingdata.com/api/v1'; this._apiToken = process.env.WORLD_TRADING_DATA_API_KEY; this._startDate = '2018-01-01'; } async getFullHistoryBySymbol(stockSymbol: string) { const response = await axios.get(`${this._urlPrefix}/history?symbol=${stockSymbol}&date_from=${this._startDate}&sort=oldest&api_token=${this._apiToken}`); return response.data.history; } async getFullHistoryBySymbolAndStartDate(stockSymbol: string, startDate: Date) { const formattedStartDate = moment(startDate).format('YYYY-MM-DD'); const response = await axios.get(`${this._urlPrefix}/history?symbol=${stockSymbol}&date_from=${formattedStartDate}&sort=oldest&api_token=${this._apiToken}`); return response.data.history; } async getMultipleSingleDayHistory(symbols: string[], date) { const symbolPairs = chunk(symbols, 2); const responsePromises = symbolPairs.map(p => this._getPairSingleDayHistory(p, date)); const responses = await Promise.all(responsePromises); const flattenedResponse = reduce(responses, (result, current) => Object.assign(result, current), {}); const result = new Promise(resolve => resolve(flattenedResponse)); return result; } private async _getPairSingleDayHistory(symbols: string[], date) { const symbolParams = symbols.join(','); const response = await axios.get(`${this._urlPrefix}/history_multi_single_day?symbol=${symbolParams}&date=${date}&api_token=${this._apiToken}`); return response.data.data; } } export default WorldTradingDataService;<file_sep>export interface Stock { StockId: number; StockSymbol: string; } <file_sep>import { Service, Inject } from 'typedi'; import { StockSaleInsert } from '../dtos'; @Service() class StockSaleRepository { constructor( @Inject('knex.connection') private _knex ) { } async insertStockSale(dto: StockSaleInsert) { const result = this._knex('StockSale').insert(dto); return result; } } export default StockSaleRepository;<file_sep>export default interface PostAddStockPositionResult { PositionId: number; StockSymbol: string; Quantity: number; BuyDate: Date; BuyPrice: number; CurrentPrice: number; } <file_sep>import moment from 'moment'; import { Service, Inject } from 'typedi'; import { StockRepository, StockHistoryRepository } from '../db/repositories'; import WorldTradingDataService from './world-trading-data'; import { StockHistoryRefresh, StockHistoryInsert } from '../db/dtos'; @Service() class StockHistoryService { @Inject() private _stockRepository: StockRepository; @Inject() private _stockHistoryRepository: StockHistoryRepository; @Inject() private _worldTradingDataService: WorldTradingDataService; async refreshAll() { const rawResult = await this._stockRepository.getAllStocksWithMostRecentHistory(); const stocks: StockHistoryRefresh[] = rawResult[0]; await Promise.all(stocks.map(s => this._fetchAndRefreshStockHistory(s))); return new Promise(resolve => resolve(true)); } private async _fetchAndRefreshStockHistory(stock: StockHistoryRefresh) { const startDate = moment(stock.RecordDate).add(1, 'days'); const stockHistory = await this._worldTradingDataService.getFullHistoryBySymbolAndStartDate(stock.StockSymbol, startDate.toDate()); if (!stockHistory) { return new Promise(resolve => resolve(true)); } const stockHistoryInsert: StockHistoryInsert[] = Object.keys(stockHistory).map(date => { return { StockId: stock.StockId, RecordDate: date, OpenPrice: stockHistory[date].open, ClosePrice: stockHistory[date].close }; }); await this._stockHistoryRepository.insertStockHistory(stockHistoryInsert); return new Promise(resolve => resolve(true)); } } export default StockHistoryService;<file_sep>import { Router } from 'express'; import position from './routes/position'; import watchlist from './routes/watchlist'; import stock from './routes/stock'; export default () => { const app = Router(); position(app); watchlist(app); stock(app); return app; }; <file_sep>import { Service } from 'typedi'; import sgMail from '@sendgrid/mail'; require('dotenv').config(); @Service() class SendgridService { constructor() { sgMail.setApiKey(process.env.SENDGRID_API_KEY); } async sendTemplateMessage(templateId: string, templateData: object) { const msg = { to: process.env.USER_EMAIL, from: process.env.USER_EMAIL, template_id: templateId, "dynamic_template_data": templateData }; return sgMail.send(msg); } } export default SendgridService<file_sep>export interface WatchlistStock { WatchlistStockId: number; StockId: number; WatchDate: Date; WatchPrice: number; }<file_sep>export default interface PostAddStockPosition { StockSymbol: string; Quantity: number; BuyDate: Date; BuyPrice: number; } <file_sep>import { Service, Inject } from 'typedi'; import StockHistoryInsert from '../dtos/stock-history-insert'; @Service() class StockHistoryRepository { constructor( @Inject('knex.connection') private _knex ) { } async insertStockHistory(history: StockHistoryInsert[]) { const result = this._knex('StockHistory').insert(history); return result; } async getMostRecentPriceByStockId(stockId: number) { const result = this._knex('StockHistory') .where('StockId', stockId) .orderBy('RecordDate', 'desc') .first(); return result; } } export default StockHistoryRepository;
1e6f8ec82b2a0d3ba550cb58cf65742b2e29e1d0
[ "Markdown", "TypeScript", "JavaScript" ]
42
TypeScript
drod1000/portfolio-tracker-api
c4f82b500446d26318cf099cdb5f5f2f070e241d
7fc4d0e3c0293bc44577b3ff97b65f8649c210cc
refs/heads/master
<repo_name>triiionyx/arcade<file_sep>/router.js String.prototype.router = function(a, b=a?a:{}, pop=b.pop ? b.pop : null) { var page = '', path = (this.valueOf()).replace(window.location.host,''); window.GET = path===window.location.origin ? [] : route.get.path.dir(path), arr = []; console.log({GET,path}); return new Promise((resolve, reject) => { if(path) { body.dataset.page = page; body.dataset.path = path; history.pushState(path,null,path); resolve(path); } else { reject({error:'path error',code:666}); } }); }; window.route = { get: { path: { dir: (url,g=[]) => { url.split('/').forEach((a,i) => { a ? g.push(a) : null; }); g[0] === "" ? g.shift() : null; g[g.length - 1] === "" ? g.pop() : null; return g; }, url: dir => { return dir.length === 0 ? '/' : '/'+dir.join('/')+'/'; } } } }
20c386735715f6e0c45305b8fa574ec0b32b5ffd
[ "JavaScript" ]
1
JavaScript
triiionyx/arcade
a234072571385d47c50c5395831a021d1a037830
4b8565884845c8af5e73f21e4d0faba31f059796
refs/heads/master
<repo_name>hakobera/nodejs-vs-avatarjs<file_sep>/javafx-webview/webviewsample/WebViewSample.java package webviewsample; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; public class WebViewSample extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { WebView view = new WebView(); WebEngine engine = view.getEngine(); engine.load("http://octane-benchmark.googlecode.com/svn/latest/index.html"); primaryStage.setScene(new Scene(view, 1024, 768)); primaryStage.show(); } } <file_sep>/prepare.sh #!/bin/sh echo "==================================================" echo " Build Avatar.js " echo "==================================================" git clone https://github.com/raymondfeng/loopback-on-jvm.git for file in build.sh checkout.sh nodej do cp ./patch/$file loopback-on-jvm done cd loopback-on-jvm rm -rf ./avatar-js rm -rf ./http-parser rm -rf ./libuv ./checkout.sh ./build.sh cd .. echo "" echo "==================================================" echo " Get Octane " echo "==================================================" git clone https://github.com/dai-shi/benchmark-octane.git echo "" echo " Make JavaFX WebView" cd javafx-webview javac -cp . ./webviewsample/WebViewSample.java cd .. <file_sep>/README.md # nodejs-vs-avatarjs Benchmark: Node.js vs Avatar.js ## Prerequisites - Node.js - Java8 (JDK8) - git ## How to run ``` $ ./prepare.sh $ ./benchmark.sh ``` <file_sep>/1_fibonacci/run.sh #!/bin/sh npm install echo '[Run on Node.js]' node fibonacci.js echo '' echo '[Run on Avatar.js on Nashorn]' ../loopback-on-jvm/nodej fibonacci.js <file_sep>/patch/nodej #!/bin/bash if [ -z "$JAVA_HOME" ]; then export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home fi CD=`pwd` ROOT=`dirname $0` cd $ROOT ROOT=`pwd` OS=`uname -s` if [ "Darwin" == "$OS" ]; then export DYLD_LIBRARY_PATH=$ROOT/avatar-js/dist:$DYLD_LIBRARY_PATH else export LD_LIBRARY_PATH=$ROOT/avatar-js/dist:$LD_LIBRARY_PATH fi cd $CD $JAVA_HOME/bin/java -Xms512m -Xmx512m -XX:+UseG1GC -Xloggc:G1GC.log -jar $ROOT/avatar-js/dist/avatar-js.jar $@ <file_sep>/1_fibonacci/fibonacci.js function fibonacci(n) { if (n <= 2) return n; return fibonacci(n-1) + fibonacci(n-2); } if (typeof require !== 'undefined') { var Benchmark = require('benchmark'); } else { load('./node_modules/benchmark/benchmark.js'); } var suite = new Benchmark.Suite; for (var i = 1; i <= 3; ++i) { (function () { var n = i * 10; suite.add('fibonacci(' + n + ')', function() { fibonacci(n); }); })(); } suite.on('cycle', function (event) { console.log(String(event.target)); }) .run({ 'async': true }); <file_sep>/patch/build.sh #!/bin/bash if [ -z "$JAVA_HOME" ]; then export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home fi export PATH=$JAVA_HOME/bin:$PATH ROOT=`dirname $0` cd $ROOT ROOT=`pwd` export CLASSPATH=$ROOT/testng-6.8/testng-6.8.jar if [ -d $ROOT/apache-ant-1.9.3/bin ]; then export PATH=$ROOT/apache-ant-1.9.3/bin:$PATH fi ant -Davatar-js.home=$ROOT/avatar-js -Dsource.home=$ROOT/node-v0.10.25 -Dlibuv.home=$ROOT/libuv -Dhttp-parser.home=$ROOT/http-parser -Dbuild.type=Release -f $ROOT/avatar-js/build.xml <file_sep>/patch/checkout.sh #!/bin/bash ROOT=`dirname $0` cd $ROOT ROOT=`pwd` # Download node v0.10.25 if [ ! -d node-v0.10.25 ]; then echo 'Downloading node.js...' curl -sL http://nodejs.org/dist/v0.10.25/node-v0.10.25.tar.gz| tar zx fi if [ ! -d apache-ant-1.9.3 ]; then echo 'Downloading ant...' curl -sL http://www.apache.org/dist/ant/binaries/apache-ant-1.9.3-bin.tar.gz| tar zx fi if [ ! -d testng-6.8 ]; then echo 'Downloading testng...' curl -s http://testng.org/testng-6.8.zip -o testing-6.8.zip && unzip testing-6.8.zip fi # Clone or pull from the avatar-js repos function sync { PROJ=$1 TARGET=$2 echo Checking out $PROJ... if [ -d $TARGET/.git ]; then cd $ROOT/$TARGET git pull else git clone git://java.net/avatar-js~$PROJ $TARGET fi cd $ROOT } sync src avatar-js sync libuv-java libuv sync http-parser-java http-parser <file_sep>/benchmark.sh #!/bin/bash if [ -z "$JAVA_HOME" ]; then export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home fi echo "<< 1. Calc fibonacci >>" cd 1_fibonacci ./run.sh cd .. echo "" echo "<< 2. Octane >>" cd benchmark-octane npm install echo '[Run on Node.js]' node run.js echo '' echo '[Run on Avatar.js on Nashorn]' ../loopback-on-jvm/nodej run.js cd .. echo "" echo "<< 3. Octane on JavaFX WebView" java -Xms1g -Xmx1g -cp ./javafx-webview webviewsample.WebViewSample
dc16524f7bc46d9e093a6f8bbef1359260e8b747
[ "Markdown", "Java", "JavaScript", "Shell" ]
9
Java
hakobera/nodejs-vs-avatarjs
2851bfe3a54bcc5c2850d977ed96ee17d3c31b8e
b809477b7f13a883b6c3ec8952c4f2dfe54cd625
refs/heads/master
<file_sep>jdbc.user=root jdbc.password=<PASSWORD>.. jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc\:mysql\:///sssp<file_sep>package com.xmut.olt.seventh.service; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.xmut.olt.seventh.entity.StuPaper; import com.xmut.olt.seventh.entity.StuPaperDetail; import com.xmut.olt.seventh.repository.StuPaperDetailRepository; @Service public class StuPaperDetailService { @Autowired private StuPaperDetailRepository stuPaperDetailRepository; @Transactional(readOnly=true) public StuPaperDetail getByspdid(Integer spdid) { return stuPaperDetailRepository.getByspdid(spdid); } @Transactional(readOnly=true) public List<StuPaperDetail> getBystuPaper(StuPaper spid) { return (List<StuPaperDetail>) stuPaperDetailRepository.getBystuPaper(spid); } @Transactional public Boolean deleteStuPaperDetail(StuPaper spid) //根据外键删除试卷详情表相关字段 { boolean b=false; if(spid!=null) { b=true; List<StuPaperDetail> bystuPaper = getBystuPaper(spid); for (StuPaperDetail stuPaperDetail : bystuPaper) { stuPaperDetailRepository.delete(stuPaperDetail.getSpdid()); } } return b; } @Transactional public Page<StuPaperDetail> getBystuPaperDetailOne(final StuPaper stuPaper,Integer page) { PageRequest pageRequest=new PageRequest(page-1, 999); Specification<StuPaperDetail> specification=new Specification<StuPaperDetail>() { @Override public Predicate toPredicate(Root<StuPaperDetail> arg0, CriteriaQuery<?> arg1, CriteriaBuilder arg2) { Path<String> path=arg0.get("stuPaper"); return arg2.equal(path, stuPaper); } }; return stuPaperDetailRepository.findAll(specification, pageRequest); } @Transactional public StuPaperDetail save(StuPaperDetail stuPaperDetail) { return stuPaperDetailRepository.saveAndFlush(stuPaperDetail); } @Transactional(readOnly=true) public Page<StuPaperDetail> findStuPaper(final StuPaper paper) { PageRequest pageRequest=new PageRequest(0, 9999); Specification<StuPaperDetail> specification=new Specification<StuPaperDetail>() { @Override public Predicate toPredicate(Root<StuPaperDetail> arg0, CriteriaQuery<?> arg1, CriteriaBuilder arg2) { Path<String> path=arg0.get("stuPaper"); return arg2.equal(path, paper); } }; return stuPaperDetailRepository.findAll(specification, pageRequest); } } <file_sep>package com.xmut.olt.seventh.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.xmut.olt.seventh.entity.QItem; public interface QItemRepository extends JpaRepository<QItem, Integer>,JpaSpecificationExecutor<QItem>{ public QItem getByqiid(Integer qiid); } <file_sep>package com.xmut.olt.seventh.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.xmut.olt.seventh.entity.Student; public interface StudentRepository extends JpaRepository<Student, Integer>,JpaSpecificationExecutor<Student>{ Student getBysNum(String sNum); Student getBysName(String sName); } <file_sep>package com.xmut.olt.seventh.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.xmut.olt.seventh.entity.Teacher; public interface TeacherRepository extends JpaRepository<Teacher, Integer>,JpaSpecificationExecutor<Teacher>{ Teacher getBytNum(String tNum); } <file_sep>package com.xmut.olt.seventh.handler; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.xmut.olt.seventh.page.StaticPage; import com.xmut.olt.seventh.service.QItemService; import com.xmut.olt.seventh.service.StudentService; import com.xmut.olt.seventh.service.TeacherService; /** *控制类 * @author 叶文清 * @since 2019年1月2日 */ @Controller public class IndexHandler { @Autowired private TeacherService teacherService; @Autowired private QItemService qItemService; @Autowired private StudentService studentService; @RequestMapping("/") public String index(HttpServletRequest request) { String view=StaticPage.INDEX; ServletContext servletContext = request.getServletContext(); if(servletContext.getAttribute("countTeacher")==null) { long countTeacher = teacherService.count(); long countStudent = studentService.count(); long countQItem = qItemService.count(); servletContext.setAttribute("countTeacher", countTeacher); servletContext.setAttribute("countStudent", countStudent); servletContext.setAttribute("countQItem", countQItem); } return view; } } <file_sep>package com.xmut.olt.seventh.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import com.xmut.olt.seventh.entity.QType; public interface QTypeRepository extends JpaRepository<QType, Integer>,JpaSpecificationExecutor<QType>{ public QType getByqtid(Integer qtid); }
30d4bcf4c2817d388e7e2e4a18a1c65ffbcea270
[ "Java", "INI" ]
7
INI
YWQ98/OnlineTestYWQ
5d9ce813d0f783489795950fc817a68f7575b127
1373caee6093681148778a6ae5cf68c991575c05
refs/heads/master
<file_sep>use sakila; -- 1a Display the first and lastname of all the actors select first_name, last_name from actor; -- 1b Display the first and lastname of all the actors in upper case letters in a single column select CONCAT(UPPER(a.first_name), ' ', UPPER(a.last_name)) as ACTOR_NAME from actor a; -- 2a Find the ID number, firstname, last name of the actor whose First name is "Joe" select actor_id, first_name, last_name from actor where first_name = 'Joe'; -- 2b. Find all actors whose last name contain the letters GEN: select actor_id, first_name, last_name from actor where last_name like '%GEN%'; -- 2c. Find all actors whose last names contain the letters LI,order the rows by last name and first name: select actor_id, first_name, last_name from actor where last_name like '%LI%' order by last_name, first_name; -- 2d Display the country_id and country columns of the following countries: Afghanistan, Bangladesh, and China: select country_id, country from country where country in ('Afghanistan', 'Bangladesh', 'China'); -- 3a Add a middle_name column to the table actor. -- Position it between first_name and last_name. Hint: you will need to specify the data type. ALTER TABLE actor ADD middle_name VARCHAR(50) after first_name; -- 3b Change the data type of the 'middle_name' column ALTER TABLE actor MODIFY COLUMN middle_name blob; -- 3c the column 'middle_name' column ALTER TABLE actor DROP COLUMN middle_name; -- 4a. List the last names of actors, as well as how many actors have that last name. SELECT last_name, COUNT(*) AS nb_actors FROM actor GROUP BY last_name; -- 4b List last names of actors and the number of actors who have that last name, -- but only for names that are shared by at least two actors SELECT last_name, COUNT(*) AS nb_actors FROM actor GROUP BY last_name HAVING nb_actors > 1; -- 4c UPDATE actor SET first_name = 'HARPO' WHERE (first_name = 'GROUCHO' AND last_name = 'WILLIAMS'); -- 4d UPDATE actor SET first_name = '<NAME>' WHERE (first_name = 'HARPO' AND last_name = 'WILLIAMS'); -- 5a Locate the schema of the address table DESCRIBE address; CREATE TABLE address ( address_id smallint(5) AUTO_INCREMENT NOT NULL, address varchar(50) NOT NULL, address2 varchar(50), district varchar(20) NOT NULL, city_id smallint(5) NOT NULL, postal_code varchar(10), phone varchar(20) NOT NULL, location geometry NOT NULL , last_update timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (address_id), FOREIGN KEY(city_id) REFERENCES city(city_id) ); -- 6a. Use JOIN to display the first and last names, as well as the address, of each staff member. Use the tables staff and address select s.first_name, s.last_name, ad.address, ad.address, ad.district, ad.postal_code from staff s left join address ad on s.address_id = ad.address_id; -- 6b. Use JOIN to display the total amount rung up by each staff member in August of 2005. select s.last_name, p.staff_id, sum(p.amount) as total_amount from payment p join staff s on s.staff_id = p.staff_id where year(payment_date) = 2005 and month(payment_date) = 08 group by s.staff_id; -- 6c List each film and the number of actors who are listed for that film. Use tables film_actor and film. select f.film_id, f.title, count(a.actor_id) as num_of_actors from film f join film_actor a where f.film_id = a.film_id group by f.title; -- 6d. How many copies of the film Hunchback Impossible exist in the inventory system? select f.film_id, f.title, count(i.film_id) as nb_of_copy from inventory i join film f on i.film_id = f.film_id where f.title = 'Hunchback Impossible'; -- 6e. Using the tables payment and customer and the JOIN command, -- list the total paid by each customer. List the customers alphabetically by last name: select p.customer_id, c.last_name, c.first_name, sum(p.amount) as total_payment from payment p right join customer c on p.customer_id = c.customer_id group by c.last_name order by c.last_name; -- 7a Use subqueries to display the titles of movies starting with the letters K and Q whose language is English. select title from film where title like 'K%' or title like 'Q%' and language_id in (select language_id from language where name = 'English'); -- 7b Use subqueries to display all actors who appear in the film Alone Trip. select first_name, last_name from actor where actor_id in (select actor_id from film_actor where film_id in (select film_id from film where title = 'Alone Trip')); -- 7c. Names and email addresses of all Canadian customers. SELECT first_name, last_name, email FROM customer WHERE address_id IN (SELECT address_id FROM address WHERE city_id IN (SELECT city_id FROM city WHERE country_id IN (SELECT country_id FROM country WHERE country = 'Canada'))); -- 7d Identify all movies categorized as family films. SELECT title FROM film WHERE film_id IN (SELECT film_id FROM film_category WHERE category_id IN (SELECT category_id FROM category WHERE name = 'Family')); -- 7e. Display the most frequently rented movies in descending order. SELECT f.title, COUNT(i.inventory_id) AS FreqRent FROM film AS f JOIN inventory as i ON i.film_id = f.film_id JOIN rental AS r ON r.inventory_id = i.inventory_id GROUP BY f.title ORDER BY FreqRent DESC; -- 7f. Write a query to display how much business, in dollars, each store brought in. SELECT s.store_id, SUM(p.amount) as revenue FROM store s JOIN inventory AS i ON s.store_id = i.store_id JOIN rental AS r ON i.inventory_id = r.inventory_id JOIN payment AS p ON r.rental_id = p.rental_id GROUP BY s.store_id; -- 7g. Write a query to display for each store its store ID, city, and country. SELECT s.store_id, c.city, co.country FROM store s JOIN address AS a ON s.address_id = a.address_id JOIN city AS c ON c.city_id = a.city_id JOIN country AS co ON co.country_id = c.country_id; -- 7h. List the top five genres in gross revenue in descending order SELECT c.name, SUM(p.amount) AS revenue FROM category c JOIN film_category AS fc ON c.category_id = fc.category_id JOIN inventory AS i ON fc.film_id = i.film_id JOIN rental AS r ON r.inventory_id = i.inventory_id JOIN payment AS p ON p.rental_id = r.rental_id GROUP BY c.name ORDER BY revenue DESC LIMIT 5; -- 8a Create a view of the Top five genres by gross revenue. CREATE VIEW TopFiveGenresGrossrevenue AS SELECT c.name, SUM(p.amount) AS revenue FROM category c JOIN film_category AS fc ON c.category_id = fc.category_id JOIN inventory AS i ON fc.film_id = i.film_id JOIN rental AS r ON r.inventory_id = i.inventory_id JOIN payment AS p ON p.rental_id = r.rental_id GROUP BY c.name ORDER BY revenue DESC LIMIT 5; -- 8b Display the view of the Top five genres by gross revenue. SELECT * FROM TopFiveGenresGrossrevenue; -- 8c Delete the view of the Top five genres by gross revenue. DROP VIEW TopFiveGenresGrossrevenue;
972776590c4860f1fa80f8ddbff2e3c68e3ee9e0
[ "SQL" ]
1
SQL
lkkouam/SQL-Homework
3e4f673b7afa89e806a573042e49855fdcda9927
4fcd7286192893809b82bcf95f1db799ebcb36cd
refs/heads/master
<repo_name>radhagithub2304/Framework<file_sep>/pages/loginpage.py class Loginpage1: def __init__(self, driver): self.driver = driver self.unlocator = 'j_username' self.unpassword = '<PASSWORD>' def enter_username(self): self.driver.find_element_by_id("j_username").send_keys("admin") def enter_password(self): self.driver.find_element_by_name(self.unpassword).send_keys("<PASSWORD>")
0c57ce4ed2ab657246ea72b079b9e1f0016832a2
[ "Python" ]
1
Python
radhagithub2304/Framework
335b2f00160b79f2e5f28b2826d4e8a9903dc19a
68f251f047ab3c53eaa61c7c7c7e7f52bbf0758e
refs/heads/master
<repo_name>LeonardoBAV/perfect-test-backend<file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* Telas para ver o funcionamento sem dados */ Route::get('/', function () { return view('dashboard'); }); Route::get('/sales', function () { return view('crud_sales'); }); Route::get('/products', function () { return view('crud_products'); });
6e6546ec988a9106007a5a52ca9450e9bfb9435f
[ "PHP" ]
1
PHP
LeonardoBAV/perfect-test-backend
65ca526f87fc15818b5d1dfd3f74a5f364318a9c
31c9153b4bf0bbb98b1b798c9f79cd9f3acad8f5
refs/heads/master
<file_sep>codigo do arduino <file_sep>#include <ESP8266WiFi.h> #define capacidade 6//quatidade de cadeiras //estado das cadeiras {0=livre, 1= ocupada} int stbt1 = 0; int stbt2 = 0; int stbt3 = 0; int stbt4 = 0; int stbt5 = 0; int stbt6 = 0; //sensores int sensor1 = 1;//sensor 1 int sensor2 = 1;//sensor 2 int sts1;//estado atual do sensor 1 int sts2;//estado atual do sensor 2 int sts1a,sts2a;//estado anterior //contadores int cont;//contador geral int lugares;//contador de lugares ocupados const char* ssid = "Crazzy Host";//Rede a qual o modulo estará conectado const char* password = <PASSWORD>";//Senha da Rede WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); // Connectar a rede wifi Serial.println(); Serial.println(); Serial.print("Connectando a "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi conectado"); // Inicialização do servidor server.begin(); Serial.println("Servidor iniciado"); Serial.println(WiFi.localIP()); } String ler_st(int stbt) { if (stbt == 1){ return "Ocupada"; }else{ return "Livre"; } } String ler_sensores(){ String st_sensores; sts1a=sts1; sensor1 = digitalRead(D0); if (sensor1 == 0) { st_sensores += "Sensor 1 :: Movimento - <a id=\"s1\"> Detectado </a><br>"; digitalWrite(D3, HIGH); sts1=1; } else{ st_sensores += "Sensor 1 :: Movimento - <a id=\"s1\"> Ausente </a><br>"; digitalWrite(D3, LOW); sts1=0; } st_sensores +="<br>"; sts2a=sts2; sensor2 = digitalRead(D7); if (sensor2 == 0) { st_sensores += "Sensor 2 :: Movimento - <a id=\"s2\"> Detectado </a><br>"; digitalWrite(D3, HIGH); sts2=1; } else{ st_sensores += "Sensor 2 :: Movimento - <a id=\"s2\"> Ausente </a><br>"; digitalWrite(D3, LOW); sts2=0; } return st_sensores; } String movimento_capacidade(){ String mov_cap; mov_cap += "<h4> Status de Movimento</h4>"; mov_cap += " Status :: "; if(sts1a==1 && sts1==0 && sts2==1 ){ mov_cap += "<a id=\"status\"> Entrada</a><br>"; cont++; } if (sts2a==1 && sts2==0 && sts1==1){ mov_cap += "<a id=\"status\"> Saida</a><br>"; cont--; } if (sts2==1 && sts1==1){ mov_cap += "<a id=\"status\"> possivel problema nos sensores detectado</a><br>"; } if (sts2==0 && sts1==0){ mov_cap += "<a id=\"status\"> Inativo</a><br>"; } if(cont<0){ cont=0; } mov_cap += "<h4> Status de Capacidade</h4>"; if(cont >= capacidade){ mov_cap += "<a id=\"capacidade\">Superlotação</a><br>"; mov_cap += "Lugares disponiveis :: "; mov_cap += "<a id=\"lugdisponiveis\">0</a><br>"; } else { mov_cap += "Lugares disponiveis :: "; lugares = capacidade - cont; mov_cap += "<a id=\"lugdisponiveis\">"; mov_cap +=lugares; mov_cap +="</a><br>"; } if(lugares <0){ lugares =0; } mov_cap += "<br>"; mov_cap += "Contador :: "; mov_cap += "<a id=\"contador\">"; mov_cap += cont; mov_cap += "</a><br>"; return mov_cap; } void loop() { WiFiClient client = server.available(); if (!client) { return; } Serial.println("Novo cliente"); while(!client.available()){ delay(1); } String req = client.readStringUntil('\r'); Serial.println(req); client.flush(); String pag = ""; pag += "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n"; pag += "<html lang=\"en\"><head><meta http-equiv='refresh' content='3' name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>\r\n"; pag += "<title>ESP8266 Web Server</title>"; pag += "<style>.c{text-align: center;} div,input{padding:5px;font-size:1em;} input{width:80%;} body{text-align: center;font-family:verdana;} button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;} .q{float: right;width: 64px;text-align: right;}</style>"; pag += "</head>"; pag += "<h3>ESP8266 Web Server</h3>"; pag += "<h3>Sistema de controle de fluxo</h3>"; pag += "<h4>Status de Cadeiras: </h4>"; pag += "Cadeira 1 :: "; stbt1 = digitalRead(D1); pag += "<a id=\"c1\">"+ler_st(stbt1)+"</a><br>"; pag += "<br> Cadeira 2 :: "; stbt2 = digitalRead(D2); pag += "<a id=\"c2\">"+ler_st(stbt2)+"</a><br>"; pag +="<br> Cadeira 3 :: "; stbt3 = digitalRead(D4); pag += "<a id=\"c3\">"+ler_st(stbt3)+"</a><br>"; pag += "<br> Cadeira 4 :: "; stbt4 = digitalRead(D5); pag += "<a id=\"c4\">"+ler_st(stbt4)+"</a><br>"; pag += "<br> Cadeira 5 :: "; stbt5 = digitalRead(D6); pag += "<a id=\"c5\">"+ler_st(stbt5)+"</a><br>"; pag += "<br> Cadeira 6 :: "; stbt6 = digitalRead(D8); pag += "<a id=\"c6\">"+ler_st(stbt6)+"</a><br>"; pag += "<h4> Status dos sensores</h4>"; pag += ler_sensores(); pag += movimento_capacidade(); pag += "</html>\n"; client.print(pag); client.flush(); } <file_sep>imagens do banco de dados e eventuais arquivos <file_sep>pagina gerada pela esp pagina em desenvolvimento <file_sep># Dw-flowing coisas do projeto
983ef8d637ad765086121eac81d0599558a9e1ec
[ "Markdown", "C++" ]
5
Markdown
angeloplacebo/Dw-flowing
e518e488968a23c58390807e743105d15e598946
2cd02a9fb1404c2128b721cdbaad175409cde4b3
refs/heads/master
<repo_name>Lumenwright/GGJ2020AR<file_sep>/Assets/Scripts/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager instance; public string gameID; public Game game; DataManager dataManager; public Player playerPrefab; Player player; private void Awake() { instance = this; game = new Game(); } // Start is called before the first frame update void Start() { dataManager = DataManager.instance; player = FindObjectOfType<Player>(); // if there is a gameID in the manager than that will be used. Otherwise it will create a random one // dataManager.CreateNewGame(gameID); } // Update is called once per frame void Update() { } public void CreateNewGame(string id) { // create a new game if (id == "") { game.code = Random.Range(1000, 9999).ToString(); } else game.code = id; dataManager.WriteGameDataToFirebase(); // instantiate the player player = Instantiate(playerPrefab); player.transform.position = game.playerPosition; } public void MovePlayer() { player.transform.position = game.playerPosition; } } <file_sep>/Assets/Scripts/Game.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class Game { public string code; public Vector3 playerPosition; public Game() { } }
06cbf43f37acb7e25de86b0d42db26067265daca
[ "C#" ]
2
C#
Lumenwright/GGJ2020AR
c9a794055aa9b36a6122bbb266d325abfe1b7443
98e01c64a30292217b35619b7d5bc27a30ec8c3c
refs/heads/master
<file_sep>package org.petehering.game.btree; public class UntilSuccess<T> extends Decorator<T> { public UntilSuccess(Task<T> child) { super(child); } @Override public Task<T> copy() { return new UntilSuccess(child.copy()); } @Override public void execute(float elapsed, T model) { child.execute(elapsed, model); if(child.isFailure()) { child.reset(); } else if(child.isSuccess()) { succeed(); } } } <file_sep>package org.petehering.game.view; import java.util.Arrays; import java.util.Objects; public class Stage { private final Layer[] layers; public final int width; public final int height; public Stage(int width, int height, int layers) { if(width <= 0) { throw new RuntimeException("width <= 0"); } if(height <= 0) { throw new RuntimeException("height <= 0"); } if(layers <= 0) { throw new RuntimeException("layers <= 0"); } this.width = width; this.height = height; this.layers = new Layer[layers]; for(int i = 0; i < layers; i++) { this.layers[i] = new Layer(); } } public void markInsert(Sprite s, int layer) { if(layer < layers.length) { layers[layer].markInsert(Objects.requireNonNull(s)); } else { throw new RuntimeException("layer >= layers.length"); } } public void markRemove(Sprite s, int layer) { if(layer < layers.length) { layers[layer].markRemove(Objects.requireNonNull(s)); } else { throw new RuntimeException("layer >= layers.length"); } } public void clearMarkedSprites() { for(Layer l : layers) { l.clearMarkedSprites(); } } public Iterable<Layer> layers() { return Arrays.asList(layers); } } <file_sep>package org.petehering.game.ces; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.Stack; public class Engine<T> implements Manager { private final T MODEL; private final Set<Entity> USED, CREATE, DELETE; private final Stack<Entity> UNUSED; private final List<Processor<T>> PROCESSORS; public Engine(T model) { this.MODEL = Objects.requireNonNull(model); this.USED = new HashSet<>(); this.CREATE = new HashSet<>(); this.DELETE = new HashSet<>(); this.UNUSED = new Stack<>(); this.PROCESSORS = new ArrayList<>(); } @Override public Query query() { return new Query(this.USED); } @Override public Entity create() { if(this.UNUSED.isEmpty()) { for(int i = 0; i < 20; i++) { this.UNUSED.push(new Entity()); } } Entity e = this.UNUSED.pop(); this.CREATE.add(e); return e; } @Override public void delete(Entity entity) { if(this.USED.contains(entity)) { this.DELETE.add(entity); } } public boolean add(Processor<T> p) { return this.PROCESSORS.add(p); } public void tick(float elapsed) { // update this.PROCESSORS .stream() .filter((p) -> (p.isEnabled())) .forEach((p) -> { p.update(elapsed, this, MODEL); }); // delete this.DELETE.stream().forEach((Entity e) -> { this.USED.remove(e); e.clear(); this.UNUSED.push(e); }); this.DELETE.clear(); // create this.USED.addAll(CREATE); this.CREATE.clear(); // commit this.USED.forEach((Entity e) -> e.commit()); } } <file_sep>package org.petehering.game.app; import java.util.Objects; public class Main implements ViewObserver { private final Game GAME; private final View VIEW; private final Loop LOOP; public Main(Game game, Painter painter, String title, int width, int height) { GAME = Objects.requireNonNull(game); VIEW = new View(GAME, this, painter, title, width, height); LOOP = new Loop(GAME, VIEW); } public void launch() { VIEW.open(); LOOP.start(); } @Override public void viewClosing(View view) { LOOP.interrupt(); } } <file_sep>package org.petehering.game.view; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Point; import java.awt.geom.Rectangle2D; import java.util.Objects; public class TextSprite implements Sprite { private static final Font DEFAULT_FONT = Font.decode("SansSerif-PLAIN-12"); private static final Color DEFAULT_COLOR = Color.BLACK; private final String text; private final Font font; private final Color color; private int x, y; public TextSprite(String text, int x, int y) { this(text, x, y, DEFAULT_FONT, DEFAULT_COLOR); } public TextSprite(String text, int x, int y, Font font) { this(text, x, y, font, DEFAULT_COLOR); } public TextSprite(String text, int x, int y, Color color) { this(text, x, y, DEFAULT_FONT, color); } public TextSprite(String text, int x, int y, Font font, Color color) { this.x = x; this.y = y; this.text = Objects.requireNonNull(text); this.font = Objects.requireNonNull(font); this.color = Objects.requireNonNull(color); } @Override public void draw(Graphics g, int xOffset, int yOffset) { g.setFont(font); g.setColor(color); g.drawString(text, x - xOffset, y - yOffset); } @Override public Point getPosition(Graphics g) { return new Point(x, y - g.getFontMetrics(font).getDescent()); } @Override public Dimension getSize(Graphics g) { FontMetrics fm = g.getFontMetrics(font); Rectangle2D rect = fm.getStringBounds(text, g); int w = (int) Math.round(rect.getWidth()); int h = (int) Math.round(rect.getHeight()); return new Dimension(w, h); } } <file_sep>package org.petehering.game.ces; public interface Component { } <file_sep>package org.petehering.game.demos.a; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import org.petehering.game.app.AbstractGame; import org.petehering.game.app.Main; import org.petehering.game.app.Painter; public class DemoA extends AbstractGame implements Painter { public static void main(String[] args) throws IOException { DemoA demo = new DemoA(); Main main = new Main(demo, demo, "Demo A", 640, 480); main.launch(); } private final Image blue, red; private int x, y; private DemoA() throws IOException { URL url = getClass().getResource("/blue-ball.png"); blue = ImageIO.read(url); url = getClass().getResource("/red-ball.png"); red = ImageIO.read(url); x = -256; y = -256; } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, 640, 480); g.drawImage(blue, x, 0, null); g.drawImage(red, 0, y, null); } @Override public void update(long elapsed) { x = (x < 640)? x + 1 : -256; y = (y < 480)? y + 1 : -256; } @Override public void setUp() throws Exception { } @Override public void shutDown() throws Exception { } } <file_sep>package org.petehering.game.app; public interface ViewObserver { public void viewClosing(View view); } <file_sep>package org.petehering.game.view; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.util.Objects; public class TileSprite extends BaseSprite { private final Tile tile; public TileSprite(Tile tile, int x, int y, int width, int height) { super(x, y, width, height); this.tile = Objects.requireNonNull(tile); } @Override public void draw(Graphics g, int xOffset, int yOffset) { g.drawImage(tile.source, x - xOffset, y - yOffset, x - xOffset + width, y - yOffset + height, tile.x1, tile.y1, tile.x1 + width, tile.y1 + height, null); } @Override public Point getPosition(Graphics g) { return new Point(x, y); } @Override public Dimension getSize(Graphics g) { return new Dimension(width, height); } } <file_sep>package org.petehering.game.view; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; public interface Sprite { public void draw(Graphics g, int xOffset, int yOffset); public Point getPosition(Graphics g); public Dimension getSize(Graphics g); } <file_sep>package org.petehering.game.app; import java.awt.event.KeyListener; import javax.swing.event.MouseInputListener; public interface Game extends KeyListener, MouseInputListener { public void setUp() throws Exception; public void shutDown() throws Exception; public void update(long elapsed); } <file_sep>package org.petehering.game.ces; public abstract class Processor<T> { private boolean enabled; public Processor() { this.enabled = true; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void enable() { this.setEnabled(true); } public void disable() { this.setEnabled(false); } public abstract void update(float elapsed, Manager manager, T model); } <file_sep>package org.petehering.game.demos.c; import org.petehering.game.btree.Repeat; import org.petehering.game.btree.Sequence; public class Wander extends Repeat<Board> { public Wander(Droid droid, int maxX, int maxY) { super(new Sequence<Board>(new SetRandomGoal(droid, maxX, maxY), new MoveTo(droid))); } } <file_sep>package org.petehering.game.demos.c; import java.util.ArrayList; import java.util.List; public class Board { public final int WIDTH, HEIGHT; private final List<Droid> droids; public Board(int width, int height) { this.WIDTH = width; this.HEIGHT = height; this.droids = new ArrayList<>(); } public boolean add(Droid droid) { if(!droids.contains(droid) && isTileOpen(droid.getX(), droid.getY())) { droids.add(droid); return true; } else { return false; } } public boolean isTileOpen(int x, int y) { for(Droid d : droids) { if(d.getX() == x && d.getY() == y) { return false; } } return true; } }
606cae26a1c3a770c5f5983bac6a5eeb5dc695aa
[ "Java" ]
14
Java
pjhering/game-all
c00513287aca928d59acade6a448b45d8654a542
15cbd6c530623bc68b3d96e72503cf359008b8df
refs/heads/master
<file_sep>import React from 'react'; import Header from './Header' import { log } from 'util'; import { get } from 'http'; class App extends React.Component { state = { pageHeader: "Naming Contests" } componentDidMount() { console.log('did mount'); } componentWillUnmount() { console.log('will unmount'); } render() { return ( <div className="App"> <Header message={ this.state.pageHeader }/> </div> ) } } export default App
b8222594aa379633d16758f1023fbd37991a38ee
[ "JavaScript" ]
1
JavaScript
okichan/lynda-react-mongoDB-tutorial
b73e3277f2e8722c8fdac2b3d8f6bfc7dc86a643
5b556056e9a365a8715b579e7d38b707a21fce91
refs/heads/master
<file_sep>module Hashie2 autoload :Clash, 'hashie2/clash' autoload :Dash, 'hashie2/dash' autoload :Hash, 'hashie2/hash' autoload :HashExtensions, 'hashie2/hash_extensions' autoload :Mash, 'hashie2/mash' autoload :PrettyInspect, 'hashie2/hash_extensions' autoload :Trash, 'hashie2/trash' module Extensions autoload :Coercion, 'hashie2/extensions/coercion' autoload :DeepMerge, 'hashie2/extensions/deep_merge' autoload :KeyConversion, 'hashie2/extensions/key_conversion' autoload :IndifferentAccess, 'hashie2/extensions/indifferent_access' autoload :MergeInitializer, 'hashie2/extensions/merge_initializer' autoload :MethodAccess, 'hashie2/extensions/method_access' autoload :MethodQuery, 'hashie2/extensions/method_access' autoload :MethodReader, 'hashie2/extensions/method_access' autoload :MethodWriter, 'hashie2/extensions/method_access' autoload :StringifyKeys, 'hashie2/extensions/key_conversion' autoload :SymbolizeKeys, 'hashie2/extensions/key_conversion' end end
fcdb68cdc4c519b417053e112960024a7711682b
[ "Ruby" ]
1
Ruby
doublewide/hashie2
dd61c4563ecf767b69878761bea60eda432ef11e
1e4dc4c3dfe1fc2737b92270fe33e17657a61f58
refs/heads/main
<repo_name>priva13/Logo_detection<file_sep>/detect.py from tkinter import * from tkinter import messagebox from tkinter import filedialog import cv2 import numpy as np thumbstack_cascade = cv2.CascadeClassifier("cascade.xml") root= Tk() root.title("Thumbstack Logo detection using python") root.geometry('500x500') def openfileselectionbox(): filepath= filedialog.askopenfilename(title="Select an Image file", filetypes=(("PNG files" ,"*.png"),("JPG files","*.jpg"))) img= cv2.imread("C:/Users/Pia/Documents/Logo Detetion/2.png") gray= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) logo = thumbstack_cascade.detectMultiScale(gray,1.11,5) for(x,y,w,h) in logo: img= cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) cv2.imshow("Logos", img) cv2.waitKey(0) # messagebox.showinfo("showinfo", filepath) def opencameradetector(): vid = cv2.VideoCapture(0) while(True): ret, frame = vid.read() gray= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) logo = thumbstack_cascade.detectMultiScale(gray,1.11,5) for(x,y,w,h) in logo: frame= cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) cv2.imshow('frame', frame) key = cv2.waitKey(10) if cv2.getWindowProperty("frame", cv2.WND_PROP_VISIBLE) <1: break vid.release() cv2.destroyAllWindows() button = Button(root, text = 'Detect Logo by Image file',command=openfileselectionbox) button.pack(side = TOP, pady = 5) button2 = Button(root, text = 'Detect Logo by camera',command=opencameradetector) button2.pack(side = TOP, pady = 5) root.mainloop()<file_sep>/README.md # Thumbstack Logo Detection Using Python ## Modules used - opencv - tkinter - numpy ## How it works ### Getting cascade.xml file - Collectting various Positive Images of Logo - Collectting various Negative Images of Logo - Train it using opencv and get cascade.xml file (It is very computational process that can be take much time) ### Using tkinter for GUI - Tkinter is an inbuild module in python - Using tkinter I added two button on gui - Added specific Function on each `command` - First button is for Detect logo from system's image file - Second button is for Detect logo in camera frame ### Using opencv and cascade.xml file for detection For First Button - On clicking first button then open cv2 will get the filepath using `filedialog` method is tkinter - Using `imread` method it will open the image - Using `cvtColor` to convert image to grayscale - Using `thumbstack_cascade.detectMultiScale(gray,1.11,5)` it will detect the logo - Using `for` loop It will draw the `rectangle` around the logo on image - And finally I will show the Image using `imshow` method For Second Button - Starting a camera `frame` using opencv - In the camera frame `while` loop It will do the same process as in first button - In this loop it will detect and the logo and show on the frame rounded with blue rectangle
dacdd942b79897353c7acefbd26585086f471c9b
[ "Markdown", "Python" ]
2
Python
priva13/Logo_detection
bc3cfb85754b5c47c54a3efbf52a93006ad93344
7d33baae22b2f1fc2326491debf814a4ae241928
refs/heads/master
<file_sep>#include "basic.h" int main() { BasicDemo demo; return demo.run(); } <file_sep>#pragma once #include "DSPNode.h" class OSC_Sine: public DSPNode { public: OSC_Sine(float phase, float freq, float gain) : DSPNode(), phase(phase), freq(freq), gain(gain) {} uint8_t step() { size_t len = AUDIO_BUFFER_SIZE; // phase increment = hz (cycles per second) / sample rate (samples per second) float inc = (freq / (float)SAMPLE_RATE) * TAU; for (int i = 0; i < len; ++i) { phase += inc; TRUNC_PHASE(phase); buffer[i] = fast_sin(phase) * gain; } return 0; } float freq; private: float phase; float gain; }; class OSC_Square: public DSPNode { public: OSC_Square(float phase, float freq, float gain) : DSPNode(), phase(phase), freq(freq), gain(gain) {} uint8_t step() { size_t len = AUDIO_BUFFER_SIZE; // phase increment = hz (cycles per second) / sample rate (samples per second) float inc = (freq / (float)SAMPLE_RATE) * TAU; for (int i = 0; i < len; ++i) { phase += inc; TRUNC_PHASE(phase); buffer[i] = (phase < PI ? gain : -gain); } return 0; } float freq; private: float phase; float gain; }; <file_sep>cmake_minimum_required(VERSION 3.9) project(demos) set(CMAKE_CXX_STANDARD 11) # demo: basic add_executable(basic demos/demo.h demos/basic.h demos/basic.cpp src/DSPStack.h src/DSPNode.h src/OSC.h src/mathx.h src/IIR.h) # include synth src include_directories(src) # requirements for OS X version of dagwood find_library(PORTAUDIO portaudio) target_link_libraries(basic ${PORTAUDIO}) find_library(RTMIDI rtmidi) target_link_libraries(basic ${RTMIDI}) <file_sep>#pragma once #include "demo.h" class BasicDemo : public Demo { public: BasicDemo() : Demo() { DSPStack* stack1 = new DSPStack(); osc1 = new OSC_Square(0, 440, 0.6); stack1->append(osc1); filter = new IIR_LowPass(osc1, 220.0f, 0.8); stack1->append(filter); synth->append(stack1); } ~BasicDemo() { delete osc1; } void handleMidiControlChange(uint8_t function, uint8_t value) override { // slider mappings if (function == 0) { // osc1 freq osc1->freq = mapf((float)value, 0.0, 127, 120, 980); } if (function == 1) { // filter freq filter->setCutoff(mapf((float)value, 0, 127, 20, 440)); } if (function == 2) { // filter res filter->setRes(mapf((float)value, 0, 127, 0, 0.95)); } } private: OSC_Square* osc1; IIR_LowPass* filter; }; <file_sep>#pragma once #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include "mathx.h" #ifndef AUDIO_BUFFER_SIZE #define AUDIO_BUFFER_SIZE 32 #endif #ifndef SAMPLE_RATE #define SAMPLE_RATE 44100 #endif #define TRUNC_PHASE(phase) phase = wrapf(phase, TAU); #include "DSPStack.h" class Synth { public: Synth() {} ~Synth() {} void append(DSPStack* stack) { stacks.push_back(stack); stack->activate(); } void render(size_t frames, float* out) { for (size_t i = 0, num = frames / AUDIO_BUFFER_SIZE; i < num; i++) { // step all stacks for (int i=0; i < stacks.size(); i++) { stacks[i]->step(); } // mix down output from all stacks mixdown(&out[i * AUDIO_BUFFER_SIZE], AUDIO_BUFFER_SIZE); } } private: std::vector<DSPStack*> stacks; void mixdown(float *out, size_t len) { // sum all stack outputs per sample size_t offset = 0; size_t stride = 1; while (len--) { float sum = 0; for (int i=0; i < stacks.size(); i++) { sum += stacks[i]->sample(offset); } // // clip output // if (sum < -1.0f) { // sum = -1.0f; // } else if (sum > 1.0f) { // sum = 1.0f; // } *out = sum; out += stride; offset += stride; } } }; <file_sep>#pragma once #include <stdio.h> #include <iostream> #include <portaudio.h> #include <RtMidi.h> #include "Synth.h" #include "OSC.h" #include "IIR.h" class Demo { public: Demo() : synth{new Synth} {} int run() { PaStream *stream; PaError err; err = Pa_Initialize(); if (err != paNoError) { return handleError(err); } err = Pa_OpenDefaultStream(&stream, 0, /* no input channels */ 1, // output channels (mono/stereo) paFloat32, // 32 bit floating point output SAMPLE_RATE, 256, // frames per buffer, number of samples PortAudio will request from callback render_synth, this); // pointer you can send to yourself if (err != paNoError) { return handleError(err); } err = Pa_StartStream(stream); if (err != paNoError) { return handleError(err); } // init MIDI try { midiin = new RtMidiIn(); // attempt to connect to NanoKontrol unsigned int nPorts = midiin->getPortCount(); std::string portName; for (unsigned int i = 0; i < nPorts; i++ ) { try { portName = midiin->getPortName(i); if (portName.compare("nanoKONTROL2 SLIDER/KNOB") == 0) { // found nanoKONTROL2 std::cout << "FOUND nanoKONTROL2 :: Input Port #" << i+1 << ": " << portName << '\n'; midiin->openPort(i); midiin->setCallback(this->midiInCallback, this); std::cout << "\nReading MIDI input...\n"; } } catch (RtMidiError &error) { return handleMidiError(error); } } } catch (RtMidiError &error) { return handleMidiError(error); } // block here until user chooses to quit std::cout << "\npress <enter> to quit.\n"; char input; std::cin.get(input); err = Pa_StopStream(stream); if (err != paNoError) { return handleError(err); } err = Pa_CloseStream(stream); if (err != paNoError) { return handleError(err); } Pa_Terminate(); return 0; } virtual void handleMidiControlChange(uint8_t function, uint8_t value) = 0; static int render_synth(const void *in, void *out, unsigned long frames, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags status, void *data) { Demo* demo = (Demo*)data; demo->synth->render(frames, (float*)out); return 0; } protected: Synth* synth; private: RtMidiIn* midiin; PaError handleError(PaError err) { Pa_Terminate(); fprintf(stderr, "An error occurred while using the portaudio stream\n"); fprintf(stderr, "Error number: %d\n", err); fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(err)); return err; } int handleMidiError(RtMidiError error) { error.printMessage(); return -1; } static void midiInCallback(double deltatime, std::vector< unsigned char > *message, void *userData) { Demo* demo = (Demo*)userData; unsigned int nBytes = message->size(); // first byte determines message type uint8_t type = message->at(0); if (type == 0xB0) { // control channel 0 if (nBytes == 3) { uint8_t function = message->at(1); uint8_t value = message->at(2); std::cout << "Control Change: " << (int)function << " = " << (int)value << std::endl; demo->handleMidiControlChange(function, value); } } } };<file_sep>cmake_minimum_required(VERSION 3.9) project(dagwood) set(CMAKE_CXX_STANDARD 11) add_executable(dagwood Synth.cpp Synth.h) <file_sep>#pragma once #include "DSPNode.h" class IIR_LowPass: public DSPNode { public: IIR_LowPass(DSPNode* source, float cutoff, float res) : DSPNode(), source(source), cutoff(cutoff), res(res) { freq = 2.0f * sinf(PI * fminf(0.25f, cutoff / (SAMPLE_RATE * 2.0f))); damp = fminf(2.0f * (1.0f - powf(res, 0.25f)), fminf(2.0f, 2.0f / freq - freq * 0.5f)); printf("freq: %f, damp: %f\n", freq, damp); f[0] = 0.0f; // lp f[1] = 0.0f; // hp f[2] = 0.0f; // bp f[3] = 0.0f; // notch } uint8_t step() { size_t len = AUDIO_BUFFER_SIZE; float* src = source->buffer; for (int i = 0; i < len; ++i) { float input = *src++; // 1st pass f[3] = input - damp * f[2]; *f += freq * f[2]; f[1] = f[3] - *f; f[2] += freq * f[1]; float output = f[type]; // 2nd pass f[3] = input - damp * f[2]; *f += freq * f[2]; f[1] = f[3] - *f; f[2] += freq * f[1]; output = 0.5f * (output + f[type]); buffer[i] = output; } return 0; } void setCutoff(float c) { cutoff = c; freq = 2.0f * sinf(PI * fminf(0.25f, cutoff / (SAMPLE_RATE * 2.0f))); damp = fminf(2.0f * (1.0f - powf(res, 0.25f)), fminf(2.0f, 2.0f / freq - freq * 0.5f)); } void setRes(float r) { res = r; freq = 2.0f * sinf(PI * fminf(0.25f, cutoff / (SAMPLE_RATE * 2.0f))); damp = fminf(2.0f * (1.0f - powf(res, 0.25f)), fminf(2.0f, 2.0f / freq - freq * 0.5f)); } private: DSPNode* source; int type = 0; // low pass float cutoff; float res; float freq; float damp; float f[4]; }; <file_sep>#pragma once #include "math.h" #define PI 3.1415926535897932384626433832795029f #define TAU (2.0f * PI) #define HALF_PI (0.5f * PI) //#define QUARTER_PI (0.25f * CT_PI) //#define INV_TAU (1.0f / CT_TAU) //#define INV_PI (1.0f / CT_PI) #define INV_HALF_PI (1.0f / HALF_PI) //#define DEGREES (180.0f / CT_PI) //#define RADIANS (PI / 180.0f) static inline float wrapf(const float x, const float domain) { return ((x < 0.f) ? (domain + x) : (x >= domain ? (x - domain) : x)); } static inline float mixf(const float a, const float b, const float t) { return a + (b - a) * t; } static inline float mapf(const float x, const float a, const float b, const float c, const float d) { return mixf(c, d, (x - a) / (b - a)); } static inline float fast_cos_impl(const float x) { const float x2 = x * x; return 0.99940307f + x2 * (-0.49558072f + 0.03679168f * x2); } static inline float fast_cos(float x) { x = fmodf(x, TAU); if (x < 0) { x = -x; } switch ((size_t)(x * INV_HALF_PI)) { case 0: return fast_cos_impl(x); case 1: return -fast_cos_impl(PI - x); case 2: return -fast_cos_impl(x - PI); default: return fast_cos_impl(TAU - x); } } static inline float fast_sin(float x) { return fast_cos(HALF_PI - x); } <file_sep>// // Created by <NAME> on 4/12/18. // #include "Synth.h" <file_sep>#pragma once #include "Synth.h" #include "stdio.h" class DSPNode { public: DSPNode() : active{false}, next{nullptr}, buffer{new float[AUDIO_BUFFER_SIZE]} {} ~DSPNode() { delete[] buffer; } virtual uint8_t step() = 0; void trace() { // CT_DEBUG("-- %s --", node->id); fprintf(stdout, "some node == "); for (int i = 0; i < AUDIO_BUFFER_SIZE; i++) { fprintf(stdout, "%03d: %f, ", i, buffer[i]); } fprintf(stdout, "\n"); } float *buffer; DSPNode* next; private: bool active; };
09c2e6393094f1c6d053fe120ba96e0cbef9eb82
[ "C", "CMake", "C++" ]
11
C++
kylestew/dagwood
a7a2350bfe738a64e5005570be9a51efc8ff6e84
12e901e2af02d8456fe2ca1c27c981df606d6c10
refs/heads/main
<file_sep># algorithms-and-datastructures Collection of algorithms and datastructers <file_sep>package graphs.bfs import java.util.* class BFS { fun prepareAdjacencyList(): Map<Int, Set<Int>> { return mapOf( 1 to setOf(2, 3, 4), 2 to setOf(4, 5), 3 to setOf(4, 6), 4 to setOf(5, 6) ) } fun bfs(nodesCount: Int, startNode: Int, endNode: Int): Array<Int> { val result = LinkedList<Int>() val adjacencyLists = prepareAdjacencyList() val visited = Array(nodesCount + 1) { false } val nodesToVisit = LinkedList<Int>() nodesToVisit.add(startNode) val previous = IntArray(nodesCount + 1) { -1 } val distance = IntArray(nodesCount + 1) { -1 } distance[startNode] = 0 while (nodesToVisit.isNotEmpty()) { val node = nodesToVisit.poll() visited[node] = true adjacencyLists[node]?.forEach { if (!visited[it]) { visited[it] = true nodesToVisit.add(it) // this is not needed for this problem previous[it] = node distance[it] = distance[node] + 6 } } } distance.forEachIndexed { index, value -> if (index > 0 && value != 0) { result.add(value) } } return result.toTypedArray() } } <file_sep> rootProject.name = "algorithms-and-datastructers"
4040de53c9472951a95c5f86dab134edcda47842
[ "Markdown", "Kotlin" ]
3
Markdown
rixspi/algorithms-and-datastructures
b27fb152628e7231dc19e161233dd2fb5f06bbd9
09b819d152b53c622a27f0718a391178aeb1b905
refs/heads/master
<repo_name>MichielBaptist/SudokuParser<file_sep>/SudokuParser/scripting.py import parse import cv2 as cv import loading import os import utils as ut import matplotlib.pyplot as plt def parseLabels(f): return [[e.strip() for e in r.split(" ")] for r in f] # Where is the data? s_x = "sudokus/x" s_y = "sudokus/y" # Where should the chopped digits go? out_n = "digits" out_f = (out_n, [(f"{i}",[]) for i in range(10)]) ut.deleteOutDirStructure(out_f) ut.createOutDirStructure(out_f) # Read all sudokus and labels suds_x = sorted(os.listdir(s_x)) suds_y = sorted(os.listdir(s_y)) print(f"Putting digits in {out_n}") for (x_p, y_p) in zip(suds_x, suds_y): # Chop sudoku and attatch label xs = parse.chopSudoku_path(os.path.join(s_x, x_p)) ys = parseLabels(open(os.path.join(s_y, y_p))) print(f"Chopping sudoku: {x_p}") for xr, yr in zip(xs,ys): for x,y in zip(xr,yr): x_dir = os.path.join(out_n, str(y)) num = len(os.listdir(x_dir)) x_file = os.path.join(x_dir, f"{num}.png") cv.imwrite(x_file, img=x) print(f"Done parsing {len(list(zip(suds_x, suds_y)))} sudokus!") for i in range(10): pth = os.path.join(out_n, str(i)) print(f"Number of {i} images: {len(os.listdir(pth))}") <file_sep>/SudokuParser/recognizer.py import sklearn import numpy as np import os import cv2 as cv import utils as ut from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt class DigitRecognizer: def __init__(self): self.features = [ np.mean, np.median, lambda x: self.meanThresh(x) ] self.rf = RandomForestClassifier() pass def fit(self, X, Y): # 1) Preprocess the data: X = self.resizeAll(X) X = np.array(X) X = X[:,4:28,8:24,:] # 2) Separate digits from non digits # TODO: add utility to take using numpy not list comprehensions? Ids = ut.getIndex(Y, lambda x: x != 0) Y_binary = ut.setIfIndex(Y, Ids, 1) # 3) train a binary classifier # 3.1) convert to grayscale X_gray = applyFToXs( lambda img: cv.cvtColor(img, cv.COLOR_BGR2GRAY), X) X_threshed = applyFToXs( lambda img: cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, blockSize = 3, C = 5), X_gray ) contours = applyFToXs( lambda x: cv.findContours( x, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE )[0], X_threshed ) max_contours = applyFToXs(findMaxContour, contours) bounding_rects = applyFToXs(findBindingRect, max_contours) areas = applyFToXs(findRectArea, bounding_rects) cv.imshow("1", X_threshed[0]) cv.imshow("2", X_threshed[1]) cv.waitKey() print(np.array(X_threshed).shape) means = applyFToXs(np.mean, X_threshed) #print(means) plt.plot(areas, Y_binary, 'd') plt.show() quit() X_flat = np.reshape(X, ()) X = self.extractFeatures(X) self.rf.fit(X, Y) def showDebug(self): for i in range(10): nidxs = ut.getIndex(Y, lambda x: x==i) dat = np.take(X, nidxs, axis = 0) plt.plot(dat[:,2], dat[:,1], 'o', label = f"{i}") plt.legend() plt.show() def resizeAll(self, X): new_size = (32, 32) F = lambda x: cv.resize(x, dsize = new_size, interpolation = cv.INTER_LINEAR) return applyFToXs(F, X) def preProcess(self, X): # 1) X = applyFToXs(lambda x: cv.resize(x, dsize = new_size, interpolation = cv.INTER_LINEAR), X) #print(X) # 1) crop to the digit print(len(X)) print(np.array(X).shape) quit() digitContours = list(map(ut.findLargestContourAT, X)) #cropRect = cv.boundingRect(digitContours) print("Here") # 2) Resize digit to common size return X def extractFeatures(self, X): return np.array(applyFsToXs(self.features, X)) def predict(self, X): X = self.extractFeatures(X) return self.rf.predict(X) def meanThresh(self, img): img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) thresh = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, 5, 3) return np.mean(thresh) def applyFsToXs(Fs, Xs): return list(map(lambda x: applyFsToX(Fs, x), Xs)) def applyFsToX(Fs, X): return list(map(lambda f: f(X), Fs)) def applyFToXs(F, Xs): return list(map(F, Xs)) def loadFile(path): return cv.imread(path) def loadDigitData(str, i): dir = os.path.join(str, f"{i}") files = [os.path.join(dir, f) for f in os.listdir(dir)] Xs = [loadFile(f) for f in files] Ys = [i for j in range(len(Xs))] return (Xs, Ys) def findMaxContour(cntrs): if len(cntrs) == 0: return [] return ut.max(cntrs, cv.contourArea) def findBindingRect(cntr): if len(cntr) == 0: return (0,0,0,0) return cv.boundingRect(cntr) def findRectArea(rect): _, _, w, h = rect return w*h def loadData(str): sets = [loadDigitData(str, i) for i in range(10)] Xs = ut.flatten([X for X,Y in sets], 1) Ys = ut.flatten([Y for X,Y in sets], 1) return Xs, Ys Xs, Ys = loadData("digits") Xs_train, Xs_test, Ys_train, Ys_test = train_test_split(Xs, Ys, test_size = 0.33) rec = DigitRecognizer() rec.fit(Xs_train, Ys_train) Ys_pred = rec.predict(Xs_test) Ytest_nz, Ypred_nz = ut.mutFilter(Ys_test, lambda x: x != 0, Ys_pred) print(accuracy_score(Ytest_nz, Ypred_nz)) print(accuracy_score(Ys_test, Ys_pred)) <file_sep>/SudokuParser/parse.py import cv2 as cv from functools import reduce import utils as ut import transformation as trns import loading import numpy as np def parseSudoku_path(path, params = {}, debug = False): return parseSudoku(loading.loadImage(path), params, debug) def chopSudoku_path(path, params = {}, debug = False): return chopSudoku(loading.loadImage(path), params, debug) def chopSudoku(img, params = None, debug = False): # 1) Find the sudoku in the image. crop_transformations = getCropTrns(params, debug) cropped_sudoku = trns.applyTransformations(img, crop_transformations) # 2) Chop up the cropped image chop_transformations = getChopTrns(params, debug) chopped_sudoku = trns.applyTransformations(cropped_sudoku, chop_transformations ) return chopped_sudoku def parseSudoku(img, params = None, debug = False): params["debug"] = debug # 1) Find the sudoku in the image. crop_transformations = getCropTrns(params, debug) cropped_sudoku = trns.applyTransformations(img, crop_transformations) # 2) Chop up the cropped image chop_transformations = getChopTrns(params, debug) chopped_sudoku = trns.applyTransformations(cropped_sudoku, chop_transformations ) #piece = chopped_sudoku[0][3] #digit_trns = getDigitTrns(params) #trns.applyTransformations(piece, digit_trns) # 3) Digit recognition #parsed_sudoku = parseChoppedSudoku(chopped_sudoku) # Return parsed sudoku return def parseChoppedSudoku(chopped): return [[parseSudokuPiece(p) for p in row] for row in chopped] def parseSudokuPiece(piece_img): # Parse the digits here return 0 def getAllParameters(): lst = ut.flatten([t.getParamList() for t in getCropTrns()]) lst+= ut.flatten([t.getParamList() for t in getChopTrns()]) #lst+= ut.flatten([t.getParamList() for t in getDigitTrns()]) return lst def getDigitTrns(params = {}, debug = False): return [ trns.findDigitTrn(params = params, debug = debug) ] def getChopTrns(params = {}, debug = False): return [ trns.ChopTrn(params = params, debug = debug) ] def getCropTrns(params = {}, debug = False): return [ #trns.RotateTrn(params = params, debug = debug), # Debug and test trns.ResizeTrn(params = params, debug = debug), # Resize trns.CropTrn(params = params, debug = debug), # Crop to sudoku #trns.GridLinesTrn(params = params, debug = debug) # Debug and test ] def reparse(sudoku, params, debug = False): parseSudoku(sudoku, params, debug) def paramChange(name, params, sudoku): return lambda val: setParamValueAndReparse(name, val, params, sudoku) def setParamValueAndReparse(name, val, params, sudoku): print(f"Param: {name} changed to {val}") for k,v in params.items(): print(f"{k} --> {v}") params[name] = val reparse(sudoku, params, True) """ pth = "sudokus/x/12.jpg" sud = loading.loadImage(pth) cv.namedWindow("Parameters") params = getAllParameters() params_dict = {a:c for _,a,_,_,_,c in params} for n, a, l, h, d, c in params: cv.createTrackbar(n, "Parameters", c, h, paramChange(a, params_dict, sud)) cv.imshow("Parameters", np.zeros((1,400))) reparse(sud, params_dict, True) cv.waitKey() """ <file_sep>/SudokuParser/loading.py import cv2 as cv def loadImage(path): # Todo: do some checking return cv.imread(path) <file_sep>/README.md # SudokuParser A simple sudoku parser (WIP) <file_sep>/SudokuParser/transformation.py import numpy as np import cv2 as cv import utils as ut from functools import reduce import imutils import matplotlib.pyplot as plt class Transformation: def __init__(self, debug = False, params = {}): self.debug = debug self.setName() self.setParams(params) def apply(self, original, img): pass def logStr(self, str): return f"{self.getName()} - {str}" def ifDebug(self, fn): if self.debug: fn() def getParamList(self): lst = self.getParamListNCV() lst = [(n, a, l, h, d, self.attrValue(a)) for (n,a,l,h,d) in lst] return lst def getParamListNCV(self): pass def setParams(self, params = {}): for param in self.getParamListNCV(): self.setParam(param, params) def setParam(self, param, params = {}): n, a, l, h, d = param val = d if a not in params else params[a] setattr(self, a, val) def attrValue(self, attr): return None if not hasattr(self, attr) else getattr(self, attr) class findDigitTrn(Transformation): def setName(self): self.name = "Digit" def getName(self): return self.name def threshMethod(self): if self.gaussian: m = cv.ADAPTIVE_THRESH_GAUSSIAN_C else: m = cv.ADAPTIVE_THRESH_MEAN_C return m def getParamListNCV(self): return [ (self.logStr("Gaussian"), "gaussian", 0, 1, 1), (self.logStr("Block Size"), "block_size", 0, 51, 7), (self.logStr("C"), "c", 0, 50, 10), (self.logStr("Opening"), "opening", 0, 20, 3 ) ] def apply(self, original, img): # 1) thresholding to find the digit gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) thresh = cv.adaptiveThreshold(gray, 255, self.threshMethod(), cv.THRESH_BINARY_INV, self.block_size, self.c) kernel = np.ones((self.opening, self.opening), np.uint8) eroded = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel) contours, hierarchy= cv.findContours(eroded, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) #self.ifDebug(lambda : self.paintContours(img, contours, sudoku_contour, corners)) self.ifDebug(lambda : cv.imshow(self.logStr("Digit"), thresh)) self.ifDebug(lambda : cv.imshow(self.logStr("Opening"), eroded)) return def paintContours(self, img, contours, sudoku_contour, corners): img_cp = np.array(img) cv.drawContours(img_cp, contours, -1,ut.BLUE, thickness = 2) cv.drawContours(img_cp, [sudoku_contour], -1, ut.RED, thickness = 2) for cnr in corners: cv.circle(img_cp, tuple(cnr), 5, ut.GREEN, thickness = -1) cv.imshow(self.logStr("Contours"), img_cp) class ChopTrn(Transformation): def setName(self): self.name = "Chop" def getName(self): return self.name def getParamListNCV(self): return [ (self.logStr("Padding"), "padding", 0, 50, 0) ] def imgBlock_index(self, i, j, bs_h, bs_w, img): l = (int)(i*bs_w) r = (int)((i+1)*bs_w) u = (int)(j*bs_h) d = (int)((j+1)*bs_h) return self.imgBlock(u,d,l,r,img) def imgBlock(self, u, d, l, r, img): u, d, l, r = self.blockPadding(u,d,l,r, img) return img[u:d, l:r] def blockPadding(self, u, d, l, r, img): h = img.shape[0] w = img.shape[1] l = max(l - self.padding, 0) r = min(r + self.padding, w - 1) u = max(u - self.padding, 0) d = min(d + self.padding, h - 1) return u,d,l,r def apply(self, original, img): block_size = (img.shape[0]/9, img.shape[1]/9) blocks = [[(i,j) for i in range(9)] for j in range(9)] blocks = [[self.imgBlock_index(*b, *block_size, img) for b in row]for row in blocks] self.ifDebug(lambda : cv.imshow(self.logStr("block"),blocks[0][3])) return blocks class RotateTrn(Transformation): def getParamListNCV(self): return [ (self.logStr("Angle"), "rotation_angle", 0, 180, 0), (self.logStr("Cutaway/full"), "rotation_cut_away", 0, 1, 0) ] def setName(self): self.name = "Rotation" def getName(self): return self.name def apply(self, original, img): if self.rotation_cut_away: transformed = imutils.rotate(img, self.rotation_angle) else: transformed = imutils.rotate_bound(img, self.rotation_angle) return transformed class GridLinesTrn(Transformation): def setName(self): self.name = "Grid lines of 9x9" def getName(self): return self.name def getParamListNCV(self): return [ (self.logStr("Grid line width"), "grid_thick", 0, 10, 3) ] def drawHlines(self, img): h, w, _ = img.shape hf = h/9 for i in range(1, 9): hi = (int)(hf*i) cv.line(img, (0,hi), (w, hi), ut.RED, 2) return np.array(img) def drawVlines(self, img): h, w, _ = img.shape wf = w/9 for i in range(1, 9): wi = (int)(wf*i) cv.line(img, (wi,0), (wi, h), ut.RED, 2) return np.array(img) def apply(self, original, img): gridded = self.drawVlines(self.drawHlines(np.array(img))) self.ifDebug(lambda : cv.imshow(self.logStr("Grid"), gridded)) return gridded class IdentityTrn(Transformation): def apply(self, original, img): return img class CropTrn(Transformation): def setName(self): self.name = "Crop" def getName(self): return self.name def getParamListNCV(self): return [ (self.logStr("Edge detection: Canny/thresholding"), "canny_thresh", 0, 1, 1), (self.logStr("Canny: upper threshold"), "canny_max", 0, 1000, 650), (self.logStr("Canny: lower threshold"), "canny_min", 0, 1000, 250), (self.logStr("Thresholding: Mean/Gaussian"), "thresh_gaussian", 0, 1, 1), (self.logStr("Thresholding: Block size"), "thresh_block_size",0, 70, 21), (self.logStr("Thresholding: C"), "thresh_C",0, 100, 7), (self.logStr("Sobel window"), "sobel_window", 1, 15, 3), (self.logStr("Sobel dx"), "sobel_dx", 0, 9, 1), (self.logStr("Sobel dy"), "sobel_dy", 0, 9, 1) ] def threshMethod(self): if self.thresh_gaussian: m = cv.ADAPTIVE_THRESH_GAUSSIAN_C else: m = cv.ADAPTIVE_THRESH_MEAN_C return m def findEdges(self, img): if not self.canny_thresh: # Find edges with Canny() edges = cv.Canny(img, self.canny_min, self.canny_max) else: gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) edges = cv.adaptiveThreshold(gray, 255, self.threshMethod(), cv.THRESH_BINARY_INV, self.thresh_block_size, self.thresh_C) return edges def apply(self, original, img): # To crop the image to only the sudoku squarem: img_cp = np.array(img) # 1) Find edges in the sudoku edges = self.findEdges(img_cp) self.ifDebug(lambda : cv.imshow(self.logStr("Canny edges"), edges)) # 2) find contours contours, hierarchy = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) # 3) Find the sudoku contour sudoku_contour = self.findSudokuContour(contours) # 4) Find the corners of the contour corners = self.findCorners(sudoku_contour) self.ifDebug(lambda : self.paintContours(img_cp, contours, sudoku_contour, corners)) # 5) Warp the perspective of the sudoku perspective, width, height = self.findSudokuPerspective(corners) warped_img = cv.warpPerspective(img_cp, perspective, (width, height)) self.ifDebug(lambda : cv.imshow(self.logStr("Warped image"), warped_img)) return warped_img def paintContours(self, img, contours, sudoku_contour, corners): img_cp = np.array(img) cv.drawContours(img_cp, contours, -1,ut.BLUE, thickness = 2) cv.drawContours(img_cp, [sudoku_contour], -1, ut.RED, thickness = 2) for cnr in corners: cv.circle(img_cp, tuple(cnr), 5, ut.GREEN, thickness = -1) cv.imshow(self.logStr("Contours"), img_cp) def findCorners(self, cnt): bl = ut.min(cnt[:,0,:], lambda x: x[0] - x[1]) tl = ut.min(cnt[:,0,:], lambda x: x[0] + x[1]) br = ut.min(cnt[:,0,:], lambda x: -x[0]- x[1]) tr = ut.min(cnt[:,0,:], lambda x: -x[0]+ x[1]) return tl, tr, br, bl def findSudokuPerspective(self, frm): tl, tr, br, bl = frm new_width = (int)(max(ut.eucl(tl, tr), ut.eucl(bl, br)) - 1) new_height= (int)(max(ut.eucl(tr, br), ut.eucl(tl, bl)) - 1) mx = max(new_width, new_height) to = [ [0, 0], [mx, 0], [mx, mx], [0, mx] ] perspective = cv.getPerspectiveTransform(np.float32(frm), np.float32(to)) return perspective, mx, mx def findSudokuContour(self, contours, edges = None, hierarchy = None): return ut.max(contours, cv.contourArea) class ResizeTrn(Transformation): def setName(self): self.name = "Resize" def getName(self): return self.name def getParamListNCV(self): return [ (self.logStr("Scale"), "scale", 0, 100, 100), (self.logStr("Maximum width"), "mx_ver",0, 2000, 1300), (self.logStr("Maximum height"), "mx_hor",0, 2000, 1300) ] def getScale(self): return self.scale / 100 def apply(self, original, img): new_img = np.array(img) r, c, _ = new_img.shape hscale = self.calcScale(c, self.mx_hor) vscale = self.calcScale(r, self.mx_ver) scale = min(hscale, vscale, self.getScale()) self.ifDebug(lambda : self.logStr(f"Scale: {scale}")) return self.scaleImg(new_img, scale) def scaleImg(self, img, scale): nr = (int)(img.shape[0] * scale) nc = (int)(img.shape[1] * scale) return cv.resize(img, (nr,nc)) def calcScale(self, frm, to): return (to/frm) def applyTransformations(img, trns): return reduce(lambda x, y: y.apply(np.array(img), x), trns, np.array(img)) <file_sep>/SudokuParser/utils.py import numpy as np import functools import shutil import os import cv2 as cv RED = (0,0,255) BLUE = (0,255,0) GREEN = (255,0,0) IMT = (1,0,2) GS_MAX = 255 GAUSSIAN = cv.ADAPTIVE_THRESH_GAUSSIAN_C MEAN = cv.ADAPTIVE_THRESH_MEAN_C # Transposes an image (a cv2 image) def imT(img): return np.transpose(np.array(img), IMT) def flt2d(lst): """ Flattens a list of lists: [[], ..., []] -> [] This method will remove exactly the layer at index 1. This method assumes that every element in the list is a list itself. """ return [e for sl in lst for e in sl] def argmax(lst, fn = lambda x: x, default = None): if len(lst) == 0: return default return np.argmax([fn(e) for e in lst]) def max(lst, fn = lambda x: x, default = None): if len(lst) == 0: return default return lst[argmax(lst, fn)] def min(lst, fn = lambda x: x, default = None): if len(lst) == 0: return default return lst[argmin(lst, fn)] def argmin(lst, fn = lambda x: x, default = None): if len(lst) == 0: return default return np.argmin([fn(e) for e in lst]) def eucl(p1, p2): return np.linalg.norm(p1-p2) def flatten(l, d = None): def pack(e): return [e] if not isinstance(e, list) else e if d == 0: return l elif d == None: nd = None else: nd = d - 1 if isinstance(l, list): l = flt2d(map(pack, map(lambda x: flatten(x, nd), l))) return l def take(lst, ixs): return [lst[i] for i in ixs] # lst: list to be filtered # fn: funtion to filter # lsts: other mutual lists def mutFilter(lst1, fn, lst2): ixs = getIndex(lst1, fn) return take(lst1, ixs), take(lst2, ixs) def getIndex(lst, fn): return [i for i, e in enumerate(lst) if fn(e)] def setIfIndex(lst, ids, val): # TODO: make this more efficient return [(val if i in ids else e) for i, e in enumerate(lst)] def isDigit(str): try: toDigit(str) return True except: return False def toDigit(str): d = int(str) if d not in range(10): raise Exception("Not digit") return d def emptyStrct(strct): return strct == [] def getRoot(strct): return strct[0] def getSubStrct(strct): return strct[1] def deleteOutDirStructure(strct): root = getRoot(strct) if os.path.exists(root): shutil.rmtree(root) def createOutDirStructure(strct, cd = ""): if emptyStrct(strct): return root = getRoot(strct) subStrct = getSubStrct(strct) root = os.path.join(cd, root) if not os.path.exists(root): os.mkdir(root) for subF in subStrct: createOutDirStructure(subF, root) def h(x): print("Hallo?") """Find the largest contour of the given image. If no contour is found on the image, the contour is the edges of the image. This method exclusively uses adaptiveThresholding.""" def findLargestContourAT(img, method = GAUSSIAN, window_size_fraction = 0.15, window_size = 5, threshold_C = 15): img_cp = np.array(img) if window_size == None: w, h, _ = img_cp.shape window_size = int( window_size_fraction * min(w,h)) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) edges = cv.adaptiveThreshold(gray, GS_MAX, method, cv.THRESH_BINARY_INV, window_size, threshold_C) contours, hierarchy = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) print(f"contours: {len(contours)}") img_cp = cv.drawContours(img_cp, contours, -1, GREEN) cv.imshow("img", img_cp) cv.waitKey() if contours == []: print(None) largest_contour = ut.max(contours, cv.contourArea) return largest_contour
e86fe93ac1f9c0d63c1fd56212f8e09327cc75cd
[ "Markdown", "Python" ]
7
Python
MichielBaptist/SudokuParser
a70bda3ec7b0df56109d85ab78271d13259d93e5
9ef124d3683efdc69a168e7691dd0955924e0767
refs/heads/master
<file_sep><?php /* * * OGP - Open Game Panel * Copyright (C) 2008 - 2017 The OGP Development Team * * http://www.opengamepanel.org/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ define('manage_listings', "Administrar Artículos"); define('add_new_listing', "Publicar Artículo"); define('your_current_listings', "Artículos Publicados"); define('edit', "Editar"); define('date', "Fecha"); define('images', "Imágenes"); define('title', "Título"); define('description', "Contenido"); define('written_by', "Escrito por"); define('details', "Leer Más"); define('modify', "Modificar"); define('save', "Guardar"); define('delete', "Eliminar"); define('sure_to_delete', "¿Está seguro que quiere eliminar el/los artículo/s?"); define('go_back', "Atrás"); define('new_added_success', "Artículo publicado correctamente!"); define('add_another', "Añadir Otro"); define('or_message', "o"); define('please_select', "Seleccionar"); define('submit', "Enviar"); define('edit_listing', "Editar Articulos"); define('modifications_saved', "Los cambios han sido guardados!"); define('modify_images', "Modificar las imágenes del nuevo artículo"); define('upload_more_images', "Subir más imágenes"); define('latest_news', "Últimos artículos"); define('search_results', "Resultado de la búsqueda"); define('no_results', "No se encontraron artículos."); define('config_options', "Opciones"); define('date_format', "Formato de Fecha"); define('results_per_page', "Artículos por página"); define('enable_search', "Activar motor de Búsqueda"); define('image_quality', "Calidad de Imagen (0-100)"); define('max_image_width', "Ancho máximo por imágen (px)"); define('gallery_theme', "Image gallery skin"); define('images_bottom', "Position of the images gallery"); define('img_bottom', "Under the article"); define('img_right', "Right side of the article"); define('no_word', "No"); define('yes_word', "Sí"); define('no_access', "No tienes derecho a acceder a esta página. Su acción se registrará para una inspección más detallada."); define('write_permission_required', "Se requiere permiso de escritura"); define('fix_permission', "Corregir los permisos. El módulo no funcionará como se pretende hasta que corrija todos los permisos."); define('check_permissions', "Chequear permisos"); define('OK_permission', "Los permisos necesarios están bien!"); define('empty_title', "Por favor llene el título"); define('empty_description', "Por favor escriba contenido antes"); define('empty_author', "Por favor llene el nombre del autor"); define('GD_fail', "La extensión GD NO está cargada en el servidor. Se desactivó la subida de imágenes."); define('search_news', "Buscar artículos"); define('help', "ayuda"); define('help_date', "Obtener ayuda sobre los diferentes formatos de fecha"); define('ID_invalid', "El ID de artículo no existe"); define('ID_not_set', "El ID de artículo no está establecido"); define('unauthorized_access', "Acceso no autorizado desde"); define('WYSIWYG', "WYSIWYG editor"); define('tinymce_lang', "Tiny MCE language"); define('da', "Danish"); define('de', "German"); define('en_GB', "English"); define('es', "Spanish"); define('fi', "Finnish"); define('fr_FR', "French"); define('it', "Italian"); define('pl', "Polish"); define('pt_PT', "Portuguese"); define('ru', "Russian"); define('tinymce_skin', "Tiny MCE skin"); define('tinymce_skin_custom', "You absolutely need to upload your own custom skin in <b>modules/news/js/tinymce/skins/custom/</b> folder to be able to use this skin. If you select it without doing so, you'll encounter problems. Create your own custom skin here <a href='http://skin.tinymce.com/' target='_blank'>http://skin.tinymce.com/</a>."); define('safe_HTML', "HTML Purifier"); define('safe_HTML_en', "HTML Purifier enabled"); define('safe_HTML_dis', "HTML Purifier disabled"); define('safe_HTML_en_info', "The HTML content of the article in the detailed view will be purified. This will lead in the removal of some HTML tags like iframes. Edit the file <b>modules/news/config.php</b> to change the setting 'safe_HTML' from value '1' (enabled) to value '0' (disabled) to diabled this bahavior and allow usage of full HTML without restriction."); define('safe_HTML_dis_info', "The HTML content of the article in the detailed view will not be purified. Edit the file <b>modules/news/config.php</b> to change the setting 'safe_HTML' from value '0' (disabled) to value '1' (enabled) to enable safe HTML tags usage only."); ?> <file_sep><?php /* * * OGP - Open Game Panel * Copyright (C) 2008 - 2017 The OGP Development Team * * http://www.opengamepanel.org/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ define('manage_listings', "Gérer vos News"); define('add_new_listing', "Poster une News"); define('your_current_listings', "Vos News"); define('edit', "Editer"); define('date', "Date"); define('images', "Images"); define('title', "Titre"); define('description', "Contenu de la News"); define('written_by', "Ecrit par"); define('details', "Lire la suite"); define('modify', "Modifier"); define('save', "Enregistrer"); define('delete', "Effacer"); define('sure_to_delete', "Etes-vous sûr de vouloir effacer les news?"); define('go_back', "Retour"); define('new_added_success', "La News a bien été envoyée!"); define('add_another', "Ajouter une autre"); define('or_message', "ou"); define('please_select', "Veuillez Sélectionner"); define('submit', "Envoyer"); define('edit_listing', "Editer la News"); define('modifications_saved', "Les nouvelles valeurs ont bien été enregistrées!"); define('modify_images', "Modifier les images de la News"); define('upload_more_images', "Envoyer plus d'images"); define('latest_news', "Dernières News"); define('search_results', "Resultats de la Recherche"); define('no_results', "Aucune News trouvée."); define('config_options', "Options des News"); define('date_format', "Format de la date"); define('results_per_page', "News par page"); define('enable_search', "Activer le moteur de recherche"); define('image_quality', "Qualité d'image (0-100)"); define('max_image_width', "Largeur max. des images (px)"); define('gallery_theme', "Thème de la gallerie d'images"); define('images_bottom', "Position de la gallerie d'images"); define('img_bottom', "Dessous l'article"); define('img_right', "A droite de l'article"); define('no_word', "Non"); define('yes_word', "Oui"); define('no_access', "Vous n'avez pas le droit d'accéder à cette page. Votre action va être logguée pour une inspection plus approfondie."); define('write_permission_required', "Permission en écriture requise"); define('fix_permission', "Veuillez corriger les permissions. Le module ne fonctionnera pas correctement tant que vous ne corrigez pas toutes les permissions."); define('check_permissions', "Vérifier les Permissions"); define('OK_permission', "Les permissions requises sont toutes OK!"); define('empty_title', "Veuillez renseigner un titre"); define('empty_description', "Veuillez renseigner le contenu"); define('empty_author', "Veuillez renseigner le nom de l'auteur"); define('GD_fail', "L'extension GD n'est PAS chargée sur votre serveur. L'envoi d'images est désactivé."); define('search_news', "Rechercher les News"); define('help', "aide"); define('help_date', "Obtenir de l'aide concernant les différentes mise en forme de la date"); define('ID_invalid', "L'ID de la News n'existe pas"); define('ID_not_set', "L'ID de la News n'est pas défini"); define('unauthorized_access', "Accès non authorisé depuis"); define('WYSIWYG', "Editeur WYSIWYG"); define('tinymce_lang', "Langue de Tiny MCE"); define('da', "Danois"); define('de', "Allemand"); define('en_GB', "Anglais"); define('es', "Espagnol"); define('fi', "Finlandais"); define('fr_FR', "Français"); define('it', "Italien"); define('pl', "Polonais"); define('pt_PT', "Portuguais"); define('ru', "Russe"); define('tinymce_skin', "Thème de Tiny MCE"); define('tinymce_skin_custom', "Vous devez impérativement avoir déposé votre thème personnalisé dans le dossier <b>modules/news/js/tinymce/skins/custom/</b> pour pouvoir l'utiliser. Si vous choisissez ce thème sans l'avoir fait, vous rencontrerez des problèmes. Créez votre propre thème sur <a href='http://skin.tinymce.com/' target='_blank'>http://skin.tinymce.com/</a>."); define('safe_HTML', "Purificateur HTML"); define('safe_HTML_en', "Purificateur HTML activé"); define('safe_HTML_dis', "Purificateur HTML désactivé"); define('safe_HTML_en_info', "Le contenu HTML de l'article sera contrôlé et purifié dans l'affichage détaillé. Cela entrainera la suppression de balises HTML comme les iframes. Editez le fichier <b>modules/news/config.php</b> pour changer le paramètre 'safe_HTML' de la valeur '1' (activé) vers la valeur '0' (désactivé) pour désactiver ce comportement et autoriser le HTML sans restriction."); define('safe_HTML_dis_info', "Le contenu HTML de l'article ne sera pas contrôlé et purifié dans l'affichage détaillé. Editez le fichier <b>modules/news/config.php</b> pour changer le paramètre 'safe_HTML' de la valeur '0' (désactivé) vers la valeur '1' (activé) pour n'autoriser seulement le HTML sûr."); ?><file_sep><?php /* * * OGP - Open Game Panel * Copyright (C) 2008 - 2017 The OGP Development Team * * http://www.opengamepanel.org/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ define('manage_listings', "Manage your news"); define('add_new_listing', "Post News"); define('your_current_listings', "Your current news"); define('edit', "Edit"); define('date', "Date"); define('images', "Images"); define('title', "Title"); define('description', "News Content"); define('written_by', "Written by"); define('details', "Read More"); define('modify', "Modify"); define('save', "Save"); define('delete', "Delete"); define('sure_to_delete', "Are you sure that you would like to delete these news?"); define('go_back', "Go Back"); define('new_added_success', "The news has been posted successfully!"); define('add_another', "Add another one"); define('or_message', "or"); define('please_select', "Please Select"); define('submit', "Submit"); define('edit_listing', "Edit the news"); define('modifications_saved', "The new values have been saved successfully!"); define('modify_images', "Modify the new article images"); define('upload_more_images', "Upload more images"); define('latest_news', "Latest News"); define('search_results', "Search Results"); define('no_results', "No news was found."); define('config_options', "News Options"); define('date_format', "Date Format"); define('results_per_page', "News per Page"); define('enable_search', "Enable Search engine"); define('image_quality', "Image quality (0-100)"); define('max_image_width', "Maximum image width (px)"); define('gallery_theme', "Image gallery skin"); define('images_bottom', "Position of the images gallery"); define('img_bottom', "Under the article"); define('img_right', "Right side of the article"); define('no_word', "No"); define('yes_word', "Yes"); define('no_access', "You do not have the right to access this page. Your action will be logged for further inspection."); define('write_permission_required', "Write permission required"); define('fix_permission', "Please fix permissions. The module will not work as intended until you fix all permissions."); define('check_permissions', "Check Permissions"); define('OK_permission', "Required permissions are all OK!"); define('empty_title', "Please fill the title"); define('empty_description', "Please fill the content"); define('empty_author', "Please fill the author name"); define('GD_fail', "GD extension is NOT loaded on your server. Images upload disabled."); define('search_news', "Search the News"); define('help', "help"); define('help_date', "Get help regarding different formating of the date"); define('ID_invalid', "The News ID does not exist"); define('ID_not_set', "The News ID isn't set"); define('unauthorized_access', "Unauthorized access from"); define('WYSIWYG', "WYSIWYG editor"); define('tinymce_lang', "Tiny MCE language"); define('da', "Danish"); define('de', "German"); define('en_GB', "English"); define('es', "Spanish"); define('fi', "Finnish"); define('fr_FR', "French"); define('it', "Italian"); define('pl', "Polish"); define('pt_PT', "Portuguese"); define('ru', "Russian"); define('tinymce_skin', "Tiny MCE skin"); define('tinymce_skin_custom', "You absolutely need to upload your own custom skin in <b>modules/news/js/tinymce/skins/custom/</b> folder to be able to use this skin. If you select it without doing so, you'll encounter problems. Create your own custom skin here <a href='http://skin.tinymce.com/' target='_blank'>http://skin.tinymce.com/</a>."); define('safe_HTML', "HTML Purifier"); define('safe_HTML_en', "HTML Purifier enabled"); define('safe_HTML_dis', "HTML Purifier disabled"); define('safe_HTML_en_info', "The HTML content of the article in the detailed view will be purified. This will lead in the removal of some HTML tags like iframes. Edit the file <b>modules/news/config.php</b> to change the setting 'safe_HTML' from value '1' (enabled) to value '0' (disabled) to diabled this bahavior and allow usage of full HTML without restriction."); define('safe_HTML_dis_info', "The HTML content of the article in the detailed view will not be purified. Edit the file <b>modules/news/config.php</b> to change the setting 'safe_HTML' from value '0' (disabled) to value '1' (enabled) to enable safe HTML tags usage only."); ?> <file_sep># Module-News # NOW MOVED TO OGP EXTRAS, THIS IS NOW NOT UPDATED ANYMORE SEE FOLLOWING LINK: http://www.opengamepanel.org/forum/viewthread.php?thread_id=5289&rowstart=60#post_27229 Simple news module for OGP Based on News Lister from www.netartmedia.net/ **Install Requirement and Other** - Place the "lang" and "modules" folder inside OGP Panel main directory, then install module from Administration->Modules - NO database required, news are stored in XML files - Following folders/file need to have write access: "data", "data/listings.xml", "thumbnails", "uploads", and "uploaded_images"
787ddce2aace3f102332202e86729f79c6428d59
[ "Markdown", "PHP" ]
4
PHP
Zorrototo/Module-News
65eb453c623ccd9adfb22df91949df35b122e9d6
010b8d54720f20e94a5f5050529437159799d7fe
refs/heads/master
<file_sep>#Functions for calculating inversion of the matrix smart way (lazy evaluation + caching) #'makeCacheMatrix' creates special matrix (list of functions) that is able to cache result of 'solve' function #parameters: # currentMatrix - matrix to store #result: # special matrix (to be used as a parameter for 'cacheSolve' function) makeCacheMatrix <- function(currentMatrix = matrix()) { #cached value (inverted matrix) invertedMatrix <- NULL #matrix setter set <- function(newMatrix) { #store new matrix currentMatrix <<- newMatrix #invalidate old inversion of the matrix (because currentMatrix has changed) invertedMatrix <<- NULL } #matrix getter get <- function() { currentMatrix } #inverse matrix setter setinv <- function(inv) { invertedMatrix <<- inv } #inverse matrix getter getinv <- function() { invertedMatrix } #return list of functions list(set=set, get=get, setinv=setinv, getinv=getinv) } #'cacheSolve' calls solve on special matrix ('solve' function is called only once for given matrix) #params: # cacheMatrix - special matrix created by 'makeCacheMatrix' function # ... - any other parameter will be passed to 'solve' function (it will only happen once - for given matrix) #result: # inversion of matrix (result of 'solve' function) cacheSolve <- function(cacheMatrix, ...) { #get a matrix that is the inverse of 'cacheMatrix' inv = cacheMatrix$getinv() if (is.null(inv)) { #inversion not yet computed #get original matrix mat = cacheMatrix$get() #calculate inversion invMat = solve(mat, ...) #cache result cacheMatrix$setinv(invMat) return(invMat) } else { #inversion already calculated, nothing to do return(inv) } }
e7518aca36d83c0c4543193c3b2f5c286bb0184d
[ "R" ]
1
R
Varay/ProgrammingAssignment2
3652e6c33528f7f3b5a627514112714d40234da6
2263200b1688361b33e5e3503ba3f02db82e72cc
refs/heads/master
<file_sep>export default { install: function (Vue) { Vue.prototype.$helpers = { getServiceMethods: async function(serviceName, instance) { try { if (this.$services[serviceName]) { let methods = await this.$services[serviceName].getMethods(instance) return methods } else { return null } } catch (err) { console.log(err) return null } }, getServiceInstances: async function(serviceName) { try { if (this.$services[serviceName] && this.$services[serviceName].getInstances) { let instances = await this.$services[serviceName].getInstances() return instances } else { return null } } catch (err) { console.log(err) return null } } } } } <file_sep>#!/bin/sh docker stack remove chaman-populate <file_sep>#!/bin/sh docker stack remove chaman <file_sep>#!/bin/sh export IIOS_DLAKE_VERSION=3.4.0 export IIOS_AUTH_VERSION=1.2.0 docker network create --opt encrypted -d overlay infra docker stack deploy -c swarm/docker-compose.yml chaman <file_sep>FROM node:12-alpine RUN mkdir -p /opt && mkdir -p /opt/chaman ADD . /opt/chaman WORKDIR /opt/chaman RUN npm install && npm run client:build CMD ["npm", "run", "server:start"] <file_sep>#!/bin/sh export IIOS_POPULATE_ALL=true # don't forget to add your server to Mongo Atlas white list # export IIOS_MONGODB_PASSWORD=<<PASSWORD>> ./tools/js/populate_db-mongo.js <file_sep>import * as d3 from 'd3' export function loadSchema(vueObjRef, collection) { return new Promise((resolve, reject) => { vueObjRef.$utils.waitForProperty(vueObjRef, '$db').then(db => { db.collection('schemas').then(async schemas => { let schema = await schemas.dGet({ name: collection }) if (schema) { // manage naming restrictions for Mongo schema.$schema = schema._schema delete schema._schema resolve(schema) } else { // console.log(window.location.origin + '/data/schemas/' + collection + '.schema.json') d3.json(window.location.origin + '/data/schemas/' + collection + '.schema.json') .then(async data => { // console.log(data) data._schema = data.$schema delete data.$schema await schemas.dPut(data) resolve(data) }).catch(err => { console.log(err) reject(new Error('no schema for collection [' + collection + ']')) }) } }).catch(err => reject(err)) }).catch(err => reject(err)) }) } export function jsonDocNormalize(doc) { if (!doc) return doc let keys = Object.keys(doc) if (keys) { for (let k of keys) { if (k.match(/^\$/)) { doc[k.replace('$', '_')] = doc[k] delete doc[k] k = k.replace('$', '_') } if (typeof doc[k] === 'object') { doc[k] = jsonDocNormalize(doc[k]) } } } return doc }
b884413e44cee973212e35cb47af90d1df2690e8
[ "JavaScript", "Dockerfile", "Shell" ]
7
JavaScript
ignitialio/chaman
c1c388ff5ad72cf82f8a4da7c4e6e621301d2854
b3e0d80f50c09052c902ede5ef106c7af513a541
refs/heads/master
<file_sep>package sumchecker_test import ( "crypto" "encoding/hex" "testing" "github.com/WillAbides/checksum/sumchecker" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var knownHexSums = map[crypto.Hash]map[string]string{ crypto.SHA256: { "foo": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", "": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", }, crypto.SHA512: { "foo": "f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7", "": "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", }, crypto.SHA1: { "foo": "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33", "": "da39a3ee5e6b4b0d3255bfef95601890afd80709", }, crypto.MD5: { "foo": "acbd18db4cc2f85cedef654fccc4a4d8", "": "d41d8cd98f00b204e9800998ecf8427e", }, } func TestChecksum(t *testing.T) { t.Run("known hashes", func(t *testing.T) { for hsh, sums := range knownHexSums { for input, wantHex := range sums { got, err := sumchecker.Checksum(hsh, []byte(input)) assert.NoError(t, err) gotHex := hex.EncodeToString(got) assert.Equal(t, wantHex, gotHex) } } }) } func TestValidateChecksum(t *testing.T) { t.Run("known hashes", func(t *testing.T) { for hsh, sums := range knownHexSums { for input, wantHex := range sums { want, err := hex.DecodeString(wantHex) require.NoError(t, err) got, err := sumchecker.ValidateChecksum(hsh, want, []byte(input)) assert.NoError(t, err) assert.True(t, got) got, err = sumchecker.ValidateChecksum(hsh, want, []byte(input+"bogus")) assert.NoError(t, err) assert.False(t, got) } } }) } <file_sep>package sumchecker import ( "bytes" "crypto" "fmt" "hash" ) type HashRunner interface { WithHash(crypto.Hash, func(hash.Hash) error) error } type Checker struct { runner HashRunner } type defaultRunner struct{} func (r *defaultRunner) WithHash(hsh crypto.Hash, fn func(hash.Hash) error) error { if !hsh.Available() { return fmt.Errorf("unregistered hash") } return fn(hsh.New()) } func New(runner HashRunner) *Checker { if runner == nil { runner = new(defaultRunner) } return &Checker{ runner: runner, } } var defaultChecker = New(nil) func Checksum(hasher crypto.Hash, data []byte) ([]byte, error) { return defaultChecker.Checksum(hasher, data) } func (p *Checker) Checksum(hasher crypto.Hash, data []byte) ([]byte, error) { var sum []byte err := p.runner.WithHash(hasher, func(hsh hash.Hash) error { _, e := hsh.Write(data) if e != nil { return e } sum = hsh.Sum(nil) return nil }) return sum, err } func ValidateChecksum(hasher crypto.Hash, wantSum []byte, data []byte) (bool, error) { return defaultChecker.ValidateChecksum(hasher, wantSum, data) } func (p *Checker) ValidateChecksum(hasher crypto.Hash, wantSum []byte, data []byte) (bool, error) { sum, err := p.Checksum(hasher, data) if err != nil { return false, err } return bytes.Equal(wantSum, sum), nil } <file_sep>package sumchecker_test import ( "crypto" "encoding/hex" "fmt" "github.com/WillAbides/checksum/sumchecker" ) func Example() { exampleData := []byte("foo bar") sum, err := sumchecker.Checksum(crypto.MD5, exampleData) if err != nil { panic(err) } ok, err := sumchecker.ValidateChecksum(crypto.MD5, sum, exampleData) if err != nil { panic(err) } fmt.Println(ok) fmt.Println(hex.EncodeToString(sum)) // Output: // true // 327b6f07435811239bc47e1544353273 } <file_sep>package cachecopy import ( "bytes" "fmt" "io" "io/ioutil" "os" ) type Cache interface { io.WriteCloser Reader() (io.ReadCloser, error) } type Validator func(io.Reader) (bool, string) type ValidatorError struct { msg string } func (e *ValidatorError) Error() string { if e.msg == "" { return "validator returned false with no message" } return fmt.Sprintf("validator returned false with the message: %q", e.msg) } type Copier struct { Cache Cache Validator Validator } func (c *Copier) Copy(dst io.Writer, src io.Reader) (int64, error) { return Copy(dst, src, c.Validator, c.Cache) } func NewBufferCache(buf *bytes.Buffer) Cache { if buf == nil { buf = new(bytes.Buffer) } return &bufferCache{ Buffer: *buf, } } type bufferCache struct { bytes.Buffer } func (c *bufferCache) Reader() (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewReader(c.Buffer.Bytes())), nil } func (c *bufferCache) Close() error { return nil } func NewFileCache(file *os.File) Cache { return &fileCache{ File: *file, } } type fileCache struct { os.File } func (c *fileCache) Reader() (io.ReadCloser, error) { return os.Open(c.File.Name()) } func Copy(dst io.Writer, src io.Reader, validator func(io.Reader) (bool, string), cache Cache) (written int64, err error) { if validator == nil { return written, fmt.Errorf("validator cannot be nil") } if cache == nil { cache = NewBufferCache(nil) } defer func() { _ = cache.Close() }() _, err = io.Copy(cache, src) if err != nil { return written, fmt.Errorf("error copying to cache") } vReader, err := cache.Reader() if err != nil { return written, fmt.Errorf("error getting cache reader") } ok, validatorMsg := validator(vReader) _ = vReader.Close() if !ok { return written, &ValidatorError{msg: validatorMsg} } rdr, err := cache.Reader() if err != nil { return written, fmt.Errorf("error getting cache reader") } defer func() { _ = rdr.Close() }() written, err = io.Copy(dst, rdr) return written, err } <file_sep>package main import ( _ "crypto/md5" _ "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "encoding/hex" "flag" "fmt" "io" "io/ioutil" "os" "path/filepath" "github.com/WillAbides/checksum/cachecopy" "github.com/WillAbides/checksum/knownsums/hashnames" "github.com/WillAbides/checksum/sumchecker" ) func errOut(format string, a ...interface{}) { _, _ = fmt.Fprintf(os.Stderr, format, a...) } func exitErr(format string, a ...interface{}) { errOut(format, a...) os.Exit(1) } func main() { var hashName string flag.StringVar(&hashName, "a", "sha256", "Hash algorithm to use. One of sha1, sha256, sha512 or md5.") flag.Usage = func() { errOut(` safetyvalve reads from stdin, verifies that data received matched the given checksum, then writes to stdout. When the checksum does not match, safetyvalve returns 1 and writes nothing to stdout. Usage of %s: %s [options] checksum Options: `, filepath.Base(os.Args[0]), os.Args[0]) flag.PrintDefaults() } flag.Parse() if flag.NArg() != 1 { flag.Usage() os.Exit(2) } info, err := os.Stdin.Stat() if err != nil { panic(err) } if info.Mode()&os.ModeCharDevice != 0 { flag.Usage() errOut("\n\n¡nothing piped to stdin!\n") os.Exit(2) } wantSum, err := hex.DecodeString(flag.Arg(0)) if err != nil { exitErr("checksum must be a hex value\n") } hsh := hashnames.LookupHash(hashName) var validated bool copier := &cachecopy.Copier{ Cache: cachecopy.NewBufferCache(nil), Validator: func(rdr io.Reader) (bool, string) { b, err := ioutil.ReadAll(rdr) if err != nil { exitErr("error reading input stream: %v\n", err) return false, "" } got, err := sumchecker.ValidateChecksum(hsh, wantSum, b) if err != nil { exitErr("error validating the checksum: %v\n", err) return false, "" } validated = got return got, "" }, } _, err = copier.Copy(os.Stdout, os.Stdin) if err != nil { exitErr("error copying to stdout: %v\n", err) } if !validated { exitErr("input did not match the checksum %x using the hash algorithm %s\n", wantSum, hashName) } } <file_sep>package knownsums import ( "encoding/hex" "encoding/json" "github.com/WillAbides/checksum/knownsums/hashnames" ) type jsonKnownSum struct { Name string `json:"name"` HashName string `json:"hash"` Checksum string `json:"checksum"` } func (j *jsonKnownSum) knownSum() (*knownSum, error) { sum, err := hex.DecodeString(j.Checksum) if err != nil { return nil, err } return &knownSum{ Name: j.Name, Hash: hashnames.LookupHash(j.HashName), Checksum: sum, }, nil } func (k *knownSum) jsonKnownSum() *jsonKnownSum { return &jsonKnownSum{ Name: k.Name, HashName: hashnames.HashName(k.Hash), Checksum: hex.EncodeToString(k.Checksum), } } func (k *knownSum) MarshalJSON() ([]byte, error) { return json.Marshal(k.jsonKnownSum()) } func (k *knownSum) UnmarshalJSON(data []byte) error { j := &jsonKnownSum{} err := json.Unmarshal(data, j) if err != nil { return err } k2, err := j.knownSum() if err != nil { return err } *k = *k2 return nil } func (k *KnownSums) MarshalJSON() ([]byte, error) { return json.Marshal(k.knownSums) } func (k *KnownSums) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &k.knownSums) } <file_sep>package main import ( "crypto" _ "crypto/md5" _ "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "github.com/WillAbides/checksum/knownsums" "github.com/WillAbides/checksum/knownsums/hashnames" "github.com/WillAbides/checksum/sumchecker" "github.com/alecthomas/kong" ) type existingChecksums struct { Checksums string `kong:"required,type=existingfile,short='c',help='checksums file'"` } func (c existingChecksums) knownSums() (*knownsums.KnownSums, error) { sums := knownsums.KnownSums{ Checker: sumchecker.New(nil), } b, err := ioutil.ReadFile(c.Checksums) if err != nil { return &sums, err } err = json.Unmarshal(b, &sums) if err != nil { return &sums, err } return &sums, err } type mainCmd struct { Add addCmd `kong:"cmd"` Validate validateCmd `kong:"cmd"` Init initCmd `kong:"cmd"` } type initCmd struct { Checksums string `kong:"required,type=file,short='c',help='checksums file'"` } func fileExists(filename string) (bool, error) { _, err := os.Stat(filename) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } func (c *initCmd) Run() error { exists, err := fileExists(c.Checksums) if err != nil { return err } if exists { return fmt.Errorf("%s already exists", c.Checksums) } return writeKnownSumsToFile(&knownsums.KnownSums{}, c.Checksums) } type nameFileAlgo struct { File string `kong:"arg,existingfile"` Name string `kong:"arg,optional"` Algorithm string `kong:"short=a,enum=${algo_enum},default=${algo_default},help=${algo_help}"` } func (n nameFileAlgo) hash() crypto.Hash { return hashnames.LookupHash(n.Algorithm) } func (n nameFileAlgo) name() string { if n.Name != "" { return n.Name } return filepath.Base(n.File) } type addCmd struct { NameFileAlgo nameFileAlgo `kong:"embed"` ExistingChecksums existingChecksums `kong:"embed"` } type validateCmd struct { NameFileAlgo nameFileAlgo `kong:"embed"` ExistingChecksums existingChecksums `kong:"embed"` } func writeKnownSumsToFile(sums *knownsums.KnownSums, filename string) error { b, err := json.MarshalIndent(&sums, "", " ") if err != nil { return err } return ioutil.WriteFile(filename, b, 0640) } func (c *addCmd) Run() error { checksums, err := c.ExistingChecksums.knownSums() if err != nil { return err } data, err := ioutil.ReadFile(c.NameFileAlgo.File) if err != nil { return err } err = checksums.Add(c.NameFileAlgo.name(), c.NameFileAlgo.hash(), data) if err != nil { return err } return writeKnownSumsToFile(checksums, c.ExistingChecksums.Checksums) } func (c *validateCmd) Run() error { checksums, err := c.ExistingChecksums.knownSums() if err != nil { return err } data, err := ioutil.ReadFile(c.NameFileAlgo.File) if err != nil { return err } hsh := c.NameFileAlgo.hash() got, err := checksums.Validate(c.NameFileAlgo.name(), &hsh, data) if err != nil { return err } if !got { return fmt.Errorf("checksum for %s did not match", c.NameFileAlgo.File) } return nil } var cli mainCmd func main() { vars := kong.Vars{ "algo_enum": strings.Join(hashnames.AvailableHashNames(), ","), "algo_default": hashnames.HashName(crypto.SHA256), "algo_help": fmt.Sprintf("The hash algorithm to use. One of %s", strings.Join(hashnames.AvailableHashNames(), ", ")), } kctx := kong.Parse(&cli, vars) err := kctx.Run() kctx.FatalIfErrorf(err) } <file_sep>package knownsums import ( "crypto" "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestKnownSums_MarshalJSON(t *testing.T) { ks := KnownSums{ knownSums: []*knownSum{ { Name: "foo", Hash: crypto.MD5, Checksum: []byte("baz"), }, { Name: "qux", Hash: crypto.MD5, Checksum: []byte("bar"), }, }, } want := ` [ { "name": "foo", "hash": "md5", "checksum": "62617a" }, { "name": "qux", "hash": "md5", "checksum": "626172" } ] ` got, err := json.MarshalIndent(&ks, "", " ") assert.NoError(t, err) assert.JSONEq(t, want, string(got)) } func TestKnownSums_UnmarshalJSON(t *testing.T) { j := ` [ { "name": "foo", "hash": "sha1", "checksum": "62617a" }, { "name": "qux", "hash": "md5", "checksum": "626172" } ] ` want := KnownSums{ knownSums: []*knownSum{ { Name: "foo", Hash: crypto.SHA1, Checksum: []byte("baz"), }, { Name: "qux", Hash: crypto.MD5, Checksum: []byte("bar"), }, }, } got := KnownSums{} err := json.Unmarshal([]byte(j), &got) assert.NoError(t, err) assert.Equal(t, want, got) } func TestKnownSum_UnmarshalJSON(t *testing.T) { t.Run("single", func(t *testing.T) { j := ` { "name": "foo", "hash": "md5", "checksum": "62617a" } ` want := knownSum{ Name: "foo", Hash: crypto.MD5, Checksum: []byte("baz"), } var got knownSum err := json.Unmarshal([]byte(j), &got) assert.NoError(t, err) assert.Equal(t, want, got) }) t.Run("slice", func(t *testing.T) { j := ` [ { "name": "foo", "hash": "sha1", "checksum": "62617a" }, { "name": "qux", "hash": "md5", "checksum": "626172" } ] ` want := []*knownSum{ { Name: "foo", Hash: crypto.SHA1, Checksum: []byte("baz"), }, { Name: "qux", Hash: crypto.MD5, Checksum: []byte("bar"), }, } var got []*knownSum err := json.Unmarshal([]byte(j), &got) assert.NoError(t, err) assert.Equal(t, want, got) }) } func TestKnownSum_MarshalJSON(t *testing.T) { t.Run("single", func(t *testing.T) { ks := &knownSum{ Name: "foo", Hash: crypto.MD5, Checksum: []byte("baz"), } want := ` { "name": "foo", "hash": "md5", "checksum": "62617a" } ` got, err := json.MarshalIndent(ks, "", " ") assert.NoError(t, err) assert.JSONEq(t, want, string(got)) }) t.Run("slice", func(t *testing.T) { ks := []*knownSum{ { Name: "foo", Hash: crypto.MD5, Checksum: []byte("baz"), }, { Name: "qux", Hash: crypto.MD5, Checksum: []byte("bar"), }, } want := ` [ { "name": "foo", "hash": "md5", "checksum": "62617a" }, { "name": "qux", "hash": "md5", "checksum": "626172" } ] ` got, err := json.MarshalIndent(ks, "", " ") assert.NoError(t, err) assert.JSONEq(t, want, string(got)) }) } <file_sep>module github.com/WillAbides/checksum go 1.13 require ( github.com/alecthomas/kong v0.2.1 github.com/stretchr/testify v1.4.0 ) <file_sep>package cachecopy import ( "bytes" "io" "io/ioutil" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const lorem = ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Faucibus scelerisque eleifend donec pretium vulputate sapien. A iaculis at erat pellentesque adipiscing commodo elit at. Proin libero nunc consequat interdum varius sit amet. Tincidunt augue interdum velit euismod in. Aliquam ut porttitor leo a diam sollicitudin tempor. Eu scelerisque felis imperdiet proin fermentum leo vel orci. Eget duis at tellus at urna condimentum mattis pellentesque. Augue lacus viverra vitae congue eu consequat ac felis. Magna fermentum iaculis eu non diam phasellus vestibulum lorem. Metus vulputate eu scelerisque felis. Eget mi proin sed libero enim sed faucibus turpis. Habitant morbi tristique senectus et. Morbi tristique senectus et netus et malesuada fames ac. Diam quis enim lobortis scelerisque. ` func loremBuf(t *testing.T) *bytes.Buffer { t.Helper() var buf bytes.Buffer for i := 0; i < 100; i++ { _, err := buf.WriteString(lorem) require.NoError(t, err) } return &buf } func tmpFile(t *testing.T) (*os.File, func()) { t.Helper() file, err := ioutil.TempFile("", "") require.NoError(t, err) return file, func() { require.NoError(t, os.Remove(file.Name())) } } var failingValidator = func(reader io.Reader) (bool, string) { return false, "failing validator always fails" } var failingValidatorErr = &ValidatorError{msg: "failing validator always fails"} func loremValidator(t *testing.T) func(reader io.Reader) (bool, string) { t.Helper() return func(rdr io.Reader) (bool, string) { t.Helper() got, e := ioutil.ReadAll(rdr) require.NoError(t, e) return bytes.Equal(got, loremBuf(t).Bytes()), "" } } func TestCopy(t *testing.T) { t.Run("buffer", func(t *testing.T) { t.Run("valid", func(t *testing.T) { var buf bytes.Buffer cache := NewBufferCache(&buf) var dst bytes.Buffer validator := loremValidator(t) _, err := Copy(&dst, loremBuf(t), validator, cache) assert.NoError(t, err) assert.Equal(t, loremBuf(t).String(), dst.String()) }) t.Run("invalid", func(t *testing.T) { var buf bytes.Buffer cache := NewBufferCache(&buf) var dst bytes.Buffer _, err := Copy(&dst, loremBuf(t), failingValidator, cache) assert.Equal(t, failingValidatorErr, err) assert.Empty(t, dst.String()) }) }) t.Run("file", func(t *testing.T) { t.Run("valid", func(t *testing.T) { cacheFile, cacheTeardown := tmpFile(t) defer cacheTeardown() cache := NewFileCache(cacheFile) var dst bytes.Buffer validator := loremValidator(t) _, err := Copy(&dst, loremBuf(t), validator, cache) assert.NoError(t, err) assert.Equal(t, loremBuf(t).String(), dst.String()) }) t.Run("invalid", func(t *testing.T) { cacheFile, cacheTeardown := tmpFile(t) defer cacheTeardown() cache := NewFileCache(cacheFile) var dst bytes.Buffer _, err := Copy(&dst, loremBuf(t), failingValidator, cache) assert.Equal(t, failingValidatorErr, err) assert.Empty(t, dst.String()) }) }) } <file_sep>package hashnames import ( "crypto" "fmt" "regexp" "sort" "strconv" "sync" ) const invalid = "invalid" var knownNames []string var knownHashes []crypto.Hash var reverseKnownHashNames map[string]crypto.Hash var knownHashNames = map[crypto.Hash]string{ crypto.MD4: "md4", crypto.MD5: "md5", crypto.SHA1: "sha1", crypto.SHA224: "sha224", crypto.SHA256: "sha256", crypto.SHA384: "sha384", crypto.SHA512: "sha512", crypto.MD5SHA1: "md5sha1", crypto.RIPEMD160: "ripemd160", crypto.SHA3_224: "sha3_224", crypto.SHA3_256: "sha3_256", crypto.SHA3_384: "sha3_384", crypto.SHA3_512: "sha3_512", crypto.SHA512_224: "sha512_224", crypto.SHA512_256: "sha512_256", crypto.BLAKE2s_256: "blake2s_256", crypto.BLAKE2b_256: "blake2b_256", crypto.BLAKE2b_384: "blake2b_384", crypto.BLAKE2b_512: "blake2b_512", } func init() { mux.Lock() resetValues() mux.Unlock() } func resetValues() { knownHashes = make([]crypto.Hash, 0, len(knownHashNames)) reverseKnownHashNames = make(map[string]crypto.Hash, len(knownHashNames)) for hash, name := range knownHashNames { reverseKnownHashNames[name] = hash knownHashes = append(knownHashes, hash) } sort.Slice(knownHashes, func(i, j int) bool { return knownHashes[i] < knownHashes[j] }) knownNames = make([]string, len(knownHashes)) for i, hash := range knownHashes { knownNames[i] = knownHashNames[hash] } } var mux sync.RWMutex func UpdateHashName(hash crypto.Hash, name string) error { mux.Lock() defer mux.Unlock() _, duplicate := reverseKnownHashNames[name] if duplicate { return fmt.Errorf("duplicate names are not allowed") } knownHashNames[hash] = name resetValues() return nil } //AvailableHashes lists all available crypto.Hashes func AvailableHashes() []crypto.Hash { result := make([]crypto.Hash, 0, 256) for i := crypto.Hash(0); i < 256; i++ { if i.Available() { result = append(result, i) } } return result } func AvailableHashNames() []string { hashes := AvailableHashes() result := make([]string, len(hashes)) for i, hash := range hashes { result[i] = HashName(hash) } return result } //HashName returns either the name mapped in KnownHashNames of "unknown(%d)" func HashName(hash crypto.Hash) string { name, ok := knownHashNames[hash] if ok { return name } if hash == 0 { return invalid } return fmt.Sprintf("unknown(%d)", hash) } var reNameLookup = regexp.MustCompile(`unknown\((\d+)\)`) func LookupHash(name string) crypto.Hash { if result, ok := reverseKnownHashNames[name]; ok { return result } if name == invalid { return 0 } matches := reNameLookup.FindStringSubmatch(name) if len(matches) > 0 { n, err := strconv.ParseUint(matches[1], 10, 32) if err != nil { return 0 } return crypto.Hash(n) } return 0 } <file_sep>package knownsums import ( "crypto" _ "crypto/md5" _ "crypto/sha1" _ "crypto/sha256" _ "crypto/sha512" "encoding/hex" "testing" "github.com/WillAbides/checksum/sumchecker" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var knownHexSums = map[string]map[string]string{ "sha256": { "foo": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", "": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", }, "sha512": { "foo": "f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7", "": "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", }, "sha1": { "foo": "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33", "": "da39a3ee5e6b4b0d3255bfef95601890afd80709", }, "md5": { "foo": "acbd18db4cc2f85cedef654fccc4a4d8", "": "d41d8cd98f00b204e9800998ecf8427e", }, } func mustHexDecode(t *testing.T, s string) []byte { t.Helper() b, err := hex.DecodeString(s) require.NoError(t, err) return b } func TestKnownSums_Add(t *testing.T) { t.Run("success", func(t *testing.T) { knownSums := &KnownSums{ Checker: sumchecker.New(nil), } data := []byte("foo") name := "sumname" hash := crypto.MD5 err := knownSums.Add(name, hash, data) assert.NoError(t, err) want := []*knownSum{ { Hash: hash, Name: name, Checksum: mustHexDecode(t, knownHexSums["md5"]["foo"]), }, } assert.Equal(t, want, knownSums.knownSums) }) t.Run("unregistered hash", func(t *testing.T) { knownSums := &KnownSums{ Checker: sumchecker.New(nil), } data := []byte("foo") name := "sumname" err := knownSums.Add(name, 999, data) assert.EqualError(t, err, "hash is not available") assert.Empty(t, knownSums.knownSums) }) t.Run("nil Checker", func(t *testing.T) { knownSums := &KnownSums{} data := []byte("foo") name := "sumname" err := knownSums.Add(name, crypto.MD5, data) assert.EqualError(t, err, "checker cannot be nil") assert.Empty(t, knownSums.knownSums) }) } func TestKnownSums_Validate(t *testing.T) { t.Run("success", func(t *testing.T) { data := []byte("foo") name := "sumname" hash := crypto.MD5 knownSums := &KnownSums{ Checker: sumchecker.New(nil), knownSums: []*knownSum{ { Name: name, Hash: hash, Checksum: mustHexDecode(t, knownHexSums["md5"]["foo"]), }, }, } got, err := knownSums.Validate(name, &hash, data) assert.NoError(t, err) assert.True(t, got) }) t.Run("nil hash", func(t *testing.T) { data := []byte("foo") name := "sumname" knownSums := &KnownSums{ Checker: sumchecker.New(nil), knownSums: []*knownSum{ { Name: name, Hash: crypto.MD5, Checksum: mustHexDecode(t, knownHexSums["md5"]["foo"]), }, { Name: name, Hash: crypto.SHA1, Checksum: mustHexDecode(t, knownHexSums["sha1"]["foo"]), }, }, } got, err := knownSums.Validate(name, nil, data) assert.NoError(t, err) assert.True(t, got) }) t.Run("one of many invalid", func(t *testing.T) { data := []byte("foo") name := "sumname" knownSums := &KnownSums{ Checker: sumchecker.New(nil), knownSums: []*knownSum{ { Name: name, Hash: crypto.MD5, Checksum: mustHexDecode(t, knownHexSums["md5"]["foo"]), }, { Name: name, Hash: crypto.SHA1, Checksum: []byte("deadbeef"), }, { Name: name, Hash: crypto.SHA256, Checksum: mustHexDecode(t, knownHexSums["sha256"]["foo"]), }, }, } got, err := knownSums.Validate(name, nil, data) assert.NoError(t, err) assert.False(t, got) }) t.Run("unregistered hash in known sums", func(t *testing.T) { data := []byte("foo") name := "sumname" knownSums := &KnownSums{ Checker: sumchecker.New(nil), knownSums: []*knownSum{ { Name: name, Hash: 999, Checksum: []byte("deadbeef"), }, }, } got, err := knownSums.Validate(name, nil, data) assert.NoError(t, err) assert.False(t, got) }) t.Run("unregistered hash in arguments", func(t *testing.T) { data := []byte("foo") name := "sumname" knownSums := &KnownSums{ Checker: sumchecker.New(nil), knownSums: []*knownSum{ { Name: name, Hash: 999, Checksum: []byte("deadbeef"), }, }, } hash := crypto.Hash(999) got, err := knownSums.Validate(name, &hash, data) assert.NoError(t, err) assert.False(t, got) }) t.Run("nil checker", func(t *testing.T) { data := []byte("foo") name := "sumname" knownSums := &KnownSums{ knownSums: []*knownSum{ { Name: name, Hash: crypto.MD5, Checksum: []byte("foo"), }, }, } got, err := knownSums.Validate(name, nil, data) assert.EqualError(t, err, "checker cannot be nil") assert.False(t, got) }) } func TestKnownSums_AddPrecalculatedSum(t *testing.T) { t.Run("success", func(t *testing.T) { knownSums := &KnownSums{} name := "sumname" hash := crypto.MD5 sum := []byte("bar") want := []*knownSum{{ Name: name, Hash: hash, Checksum: sum, }} err := knownSums.AddPrecalculatedSum(name, hash, sum) assert.NoError(t, err) assert.ElementsMatch(t, want, knownSums.knownSums) }) t.Run("duplicate", func(t *testing.T) { name := "sumname" hash := crypto.MD5 knownSums := &KnownSums{ knownSums: []*knownSum{{ Name: name, Hash: hash, Checksum: []byte("foo"), }}, } err := knownSums.AddPrecalculatedSum(name, hash, []byte("bar")) assert.EqualError(t, err, "cannot add duplicate name and hash") assert.Equal(t, []*knownSum{{ Name: name, Hash: hash, Checksum: []byte("foo"), }}, knownSums.knownSums) }) } func TestKnownSums_Remove(t *testing.T) { startSums := func() []*knownSum { return []*knownSum{ { Name: "foo", Hash: crypto.MD5, }, { Name: "foo", Hash: crypto.SHA256, }, { Name: "baz", Hash: crypto.SHA256, }, { Name: "baz", Hash: crypto.MD5, }, } } t.Run("name and hashName exists", func(t *testing.T) { knownSums := &KnownSums{ knownSums: startSums(), } want := []*knownSum{ { Name: "foo", Hash: crypto.SHA256, }, { Name: "baz", Hash: crypto.SHA256, }, { Name: "baz", Hash: crypto.MD5, }, } h := crypto.MD5 knownSums.Remove("foo", &h) assert.ElementsMatch(t, want, knownSums.knownSums) }) t.Run("empty hashName removes all hashNames", func(t *testing.T) { knownSums := &KnownSums{ knownSums: startSums(), } want := []*knownSum{ { Name: "baz", Hash: crypto.SHA256, }, { Name: "baz", Hash: crypto.MD5, }, } knownSums.Remove("foo", nil) assert.ElementsMatch(t, want, knownSums.knownSums) }) } <file_sep>package knownsums import ( "crypto" "fmt" "sync" ) type Checker interface { Checksum(hasher crypto.Hash, data []byte) ([]byte, error) ValidateChecksum(hasher crypto.Hash, wantSum []byte, data []byte) (bool, error) } type knownSum struct { Hash crypto.Hash Name string Checksum []byte } //KnownSums contains a list of checksums that can be validated with the Validate func type KnownSums struct { sync.RWMutex Checker Checker knownSums []*knownSum } //Add adds a checksum that can be validated by KnownSums. //It uses KnownSums' SumChecker to calculate data's checksum. func (c *KnownSums) Add(name string, hash crypto.Hash, data []byte) error { if c.Checker == nil { return fmt.Errorf("checker cannot be nil") } if !hash.Available() { return fmt.Errorf("hash is not available") } sum, err := c.Checker.Checksum(hash, data) if err != nil { return fmt.Errorf("error calculating sum: %w", err) } return c.AddPrecalculatedSum(name, hash, sum) } //AddPrecalculatedSum adds a sum that has already been calculated. //This is primarily intended to be used for serialization func (c *KnownSums) AddPrecalculatedSum(name string, hash crypto.Hash, sum []byte) error { c.Lock() defer c.Unlock() existing := withNameAndHash(c.knownSums, name, &hash) if len(existing) != 0 { return fmt.Errorf("cannot add duplicate name and hash") } c.knownSums = append(c.knownSums, &knownSum{ Name: name, Hash: hash, Checksum: sum, }) return nil } //Remove removes a checksum from KnownSums func (c *KnownSums) Remove(name string, hash *crypto.Hash) { c.Lock() defer c.Unlock() newSums := make([]*knownSum, 0, len(c.knownSums)) for _, sum := range c.knownSums { if matchNameAndHash(name, hash, sum) { continue } newSums = append(newSums, sum) } c.knownSums = newSums } //Validate returns true if data's checksum matches the sum stored in KnownSums. //Looks for the known sum with the given name and hashName and uses SumChecker to validate that the sums match. //If hashName is empty, it will return true if all known sums with the given name return true. func (c *KnownSums) Validate(name string, hash *crypto.Hash, data []byte) (bool, error) { c.RLock() defer c.RUnlock() if c.Checker == nil { return false, fmt.Errorf("checker cannot be nil") } sums := withNameAndHash(c.knownSums, name, hash) var err error var ok bool for _, sum := range sums { if !sum.Hash.Available() { continue } ok, err = c.Checker.ValidateChecksum(sum.Hash, sum.Checksum, data) if err != nil { err = fmt.Errorf(`error validating known sum %s: %w`, name, err) break } if !ok { break } } return ok, err } //returns true if sum.Name == name and hash is either nil or matches sum.HashName func matchNameAndHash(name string, hash *crypto.Hash, sum *knownSum) bool { if sum == nil { return false } if hash != nil && sum.Hash != *hash { return false } return sum.Name == name } func withNameAndHash(sums []*knownSum, name string, hash *crypto.Hash) []*knownSum { result := make([]*knownSum, 0, len(sums)) for _, sum := range sums { if matchNameAndHash(name, hash, sum) { result = append(result, sum) } } return result }
5cedf72a26c4a5e0ecc5ab57076a9d06c8434bdc
[ "Go Module", "Go" ]
13
Go
WillAbides/checksum
38c4d2ee7f1ce312b2479ad26ba3699a76d7b026
cda04dab916df5b9223086abbd67e57001bf790e
refs/heads/master
<repo_name>fattouchsquall/AMFFourSquareBundle<file_sep>/Resources/doc/index.md Symfony2 FourSquare Bundle ======================== 1) Installation ---------------------------------- 2) Configuration ------------------------------- [Read the whole configuration reference](01-config-reference.md) 3) Utilisation ------------------------------- 4) Dépendance -------------------------------<file_sep>/Service/FourSquare.php <?php /** * Provides an abstraction for making a requests to the Foursquare API. * * @package FourSquareBundle * @subpackage Service * @author <NAME> <<EMAIL>> */ namespace AMF\FourSquareBundle\Service; use Nordnet\LoginBundle\Model\HttpMethodConstants; use Nordnet\LoginBundle\Model\UrlConstants; /** * Provides an abstraction for making a requests to the Foursquare API. * * @package FourSquareBundle * @subpackage Service * @author <NAME> <<EMAIL>> */ class FourSquare { /** * @var string */ protected $baseUrl; /** * @var string */ protected $clientId; /** * @var string */ protected $clientSecret; /** * @var string */ protected $locale; /** * @var string */ protected $redirectUri; /** * @var string */ protected $version; /** * @var string */ protected $authenticationToken; /** * Constructor class. * * @param string $clientId * @param string $clientSecret * @param string $locale * @param string $redirectUri * @param string $version * @param string $locale */ public function __construct($clientId, $clientSecret, $locale, $redirectUri, $version) { $this->baseUrl = UrlConstants::URL_BASE . $version; $this->clientId = $clientId; $this->clientSecret = $clientSecret; $this->locale = $locale; $this->redirectUri = $redirectUri; $this->version = $version; } /** * Performs a request for a public resource. * * @param string $endPoint A particular endpoint of the Foursquare API. * @param array $parameters A set of parameters to be appended to the request (defaults to empty). * * @return string */ public function performPublicRequest($endPoint, array $parameters=array()) { // build the full URL $url = $this->baseUrl . trim($endPoint, "/"); // append the details of client to parameters $parameters['client_id'] = $this->clientId; $parameters['client_secret'] = $this->clientSecret; $parameters['version'] = $this->version; $parameters['locale'] = $this->locale; $jsonResponse = $this->performGet($url, $parameters); return $jsonResponse; } /** * Performs a request for a private resource. * * @param string $endPoint A particular endpoint of the Foursquare API. * @param array $parameters A set of parameters to be appended to the request (defaults to empty). * @param boolean $isPost Whether or not to use a POST request. * * @return string */ public function performPrivateRequest($endPoint, array $parameters=array(), $isPost=false) { $url = $this->baseUrl . trim($endPoint, "/"); $parameters['oauth_token'] = $this->authenticationToken; $parameters['version'] = $this->version; $parameters['locale'] = $this->locale; if ($isPost === true) { $jsonReponse = $this->performGet($url, $parameters); } else { $jsonReponse = $this->performPost($url, $parameters); } return $jsonReponse; } /** * Performs a multiple requests for move then one private or public resource. * * @param array $requests A set of arrays containing the endpoint and a set of parameters. * @param boolean $isPost Whether or not to use a POST request. * * @return string */ public function performMultileRequest(array $requests=array(), $isPost=false) { $url = $this->baseUrl . "multi/"; $parameters = array(); $parameters['oauth_token'] = $this->authenticationToken; $parameters['version'] = $this->version; if (is_array($requests)) { $requestQueries = array(); foreach ($requests as $request) { $query = $request['endpoint']; if (array_key_exists('params', $request)) { if (!empty($request) && is_array($request['params'])) { $query .= '?' . http_build_query($request); } } $requestQueries[] = $query; } $parameters['requests'] = implode(',', $requestQueries); } if (!$isPost === true) { $jsonReponse = $this->performGet($url, $parameters); } else { $jsonReponse = $this->performPost($url, $parameters); } return $jsonReponse; } /** * Returns the response from json. * * @param string $json The value encoded in json. * * @throws \Exception Throws exception when the response is not valid. * * @return string */ public function getResponseFromJsonString($json) { $json = json_decode($json); if (!isset($json->response)) { throw new \Exception('Invalid response'); } if (!isset( $json->meta->code ) || 200 !== $json->meta->code ) { throw new \Exception( 'Invalid response' ); } return $json->response; } /** * Performs a Get request. * * @param string $url The base url. * @param array $parameters A set of parameters to be appended to the request (defaults to empty). * * @return string */ protected function performGet($url, array $parameters=array()) { // create url for Get request $url = $this->buildGetUrl($url, $parameters); $jsonReponse = $this->performRequest($url, $parameters, HttpMethodConstants::HTTP_GET); return $jsonReponse; } /** * Performs a Post request. * * @param string $url The base url. * @param array $parameters A set of parameters to be appended to the request (defaults to empty). * * @return string */ protected function performPost($url, array $parameters=array()) { $jsonReponse = $this->performRequest($url, $parameters, HttpMethodConstants::HTTP_POST); return $jsonReponse; } /** * Performs the request to Foursquare API via cURL. * * @param string $url The base url. * @param array $parameters A set of parameters to be appended to the request (defaults to empty). * @param string $requestType The type of request (POST or GET). * * @return string */ protected function performRequest($url, array $parameters=array(), $requestType=HttpMethodConstants::HTTP_GET) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if (isset($_SERVER['HTTP_USER_AGENT'])) { curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); } else { // Handle the useragent like we are Google Chrome curl_setopt($ch, CURLOPT_USERAGENT, 'Moamf/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.X.Y.Z Safari/525.13.'); } curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $acceptLanguage[] = "Accept-Language:" . $this->locale; curl_setopt($ch, CURLOPT_HTTPHEADER, $acceptLanguage); // populate the data for POST if ($requestType === HttpMethodConstants::HTTP_POST) { curl_setopt($ch, CURLOPT_POST, 1); if (!empty($parameters)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); } } $result = curl_exec($ch); curl_close($ch); return $result; } /** * Performs a request to google maps API to get the lat and lng of an address accepted by google maps. * * @param string $address An address string accepted by the google maps api. * * @return array|boolean */ public function geolocateAddress($address) { $params = array("address" => $address, "sensor" => "false"); $jsonResponse = $this->performGet(UrlConstants::GOOGLE_MAPS, $params); $reponse = json_decode($jsonResponse); if ($reponse->status === "ZERO_RESULTS") { return false; } else { return array('latitude' => $reponse->results[0]->geometry->location->lat, 'longitude' => $reponse->results[0]->geometry->location->lng); } } /** * Creates a complete url with each parameter as a GET parameter. * * @param string $url The base URL to append the query string to. * @param array $parameters The parameters to pass to the URL via Get method. * * @return string */ protected function buildGetUrl($url, array $parameters=array()) { if (!empty($parameters)) { $parametersForGet = http_build_query($parameters); $url = trim($url) . '?' . $parametersForGet; } return $url; } /** * Returns the url for the Foursquare web authentication page. * * @param string $redirect The configured redirect uri for the provided client credentials. * * @return string */ public function retrieveAuthenticationUrl($redirectUri=null) { if (!isset($redirectUri) && 0 === strlen($redirectUri)) { $redirectUri = $this->redirectUri; } $parameters = array("client_id" => $this->clientId, "response_type" => "code", "redirect_uri" => $redirectUri); return $this->buildGetUrl($this->authenticateUrl, $parameters); } /** * getToken * Performs a request to Foursquare for a user token, and returns the token, while also storing it * locally for use in private requests * * @param string $code The 'code' parameter provided by the Foursquare webauth callback redirect * @param string $redirect The configured redirect uri for the provided client credentials. * * @return string|boolean */ public function getToken($code, $redirectUri=null) { if (!isset($redirectUri) && 0 === strlen($redirectUri)) { $redirectUri = $this->redirectUri; } $parameters = array("client_id" => $this->clientId, "client_secret" => $this->clientSecret, "grant_type" => "authorization_code", "redirect_uri" => $redirectUri, "code" => $code); $result = $this->performGet(UrlConstants::TOKEN, $parameters); $json = json_decode($result); // <NAME> Check if we get token if (property_exists($json, 'access_token')) { $this->setAuthenticationToken($json->access_token); return $json->access_token; } else { return false; } } /** * Setter for authentication token. * * @param string $authenticationToken */ public function setAuthenticationToken($authenticationToken) { $this->authenticationToken = $authenticationToken; } /** * Setter for redirectUri. * * @param string $redirectUri * * @return FourSquare. */ public function setRedirectUri($redirectUri) { $this->redirectUri = $redirectUri; return $this; } /** * Getter for redirectUri. * * @return string */ public function getRedirectUri() { return $this->redirectUri; } } <file_sep>/Model/UrlConstants.php <?php /** * @package FourSquareBundle * @subpackage Model * @author <NAME> <<EMAIL>> */ namespace Nordnet\LoginBundle\Model; /** * Define constants for variours urls. * * @package FourSquareBundle * @subpackage Model * @author <NAME> <<EMAIL>> */ class UrlConstants { const URL_BASE = "https://api.foursquare.com/"; const URL_AUTHENTICATION = "https://foursquare.com/oauth2/authenticate"; const URL_TOKEN = "https://foursquare.com/oauth2/access_token"; const URL_GOOGLE_MAPS = "http://maps.googleapis.com/maps/api/geocode/json"; } ?> <file_sep>/DependencyInjection/AMFFourSquareExtension.php <?php namespace AMF\FourSquareBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class AMFFourSquareExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('foursquare.yml'); if (!empty($config['settings'])) { $this->remapParametersNamespaces($config, $container, array( 'settings' => 'amf_foursquare.settings.%s', )); } } protected function remapParametersNamespaces(array $config, ContainerBuilder $container, array $namespaces) { foreach ($namespaces as $namespace => $map) { if ($namespace) { if (!array_key_exists($namespace, $config)) { continue; } $namespaceConfig = $config[$namespace]; } else { $namespaceConfig = $config; } foreach ($namespaceConfig as $name => $value) { $container->setParameter(sprintf($map, $name), $value); } } } } <file_sep>/Model/HttpMethodConstants.php <?php /** * @package FourSquareBundle * @subpackage Model * @author <NAME> <<EMAIL>> */ namespace Nordnet\LoginBundle\Model; /** * Define constants for http method. * * @package FourSquareBundle * @subpackage Model * @author <NAME> <<EMAIL>> */ class HttpMethodConstants { const HTTP_GET = "GET"; const HTTP_POST = "POST"; } ?> <file_sep>/DependencyInjection/Configuration.php <?php namespace AMF\FourSquareBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; use \Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('amf_foursquare'); $this->addSettingsSection($rootNode); return $treeBuilder; } public function addSettingsSection(ArrayNodeDefinition $node) { $node->children() ->arrayNode('settings') ->addDefaultsIfNotSet() ->canBeUnset() ->children() ->scalarNode('client_id')->defaultFalse()->cannotBeEmpty()->isRequired()->end() ->scalarNode('client_secret')->defaultFalse()->cannotBeEmpty()->isRequired()->end() ->scalarNode('client_locale')->defaultValue('fr')->cannotBeEmpty()->end() ->scalarNode('version')->defaultValue('v2')->cannotBeEmpty()->end() ->scalarNode('redirect_uri')->defaultNull()->end() ->end() ->end(); } public function addSearchSection(ArrayNodeDefinition $node) { $node->children() ->arrayNode('search') ->addDefaultsIfNotSet() ->canBeUnset() ->children() ->scalarNode('ll')->defaultFalse()->end() ->scalarNode('near')->defaultFalse()->end() ->scalarNode('llAcc')->defaultValue('20120228')->cannotBeEmpty()->end() ->scalarNode('alt')->defaultValue(0)->end() ->scalarNode('altAcc')->defaultNull()->end() ->scalarNode('query')->defaultNull()->end() ->scalarNode('limit')->defaultNull()->end() ->scalarNode('intent')->defaultNull()->end() ->scalarNode('radius')->defaultNull()->end() ->scalarNode('sw')->defaultNull()->end() ->scalarNode('ne')->defaultNull()->end() ->scalarNode('categoryId')->defaultNull()->end() ->scalarNode('url')->defaultNull()->end() ->scalarNode('providerId')->defaultNull()->end() ->scalarNode('linkedId')->defaultNull()->end() ->end() ->end(); } } <file_sep>/Resources/doc/01-config-reference.md Configuration Reference ======================= All configuration options with default values are listed below:: ```yaml # app/config/config.yml amf_foursquare: ``` <file_sep>/Controller/VenueController.php <?php /** * @package FourSquareBundle * @subpackage Controller * @author <NAME> <<EMAIL>> */ namespace AMF\FourSquareBundle\Controller; use Symfony\Component\DependencyInjection\ContainerAware; use Symfony\Component\HttpFoundation\Response; /** * Controller for venues. * * @package FourSquareBundle * @subpackage Controller * @author <NAME> <<EMAIL>> */ class VenueController extends ContainerAware { /** * Finds places around an area. * * @param string $latitude * @param string $longitude * * @return Response */ public function searchAction($latitude, $longitude) { $request = $this->container->get('request'); if ($request->isXmlHttpRequest()) { $latLng = (float) $latitude . "," . (float) $longitude; $parameters = array("ll" => $latLng, 'radius' => 100000); $foursquareService = $this->container->get('amf_foursquare.service'); $placesJson = $foursquareService->performPublicRequest("venues/search", $parameters); return new Response($placesJson); } return new Response(); } /** * Adds a new place. * * * @return Response */ public function addAction($name) { $request = $this->container->get('request'); $parameters = array('name' => $name); $foursquareService = $this->container->get('amf_foursquare.service'); $placesJson = $foursquareService->performPublicRequest("venues/add", $parameters); return new Response($placesJson); } } <file_sep>/AMFFourSquareBundle.php <?php namespace AMF\FourSquareBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AMFFourSquareBundle extends Bundle { } <file_sep>/README.md AMFFourSquareBundle ================ This bundle provides foursquare features for a Symfony2 application. Features available include: - Venues scan. Documentation ------------- Documentation for this bundle is stored under `Resources/doc` in this repository. [Read the documentation for master](https://github.com/fattouchsquall/AMFFourSquareBundle/tree/master/Resources/doc/index.md) Installation ------------ All the installation instructions are located in the documentation. License ------- This bundle is under the MIT license. See the complete license in the bundle: ``` Resources/meta/LICENSE ```
18f565e8308f67de5e2c4632fc5bbebab0d91628
[ "Markdown", "PHP" ]
10
Markdown
fattouchsquall/AMFFourSquareBundle
e0a39c20289d78f54b5599b80f5c891118dac704
c56761f76cd5b629ca243a9613998ffcf304ec41
refs/heads/master
<repo_name>NiharikaNishu/Weekend-Hackathon-3---Todo-List-React<file_sep>/src/components/EditBox.js import React from "react"; export default function EditBox({ editItem, handleEditChange, saveEditToDo }) { return ( <> <input className="editTask" type="string" onChange={handleEditChange} value={editItem} /> <button disabled={editItem === ""} className="saveTask" style={{ marginLeft: "5px" }} onClick={saveEditToDo} > Save </button> </> ); }
74c161be355221f6f891ebc7d64d64157fcadf8b
[ "JavaScript" ]
1
JavaScript
NiharikaNishu/Weekend-Hackathon-3---Todo-List-React
40a069d76c60165fb9e3cafd6d5f3d58f6abcdea
50b9b8d8cdaefcd7de32abeee54fd815be6d5d49
refs/heads/master
<repo_name>eSlider/vkbansal.me<file_sep>/scripts/utils/readFile.ts import * as path from 'path'; import * as fs from 'fs-extra'; import { getURL, renderMarkdown } from './miscUtils'; import { AllFileContent, TSFileContents, MDFileContents, FileType } from '../../typings/common'; export async function readFile(filePath: string): Promise<AllFileContent> { const { ext, name, dir } = path.parse(filePath); const absPath = path.resolve(process.cwd(), filePath); const url = getURL(dir, name); switch (ext) { case '.ts': case '.tsx': const tsContents = await import(absPath); if (!Object.prototype.hasOwnProperty.call(tsContents, 'render')) { throw new Error(`"${filePath}" does not have a export named "render"!`); } const tsFileContents: TSFileContents = { type: FileType.TS, url, render: tsContents.render, styles: tsContents.styles, attributes: tsContents.attributes, rawPath: filePath }; return tsFileContents; case '.md': const mdContents = renderMarkdown(fs.readFileSync(absPath, 'utf8')); const isPost = url.startsWith('/blog'); if (isPost && !mdContents.attributes) { throw new Error( `${filePath} is a post, but does not have attributes defined in header` ); } const mdFileContents: MDFileContents = { type: FileType.MD, url, attributes: mdContents.attributes, content: mdContents.body, rawPath: filePath, isPost }; return mdFileContents; default: throw new Error(`extension "${ext}" not supported!`); } } <file_sep>/pages/blog/2016/machine-learning/advice-for-applying-machine-learning.md --- title: "Advice for Applying Machine Learning" author: name: <NAME> site: http://vkbansal.me date: 2016-05-30 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Deciding What to Try Next Errors in your predictions can be troubleshooted by: - Getting more training examples - Trying smaller sets of features - Trying additional features - Trying polynomial features - Increasing or decreasing $\lambda$ Don't just pick one of these avenues at random. We'll explore diagnostic techniques for choosing one of the above solutions in the following sections. ## Evaluating a Hypothesis A hypothesis may have low error for the training examples but still be inaccurate (because of overfitting). With a given dataset of training examples, we can split it up the data into two sets: a **training set** (70%) and a **test set** (30%). The new procedure using these two sets is then: 1. Learn $\Theta$ and minimize $J_{train}(\Theta)$ using the training set. 2. Compute the test set error $J_{test}(\Theta)$. ### The test set error **For linear regression**: $$ J_{test}(\Theta)=\frac{1}{2m_{test}}\sum_{i=1}^{m_{test}} \left(h_\Theta(x^{(i)}_{test})−y^{(i)}_{test}\right)^2 $$ **For classification**: Misclassification error (aka 0/1 misclassification error): $$ \begin{align*} err(h_\Theta(x), y)= \begin{matrix} & 1 &\text{ if }h_\Theta(x) \geq 0.5 \text{ and } y=0 \text{ or } h_\Theta(x) < 0.5 \text{ and } y = 1 \\ & 0 &\text { otherwise}\end{matrix} \end {align*} $$ This gives us a binary $0$ or $1$ error result based on a misclassification. The average test error for the test set is $$ \text{Test Error} = \frac{1}{m_{test}} \sum^{m_{test}}_{i=1} err(h_\Theta(x^{(i)}_{test}),y^{(i)}_{test}) $$ This gives us the proportion of the test data that was misclassified. ## Model Selection and Train/Validation/Test Sets Just because a learning algorithm fits a training set well, that does not mean it is a good hypothesis. The error of your hypothesis as measured on the data set with which you trained the parameters will be lower than any other data set. In order to choose the model of your hypothesis, you can test each degree of polynomial and look at the error result. 1. Optimize the parameters in $\Theta$ using the training set for each polynomial degree. 2. Find the polynomial degree $d$ with the least error using the test set. 3. Estimate the generalization error also using the test set with $J_{test}(\Theta^{(d)})$, (d = theta from polynomial with lower error); In this case, we have trained one variable, $d$, or the degree of the polynomial, using the test set. This will cause our hypothesis to work well only the test set and the error value will be greater for any other set of data. To solve this, we can introduce a third set, the **Cross Validation Set**, to serve as an intermediate set that we can train $d$ with. Then our test set will give us an accurate, non-optimistic error. One example way to break down our dataset into the three sets is: - Training set: 60% - Cross validation set: 20% - Test set: 20% We can now calculate three separate error values for the three different sets: 1. Optimize the parameters in $\Theta$ using the training set for each polynomial degree. 2. Find the polynomial degree $d$ with the least error using the cross validation set. 3. Estimate the generalization error using the test set with $J_{test}(\Theta^{(d)})$, (d = theta from polynomial with lower error); This way, the degree of the polynomial $d$ has not been trained using the test set. ## Diagnosing Bias vs. Variance In this section we examine the relationship between the degree of the polynomial d and the underfitting or overfitting of our hypothesis. - We need to distinguish whether **bias** or **variance** is the problem contributing to bad predictions. - High bias is underfitting and high variance is overfitting. We need to find a golden mean between these two. The training error will tend to **decrease** as we increase the degree $d$ of the polynomial. At the same time, the cross validation error will tend to **decrease** as we increase d up to a point, and then it will **increase** as d is increased, forming a convex curve. The is represented in the figure below: ![Features-and-polynom-degree](./images/features-and-polynomial-degree.png) <!--{.img-center}--> ## Regularization and Bias/Variance Instead of looking at the degree $d$ contributing to bias/variance, now we will look at the regularization parameter $\lambda$. A large lambda heavily penalizes all the $\Theta$ parameters, which greatly simplifies the line of our resulting function, so causes underfitting. On the other hand, if use small $\lambda$, the resulting function may have high variance. The figure below illustrates the relationship between lambda and the cost: ![Features-and-lambda](./images/features-and-lambda.png) <!--{.img-center}--> In order to choose the model and the regularization $\lambda$, we need: 1. Create a list of lambda (i.e.$ λ \in \{0,0.01,0.02,0.04,0.08,0.16,0.32,0.64,1.28,2.56,5.12,10.24\}$); 2. Select a lambda to compute; 3. Create a model set like degree of the polynomial or others; 4. Select a model to learn $\Theta$; 5. Learn the parameter $\Theta$ for the model selected, using $J_{train}(\Theta)$ **with** $\lambda$ selected (this will learn $\Theta$ for the next step); 6. Compute the train error using the learned $\Theta$ (computed with $\lambda$ ) on the $J_{train}(\Theta)$ **without** regularization or $\lambda = 0$; 7. Compute the cross validation error using the learned $\Theta$ (computed with $\lambda$) on the $J_{CV}(\Theta)$ **without** regularization or $\lambda = 0$; 8. Do this for the entire model set and lambdas, then select the best combo that produces the lowest error on the cross validation set; 9. Now if you need visualize to help you understand your decision, you can plot to the figure like above with: ($\lambda \times \text{Cost } J_{train}(\Theta)$) and ($\lambda \times \text{Cost } J_{CV}(\Theta)$); 10. Now using the best combo $\Theta$ and $\lambda$, apply it on $J_{test}(\Theta)$ to see if it have a good generalization of the problem. 11. To help decide the best polynomial degree and $\lambda$ to use, we can diagnose with the learning curves, that is the next subject. ## Learning Curves Training $3$ examples will easily have $0$ errors because we can always find a quadratic curve that exactly touches $3$ points. - As the training set gets larger, the error for a quadratic function increases. - The error value will plateau out after a certain $m$, or training set size. **With high bias :** - **Low training set size**: causes $J_{train}(\Theta)$ to be low and $J_{CV}(\Theta)$ to be high. - **Large training set size**: causes both $J_{train}(\Theta)$ and $J_{CV}(\Theta)$ to be high with $ J_{train}(\Theta)\approx J_{CV}(\Theta)$. If a learning algorithm is suffering from **high bias**, getting more training data **will not (by itself) help much**. For high variance, we have the following relationships in terms of the training set size: **With high variance :** - **Low training set size**: $J_{train}(\Theta)$ will be low and $J_{CV}(\Theta)$ will be high. - **Large training set size**: $J_{train}(\Theta)$ increases with training set size and $J_{CV}(\Theta)$ continues to decrease without leveling off. Also, $J_{train}(\Theta) < J_{CV}(\Theta)$ but the difference between them remains significant. If a learning algorithm is suffering from **high variance**, getting more training data is **likely to help.** **Learning curve for high bias (at fixed model complexity)** ![Learning curve for high bias](./images/Learning2.png) <!--{.img-center}--> **Learning curve for high variance (at fixed model complexity)** ![Learning1](./images/Learning1.png) <!--{.img-center}--> ## Deciding What to Do Next Revisited Our decision process can be broken down as follows: - Getting more training examples => Fixes **high variance** - Trying smaller sets of features => Fixes **high variance** - Adding features => Fixes **high bias** - Adding polynomial features => Fixes **high bias** - Decreasing $\lambda$ Fixes **high bias** - Increasing $\lambda$ Fixes **high variance** ### Diagnosing Neural Networks - A neural network with fewer parameters is **prone to underfitting**. It is also **computationally cheaper**. - A large neural network with more parameters is **prone to overfitting**. It is also **computationally expensive**. In this case you can use regularization (increase $\lambda$) to address the overfitting. Using a single hidden layer is a good starting default. You can train your neural network on a number of hidden layers using your cross validation set. ## Model Selection: - Choosing $M$ the order of polynomials. - How can we tell which parameters $\Theta$ to leave in the model (known as **model selection**)? There are several ways to solve this problem: 1. Get more data (very difficult). 2. Choose the model which best fits the data without overfitting (very difficult). 3. Reduce the opportunity for overfitting through regularization. **Bias**: approximation error (Difference between expected value and optimal value) - High Bias = UnderFitting - $J_{train}(\Theta)$ and $J_{CV}(\Theta)$ both will be high and Jtrain(Θ)≈JCV(Θ) **Variance**: estimation error due to finite data - High Variance = OverFitting - $J_{train}(\Theta)$ is low and $J_{CV}(\Theta) \gg J_{train}(\Theta)$ **Intuition for the bias-variance trade-off**: - Complex model => sensitive to data => much affected by changes in X => high variance, low bias. - Simple model => more rigid => does not change as much with changes in X => low variance, high bias. One of the most important goals in learning: finding a model that is just right in the bias-variance trade-off. #### Regularization Effects: - Small values of $\lambda$ allow model to become finely tuned to noise leading to large variance => overfitting. - Large values of $\lambda$ pull weight parameters to zero leading to large bias => underfitting. #### Model Complexity Effects: - Lower-order polynomials (low model complexity) have high bias and low variance. In this case, the model fits poorly consistently. - Higher-order polynomials (high model complexity) fit the training data extremely well and the test data extremely poorly. These have low bias on the training data, but very high variance. - In reality, we would want to choose a model somewhere in between, that can generalize well but also fits the data reasonably well. #### A typical rule of thumb when running diagnostics is: - More training examples fixes high variance but not high bias. - Fewer features fixes high variance but not high bias. - Additional features fixes high bias but not high variance. - The addition of polynomial and interaction features fixes high bias but not high variance. - When using gradient descent, decreasing lambda can fix high bias and increasing lambda can fix high variance (lambda is the regularization parameter). - When using neural networks, small neural networks are more prone to under-fitting and big neural networks are prone to over-fitting. Cross-validation of network size is a way to choose alternatives.<file_sep>/pages/blog/2016/machine-learning/neural-networks-learning.md --- title: "Neural Networks: Learning" author: name: <NAME> site: http://vkbansal.me date: 2016-05-14 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Cost Function Let's first define a few variables that we will need to use: $$ \begin{align*} L &= \text{total number of layers in the network}\\ s_l &= \text{number of units (not counting bias unit) in layer }l \\ K &= \text{number of output units/classes} \end{align*} $$ Recall that in neural networks, we may have many output nodes. We denote $h_\Theta(x)_k$ as being a hypothesis that results in the $k^{th}$ output. Our cost function for neural networks is going to be a generalization of the one we used for logistic regression. Recall that the cost function for regularized logistic regression was: $$ J(\theta)=\frac{−1}{m} \sum_{i=1}^{m}\left[y^{(i)} log(h_\theta(x^{(i)}))+(1−y^{(i)}) log(1−h_\theta(x^{(i)}))\right]+\frac{\lambda}{2m} \sum_{j=1}^{n} \theta_j^2 $$ For neural networks, it is going to be slightly more complicated: $$ J(\Theta)=\frac{−1}{m}\left[ \sum_{i=1}^{m} \sum_{k=1}^{K} y^{(i)}_klog((h_\Theta(x^{(i)}))_k)+(1−y^{(i)}_k) log(1−(h_\Theta(x^{(i)}))_k)\right]+\frac{\lambda}{2m}\sum_{l=1}^{L−1} \sum_{i=1}^{s_l} \sum_{j=1}^{s_{l+1}}(\Theta^{(l)}_{j,i})^2 $$ We have added a few nested summations to account for our multiple output nodes. In the first part of the equation, between the square brackets, we have an additional nested summation that loops through the number of output nodes. In the regularization part, after the square brackets, we must account for multiple theta matrices. The number of columns in our current theta matrix is equal to the number of nodes in our current layer (including the bias unit). The number of rows in our current theta matrix is equal to the number of nodes in the next layer (excluding the bias unit). As before with logistic regression, we square every term. Note: - The double sum simply adds up the logistic regression costs calculated for each cell in the output layer; and. - The triple sum simply adds up the squares of all the individual $\Theta$s in the entire network. - The $i$ in the triple sum does **not** refer to training example $i$. ## Backpropagation Algorithm **Backpropagation** is neural-network terminology for minimizing our cost function, just like what we were doing with gradient descent in logistic and linear regression. Our goal is to compute: $$ \min_\Theta J(\Theta) $$ That is, we want to minimize our cost function $J$ using an optimal set of parameters in theta. In this section we'll look at the equations we use to compute the partial derivative of $J(\Theta)$: $$ \frac{\partial}{\partial \Theta^{(l)}_{i,j}} J(\Theta) $$ In backpropagation we're going to compute for every node: $$ \delta^{(l)}_j = error \text{ of node} j \text{ in layer } l $$ Recall that $a^{(l)}_j$ is activation node $j$ in layer $l$. For the **last layer**, we can compute the vector of delta values with: $$ \delta^{(L)} = a^{(L)} - y $$ Where $L​$ is our total number of layers and $a^{(L)}​$ is the vector of activation units for the last layer. So our **error values** for the last layer are simply the differences of our actual results in the last layer and the correct outputs in $y​$. To get the delta values of the layers before the last layer, we can use an equation that steps us back from right to left: $$ \delta^{(l)} = ((\Theta^{(l)})^T \delta^{(l+1)}).*g'(z^{(l)}) $$ The delta values of layer $l$ are calculated by multiplying the delta values in the next layer with the theta matrix of layer $l$. Here $\Theta$ **does not include** bias terms. We then element-wise multiply that with a function called $g'$, or g-prime, which is the derivative of the activation function $g$ evaluated with the input values given by $z^{(l)}$. The g-prime derivative terms can also be written out as: $$ g'(z^{(l)}) = a^{(l)}.*(1-a^{(l)}) $$ The full backpropagation equation for the inner nodes is then: $$ \delta^{(l)} = \left( (\Theta^{(l)})^T \delta^{(l+1)} \right).* \space a^{(l)} .* \space (1-a^{(l)}) $$ We can compute our partial derivative terms by multiplying our activation values and our error values for each training example $t$: $$ \frac{\partial J(\Theta)}{\partial \Theta_{i,j}} = \frac{1}{m} \sum_{t=1}^m a^{(t)(l)}_j \delta^{(t)(l+1)}_i $$ Vectorized implementation: $$ \Delta^{(l)} = \delta^{(l +1)}(a^{(l)})^T $$ This however ignores regularization, which we'll deal with later. We can now take all these equations and put them together into a backpropagation algorithm: **Backpropagation Algorithm** - Given training set $\{(x^{(1)},y^{(1)}), \dots, (x^{(m)},y^{(m)})\}$ - Set $\Delta^{(l)}_{i,j} :=0$ for all $(l,i,j)$ - For training example $t=1$ to $m$: - Set $a^{(1)} :=x^{(t)}$ - Perform forward propagation to compute $a^{(l)}$ for $l=2,3, \dots,L$ - Using $y^{(t)}$, compute $\delta^{(L)}=a^{(L)}−y^{(t)}$ - Compute $\delta^{(L−1)},\delta^{(L−2)},\dots,\delta^{(2)}$ using $\delta^{(l)}= \left( (\Theta^{(l)})^T \delta^{(l+1)}\right) .* g'(z^{(l)})$ - $\Delta^{(l)}_{i,j} := \Delta^{(l)}_{i,j} + a^{(l)}_j \delta^{(l+1)}_i$ or with vectorization, $\Delta^{(l)} :=\Delta^{(l)}+\delta^{(l+1)}(a^{(l)})^T$ - $D^{(l)}_{i,j} := \frac{1}{m} \Delta^{(l)}_{i,j} + \lambda \Theta^{(l)}_{i,j}$. **If** $j \neq 0$. - $D^{(l)}_{i,j} := \frac{1}{m} \Delta^{(l)}_{i,j}$ . **If** $j=0$ The capital-delta matrix is used as an **accumulator** to add up our values as we go along and eventually compute our partial derivative. The actual proof is quite involved, but, the $D^{(l)}_{i,j}$ terms are the partial derivatives and the results we are looking for: $$ D^{(l)}_{i,j} = \frac{\partial J(\Theta)}{\partial \Theta^{(l)}_{i,j}} $$ ## Backpropagation Intuition The cost function is: $$ J(\Theta)=\frac{−1}{m}\left[ \sum_{i=1}^{m} \sum_{k=1}^{K} y^{(i)}_klog((h_\Theta(x^{(i)}))_k)+(1−y^{(i)}_k) log(1−(h_\Theta(x^{(i)}))_k)\right]+\frac{\lambda}{2m}\sum_{l=1}^{L−1} \sum_{i=1}^{s_l} \sum_{j=1}^{s_{l+1}}(\Theta^{(l)}_{j,i})^2 $$ If we consider simple non-multiclass classification (k = 1) and disregard regularization, the cost is computed with: $$ cost(t) = y^{(t)} \space log(h_\theta(x^{(t)})) + (1 - y^{(t)}) \space log(1 - h_\theta(x^{(t)})) $$ More intuitively you can think of that equation roughly as: $$ cost(t) \approx (h_\theta(x^{(t)}) - y ^{(t)})^2 $$ Intuitively, $\delta^{(l)}_j$ is the **error** for $a^{(l)}_j$ (unit $j$ in layer $l$). More formally, the delta values are actually the derivative of the cost function: $$ \delta^{(l)}_j = \frac{\partial}{\partial z^{(l)}_j} cost(t) $$ Recall that our derivative is the slope of a line tangent to the cost function, so the steeper the slope the more incorrect we are. Note: In lecture, sometimes $i$ is used to index a training example. Sometimes it is used to index a unit in a layer. In the Back Propagation Algorithm described here, $t$ is used to index a training example rather than overloading the use of $i$. ## Implementation Note: Unrolling Parameters With neural networks, we are working with sets of matrices: $$ \Theta_1, \Theta_2, \Theta_3, \dots \\ D_1, D_2, D_3, \dots $$ In order to use optimizing functions such as `fminunc()`, we will want to **unroll** all the elements and put them into one long vector: ```octave thetaVector = [ Theta1(:); Theta2(:); Theta3(:); ] deltaVector = [ D1(:); D2(:); D3(:) ] ``` If the dimensions of Theta1 is $10 \times 11$, Theta2 is $10 \times 11$ and Theta3 is $1 \times 11$, then we can get back our original matrices from the **unrolled** versions as follows: ```octave Theta1 = reshape(thetaVector(1:110),10,11) Theta2 = reshape(thetaVector(111:220),10,11) Theta3 = reshape(thetaVector(221:231),1,11) ``` ## Gradient Checking Gradient checking will assure that our backpropagation works as intended. We can approximate the derivative of our cost function with: $$ \frac{\partial}{\partial \Theta} J (\Theta) \approx \frac{J(\Theta + \epsilon) - J(\Theta - \epsilon)}{2 \epsilon} $$ With multiple theta matrices, we can approximate the derivative **with respect to** $\Theta_j$ as follows: $$ \frac{\partial}{\partial \Theta_j} J(\Theta) \approx \frac{J(\Theta_1, \dots, \Theta_{j+ \epsilon}, \dots, \Theta_n) - J(\Theta_1, \dots, \Theta_{j - \epsilon}, \dots, \Theta_n)}{2 \epsilon} $$ A good small value for $\epsilon$ (epsilon), guarantees the math above to become true. If the value be much smaller, may we will end up with numerical problems. The professor Andrew usually uses the value $\epsilon = 10^{−4}$. We are only adding or subtracting epsilon to the $\Theta_j$ matrix. In octave we can do it as follows: ```octave epsilon = 1e-4; for i = 1:n, thetaPlus = theta; thetaPlus(i) += epsilon; thetaMinus = theta; thetaMinus(i) -= epsilon; gradApprox(i) = (J(thetaPlus) - J(thetaMinus))/(2*epsilon) end; ``` We then want to check that gradApprox ≈ deltaVector. Once you've verified **once** that your backpropagation algorithm is correct, then you don't need to compute gradApprox again. The code to compute gradApprox is very slow. ## Random Initialization Initializing all theta weights to zero does not work with neural networks. When we backpropagate, all nodes will update to the same value repeatedly. Instead we can randomly initialize our weights: Initialize each $\Theta^{(l)}_{i,j}$ to a random value between $[− \epsilon, \epsilon]$. ```octave % If the dimensions of Theta1 is 10x11, Theta2 is 10x11 and Theta3 is 1x11. Theta1 = rand(10,11) * (2 * INIT_EPSILON) - INIT_EPSILON; Theta2 = rand(10,11) * (2 * INIT_EPSILON) - INIT_EPSILON; Theta3 = rand(1,11) * (2 * INIT_EPSILON) - INIT_EPSILON; ``` `rand(x,y)` will initialize a matrix of random real numbers between $0$ and $1$. (Note: this *epsilon* is unrelated to the *epsilon* from Gradient Checking) ## Putting it Together First, pick a network architecture; choose the layout of your neural network, including how many hidden units in each layer and how many layers total. - Number of input units = dimension of features $x^{(i)}$ - Number of output units = number of classes - Number of hidden layers = Reasonable default of 1 or if more than 1 hidden layer, then the same number of units in every hidden layer. - Number of hidden units per layer = usually more the better (must balance with cost of computation as it increases with more hidden units) **Training a Neural Network** 1. Randomly initialize the weights 2. Implement forward propagation to get $h_\Theta(x^{(i)})$ 3. Implement the cost function $J(\Theta)$ 4. Implement backpropagation to compute partial derivatives $\frac{\partial J(\Theta)}{\partial \Theta^{(l)}_{i,j}}$ 5. Use gradient checking to compare $\frac{\partial J(\Theta)}{\partial \Theta^{(l)}_{i,j}}$ computed using backpropagation and using numerical estimate of gradient. Then disable gradient checking. 6. Use gradient descent or a built-in optimization function to minimize the cost function with the weights in theta. When we perform forward and back propagation, we loop on every training example: $$ \begin{align*} &\text{for } i = 1:m \\ & \hspace{2em} \text{Perform forward propagation and backpropagation using example } (x^{(i)},y^{(i)}) \\ & \hspace{2em} \text{(Get activations } a^{(l)} \text{ and delta terms } \delta^{(l)} \text{ for } l = 2,\dots,L \text{)} \end{align*} $$ ## Explanation of Derivatives Used in Backpropagation We know that for a logistic regression classifier (which is what all of the output neurons in a neural network are), we use the cost function, $J(\theta)=−y \space log(h_\theta(x))−(1−y)\space log(1 − h_\theta(x))$, and apply this over the $K$ output neurons, and for all $m$ examples. The equation to compute the partial derivatives of the theta terms in the output neurons can be written as: $$ \frac{\partial J(\theta)}{\partial \theta^{(L-1)}} = \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L)}} \frac{\partial z^{(L)}}{\partial \theta^{(L-1)}} $$ And the equation to compute partial derivatives of the theta terms in the [last] hidden layer neurons (layer $L-1$) can be written as: $$ \frac{\partial J(\theta)}{\partial \theta^{(L-2)}} = \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L-1)}} \frac{\partial z^{(L-1)}}{\partial a^{(L-1)}} \frac{\partial a^{(L-1)}}{\partial z^{(L-2)}} \frac{\partial z^{(L-2)}}{\partial \theta^{(L-2)}} $$ Clearly they share some pieces in common, so a delta term ($\delta(L)$) can be used for the common pieces between the output layer and the hidden layer immediately before it (with the possibility that there could be many hidden layers if we wanted): $$ \delta^{(L)} = \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L)}} $$ And we can go ahead and use another delta term $\delta^{(L−1)}$ for the pieces that would be shared by the final hidden layer and a hidden layer before that, if we had one. Regardless, this delta term will still serve to make the math and implementation more concise. $$ \begin{align*} \delta^{(L-1)} &= \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L)}} \frac{\partial z^{(L)}}{\partial a^{(L -1)}} \frac{\partial a^{(L-1)}}{\partial z^{(L-1)}} \\ &=\delta^{(L)} \frac{\partial z^{(L)}}{\partial a^{(L -1)}} \frac{\partial a^{(L-1)}}{\partial z^{(L-1)}} \end{align*} $$ With these delta terms, our equations become: $$ \begin{align*} \frac{\partial J(\theta)}{\partial \theta^{(L-1)}} &= \delta^{(L)} \frac{\partial z^{(L)}}{\partial \theta^{(L-1)}} \\ \frac{\partial J(\theta)}{\partial \theta^{(L-2)}} &= \delta^{(L-1)} \frac{\partial z^{(L-1)}}{\partial \theta^{(L-2)}} \\ \end{align*} $$ Now, time to evaluate these derivatives: Let's start with the output layer: $$ \begin{align*} \frac{\partial J(\theta)}{\partial \theta^{(L - 1 )}} & = \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L)}} \frac{\partial z^{(L)}}{\partial \theta^{(L - 1)}} \\ &= \delta^{(L)} \frac{\partial z^{(L)}}{\partial \theta^{(L - 1)}} \end{align*} $$ Given $J(\theta)=−y \space log(a^{(L)})−(1−y) \space log(1−a^{(L)})$, where $a^{(L)}=h_\theta(x)$, the partial derivative is: $$ \frac{\partial J(\theta)}{\partial a^{(L)}} = \frac{-y}{a^{(L)}} - \frac{(1-y)}{1-a^{(L)}} $$ And given $a=g(z)$, where $g=\frac{1}{1+e^{−z}}$, the partial derivative is: $$ \frac{\partial a^{(L)}}{\partial z^{(L)}} = a^{(L)}(1-a^{(L)}) $$ So, let's substitute these in for $\delta(L)$: $$ \begin{align*} \delta(L) &= \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L)}} \\ \\ &= \left( \frac{-y}{a^{(L)}} - \frac{(1-y)}{1-a^{(L)}} \right) a^{(L)}(1-a^{(L)}) \\ \\ &= -y(1-a^{(L)}) - a^{(L)}(1-y) \\ \\ &= a^{(L)} -y \end{align*} $$ Now, given $z=\theta ∗ input$, and in layer $L$ the $input$ is $a^{(L−1)}$, the partial derivative is: $$ \frac{\partial z^{(L)}}{\partial \theta^{(L-1)}} = a^{(L-1)} $$ Putting it together for the output layer: $$ \begin{align*} \frac{\partial J(\theta)}{\partial \theta^{(L - 1 )}} &= \delta^{(L)} \frac{\partial z^{(L)}}{\partial \theta^{(L - 1)}} \\ \\ &= (a^{(L)} -y) \space a^{(L-1)} \end{align*} $$ Let's continue on for the hidden layer (assuming we only have 1 hidden layer): $$ \begin{align*} \frac{\partial J(\theta)}{\partial \theta^{(L-2)}} &= \frac{\partial J(\theta)}{\partial a^{(L)}} \frac{\partial a^{(L)}}{\partial z^{(L-1)}} \frac{\partial z^{(L-1)}}{\partial a^{(L-1)}} \frac{\partial a^{(L-1)}}{\partial z^{(L-2)}} \frac{\partial z^{(L-2)}}{\partial \theta^{(L-2)}} \\ \\ &=\delta^{(L)} \frac{\partial z^{(L)}}{\partial a^{(L -1)}} \frac{\partial a^{(L-1)}}{\partial z^{(L-1)}} \\ \\ &= \delta^{(L-1)} \frac{\partial z^{(L-1)}}{\partial \theta^{(L-2)}} \\ \end{align*} $$ Let's compute $\delta^{(L - 1)}$. Once again, given $z=θ ∗ input$, the partial derivative is: $$ \frac{\partial z^{(L)}}{\partial a^{(L-1)}} = \theta^{(L-1)} $$ And given $a=g(z)$, where $g=\frac{1}{1+e^{−z}}$, the partial derivative is: $$ \frac{\partial a^{(L-1)}}{\partial z^{(L-1)}} = a^{(L-1)}(1-a^{(L-1)}) $$ So, let's substitute these in $\delta^{(L−1)}$: $$ \begin{align*} \delta^{(L-1)} &=\delta^{(L)} \frac{\partial z^{(L)}}{\partial a^{(L -1)}} \frac{\partial a^{(L-1)}}{\partial z^{(L-1)}} \\ \\ &= \delta^{(L)} \theta^{(L-1)} a^{(L-1)}(1-a^{(L-1)}) \\ \\ &= \delta^{(L)} \theta^{(L-1)} g'(a^{(L-1)}) \end{align*} $$ Put it together for the [last] hidden layer: $$ \begin{align*} \frac{\partial J(\theta)}{\partial \theta^{(L - 2)}} &= \delta^{(L-1)} \frac{\partial z^{(L-1)}}{\partial \theta^{(L-2)}} \\ \\ &= \delta^{(L)} \theta^{(L-1)} a^{(L-1)} (1 - a^{(L-1)}) a^{(L-2)} \end{align*} $$ <file_sep>/pages/blog/2016/machine-learning/large-scale-machine-learning.md --- title: "Large Scale Machine Learning" author: name: <NAME> site: http://vkbansal.me date: 2016-07-30 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" draft: true math: true --- ## Learning with Large Datasets We mainly benefit from a very large dataset when our algorithm has *high variance* . If our algorithm has *high bias*, more data will not have any benefit. Datasets can often approach such sizes as $m=100,000,000$. In this case, our gradient descent step will have to make a summation over all one hundred million examples , which can be computationally expensive and we will want to try to avoid this -- the approaches for doing so are described below. ## Stochastic Gradient Descent Stochastic gradient descent is an alternative to classic (or batch) gradient descent and is more efficient and scalable to large data sets. Stochastic gradient descent is written out in a different but similar way: $$ cost(\theta, (x^{(i)}, y^{(i)})) = \frac{1}{2} (h_\theta(x^{(i)}) - y^{(i)})^2 $$ The only difference in the above cost function is the elimination of the $m$ constant within $\frac{1}{2}$. $$ J_{train}(\theta) = \frac{1}{m} \sum_{i=1}^m cost(\theta, (x^{(i)}, y^{(i)})) $$ $J_{train}$ is now just the average of the cost applied to all of our training examples. The algorithm is as follows: 1. Randomly **shuffle** the dataset 2. For $i = 1,\dots, m$ $$ \theta_j := \theta_j - \alpha(h_\theta(x^{(i)})- y^{(i)}) \cdot x^{(i)}_j \hspace{2em} \text{(for } j = 0, \dots,n \text{)} $$ This algorithm will only try to fit one training example at a time. This way we can make progress in gradient descent without having to scan all $m$ training examples first. Stochastic gradient descent will be unlikely to converge at the global minimum and will instead wander around it randomly, but usually yields a result that is close enough. Stochastic gradient descent will usually take $1-10$ passes through your data set to get near the global minimum. ## Mini-Batch Gradient Descent Mini-batch gradient descent can sometimes be even faster than stochastic gradient descent. Instead of using all $m$ examples as in batch gradient descent, and instead of using only $1$ example as in stochastic gradient descent, we will use some in-between number of examples $b$. Typical values for $b$ range from $2-100$ or so. For example, with $b=10$ and $m=1000$: $$ \begin{align*} &\text{Repeat : \{} \\ & \hspace{2em} \text{for } i = 1,11, 21,31, \dots, 991:\\ & \hspace{4em} \theta_j := \theta_j - \alpha \frac{1}{10} \sum_{k=i}^{i+9}(h_\theta(x^{(k)})-y^{(k)}) x^{(k)}_j \\ & \} \end{align*} $$ We're simply summing over ten examples at a time. The advantage of computing more than one example at a time is that we can use **vectorized** implementations over the $b$ examples. ## Stochastic Gradient Descent Convergence How do we choose the learning rate α for stochastic gradient descent? Also, how do we debug stochastic gradient descent to make sure it is getting as close as possible to the global optimum? One strategy is to plot the average cost of the hypothesis applied to every 1000 or so training examples. We can compute and save these costs during the gradient descent iterations. With a smaller learning rate, it is **possible** that you may get a slightly better solution with stochastic gradient descent. That is because stochastic gradient descent will oscillate and jump around the global minimum, and it will make smaller random jumps with a smaller learning rate. If you increase the number of examples you average over to plot the performance of your algorithm, the plot's line will become smoother. With a very small number of examples for the average, the line will be too noisy and it will be difficult to find the trend. One strategy for trying to actually converge at the global minimum is to **slowly decrease α over time**. For example $α=\frac{const1}{iterationNumber+const2}$. However, this is not often done because people don't want to have to fiddle with even more parameters. ## Online Learning With a continuous stream of users to a website, we can run an endless loop that gets $(x,y)$, where we collect some user actions for the features in $x$ to predict some behavior $y$. You can update $\theta$ for each individual $(x,y)$ pair as you collect them. This way, you can adapt to new pools of users, since you are continuously updating theta. ## Map Reduce and Data Parallelism We can divide up batch gradient descent and dispatch the cost function for a subset of the data to many different machines so that we can train our algorithm in parallel. You can split your training set into $z$ subsets corresponding to the number of machines you have. On each of those machines calculate $\sum_{i=p}^q(h_\theta(x^{(i)})−y^{(i)})⋅x^{(i)}_j$, where we've split the data starting at $p$ and ending at $q$. MapReduce will take all these dispatched (or 'mapped') jobs and 'reduce' them by calculating: $$ \theta_j := \theta_j - \alpha \frac{1}{z}(temp^{(1)}_j + temp^{(2)}_j + \cdots + temp^{(z)}_j) $$ For all $j=0,\dots,n$. This is simply taking the computed cost from all the machines, calculating their average, multiplying by the learning rate, and updating theta. Your learning algorithm is MapReduceable if it can be *expressed as computing sums of functions over the training set*. Linear regression and logistic regression are easily parallelizable. For neural networks, you can compute forward propagation and back propagation on subsets of your data on many machines. Those machines can report their derivatives back to a 'master' server that will combine them. <file_sep>/scripts/utils/processCSS.ts import * as path from 'path'; import sass from 'sass'; import postcss from 'postcss'; import localByDefault from 'postcss-modules-local-by-default'; import Scope from 'postcss-modules-scope'; import cssNano from 'cssnano'; import { isProduction, stringHash } from './miscUtils'; import options from '../options.json'; import { fileLoader } from './fileLoader'; const scope = Scope({ generateScopedName(exportedName, _, css) { const hash = stringHash(exportedName + css, 'sha1', 'hex').slice(0, 8); if (isProduction()) { return `css-${hash}`; } return `css_${exportedName}_${hash}`; } }); const extractAssets = postcss.plugin('postcss-extract-assets', () => { return function(root) { root.each((node) => { if (node.type == 'rule') { node.each((decl) => { if (decl.type == 'decl' && decl.value.startsWith('url(')) { const [, srcPath] = decl.value.match(/url\((.*)\)/) || ['', '']; const newPath = fileLoader( srcPath, path.join(process.cwd(), options.srcPath, 'dummy.css') ); decl.value = `url(${newPath})`; } }); } }); }; }); export async function processCSS(data: string, mode: 'local' | 'global' = 'local') { try { const exportTokens: Record<string, string> = {}; const extractExports = postcss.plugin('postcss-extract-imports', () => { return function(root) { root.each((node) => { if (node.type === 'rule' && node.selector === ':export') { node.each((decl) => { if (decl.type === 'decl') { exportTokens[decl.prop] = decl.value; } }); node.remove(); } }); }; }); const postCSSPlugins: postcss.AcceptedPlugin[] = [ (localByDefault({ mode }) as unknown) as postcss.Transformer, (scope as unknown) as postcss.Transformer, extractExports, extractAssets ]; if (isProduction()) { postCSSPlugins.push((cssNano as unknown) as postcss.Plugin<cssNano.CssNanoOptions>); } const css = sass.renderSync({ data, includePaths: [path.join(process.cwd(), 'styles')] }); const parser = postcss(postCSSPlugins); const result = await parser.process(css.css, { from: undefined }); return { css: result.css, exports: exportTokens }; } catch (e) { console.log(e); process.exit(1); } } <file_sep>/typings/markdown-it-mathjax/index.d.ts declare module 'markdown-it-mathjax' { const plugin: any; export default plugin; } <file_sep>/scripts/rss.js import RSS from 'rss'; export default function ({ settings, posts }) { let feedOptions = { title: settings.site.title, description: settings.site.description, feed_url: settings.site.base_url.replace(/\/$/, '') + '/blog/feed.xml', site_url: settings.site.base_url }; let feed = new RSS(feedOptions); posts.slice(0, 15).forEach((post) => { let itemOptions = { title: post.title, description: post.description, url: post.permalink, date: post.date }; feed.item(itemOptions); }); return feed.xml({ indent: true }); } <file_sep>/pages/blog/2016/machine-learning/dimensionality-reduction.md --- title: "Dimensionality Reduction" author: name: <NAME> site: http://vkbansal.me date: 2016-07-24 description: My notes from Machine Learning Course by <NAME>. tag: - notes - "machine-learning" draft: true math: true --- ## Motivation I: Data Compression - We may want to reduce the dimension of our features if we have a lot of redundant data. - To do this, we find two highly correlated features, plot them, and make a new line that seems to describe both features accurately. We place all the new features on this single line. Doing dimensionality reduction will reduce the total data we have to store in computer memory and will speed up our learning algorithm. Note: in dimensionality reduction, we are reducing our features rather than our number of examples. Our variable m will stay the same size; n, the number of features each example from x(1) to x(m) carries, will be reduced. ## Motivation II: Visualization It is not easy to visualize data that is more than three dimensions. We can reduce the dimensions of our data to 3 or less in order to plot it. We need to find new features, z1,z2 (and perhaps z3) that can effectively **summarize** all the other features. Example: hundreds of features related to a country's economic system may all be combined into one feature that you call "Economic Activity." ## Principal Component Analysis Problem Formulation The most popular dimensionality reduction algorithm is *Principal Component Analysis* (PCA) **Problem formulation** Given two features, x1 and x2, we want to find a single line that effectively describes both features at once. We then map our old features onto this new line to get a new single feature. The same can be done with three features, where we map them to a plane. The **goal of PCA** is to **reduce** the average of all the distances of every feature to the projection line. This is the **projection error**. > Reduce from 2d to 1d: find a direction (a vector u(1)∈Rn) onto which to project the data so as to minimize the projection error. The more general case is as follows: > Reduce from n-dimension to k-dimension: Find k vectors u(1),u(2),…,u(k) onto which to project the data so as to minimize the projection error. If we are converting from 3d to 2d, we will project our data onto two directions (a plane), so k will be 2. **PCA is not linear regression** - In linear regression, we are minimizing the **squared error** from every point to our predictor line. These are vertical distances. - In PCA, we are minimizing the **shortest distance**, or shortest *orthogonal* distances, to our data points. More generally, in linear regression we are taking all our examples in x and applying the parameters in Θ to predict y. In PCA, we are taking a number of features x1,x2,…,xn, and finding a closest common dataset among them. We aren't trying to predict any result and we aren't applying any theta weights to the features. ## Principal Component Analysis Algorithm Before we can apply PCA, there is a data pre-processing step we must perform: **Data preprocessing** > Given training set: x(1),x(2),…,x(m) > > Preprocess (feature scaling/mean normalization): > > μj=1m∑mi=1x(i)j > > Replace each x(i)j with x(i)j−μj > > If different features on different scales (e.g., x1= size of house, x2= number of bedrooms), scale features to have comparable range of values. Above, we first subtract the mean of each feature from the original feature. Then we scale all the features (x(i)j=x(i)j−μjsj) We can define specifically what it means to reduce from 2d to 1d data as follows: x(i)∈R2→z(i)∈R The z values are all real numbers and are the projections of our features onto u(1). So, PCA has two tasks: figure out u(1),…,u(k) and also to find z1,z2,…,zm. The mathematical proof for the following procedure is complicated and beyond the scope of this course. **1. Compute "covariance matrix"** Σ=1m∑mi=1(x(i))(x(i))T This can be vectorized in Octave as: ``` Sigma = (1/m) * X' * X; ``` We denote the covariance matrix with a capital sigma (which happens to be the same symbol for summation, confusingly---they represent entirely different things). Note that x(i) is an n×1 vector, (x(i))T is an 1×n vector and X is a m×n matrix (row-wise stored examples). The product of those will be an n×n matrix, which are the dimensions of Σ. **2. Compute "eigenvectors" of covariance matrix Σ** ``` [U,S,V] = svd(Sigma); ``` svd() is the 'singular value decomposition', a built-in Octave function. What we actually want out of svd() is the 'U' matrix of the Sigma covariance matrix: U∈Rn×n. U contains u(1),…,u(n), which is exactly what we want. **3. Take the first k columns of the U matrix and compute z** We'll assign the first k columns of U to a variable called 'Ureduce'. This will be an n×k matrix. We compute z with: z(i)=UreduceT⋅x(i) UreduceT will have dimensions k×n while x(i) will have dimensions n×1. The product UreduceT⋅x(i) will have dimensions k×1. To summarize, the whole algorithm in octave is roughly: ``` Sigma = (1/m) * X' * X;  % compute the covariance matrix [U,S,V] = svd(Sigma);  % compute our projected directions Ureduce = U(:,1:k);  % take the first k directions z = Ureduce' * x;  % compute the projected data points ``` ## Choosing the Number of Principal Components How do we choose k, also called the *number of principal components*? Recall that k is the dimension we are reducing to. One way to choose k is by using the following formula: > Given the average squared projection error: 1m∑mi=1||x(i)−x(i)approx||2 > > Also given the total variation in the data: 1m∑mi=1||x(i)||2 > > Choose k to be the smallest value such that: 1m∑mi=1∣∣∣∣x(i)−x(i)approx∣∣∣∣21m∑mi=1∣∣∣∣x(i)∣∣∣∣2≤0.01 (1%) In other words, the squared projection error divided by the total variation should be less than one percent, so that **99% of the variance is retained**. **Algorithm for choosing k** 1. Try PCA with k=1,2,… 2. Compute Ureduce,z,x 3. Check the formula given above that 99% of the variance is retained. If not, go to step one and increase k. This procedure would actually be horribly inefficient. In Octave, we will call svd: ``` [U,S,V] = svd(Sigma) ``` Which gives us a matrix S. We can actually check for 99% of retained variance using the S matrix as follows: ∑ki=1Sii∑ni=1Sii≥0.99 ## Reconstruction from Compressed Representation If we use PCA to compress our data, how can we uncompress our data, or go back to our original number of features? To go from 1-dimension back to 2d we do: z∈R→x∈R2. We can do this with the equation: x(1)approx=Ureduce⋅z(1). Note that we can only get approximations of our original data. ## Advice for Applying PCA The most common use of PCA is to speed up supervised learning. Given a training set with a large number of features (e.g. x(1),…,x(m)∈R10000) we can use PCA to reduce the number of features in each example of the training set (e.g. z(1),…,z(m)∈R1000). Note that we should define the PCA reduction from x(i) to z(i) **only on the training set** and not on the cross-validation or test sets. You can apply the mapping z(i) to your cross-validation and test sets after it is defined on the training set. **Applications** - Compressions - Reduce space of data - Speed up algorithm - Visualization of data - Choose k = 2 or k = 3 **Bad use of PCA**: trying to prevent overfitting. We might think that reducing the features with PCA would be an effective way to address overfitting. It might work, but is not recommended because it does not consider the values of our results y. Using just regularization will be at least as effective. Don't assume you need to do PCA. **Try your full machine learning algorithm without PCA first.** Then use PCA if you find that you need it. <file_sep>/pages/blog/2016/machine-learning/linear-regression-with-one-variable/readme.md --- title: Linear Regression with One Variable author: name: <NAME> site: http://vkbansal.me date: 2016-05-01 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Model Representation In *regression problems*, we taking input variables and trying to fit the output onto a*continuous* expected result function. Linear regression with one variable is also known as "univariate linear regression." Univariate linear regression is used when you want to predict a **single output** value from a **single input** value. We now introduce notation for equations. $$ \begin{align*} m &= \text{number of training examples} \\ x 's &= \text{input variable/features} \\ y's &= \text{output variable/target variable} \\ (x, y) &= \text{one training example} \\ (x^{(i)}, y^{(i)}) &= i^{th} \text{ training example} \end{align*} $$ We're doing **supervised learning** here, so that means we already have an idea about what the input/output cause and effect should be. So h We feed training set a learning algorithm. Is the job of a learning algorithm to then output a function which by convention is usually denoted lowercase $h$ and $h$ stands for **hypothesis**. And hypothesis is a function that maps from $x$'s to $y$'s. ![hypothesis](./hypothesis.png) <!--{.img-center}--> ## The Hypothesis Function Our hypothesis function has the general form: $h_\theta(x) = \theta_0 + \theta_1 x$ Note that this is like the equation of a straight line and $\theta_1$ is the slope of the line. We give to $h_\theta(x)$ values for $\theta_0$ and $\theta_1$ to get our output $y$. In other words, we are trying to create a function called $h_\theta$ that is trying to map our input data (the $x$'s) to our output data (the $y$'s). **Example:** | x (input) | y (output) | | :-------: | :--------: | | 0 | 4 | | 1 | 7 | | 2 | 7 | | 3 | 8 | Now we can make a random guess about our $h_\theta$ function: $\theta_0=2$ and $\theta_1=2$. The hypothesis function becomes $h_\theta(x)= 2 + 2x$. ![univariate-linear-regression-hypothesis](./univariate-linear-regression-hypothesis.png) <!--{.img-center}--> The red crosses indicate $y$'s and the blue line is our hypothesis. So for input of $1$ to our hypothesis, $y$ will be $4$. This is off by $3$. Note that we will be trying out various values of $\theta_0$ and $\theta_1$ to try to find values which provide the best possible "fit" or the most representative "straight line" through the data points mapped on the x-y plane. ## Cost Function We can measure the accuracy of our hypothesis function by using a **cost function**. This takes an average (actually a fancier version of an average) of all the results of the hypothesis with inputs from x's compared to the actual output y's. $$ J(\theta_0, \theta_1) = \dfrac {1} {2m} \displaystyle \sum _{i=1}^m \left ( h_\theta(x_{i}) - y_{i}\right)^2 $$ This function is otherwise called the **Squared error function**, or **Mean squared error**. The mean is halved ($\dfrac {1}{2m}$) as a convenience for the computation of the gradient descent, as the derivative term of the square function will cancel out the $\dfrac {1}{2}$ term. To break it apart, it is $\dfrac {1}{2} \bar x$ where $\bar x$ is the mean of the squares of $h_\theta(x_{i})−y_{i}$, or the difference between the predicted value and the actual value as it can be seen in figure below. ![univariate-linear-regression-hypothesis](./univariate-linear-regression-error.png) <!--{.img-center}--> We are trying to make straight line (defined by $h_\theta(x)$) which passes through our set of data. Our objective is to get the best possible line. The best possible line will be such so that the average distances of the scattered points from the line will be the least. In the best case, the line should pass through all the points of our training data set. In such a case the value of $J(\theta_0,\theta_1)$ will be $0$. ## Gradient Descent So we have our hypothesis function and we have a way of measuring how accurate it is. Now what we need is a way to automatically improve our hypothesis function. That's where gradient descent comes in. If we graph our hypothesis function based on its fields $\theta_0$ and $\theta_1$.We put $\theta_0$ on the x axis and $\theta_1$ on the y axis, with the cost function on the vertical z axis. The points on our graph will be the result of the **cost function** using our hypothesis with those specific theta parameters. We are not graphing $x $and $y$ itself, but the parameter range of our hypothesis function and the cost resulting from selecting particular set of parameters. ![Gradient Descent](./gradient-descent.png) <!--{.img-center}--> We will know that we have succeeded when our cost function is at the very bottom of the pits in our graph, i.e. when its value is the minimum. The way we do this is by taking the **derivative** (the line tangent to a function) of our cost function. The slope of the tangent is the derivative at that point and it will give us a direction to move towards. We make steps down that derivative by the parameter $\alpha$, called the **learning rate**, until we reach a local minima. The gradient descent algorithm is: $$ \begin{alignat}{0} \text {repeat until convergence: } \lbrace \\ \hspace{2em} \theta_j := \theta_j - \alpha \frac{\partial}{\partial \theta_j} J(\theta_0, \theta_1)\\ \rbrace \hspace{2em} \text {for } j = 0 \text{ and } j = 1 \end{alignat} $$ Note: We need to use simultaneous updates $$ \begin{align*} temp0 &:= \theta_0 - \alpha \frac{\partial}{\partial \theta_0} J (\theta_0, \theta_1) \\ temp1 &:= \theta_1 - \alpha \frac{\partial}{\partial \theta_1} J (\theta_0, \theta_1) \\ \theta_0 &:= temp0 \\ \theta_1 &:= temp1\\ \end{align*} $$ Intuitively, this could be thought of as: $$ \begin{align*} & \text{repeat until convergence: } \lbrace & \newline & \hspace{2em} \theta_j:= \theta_j - \alpha[\text{Slope of tangent in j dimension}] \newline & \rbrace \\ \end{align*} $$ ## Gradient Descent for Linear Regression When specifically applied to the case of linear regression, a new form of the gradient descent equation can be derived. We can substitute our actual cost function and our actual hypothesis function and modify the equation to (the derivation of the formulas can be found at end): $$ \begin{align*} & \text{repeat until convergence: } \lbrace & \newline & \hspace{2em} \theta_0 := \theta_0 - \alpha \frac{1}{m} \sum\limits_{i=1}^{m}(h_\theta(x_{i}) - y_{i}) \newline & \hspace{2em} \theta_1 := \theta_1 - \alpha \frac{1}{m} \sum\limits_{i=1}^{m}\left((h_\theta(x_{i}) - y_{i}) x_{i}\right) \newline & \rbrace \newline \end{align*} $$ where $m$ is the size of the training set, $\theta_0$ a constant that will be changing simultaneously with $\theta_1$ and $x_i$, $y_i$ are values of the given training set (data). Note that we have separated out the two cases for $\theta_j$ into separate equations for $ \theta_0$ and $\theta_1$; and that for $\theta_1$ we are multiplying $x_i$ at the end due to the derivative. The point of all this is that if we start with a guess for our hypothesis and then repeatedly apply these gradient descent equations, our hypothesis will become more and more accurate. ## Gradient Descent for Linear Regression: Intuition Let us start with simple hypothesis $h_\theta = \theta_1 x$. (i.e $\theta_0 = 0$) If we plot a graph between parameter $\theta_1$ and cost function $J(\theta_1)$, it will look something like this. ![Parabola](./parabola.png) <!--{.img-center}--> Suppose we start with $\theta_1$ that has positive slope: ![Parabola](./parabola-p-slope.png) <!--{.img-center}--> The $\theta_1$ value will be updated as $\theta_1 := \theta_1 - \alpha [\text{positive number}]$, thus $\theta_1$ will decrease until it reaches local minima. On the other hand, if we start with $\theta_1$ with negative slope: ![Parabola -ve](./parabola-n-slope.png) <!--{.img-center}--> The $\theta_1$ value will be updated as $\theta_1 := \theta_1 - \alpha [\text{negative number}]$, thus $\theta_1$ will increase until it reaches local minima. If $\alpha$ is too small, gradient descent can be too slow, where as if it is too large, it can overshoot the minima. It may fail to converge, or even diverge. Gradient descent can converge to a local minimum, even with the learning rate $\alpha$ fixed. As we approach a local minimum, gradient descent will automatically take smaller steps. So, no need to decrease $\alpha$ over time. The same can be extended to hypothesis: $h_\theta (x)= \theta_0 + \theta_1 x$. The plot for cost function in this case will be a surface plot: ![Gradient Descent](./gradient-descent.png) <!--{.img-center}--> If we start from any arbitrary point on the graph and apply gradient descent (using slope at that point), we will reach a minima eventually. ## Frequently Asked Questions: **Q: Why is the cost function about the sum of squares, rather than the sum of cubes?** A: The sum of squares isn’t the only possible cost function, but it has many nice properties. Squaring the error means that an overestimate is "punished" just the same as an underestimate: an error of $-1$ is treated just like $+1$, and the two equal but opposite errors can’t cancel each other. If we cube the error, we lose this property. Big errors are punished more than small ones, so an error of $2$ becomes $4$. The squaring function is smooth (can be differentiated) and yields linear forms after differentiation, which is nice for optimization. It also has the property of being “convex”. A convex cost function guarantees there will be a global minimum, so our algorithms will converge. **Q: Why can’t I use 4th powers in the cost function? Don’t they have the nice properties of squares?** A: Imagine that you are throwing darts at a dartboard, or firing arrows at a target. If you use the sum of squares as the error (where the center of the bulls-eye is the origin of the coordinate system), the error is the distance from the center. Now rotate the coordinates by 30 degree, or 45 degrees, or anything. The distance, and hence the error, remains unchanged. 4th powers lack this property, which is known as “rotational invariance”. **Q: Why does 1/(2 \* m) make the math easier?** A: When we differentiate the cost to calculate the gradient, we get a factor of 2 in the numerator, due to the exponent inside the sum. This '2' in the numerator cancels-out with the '2' in the denominator, saving us one math operation in the formula. ## Derivation of Gradient Descent Equations We know that hypothesis is $h_\theta = \theta_0 + \theta_1 x$, and cost function is: $$ J(\theta_0, \theta_1) = \frac{1}{2m} \sum_{i=1}^{m} \left( h_\theta (x^{(i)}) - y^{(i)}\right)^2 $$ Solving for derivatives: $$ \begin{align*} \frac{\partial}{\partial \theta_0} J(\theta_0, \theta_1) & = \frac{\partial}{\partial \theta_0} \frac{1}{2m} \sum_{i=1}^{m} \left( h_\theta (x^{(i)}) - y^{(i)}\right)^2 \\ &= \frac{\partial}{\partial \theta_0} \frac{1}{2m} \sum_{i=1}^{m} \left( \theta_0 + \theta_1 x ^{(i)}- y^{(i)}\right)^2 \\ &= \frac{\partial}{\partial \theta_0} \frac{1}{2m} \sum_{i=1}^{m} \left( \theta_0^2 + \theta_1^2 ( x^{(i)})^2+ (y^{(i)})^2 + 2 \theta_0 \theta_1x^{(i)} - 2 \theta_0 y^{(i)} - 2 \theta_1x^{(i)}y^{(i)} \right) \\ &= \frac{1}{2m} \sum_{i=1}^{m} \left(2 \theta_0 + 2 \theta_1x^{(i)} - 2 y^{(i)} \right) \\ &= \frac{1}{m} \sum_{i=1}^{m} \left( \theta_0 + \theta_1x^{(i)} - y^{(i)} \right) \\ &= \frac{1}{m} \sum_{i=1}^{m} \left( h_\theta(x^{(i)}) - y^{(i)} \right) \\ \\ \frac{\partial}{\partial \theta_1} J(\theta_0, \theta_1) & = \frac{\partial}{\partial \theta_1} \frac{1}{2m} \sum_{i=1}^{m} \left( h_\theta (x^{(i)}) - y^{(i)}\right)^2 \\ &= \frac{\partial}{\partial \theta_1} \frac{1}{2m} \sum_{i=1}^{m} \left( \theta_0 + \theta_1 x ^{(i)}- y^{(i)}\right)^2 \\ &= \frac{\partial}{\partial \theta_1} \frac{1}{2m} \sum_{i=1}^{m} \left( \theta_0^2 + \theta_1^2 ( x^{(i)})^2+ (y^{(i)})^2 + 2 \theta_0 \theta_1x^{(i)} - 2 \theta_0 y^{(i)} - 2 \theta_1x^{(i)}y^{(i)} \right) \\ &= \frac{1}{2m} \sum_{i=1}^{m} \left(2 \theta_1 (x^{(i)})^2 + 2 \theta_0x^{(i)} - 2 x^{(i)}y^{(i)} \right) \\ &= \frac{1}{m} \sum_{i=1}^{m} \left( \theta_0 + \theta_1x^{(i)} - y^{(i)} \right) x^{(i)} \\ &= \frac{1}{m} \sum_{i=1}^{m} \left( h_\theta(x^{(i)}) - y^{(i)} \right) x^{(i)} \end{align*} $$ <file_sep>/pages/blog/2016/using-multiple-ssh-keys.md --- title: Using multiple SSH keys. author: name: <NAME> site: http://vkbansal.me date: 2016-01-04 description: Here we take a look at using multiple ssh keys. tag: - unix - ssh - server --- There might be situations where one might want to use different SSH keys for different sites. And here's how to do it. ## SSH keys I'm assuming that we have already generated different SSH keys for `github.com` and `bitbucket.org` in `~/.ssh/`. ``` $ cd ~/.ssh $ ls id_rsa id_rsa.pub github_rsa github_rsa.pub bitbucket_rsa bitbucket_rsa.pub ``` ## Config Now create a `config` file in `~/.ssh`. ``` $ cd ~/.ssh $ touch config ``` And add the following lines to the file using your favorite editor. ``` host github.com IdentityFile ~/.ssh/github_rsa host bitbucket.org IdentityFile ~/.ssh/bitbucket_rsa ``` Reload the SSH service (depends on your system) and your are all set. ## Wrap Up I hope you find this tip useful. Let me know using comments down below or tweet me [@_vkbansal](https://twitter.com/_vkbansal). <file_sep>/typings/common.ts export enum FileType { MD = 'MD', TS = 'TS' } export enum PageType { POST = 'POST', PAGE = 'PAGE' } export interface MDFileAttributes { title: string; date: Date; description: string; tag: string[]; author: { name: string; site: string; }; isDraft?: boolean; math?: boolean; } export interface BaseFileContents<T = any> { attributes: T; url: string; rawPath: string; } export interface PostContents extends BaseFileContents<MDFileAttributes> { type: PageType.POST; content: string; slug: string; writtenToDisk: boolean; } export interface PageContents extends BaseFileContents { type: PageType.PAGE; content: string; writtenToDisk: boolean; } export interface MDFileContents extends BaseFileContents<MDFileAttributes | undefined> { type: FileType.MD; content: string; isPost: boolean; } export interface RenderArgs extends BaseFileContents<MDFileAttributes | undefined> { posts: PostContents[]; assets: Record<'css' | 'js', string[]>; content: string; isProduction: boolean; isPost: boolean; slug: string; } export interface Page { url: string; content: string; } export type RenderedContent = string | Page | Page[]; export interface TSFileContents extends BaseFileContents { type: FileType.TS; render(args: RenderArgs): RenderedContent | Promise<RenderedContent>; styles(): string; } export type AllFileContent = TSFileContents | MDFileContents; export type AllContent = PageContents | PostContents; <file_sep>/pages/blog/2016/simple-dial-chart-using-react-and-d3.md --- title: Simple dial chart using react and d3 description: A simple dial using react and d3 modules. date: 2016-02-01 author: name: <NAME> site: http://vkbansal.me tag: - react - d3 - charts - javascript --- Here is a simple dial chart in react by making use of [d3-shape](https://github.com/d3/d3-shape) and [d3-scale](https://github.com/d3/d3-scale) modules. ``` jsx "use strict"; import React from "react"; import ReactDOM from "react-dom"; import { arc } from "d3-shape"; import { scaleLinear } from "d3-scale"; const startAngle = -1 * Math.PI / 3; // - 60deg const endAngle = Math.PI / 3; // 60deg //Create an arc path for dial const dial = arc() .startAngle(startAngle) .endAngle(endAngle) .innerRadius(80) .outerRadius(145); //Create a scale for using with arc const scale = scaleLinear() .domain([0, 100]) // Adjust the values according to your data .range([startAngle, endAngle]); const Chart = React.createClass({ render() { const width = 300, height = 300, transform = `translate(${width * 0.5},${0.65 * height})`, current = (x) => dial.endAngle(scale(x))(); // get arc path for given value return ( <svg viewBox={`0 0 ${width} ${height}`}> <path fill="#dddddd" d={dial()} transform={transform}/> <path fill="#f44336" d={current(this.props.fill)} transform={transform}/> </svg> ); } }); //Do not forget to include/change the id of the target element ReactDOM.render(<Chart fill={60}/>, document.getElementById("main")); ``` <p><iframe height='268' scrolling='no' src='//codepen.io/vkbansal/embed/preview/NxzBGM/?height=268&theme-id=0&default-tab=result' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/vkbansal/pen/NxzBGM/'>Simple dial chart using react and d3</a> by <NAME> (<a href='http://codepen.io/vkbansal'>@vkbansal</a>) on <a href='http://codepen.io'>CodePen</a>. </iframe> </p> <file_sep>/pages/blog/2017/pie-donut-chart-without-d3/readme.md --- title: Drawing pie/donut chart without d3 description: Create a pie/donut-chart using nothing but vanilla JS math: true date: 2017-02-26 author: name: <NAME> site: http://vkbansal.me tag: - d3 - charts - javascript --- As an exercise on learning how SVG works, I decided to create a pie/donut-chart using nothing but vanilla JS (Yes, not even d3!). ## SVG coordinate system and arcs For creating any charts, we need to understand few things about SVG first. Unlike, normal graph coordinate system, the SVG coordinate has its Y-axis reversed. As you increase y-coordinates, the point moves down instead of up and vice-cersa. (You can read more about it [here](http://tutorials.jenkov.com/svg/svg-coordinate-system.html)). Next, to draw an arc, we will be using `path` element of SVG, and we need a starting-point, radius and an end-point for it. A typical arc path looks something like this: ```html <path d="M40,20 A30,30 0 0,1 70,70" style="stroke: #0000ff; stroke-width:2; fill:none;"/> ``` We will focus mainly on `d` attribute. The two parameters after `M` indicate a starting point. The two parameters after `A` indicate the `x-radius` and `y-radius` of the arc respectively. The third parameter after `A` indicates `x-axis-rotation` and can be ignored for now. The fourth and fifth parameters after `A` indicate `large-arc-flag` and `sweep-flag` respectively. Given any two points, only two arcs can be drawn through them with give radii and it controlled using `large-arc-flag`. As shown below, the blue arc is the smaller one (denoted by `0`) and the the red arc is the the larger one (denoted by `1`). ![svg arcs](./arcs.svg) <!--{.img-center}--> The `sweep-flag` controls whether the arc is be to drawn in counter-clockwise direction (denoted by `0` and shown in blue) or clock-wise-direction (denoted by `1` and shown in red). ![svg arcs](./arcs-direction.svg) <!--{.img-center}--> For more detailed info, you can [read this](http://tutorials.jenkov.com/svg/path-element.html#arcs) ## The Math The following is a diagram of a circle in the SVG coordinate-system. We assume that `r` is the radius of the the circle. ![chart-analysis](./donught-chart-analysis.png) <!--{.img-center}--> Now suppose we want the coordinates of a point $A$ on the circle which has an angle $\theta$ from vertical axis, we will make projections of $A$ on horizontal and vertical axis as $\vec{X}$ and $\vec{Y}$ respectively. By using basic trigonometry we get: $$ \begin{align} & X = r + r sin\theta = r (1 + sin\theta) \newline & Y = r - r cos\theta = r (1 - cos\theta) \newline \newline & \text{Thus, } A = [r (1+ sin\theta), r(1 - cos\theta)] \end{align} $$ For a donut chart, we will need to make another smaller circle with radius $r'$ where $r' < r$. And similar to above example, we get coordinates of a point on this smaller circle as $$ \left[r' (1+ sin\theta), r'(1 - cos\theta)\right] $$ To make a donut-chart, we need to make these circles concentric (have same centers), thus, we need to shift the smaller circle by $r - r'$ in both directions. Thus the updated coordinates for smaller circle are: $$ \begin{align} &[(r'(1 + sin\theta)) + (r - r'), (r'(1 - cos\theta)) + (r - r')] \newline & = [r + r'sin\theta, r - r'cos\theta] \end{align} $$ ## Drawing an arc Now we will learn how to draw an arc $(\widehat{PQRS})$ as shown in picture below. We assume that the start angle of the arc is $\alpha$ and the end angle is $\beta$. We also assume that the inner-radius $(\overline{OS})$ is $r_1$ the outer-radius $(\overline{OP})$ is $r_2$. ![Drawing-arc](./drawing-arc.png) <!--{.img-center}--> From the above section, we can concluded that $$ \begin{align} & P = [r_2 + r_2 sin\alpha, r_2 - r_2 cos\alpha] \newline & Q = [r_2 + r_2 sin\beta, r_2 - r_2 cos\beta] \newline & R =[r_2 + r_1 sin\beta, r_2 - r_1 cos\beta] \newline & S = [r_2 + r_1 sin\alpha, r_2 - r_1 cos\alpha] \end{align} $$ For drawing the arc, we will start from point `P(x, y)`. Thus, we can write: ```html <path d="M P.x,P.y" /> ``` Next we move **clock-wise** to point `Q(x, y)` with radius `r2`. Thus, we can write: ```html <path d="M P.x,P.y A r2,r2 0 0,1 Q.x,Q.y" /> ``` Next we move to point `R(x, y)`. Thus we can write: ```html <path d="M P.x,P.y A r2,r2 0 0,1 Q.x,Q.y L R.x,R.y" /> ``` Next we move **counterclock-wise** to point `S(x, y)` with radius `r1`. Thus, we can write: ```html <path d="M P.x,P.y A r2,r2 0 0,1 Q.x,Q.y L R.x,R.y A r1,r1 0 0,0 S.x,S.y Z" /> ``` The final `Z` is to close the path. There is one last bit remaining. We need to decide whether to use large-arc or small-arc (flip `large-arc-flag`) based on the angle of the arc $(\beta - \alpha )$. If it is greater than $\pi$, we must use large-arc else small-arc. The final javascript code will look like this: ```javascript function arc(startAngle, endAngle, outerRadius, innerRadius = 0) { const sinAlpha = Math.sin(startAngle); const cosAlpha = Math.cos(startAngle); const sinBeta = Math.sin(endAngle); const cosBeta = Math.cos(endAngle); const largeArc = endAngle - startAngle > Math.PI; const P = { x: outerRadius + (outerRadius * sinAlpha), y: outerRadius - (outerRadius * cosAlpha) }; const Q = { x: outerRadius + (outerRadius * sinBeta), y: outerRadius - (outerRadius * cosBeta) }; const R = { x: outerRadius + (innerRadius * sinBeta), y: outerRadius - (innerRadius * cosBeta) }; const S = { x: outerRadius + (innerRadius * sinAlpha), y: outerRadius - (innerRadius* cosAlpha) } return `M${P.x},${P.y} A${outerRadius},${outerRadius} 0 ${largeArc ? '1,1' : '0,1'} ${Q.x},${Q.y} L${R.x},${R.y} A${innerRadius},${innerRadius} 0 ${largeArc ? '1,0' : '0,0'} ${S.x},${S.y} Z`; } ``` ## Plotting the chart with data Suppose you have data in the the following format: ```javascript // random data from https://www.mockaroo.com/ const data = [ { "label": "web-enabled", "value": 717, "color": "#460898" } /* ... */ ]; ``` Total can be easily calculated using `Array.proptotype.reduce`: ```javascript const total = data.reduce((p, c) => p + c.value, 0); ``` Now that we have raw data and total, we have to scale the data linearly between `0` and `2π` ```javascript function scale (value) { return value * Math.PI * 2 / total; } ``` Now we can loop over the data and plot the chart. You can use any of your favourite frameworks like React, Vue, etc., or not and simply use vanilla JS as follows: ```javascript const fragment = document.createDocumentFragment(); const outerRadius = 300; const innerRadius = 150; let startAngle = 0; data.forEach((slice) => { const { value, color, label } = slice; const sectorAngle = scale(value); const d = arc(startAngle, startAngle + sectorAngle, outerRadius, innerRadius); startAngle += sectorAngle; const path = document.createElementNS('http://www.w3.org/2000/svg','path'); const title = document.createElementNS('http://www.w3.org/2000/svg','title'); title.innerHTML = label; path.setAttribute('d', d); path.setAttribute('fill', color); path.appendChild(title); fragment.appendChild(path); }); document.getElementById('pie').appendChild(fragment); // assuming there is an svg with #pie available ``` And we are done. Now you'll a functional pie/donught chart without the need of d3! ## Final Result You can have a look at the final result in the codepen demo below. <iframe height='265' scrolling='no' title='donut-chart-no-d3' src='//codepen.io/vkbansal/embed/preview/pevBoP/?height=265&theme-id=0&default-tab=result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/vkbansal/pen/pevBoP/'>donut-chart-no-d3</a> by <NAME> (<a href='http://codepen.io/vkbansal'>@vkbansal</a>) on <a href='http://codepen.io'>CodePen</a>. </iframe> <file_sep>/typings/JSX/index.d.ts declare namespace JSX { type A = keyof HTMLElementTagNameMap; interface IntrinsicElements extends Record<A, any> {} } <file_sep>/pages/blog/2016/machine-learning/introduction.md --- title: Introduction to Machine Learning author: name: <NAME> site: http://vkbansal.me date: 2016-04-29 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - machine-learning --- ## What is Machine Learning? Two definitions of Machine Learning are offered. Arthur Samuel described it as: *the field of study that gives computers the ability to learn without being explicitly programmed.* This is an older, informal definition. Tom Mitchell provides a more modern definition: *A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.* Example: playing checkers. - E = the experience of playing many games of checkers - T = the task of playing checkers. - P = the probability that the program will win the next game. ## Supervised Learning In supervised learning, we are given a data set and already know what our correct output should look like, having the idea that there is a relationship between the input and the output. Supervised learning problems are categorized into **regression** and **classification** problems. In a **regression** problem, we are trying to predict results within a continuous output, meaning that we are trying to map input variables to some **continuous** function. In a **classification** problem, we are instead trying to predict results in a **discrete** output. In other words, we are trying to map input variables into **discrete** categories. **Example 1:** Given data about the size of houses on the real estate market, try to predict their price. Price as a function of size is a continuous output, so this is a regression problem. We could turn this example into a classification problem by instead making our output about whether the house "sells for more or less than the asking price." Here we are classifying the houses based on price into two discrete categories. **Example 2:** 1. Regression: Given a picture of Male/Female, We have to predict his/her age on the basis of given picture. 2. Classification: Given a picture of Male/Female, We have to predict Whether He/She is of High-school, College, Graduate age. 3. Another Example for Classification: Banks have to decide whether or not to give a loan to someone on the basis of his credit history. ## Unsupervised Learning Unsupervised learning, on the other hand, allows us to approach problems with little or no idea what our results should look like. We can derive structure from data where we don't necessarily know the effect of the variables. We can derive this structure by **clustering** the data based on relationships among the variables in the data. With unsupervised learning there is no feedback based on the prediction results, i.e., there is no teacher to correct you. It’s not just about clustering. For example, associative memory is unsupervised learning. **Example:** *Clustering:* Take a collection of 1000 essays written on the US Economy, and find a way to automatically group these essays into a small number that are somehow similar or related by different variables, such as word frequency, sentence length, page count, and so on. Another, non-Clustering example, is the "Cocktail Party Algorithm" which can find structure in messy data- like identifying individual voices and music from a mesh of sounds at a cocktail party.[https://en.wikipedia.org/wiki/Cocktail_party_effect]<file_sep>/scripts/utils/__tests__/getURL.test.ts import { getURL } from '../miscUtils'; describe('buid test', () => { describe('getURL tests', () => { const case1 = [ ['pages', 'index', '/'], ['pages/about', 'index', '/about/'], ['pages/about', 'readme', '/about/'], [ 'pages/blog/2016/machine-learning', 'linear-regression-with-multiple-variables', '/blog/machine-learning/linear-regression-with-multiple-variables/' ], ['pages/blog/2015', 'hello-world-2015', '/blog/hello-world-2015/'], [ 'pages/blog/2016/machine-learning/linear-regression-with-one-variable', 'readme', '/blog/machine-learning/linear-regression-with-one-variable/' ], [ 'pages/blog/2017/pie-donut-chart-without-d3', 'readme', '/blog/pie-donut-chart-without-d3/' ] ]; test.each(case1)('parse url: "%s" + "%s" => "%s"', (dir, file, expected) => { expect(getURL(dir, file)).toBe(expected); }); }); }); <file_sep>/pages/blog/2016/machine-learning/logistic-regression-classification.md --- title: "Logistic Regression: Classification" author: name: <NAME> site: http://vkbansal.me date: 2016-05-07 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- Instead of our output vector $\vec{y}$ being a continuous range of values, it will only be $0$ or $1$. $$ y \in \{ 0, 1 \} $$ Where $0$ is usually taken as the **negative class** and $1$ as the **positive class**, but you are free to assign any representation to it. We're only doing two classes for now, called a *Binary Classification Problem*. One method is to use linear regression and map all predictions greater than $0.5$ as a $1$ and all less than $0.5$ as a $0$. This method doesn't work well because classification is not actually a linear function. ## Hypothesis Representation Our hypothesis should satisfy: $$ 0 \leq h_\theta(x) \leq 1 $$ Our new form uses the **Sigmoid Function**, also called the **Logistic Function**: $$ \begin{align} h_\theta (x) & = g (\theta^Tx) \\ \\ z & = \theta^T x \\ \\ g(z) &= \frac{1}{1 + e^{-z}} \end{align} $$ ![Logistic function](./images/Logistic_function.svg) <!--{.img-center}--> The function $g(z)$, shown here, maps any real number to the $(0, 1)$ interval, making it useful for transforming an arbitrary-valued function into a function better suited for classification. We start with our old hypothesis (linear regression), except that we want to restrict the range to 0 and 1. This is accomplished by plugging $θ^Tx$ into the Logistic Function. $h_\theta$ will give us the **probability** that our output is $1$. For example, $h_\theta(x)=0.7$ gives us the probability of $70\%$ that our output is $1$. $$ \begin{alignat}{0} h_\theta(x) = P(y=1|x; \theta) = 1 - P(y=0|x; \theta) \\ \\ P(y=1|x; \theta) + P(y=0|x; \theta) = 1 \end{alignat} $$ Our probability that our prediction is $0$ is just the complement of our probability that it is $1$ (e.g. if probability that it is $1$ is $70\%$, then the probability that it is $0$ is $30\%$). ## Decision Boundary In order to get our discrete $0$ or $1$ classification, we can translate the output of the hypothesis function as follows: $$ h_\theta \geq 0.5 \longrightarrow y = 1 \\ h_\theta < 0.5 \longrightarrow y = 0 $$ The way our logistic function $g$ behaves is that when its input is greater than or equal to zero, its output is greater than or equal to $0.5$: $$ g(z) \geq 0.5 \text{ when } z \geq 0 $$ Remember: $$ z=0, e^0 =1, g(z) = 1/2 \\ z \rightarrow \infty, e^{-\infty} \rightarrow 0, g (z) = 0 \\ z \rightarrow -\infty, e^{\infty} \rightarrow \infty, g (z) = 1 $$ So if our input to $g$ is $θ^Tx$, then that means: $$ h_\theta(x) = g(\theta^T x) \geq 0.5 \\ \text{ when } \theta^Tx \geq 0 $$ From these statements we can now say: $$ \theta^T x \geq 0 \rightarrow y = 1 \\ \theta^T x < 0 \rightarrow y = 0 $$ The **decision boundary** is the line that separates the area where $y=0$ and where $y=1$. It is created by our hypothesis function. **Example**: $$ \begin{alignat}{0} \theta = \begin{bmatrix} 5 \\ -1 \\ 0 \end{bmatrix} \\ \\ y = 1 \text{ if } 5 + (-1)x_1 + 0x_2 \geq 0 \\ \\ 5 -x_1 \geq 0 \\ \\ x_1 \leq 5 \end{alignat} $$ Our decision boundary then is a straight vertical line placed on the graph where $x_1=5$, and everything to the left of that denotes $y=1$, while everything to the right denotes $y=0$. Again, the input to the sigmoid function $g(z)$ (e.g. $θ^T$x) need not be linear, and could be a function that describes a circle (e.g. $z=_0\theta+\theta_1 x_1^2 + \theta_2 x_2^2$) or any shape to fit our data. ## Cost Function We cannot use the same cost function that we use for linear regression because the Logistic Function will cause the output to be wavy, causing many local optima. In other words, it will not be a convex function. Instead, our cost function for logistic regression looks like: $$ \begin{alignat}{0} J(\theta) = \frac{1}{m} \sum_{i-1}^m Cost\left(h_\theta(x^{(i)}), y^{(i)}\right) \\ \\ Cost\left(h_\theta(x), y\right) = -log(h_\theta(x)) &\text{ if } y = 1 \\ \\ Cost\left(h_\theta(x), y\right) = -log(1 -h_\theta(x)) &\text{ if } y = 0 \\ \end{alignat} $$ **Cost function for $y=1$:** ![Logistic regression cost function positive class](./images/logistic_regression_cost_function_positive_class.png) <!--{.img-center}--> **Cost function for $y=0$:** ![Logistic regression cost function negative class](./images/logistic_regression_cost_function_negative_class.png) <!--{.img-center}--> The more our hypothesis is off from $y$, the larger the cost function output. If our hypothesis is equal to $y$, then our cost is $0$: $$ \begin{alignat}{0} Cost\left(h_\theta(x), y\right) = 0 &\text{ if } h_\theta(x) = y \\ Cost\left(h_\theta(x), y\right) \rightarrow \infty &\text{ if } y = 0 \text{ and } h_\theta(x) \rightarrow 1 \\ Cost\left(h_\theta(x), y\right) \rightarrow \infty &\text{ if } y = 1 \text{ and } h_\theta(x) \rightarrow 0 \\ \end{alignat} $$ If our correct answer $y$ is $0$, then the cost function will be $0$, if our hypothesis function also outputs $0$. If our hypothesis approaches $1$, then the cost function will approach $infinity$. If our correct answer $y$ is $1$, then the cost function will be $0$, if our hypothesis function outputs $1$. If our hypothesis approaches $0$, then the cost function will approach $infinity$. Note that writing the cost function in this way guarantees that $J(\theta)$ is convex for logistic regression. ## Simplified Cost Function and Gradient Descent We can compress our cost function's two conditional cases into one case: $$ Cost\left(h_\theta(x), y\right) = -y \space log\left(h_\theta(x)\right) - (1-y) \space log\left(1-h_\theta(x)\right) $$ Notice that when $y$ is equal to $1$, then the second term ($(1−y) \space log\left(1−h_\theta(x)\right)$) will be zero and will not affect the result. If $y$ is equal to $0$, then the first term ($−y \space log\left(h_\theta(x)\right)$) will be zero and will not affect the result. We can fully write out our entire cost function as follows: $$ J(\theta) = -\frac{1}{m} \sum_{i=1}^m[y^{(i)} \space log\left(h_\theta(x^{(i)})\right) + (1 - y^{(i)}) \space log\left(1-h_\theta(x^{(i)})\right)] $$ A vectorized implementation is: $$ J(\theta) = -\frac{1}{m}\left( log(g(X\theta))^T y + log(1-g(X\theta)^T (1-y))\right) $$ ### Gradient Descent Remember that the general form of gradient descent is: $$ \begin{align*} & \text{Repeat : } \lbrace\\ & \hspace{2em} \theta_j := \theta_j - \alpha \frac{\partial}{\partial \theta_j} J(\theta)\\ & \rbrace \end{align*} $$ We can work out the derivative part using calculus to get: $$ \begin{align*} & \text{Repeat : } \lbrace \\ & \hspace{2em} \theta_j := \theta_j - \frac{\alpha}{m} \sum_{i=1}^{m} \left(h_\theta(x^{(i)} ) - y^{(i)}\right) x_j^{(i)}\\ & \rbrace \end{align*} $$ Notice that this algorithm is identical to the one we used in linear regression. We still have to simultaneously update all values in theta. A vectorized implementation is: $$ \theta := \theta - \frac{\alpha}{m} X^T\left(g(X\theta) - \vec{y}\right) $$ ### Partial derivative of J(θ) First calculate derivative of sigmoid function (it will be useful while finding partial derivative of $J(\theta)$): $$ \begin{align} \sigma(x)' &= (\frac{1}{1 + e^{-x}})' = \frac{-(1+e^{-x})'}{(1 + e^{-x})^2} = \frac{-(-e^{-x})}{(1 + e^{-x})^2} \\ \\ & = \frac{e^{-x}}{(1 + e^{-x})^2} = (\frac{1}{1 + e^{-x}})(\frac{e^{-x}}{1 + e^{-x}}) \\ \\ &= \sigma(x) (\frac{1-1+e^{-x}}{1 + e^{-x}}) = \sigma(x) (\frac{1+e^{-x}}{1 + e^{-x}} - \frac{1}{1 + e^{-x}}) \\\\ &= \sigma(x)(1 - \sigma(x)) \end{align} $$ Now we are ready to find out resulting partial derivative: $$ \begin{align} \frac{\partial}{\partial \theta_j} J(\theta) &= \frac{\partial}{\partial \theta_j} \frac{-1}{m} \sum_{i=i}^m \space \left[y^{(i) } \space log(h_\theta(x^{(i)})) + (1-y^{(i)})log(1-h_\theta(x^{(i)}))\right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[y^{(i)} \frac{\partial}{\partial \theta_j} log(h_\theta(x^{(i)})) + (1-y^{(i)}) \frac{\partial}{\partial \theta_j}log(1-h_\theta(x^{(i)}))\right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[ \frac{y^{(i) } \frac{\partial}{\partial \theta_j} h_\theta(x^{(i)})}{h_\theta(x^{(i)})} + \frac{(1-y^{(i)}) \frac{\partial}{\partial \theta_j} (1-h_\theta(x^{(i)}))}{1-h_\theta(x^{(i)})} \right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[ \frac{y^{(i) } \frac{\partial}{\partial \theta_j} h_\theta(x^{(i)})}{h_\theta(x^{(i)})} + \frac{(1-y^{(i)}) \frac{\partial}{\partial \theta_j} (1-h_\theta(x^{(i)}))}{1-h_\theta(x^{(i)})} \right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[ \frac{y^{(i) } \frac{\partial}{\partial \theta_j} \sigma(\theta^T x^{(i)})}{h_\theta(x^{(i)})} + \frac{(1-y^{(i)}) \frac{\partial}{\partial \theta_j} (1-\sigma(\theta^T x^{(i)}))}{1-h_\theta(x^{(i)})} \right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[ \frac{y^{(i) } \sigma(\theta^T x^{(i)}) (1-\sigma(\theta^T x^{(i)})) \frac{\partial}{\partial \theta_j} \theta^T x^{(i)}}{h_\theta(x^{(i)})} + \frac{-(1-y^{(i)}) \sigma(\theta^T x^{(i)}) (1-\sigma(\theta^T x^{(i)})) \frac{\partial}{\partial \theta_j} \theta^T x^{(i)}}{1-h_\theta(x^{(i)})} \right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[ \frac{y^{(i) } h_\theta(x^{(i)}) (1-h_\theta(x^{(i)})) \frac{\partial}{\partial \theta_j} \theta^T x^{(i)}}{h_\theta(x^{(i)})} - \frac{(1-y^{(i)}) h_\theta(x^{(i)}) (1 - h_\theta(x^{(i)})) \frac{\partial}{\partial \theta_j} \theta^T x^{(i)}}{1-h_\theta(x^{(i)})} \right] \\ &= - \frac{1}{m} \sum_{i=i}^m \space \left[y^{(i)} (1-h_\theta(x^{(i)})) x_j - (1-y^{(i)}) h_\theta(x^{(i)}) x_j \right] \\ & = - \frac{1}{m} \sum_{i=i}^m \space \left[y^{(i)} (1-h_\theta(x^{(i)})) - (1-y^{(i)}) h_\theta(x^{(i)}) \right] x_j\\ & = - \frac{1}{m} \sum_{i=i}^m \space \left[y^{(i)} -y^{(i)} h_\theta(x^{(i)}) - h_\theta(x^{(i)}) + y^{(i)} h_\theta(x^{(i)}) \right] x_j\\ & = - \frac{1}{m} \sum_{i=i}^m \space \left[y^{(i)} - h_\theta(x^{(i)}) \right] x_j\\ & = \frac{1}{m} \sum_{i=i}^m \space \left[h_\theta(x^{(i)}) - y^{(i)} \right] x_j\\ \end{align} $$ ## Advanced Optimization **Conjugate gradient**, **BFGS**, and **L-BFGS** are more sophisticated, faster ways to optimize theta instead of using gradient descent. A. Ng suggests you do not write these more sophisticated algorithms yourself (unless you are an expert in numerical computing) but use them pre-written from libraries. Octave provides them. We first need to provide a function that computes $J(\theta)$ and $\frac{\partial}{\partial \theta} J(\theta)$. We can write a single function that returns both of these: ```octave function [jVal, gradient] = costFunction(theta) jval = [...code to compute J(theta)...]; gradient = [...code to compute derivative of J(theta)...]; end ``` Then we can use octave's `fminunc()` optimization algorithm along with the `optimset()` function that creates an object containing the options we want to send to `fminunc()`. (Note: the value for `MaxIter `should be an integer, not a character string) ```octave options = optimset('GradObj', 'on', 'MaxIter', 100); initialTheta = zeros(2,1); [optTheta, functionVal, exitFlag] = fminunc(@costFunction, initialTheta, options); ``` We give to the function `fminunc()` our cost function, our initial vector of theta values, and the `options` object that we created beforehand. ## Multiclass Classification: One-vs-all Now we will approach the classification of data into more than two categories. Instead of $y = \{0,1\}$ we will expand our definition so that $y = \{0,1...n\}$. In this case we divide our problem into $n+1$ ($+1$ because the index starts at $0$) binary classification problems; in each one, we predict the probability that $y$ is a member of one of our classes. $$ \begin{align} & y \in \{0, 1\cdots n\} \\ & h_\theta^{(0)} = P(y = 0|x; \theta) \\ & h_\theta^{(1)} = P(y = 0|1; \theta) \\ & \vdots \\ & h_\theta^{(n)} = P(y = n|x; \theta) \\ & \mathrm{prediction} = \max_i(h_\theta^{(i)}(x)) \end{align} $$ We are basically choosing one class and then lumping all the others into a single second class. We do this repeatedly, applying binary logistic regression to each case, and then use the hypothesis that returned the highest value as our prediction. <file_sep>/pages/blog/2016/machine-learning/linear-regression-with-multiple-variables.md --- title: Linear Regression with Multiple Variables author: name: <NAME> site: http://vkbansal.me date: 2016-05-04 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - machine-learning math: true --- ## Multiple Features Linear regression with multiple variables is also known as "multivariate linear regression". We now introduce notation for equations where we can have any number of input variables. $$ \begin{align*} x^{(i)}_j &= \text{value of feature } j \text{ in the } i^{th} \text{ training example} \\ x^{i}& = \text{the column vector of all the feature inputs of the } i^{th} \text{ training example} \\ m &= \text{the number of training examples} \\ n &= \left|x^{i}\right| \text{ (number of features)} \end{align*} $$ Now define the multivariable form of the hypothesis function as follows, accomodating these multiple features: $$ h_\theta(x) = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3 + \cdots + \theta_n x_n $$ In order to have little intuition about this function, we can think about $\theta_0$ as the basic price of a house, $\theta_1$ as the price per square meter, $\theta_2$ as the price per floor, etc. $x_1$ will be the number of square meters in the house, $x_2$ the number of floors, etc. Using the definition of matrix multiplication, our multivariable hypothesis function can be concisely represented as: $$ \begin{equation} h_\theta = \begin{bmatrix} \theta_0 \hspace{0.5em} \theta_1 \hspace{0.5em} \cdots \hspace{0.5em} \theta_n \end{bmatrix} \begin{bmatrix} x_0 \\ x_1 \\ \vdots \\ x_n \end{bmatrix} = \theta^T x \end{equation} $$ This is a vectorization of our hypothesis function for one training example. > Note: So that we can do matrix operations with $\theta$ and $x$, we will set $x^{(i)}_0=1$, for all values of $i$. This makes the two vectors $\theta$ and $x^{(i)}$ match each other element-wise (that is, have the same number of elements: $n+1$). Now we can collect all $m$ training examples each with $n$ features and record them in an $m \times n+1$ matrix. In this matrix we let the value of the superscript (the training example) also represent the row number, and, the value of the subscript (feature) also represent the column number (except the initial column is the "zeroth" column), as shown here: $$ \begin{align*} X = \begin{bmatrix} x^{(1)^T} \\ x^{(2)^T} \\ \vdots \\ x^{(m)^T} \\ \end{bmatrix} = \begin{bmatrix} x^{(1)}_0 \hspace{0.5em} x^{(1)}_1 \hspace{0.5em} \cdots \hspace{0.5em} x^{(1)}_n \\ x^{(2)}_0 \hspace{0.5em} x^{(2)}_1 \hspace{0.5em} \cdots \hspace{0.5em} x^{(2)}_n\\ \vdots \\ x^{(m)}_0 \hspace{0.5em} x^{(m)}_1 \hspace{0.5em} \cdots \hspace{0.5em} x^{(m)}_n \\ \end{bmatrix} \end{align*} $$ Notice above that the first row is the first training example (like the vector above), the second row is the second training example, and so forth. Now we can define $h_\theta(X)$ as a column vector that gives the value of $h_\theta(x)$ at each of the $m$ training examples: $$ h_\theta(X) = \begin{bmatrix} \theta_0 x_0^{(1)} + \theta_1 x_1^{(1)} + \cdots + \theta_n x_n^{(1)} \\ \theta_0 x_0^{(2)} + \theta_1 x_1^{(2)} + \cdots + \theta_n x_n^{(2)} \\ \vdots \\ \theta_0 x_0^{(m)} + \theta_1 x_1^{(m)} + \cdots + \theta_n x_n^{(m)} \\ \end{bmatrix} $$ But again using the definition of matrix multiplication, we can represent this more concisely: $$ h_\theta(X) = \begin{bmatrix} x_0^{(1)} \hspace{0.5em} x_1^{(1)} \cdots x_n^{(1)} \\ x_0^{(2)} \hspace{0.5em} x_1^{(2)} \cdots x_n^{(2)} \\ \vdots \\ x_0^{(m)} \hspace{0.5em} x_1^{(m)} \cdots x_n^{(m)} \\ \end{bmatrix} \begin{bmatrix} \theta_0 \\ \theta_1 \\ \vdots \\ \theta_n \end{bmatrix} = X\theta $$ ## Cost function For the parameter vector $\theta$ (of type $\mathbb{R}^{n+1}$ or in $\mathbb{R}^{(n+1)\times1}$), the cost function is: $$ J(\theta) = \frac {1}{2m} \sum_{i=1}^{m}\left( h_\theta(x^{(i)})-y^{(i)} \right)^2 $$ ### Matrix notation $$ J(\theta) = \frac{1}{2m}(X\theta-\vec{y})^T(X\theta - \vec{y}) $$ Where $\vec{y}$ denotes the vector of all $y$ values. ## Gradient Descent for Multiple Variables The gradient descent equation itself is generally the same form; we just have to repeat it for our $n$ features: $$ \begin{align*} & \text{repeat until covergence: } \lbrace \\ & \hspace{2em} \theta_0 := \theta_0 - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)}\right) \cdot x_0^{(i)}\\ & \hspace{2em} \theta_1 := \theta_1 - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)}\right) \cdot x_1^{(i)} \\ & \hspace{2em} \theta_2 := \theta_2 - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)}\right) \cdot x_2^{(i)} \\ & \hspace{2em} \cdots \\ & \rbrace \end{align*} $$ In other words: $$ \begin{align*} & \text{repeat until covergence: } \lbrace \\ & \hspace{2em} \theta_j := \theta_j - \alpha \frac{1}{m} \sum_{i=1}^m \left( h_\theta(x^{(i)}) - y^{(i)}\right) \cdot x_j^{(i)} \\ & \rbrace \hspace{5em} \text{simultaneously update } \theta_j \text{ for }j = (0,1,2,..n) \end{align*} $$ ### Matrix Notation The Gradient Descent rule can be expressed as: $$ \theta := \theta - \alpha \nabla J(\theta) $$ Where $\nabla J(\theta)$ is a column vector of the form: $$ \nabla J (\theta) = \begin{bmatrix} \frac{\partial J(\theta)}{\partial \theta_0} \\ \frac{\partial J(\theta)}{\partial \theta_1} \\ \vdots \\ \frac{\partial J(\theta)}{\partial \theta_n} \\ \end{bmatrix} $$ The $j^{th}$ component of the gradient is the summation of the product of two terms: $$ \begin{align*} \; \frac{\partial J(\theta)}{\partial \theta_j} = \frac{1}{m} \sum_{i = 1}^m \left( h_\theta(x^{(i)} )- y^{(i)} \right) \cdot x_j^{(i)} \\ \; = \frac{1}{m} \sum_{i = 1}^m x_j^{(i)} \cdot \left( h_\theta(x^{(i)} )- y^{(i)} \right) \end{align*} $$ Sometimes, the summation of the product of two terms can be expressed as the product of two vectors. Here, the term $x^{(i)}_j$ represents the $m$ elements of the $j^{th}$ row $\vec{x}_j$ ($j^{th}$ feature $\vec{x}_j$) of the training set $X$. The other term $\left(h_\theta(x^{(i)})−y^{(i)}\right)​$ is the vector of the deviations between the predictions $h_\theta(x^{(i)})​$ and the true values $y^{(i)}​$. Re-writing $\frac{\partial J(\theta)}{\partial \theta_j}​$, we have: $$ \frac{\partial J(\theta)}{\partial \theta_j} = \frac {1}{m} \vec{x}_j^T (X \theta - \vec{y}) \\ \nabla J(\theta) = \frac{1}{m} X^T (X \theta - \vec{y}) $$ Finally, the matrix notation (vectorized) of the Gradient Descent rule is: $$ \theta := \theta - \frac{\alpha}{m}X^T(X\theta - \vec{y}) $$ ## Feature Normalization We can speed up gradient descent by having each of our input values in roughly the same range. This is because $\theta$ will descend quickly on small ranges and slowly on large ranges, and so will oscillate inefficiently down to the optimum when the variables are very uneven. The way to prevent this is to modify the ranges of our input variables so that they are all roughly the same. Ideally: $−1≤xi≤1$ or $−0.5≤xi≤0.5$ These aren't exact requirements; we are only trying to speed things up. The goal is to get all input variables into roughly one of these ranges, give or take a few. Two techniques to help with this are **feature scaling** and **mean normalization**. Feature scaling involves dividing the input values by the range (i.e. the maximum value minus the minimum value) of the input variable, resulting in a new range of just 1. Mean normalization involves subtracting the average value for an input variable from the values for that input variable, resulting in a new average value for the input variable of just zero. To implement both of these techniques, adjust your input values as shown in this formula: $$ x_i := \frac{x_i-\mu_i}{ s_i} $$ Where $\mu_i$ is the average of all the values and $s_i$ is the maximum of the range of values minus the minimum or $s_i$ is the standard deviation. **Example**: $x_i$ is housing prices in range $100-2000$. Then, $$ x_i := \frac{price - 1000}{1900} $$ where $1000$ is the average price and $1900$ is the maximum ($2000$) minus the minimum ($100$). ### Gradient Descent Tips Debugging gradient descent: - Make a plot of the cost function, $J(\theta)$ over the number of iterations of gradient descent. If $J(\theta)$ ever increases, then you probably need to decrease $\alpha$. - Automatic convergence test: Declare convergence if $J(\theta)$ decreases by less than $\epsilon$ in one iteration, where $\epsilon$ is some small value such as $10^{−3}$. However in practice it's difficult to choose this threshold value. - It has been proven that if learning rate $\alpha$ is sufficiently small, then $J(\theta)$ will decrease on every iteration. Andrew Ng recommends decreasing $\alpha$ by multiples of $3$. ## Features and Polynomial Regression We can improve our features and the form of our hypothesis function in a couple different ways. We can combine multiple features into one. For example, we can combine $x_1$ and $x_2$ into a new feature $x_3$ by taking $x_1 \cdot x_2$. ### Polynomial Regression Our hypothesis function need not be linear (a straight line) if that does not fit the data well. We can change the behavior or curve of our hypothesis function by making it a quadratic, cubic or square root function (or any other form). For example, if our hypothesis function is $h_\theta(x)=\theta_0+\theta_1x_1$ then we can simply duplicate the instances of $x_1$ to get the quadratic function $h_\theta(x)=\theta_0+\theta_1x_1+\theta_2x_1^2$ or the cubic function $h_\theta(x)=\theta_0+\theta_1 x_1 + \theta_2 x_1^2 + \theta_3 x_1^3$ In the cubic version, we have created new features $x_2$ and $x_3$ where $x_2=x_1^2$ and $x_3=x_1^3$. To make it a square root function, we could do: $h_\theta(x)=\theta_0+\theta_1x_1+\theta_2\root \of{x_1}$ One important thing to keep in mind is, if you choose your features this way then feature scaling becomes very important. eg. if $x_1$ has range $1 - 1000$ then range of $x_1^2$ becomes $1 - 1000000$ and that of $x_1^3$ becomes $1 - 1000000000$. ## Normal Equation The "Normal Equation" is a method of finding the optimum theta without iteration. $$ \theta = (X^TX)^{-1} X^TY $$ There is no need to do feature scaling with the normal equation. The following is a comparison of gradient descent and the normal equation: | Gradient Descent | Normal Equation | | :--------------------------: | :-----------------------: | | Need to choose alpha | No need to choose alpha | | Needs many iterations | No need to iterate | | Works well when $n$ is large | Slow if $n$ is very large | <!--{table: .table}--> With the normal equation, computing the inversion has complexity $O(n^3)$. So if we have a very large number of features, the normal equation will be slow. In practice, when $n $exceeds 10,000 it might be a good time to go from a normal solution to an iterative process. ### Normal Equation Non-invertibility When implementing the normal equation in octave we want to use the `pinv` function rather than `inv`. $X^TX$ may be noninvertible. The common causes are: - Redundant features, where two features are very closely related (i.e. they are linearly dependent) - Too many features (e.g. $m\leq n$). In this case, delete some features or use **regularization** (explained in a later lesson). Solutions to the above problems include deleting a feature that is linearly dependent with another or deleting one or more features when there are too many features. ### Derivation We know that cost function is represented by: $$ J(\theta) = \frac{1}{2m}(X\theta-\vec{y})^T(X\theta - \vec{y}) $$ Thus, $$ \begin{align*} J(\theta) &= \frac{1}{2m}(X\theta-\vec{y})^T(X\theta - \vec{y}) \\ & = \frac{1}{2m} \left( (X\theta)^T - \vec{y}^T \right) (X\theta - \vec{y}) \\ & = \frac{1}{2m} \left( (X\theta)^T X\theta + \vec{y}^T\vec{y} - \vec{y}^TX\theta - (X\theta)^Ty\right) \\ & = \frac{1}{2m} \left( \theta^TX^TX\theta - 2 (X\theta)^T\vec{y} + \vec{y}^T \vec{y}\right) \end{align*} $$ and the derivative is $$ \begin{align} \frac{\partial J}{\partial \theta} &= \frac{1}{2m} (2X^TX\theta - 2X^T\vec{y}) \\ & = \frac{1}{m} X^T(X\theta - \vec{y}) \end{align} $$ For least cost, the derivative must be $0$, thus: $$ \begin{align} \hspace{5em} \frac{\partial J}{\partial \theta} &= 0 \\ \\ \frac{1}{m}(X^TX\theta - X^T \vec{y}) &= 0 \\ \\ (X^TX\theta - X^T \vec{y}) &= 0 \\ \\ X^TX\theta &= X^T \vec{y} \\ \\ \theta &= (X^TX)^{-1}X^T\vec{y} \end{align} $$ <file_sep>/scripts/utils/miscUtils.ts import * as crypto from 'crypto'; import * as fs from 'fs'; import * as path from 'path'; import { isValid as isValidDate } from 'date-fns'; import frontMatter from 'front-matter'; import markdown from 'markdown-it'; import mathjax from 'markdown-it-mathjax'; import decorate from 'markdown-it-decorate'; import { highlight, getLanguage, addLanguage, addPlugin } from 'illuminate-js'; import { javascript, typescript, json5, markup, markdown as mdLang, scss, sql, css, bash, php } from 'illuminate-js/lib/languages'; import { showLanguage } from 'illuminate-js/lib/plugins/showLanguage'; import { DefaultTreeElement } from 'parse5'; addLanguage('javascript', javascript); addLanguage('js', javascript); addLanguage('css', css); addLanguage('scss', scss); addLanguage('typescript', typescript); addLanguage('ts', typescript); addLanguage('json', json5); addLanguage('html', markup); addLanguage('html', markup); addLanguage('xml', markup); addLanguage('svg', markup); addLanguage('markdown', mdLang); addLanguage('md', mdLang); addLanguage('sql', sql); addLanguage('bash', bash); addLanguage('sh', bash); addLanguage('php', php); addPlugin(showLanguage); import { MDFileAttributes } from '../../typings/common'; export const BLOG_REGEX = /^\/?blog\/\d{4}/; export const INDEX_FILES_REGEX = /(index|readme)/i; export const PAGES_REGEX = /^pages/; export function getURL(dir: string, name: string) { let url = dir.replace(PAGES_REGEX, ''); let finalIdentifier = name; if (INDEX_FILES_REGEX.test(finalIdentifier)) { /** * if finalIdentifier is 'readme' or 'index' * update it to the last part of url * and also update the url * * @example before * finalIdentifier = 'index' * url = '/about/' */ finalIdentifier = path.basename(url); url = url.replace(finalIdentifier, '').slice(0, -1); /** * @example After * finalIdentifier = 'about' * url = '/' */ } if (BLOG_REGEX.test(url)) { url = url.replace(BLOG_REGEX, '/blog'); } return `${url}/${finalIdentifier}/`.replace(/\/+$/, '/'); } export function isProduction() { return process.env.NODE_ENV === 'production'; } export function stringHash( content: string, algorithm = 'sha1', encoding: crypto.HexBase64Latin1Encoding = 'base64' ): string { const hash = crypto.createHash(algorithm); hash.update(content, 'utf8'); return hash.digest(encoding); } export function fileHash(filePath: string): string { const data = fs.readFileSync(filePath, 'utf8'); return stringHash(data); } export type CallBack = (node: DefaultTreeElement) => DefaultTreeElement; export function walkParse5(node: DefaultTreeElement, callback: CallBack) { if (Array.isArray(node.childNodes) && node.childNodes.length > 0) { node.childNodes = node.childNodes.map(childNode => walkParse5(childNode as any, callback)); } return callback(node); } const md = markdown({ html: true, highlight(text, language) { if (getLanguage(language)) { return highlight(text, language); } return ''; } }) .use(mathjax) .use(decorate); export function renderMarkdown(content: string) { const meta = frontMatter<MDFileAttributes | undefined>(content); return { attributes: meta.attributes, body: md.render(meta.body) }; } export function validatePostAttributes(attributes: MDFileAttributes): string | boolean { if ( !('title' in attributes) || typeof attributes.title !== 'string' || attributes.title.length < 3 ) { return 'title is not valid'; } if ( !('date' in attributes) || !(attributes.date instanceof Date) || !isValidDate(attributes.date) ) { return 'date is not valid'; } if (!('description' in attributes) || attributes.description.length < 3) { return 'description is not valid'; } if (!('tag' in attributes) || !Array.isArray(attributes.tag) || attributes.tag.length === 0) { return 'tag is not an array of strings'; } if (!('author' in attributes) || !attributes.author.name || !attributes.author.site) { return 'author is not in specified format { name: string; site: string; }'; } return true; } export function getPageNumbers( currentPage: number, totalPages: number, primaryGroupLimit = 5, secondaryGroupLimit = 2 ): Array<number | null> { if (currentPage < 1 || totalPages < 1 || primaryGroupLimit < 1 || secondaryGroupLimit < 1) { throw new Error('All the arguments must be +ve integers'); } if (currentPage > totalPages) { throw new Error('currentPage cannot be greater than totalPages'); } // if (primaryGroupLimit > totalPages) { // throw new Error('primaryGroupLimit cannot be greater than totalPages'); // } // if (secondaryGroupLimit > totalPages) { // throw new Error('secondaryGroupLimit cannot be greater than totalPages'); // } const length = primaryGroupLimit + 2 * secondaryGroupLimit + 2; const lastIndex = length - 1; const mid = Math.ceil(length / 2); const midIndex = mid - 1; if (totalPages <= length) { return Array.from({ length: totalPages }, (_, i) => i + 1); } const pages: Array<number | null> = Array.from({ length }); for (let i = 0; i < secondaryGroupLimit; i++) { pages[i] = i + 1; // fill first elements pages[lastIndex - i] = totalPages - i; // fill end elements } pages[midIndex] = currentPage; pages[lastIndex - secondaryGroupLimit] = null; pages[secondaryGroupLimit] = null; const mid2 = Math.ceil(primaryGroupLimit / 2); if (currentPage <= mid) { for (let i = 0; i < mid + secondaryGroupLimit; i++) { pages[i] = i + 1; } } else if (currentPage >= totalPages - midIndex) { for (let i = 0; i < mid + secondaryGroupLimit; i++) { pages[i + midIndex - secondaryGroupLimit] = i + totalPages - secondaryGroupLimit - midIndex; } } else { pages[midIndex] = currentPage; for (let i = 1; i < mid2; i++) { pages[midIndex - i] = currentPage - i; pages[midIndex + i] = currentPage + i; } } return pages; } <file_sep>/pages/blog/2016/format-indian-currency-in-js.md --- title: Format INR currency using JavaScript description: Format INR currency using JavaScript author: name: <NAME> site: http://vkbansal.me date: 2016-09-22 tag: - tricks - javascript --- Formatting a number in JavaScript can be as simple as `toLocaleString()`, but while working on a side project, I came across a scenario where neither `toLocaleString()` nor `toFixed()` was enough. I wanted the numbers to be in `XX,XX,XXX.XX` format. So, I tried bunch of different methods. ```javascript (254.4).toLocaleString() // "254.4" (1234567.8).toLocalString() // "1,234,567.8" (1234567.8).toFixed(2) // "1234567.80" Number((1234567.8).toFixed(2)).toLocaleString() // "1,234,567.8" ``` As you can see that none of the methods worked as per my requirements. After some googling and tinkering around with `RegExp`s, I finally found a solution. ```javascript (1234567.8).toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') // "12,34,567.80" ``` The above solution works flawlessly as per my requirements. Basically the regex looks for a digit which is followed by digits (in groups of two) followed by a digit and a decimal point. ![Format Regex](./images/format-money-regex.png) <!--{.img-center}--> *(Image generated using [Regulex](https://jex.im/regulex/))* <file_sep>/scripts/html.ts export type SingleOrArray<T> = T | T[]; export async function render(component: any): Promise<string> { return await component; } function flattenDeep<T>(arr: any[]): T[] { const ret = [...arr]; for (let i = 0; i < ret.length; i++) { if (Array.isArray(ret[i])) { ret.splice(i, 1, ...ret[i--]); } } return ret; } export async function html( tag: keyof HTMLElementTagNameMap | ((props: Record<string, any>) => Promise<string>), props: Record<string, any>, ...children: Array<SingleOrArray<string> | SingleOrArray<Promise<string>>> ): Promise<string> { if (typeof tag === 'string') { if (tag === 'br') { return '<br>'; } let attrs = ''; const childrenPromises: Array<string | Promise<string>> = flattenDeep(children); const child = await Promise.all(childrenPromises); for (let prop in props) { if (typeof props[prop] !== 'undefined') { attrs += ` ${prop}="${props[prop]}"`; } } return `<${tag}${attrs}>${child.join('')}</${tag}>`; } const result = await tag({ ...props, children }); return result; } <file_sep>/pages/blog/2016/machine-learning/support-vector-machines.md --- title: "Support Vector Machines (SVMs)" author: name: <NAME> site: http://vkbansal.me date: 2016-06-19 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Optimization Objective The **Support Vector Machine** (SVM) is yet another type of *supervised* machine learning algorithm. It is sometimes cleaner and more powerful. Recall that in logistic regression, we use the following rules: $$ y = \begin{cases} \space 1 & \text{then } h_\theta(x) \approx 1 \text { and } \theta^Tx \gg 0 \\ \\ \space 0 & \text{then } h_\theta(x) \approx 0 \text { and } \theta^Tx \ll 0 \end{cases} $$ Recall the cost function for (unregularized) logistic regression: $$ \begin{align*} J(\theta) &= \frac{1}{m} \sum_{i=1}^m \left[ -y^{(i)} log(h_\theta(x^{(i)})) - (1-y^{(i)}) \space log(1-h_\theta(x^{(i)}))\right] \\ & =\frac{1}{m} \sum_{i=1}^m \left[ -y^{(i)} log \left(\frac{1}{1+e^{\theta^Tx}}\right) - (1-y^{(i)}) \space log\left(1 -\frac{1}{1+e^{\theta^Tx}}\right)\right] \\ \end{align*} $$ To make a support vector machine, we will modify the first term of the cost function $\left(−log(h_\theta(x))=−log\left(\frac{1}{1+e^{−\theta^Tx}}\right)\right)$ so that when $\theta^Tx$ (from now on, we shall refer to this as $z$) is greater than $1$, it outputs $0$. Furthermore, for values of $z$ less than $1$, we shall use a straight decreasing line instead of the sigmoid curve.(In the literature, this is called a [hinge loss](http://en.wikipedia.org/wiki/Hinge_loss) function.) ![Svm hinge loss](./images/hinge_loss.svg) <!--{.img-center}--> Similarly, we modify the second term of the cost function $\left(−log(1−h_\theta(x))=−log\left(1−\frac{1}{1+e^{−\theta^Tx}}\right)\right)$ so that when $z$ is less than $-1$, it outputs $0$. We also modify it so that for values of $z$ greater than $-1$, we use a straight increasing line instead of the sigmoid curve. ![Svm hinge loss](./images/hinge_loss_negative.svg) <!--{.img-center}--> We shall denote these as $Cost_1(z)$ and $Cost_0(z)$ respectively. Note that $Cost_1(z)$ is the cost for classifying when $y=1$, and $Cost_0(z)$ is the cost for classifying when $y=0$, and we may define them as follows (where $k$ is an arbitrary constant defining the magnitude of the slope of the line): $$ \begin{align*} z &= \theta^Tx \\ Cost_o(z) &= max(0, k(1+z)) \\ Cost_1(z) &= max (0, k(1-z)) \end{align*} $$ Recall the full cost function from (regularized) logistic regression: $$ J(\theta) = \frac{1}{m} \sum_{i=1}^m y^{(i)}(-log(h_\theta(x^{(i)})) + (1-y^{(i)})(-log(1-h_\theta(x^{(i)}))) + \frac{\lambda}{2m} \sum_{j=1}^n\theta_j^2 $$ Note that the negative sign has been distributed into the sum in the above equation. We may transform this into the cost function for support vector machines by substituting $Cost_0(z)$ and $Cost_1(z)$: $$ J(\theta) = \frac{1}{m} \sum_{i=1}^m y^{(i)}Cost_1(\theta^Tx^{(i)}) + (1-y^{(i)})Cost_0(\theta^Tx^{(i)}) + \frac{\lambda}{2m} \sum_{j=1}^n\theta_j^2 $$ We can optimize this a bit by multiplying this by $m$ (thus removing the m factor in the denominators). Note that this does not affect our optimization, since we're simply multiplying our cost function by a positive constant. $$ J(\theta) = \sum_{i=1}^m y^{(i)}Cost_1(\theta^Tx^{(i)}) + (1-y^{(i)})Cost_0(\theta^Tx^{(i)}) + \frac{\lambda}{2} \sum_{j=1}^n\theta_j^2 $$ Furthermore, convention dictates that we regularize using a factor $C$, instead of $\lambda$, like so: $$ J(\theta) = C \sum_{i=1}^m y^{(i)}Cost_1(\theta^Tx^{(i)}) + (1-y^{(i)})Cost_0(\theta^Tx^{(i)}) + \frac{1}{2} \sum_{j=1}^n\theta_j^2 $$ This is equivalent to multiplying the equation by $C=\frac{1}{\lambda}$, and thus results in the same values when optimized. Now, when we wish to regularize more (that is, reduce overfitting), we *decrease* $C$, and when we wish to regularize less (that is, reduce underfitting), we *increase* $C$. Finally, note that the hypothesis of the Support Vector Machine is *not* interpreted as the probability of $y$ being $1$ or $0$ (as it is for the hypothesis of logistic regression). Instead, it outputs either $1$ or $0$. (In technical terms, it is a discriminant function.) $$ h_\theta(x) = \begin{cases} \space 1 & \text{if } \theta^Tx \geq 0 \\ \\ \space 0 & \text{otherwise} \end{cases} $$ ## Large Margin Intuition A useful way to think about Support Vector Machines is to think of them as *Large Margin Classifiers*. $$ y = \begin{cases} \space 1 & \text{we want } \theta^Tx \geq 1 \text{ (not just} \geq 0\text{)} \\ \\ \space 0 & \text{we want } \theta^Tx \leq -1 \text{ (not just} < 0\text{)} \\ \end{cases} $$ Now when we set our constant $C$ to a very **large** value (e.g. $100,000$), our optimizing function will constrain $\theta$ such that the summation of the cost of each example equals 0. We impose the following constraints on $\theta$: $$ \theta^Tx \ge 1 \text{ if } y =1 \\ \theta^Tx \le -1 \text{ if } y =0 $$ If $C$ is very large, we must choose $\theta$ parameters such that: $$ \sum_{i=1}^m y^{(i)} Cost_1(\theta^Tx) + (1-y^{(i)}) \space Cost_0(\theta^Tx) = 0 $$ This reduces our cost function to: $$ J(\theta) = C \cdot 0 + \frac{1}{2} \sum_{j=1}^{n} \theta_j^2 $$ In SVMs, the decision boundary has the special property that it is **as far away as possible** from both the positive and the negative examples. The distance of the decision boundary to the nearest example is called the **margin**. Since SVMs maximize this margin, it is often called a *Large Margin Classifier*. The SVM will separate the negative and positive examples by a **large margin**. This large margin is only achieved when **$C$ is very large**. Data is **linearly separable** when a **straight line** can separate the positive and negative examples. If we have **outlier** examples that we don't want to affect the decision boundary, then we can **reduce** $C$. Increasing and decreasing $C$ is similar to respectively decreasing and increasing $\lambda$, and can simplify our decision boundary. ## Mathematics Behind Large Margin Classification ### Vector Inner Product Say we have two vectors, $\vec{u}$ and $\vec{v}$: $$ u = \begin{bmatrix}u_1 \\ u_2\end{bmatrix} v = \begin{bmatrix}v_1 \\ v_2\end{bmatrix} $$ The length of vector $\vec{v}$ is denoted $||v||$, and it describes the line on a graph from origin $(0,0)$ to $(v_1,v_2)$. The length of vector $\vec{v}$ can be calculated with $\sqrt{v_1^2 + v_2^2}$  by the Pythagorean theorem. The **projection** of vector $\vec{v}$ onto vector $\vec{u}$ is found by taking a right angle from $\vec{u}$ to the end of $\vec{v}$, creating a right triangle. $$ \begin{align*} p &= \text{length of projection of } \vec{v} \text{ onto the vector } \vec{u}. \\ \\ u^Tv &= p \cdot ||u|| \end{align*} $$ Note that $u^Tv=||u||\cdot||v||cos\theta$ where $\theta$ is the angle between $\vec{u}$ and $\vec{v}$. Also, $p=||v||cosθ$. If you substitute $p$ for $||v||cosθ$, you get $u^Tv=p \cdot ||u||$. So the product $u^Tv$ is equal to the length of the projection times the length of vector $\vec{u}$. If $\vec{u}$ and $\vec{v}$ are vectors of the same length, then $u^Tv=v^Tu$. uTv=vTu=p⋅||u||=u1v1+u2v2 $$ u^Tv = v^Tu = p \cdot ||u|| = u_1v_1+ u_2 v_2 $$ If the **angle** between $\vec{v}$ and $\vec{u}$ is **greater than 90 degrees**, then the projection $p$ will be **negative**. $$ \min_\theta \frac{1}{2} \sum_{j=1}^n \theta_j^2 = \frac{1}{2} (\theta_1^2 + \theta_2^2 + \cdots +\theta_n^2) = \frac{1}{2} \sqrt{(\theta_1^2 + \theta_2^2 + \cdots +\theta_n^2)^2} = \frac{1}{2} ||\Theta||^2 $$ We can use the same rules to rewrite $\Theta^Tx^{(i)}$: $$ \Theta^Tx^{(i)} = p^{(i)} \cdot ||\Theta|| = \theta_1x^{(i)}_1 + \theta_2x^{(i)}_2+ \cdots + \theta_nx^{(i)}_n $$ So we now have a new **optimization objective** by substituting $p^{(i)} \cdot ||\Theta||$ in for $\Theta^Tx^{(i)}$: $$ \begin{align*} &\text{If } y=1, \text{we want } p^{(i)} \cdot ||\Theta|| \ge 1 \\ & \text{If } y=0, \text{we want } p^{(i)} \cdot ||\Theta|| \le -1 \\ \end{align*} $$ The reason this causes a **large margin** is because: the vector for $\Theta$ is perpendicular to the decision boundary. In order for our optimization objective (above) to hold true, we need the absolute value of our projections $p^{(i)}$ to be as large as possible. If $\Theta_0=0$, then all our decision boundaries will intersect $(0,0)$. If $\Theta_o \ne 0$, the support vector machine will still find a large margin for the decision boundary. ## Kernels **Kernels** allow us to make complex, non-linear classifiers using Support Vector Machines. Given $x$, compute new feature depending on proximity to landmarks $l^{(1)}, l^{(2)}, l^{(3)}$. To do this, we find the **similarity** of $x$ and some landmark $l^{(i)}$: $$ f_i= similarity(x,l^{(i)})=exp\left(\frac{−||x−l^{(i)}||}{2\sigma^2}\right) $$ This **similarity** function is called a **Gaussian Kernel**. It is a specific example of a kernel. The similarity function can also be written as follows: $$ f_i= similarity(x,l^{(i)})=exp\left(\frac{−\sum_{j=1}^n(x_j−l^{(i)}_j)^2}{2\sigma^2}\right) $$ There are a couple properties of the similarity function: $$ \text{If } x \approx l^{(i)} \text{, then } f_i = exp \left(\frac{(\approx 0)^2}{2\sigma^2} \right) \approx 1\\ \text{If } x \text{ is far from } l^{(i)} \text{, then } f_i = exp \left(\frac{(\text{large number})^2}{2\sigma^2} \right) \approx 0\\ $$ In other words, if $x$ and the landmark are close, then the similarity will be close to $1$, and if $x$ and the landmark are far away from each other, the similarity will be close to $0$. Each landmark gives us the features in our hypothesis: $$ \begin{align*} l^{(1)} & \rightarrow f_1 \\ l^{(2)} &\rightarrow f_2 \\ l^{(3)} & \rightarrow f_3 \dots\\ h_\Theta(x) &=\Theta_1f_1+\Theta_2f_2+\Theta_3f_3+ \dots \end{align*} $$ $\sigma^2$ is a parameter of the Gaussian Kernel, and it can be modified to increase or decrease the **drop-off** of our feature $f_i$. Combined with looking at the values inside $\theta$, we can choose these landmarks to get the general shape of the decision boundary. One way to get the landmarks is to put them in the **exact same** locations as all the training examples. This gives us m landmarks, with one landmark per training example. Given example $x$: $f_1=similarity(x,l^{(1)})$ $f_2=similarity(x,l^{(2)})$ $f_3=similarity(x,l^{(3)})$, and so on. This gives us a **feature vector**,  $f^{(i)}$ of all our features for example $x^{(i)}$. We may also set $f_0=1$ to correspond with $\Theta_0$. Thus given training example $x^{(i)}$: $$ x^{(i)} \rightarrow \begin{bmatrix} f^{(i) }_1 = similarity(x^{(i)}, l^{(1)}) \\ f^{(i) }_2 = similarity(x^{(i)}, l^{(2)}) \\ \vdots \\ f^{(i) }_m = similarity(x^{(i)}, l^{(m)}) \\ \end{bmatrix} $$ Now to get the parameters $\Theta$ we can use the SVM minimization algorithm but with $f^{(i)}$ substituted in for $x^{(i)}$: $$ \min_\Theta C \sum_{i=1}^m y^{(i)} Cost_1(\Theta^Tf^{(i)}) + (1-y^{(i)}) Cost_0(\Theta^T f^{(i)}) - \frac{1}{2} \sum_{j=1}^n \Theta_j^2 $$ Using kernels to generate $f^{(i)}$ is not exclusive to SVMs and may also be applied to logistic regression. However, because of computational optimizations on SVMs, kernels combined with SVMs is much faster than with other algorithms, so kernels are almost always found combined only with SVMs. ### Choosing SVM Parameters Choosing $C$ (recall that $C=\frac{1}{λ}$) - If $C$ is large, then we get higher variance/lower bias - If $C$ is small, then we get lower variance/higher bias The other parameter we must choose is $\sigma^2$ from the Gaussian Kernel function: - With a large $\sigma^2$, the features $f_i$ vary more smoothly, causing higher bias and lower variance. - With a small $\sigma^2$, the features $f_i$ vary less smoothly, causing lower bias and higher variance. ## Using An SVM There are lots of good SVM libraries already written. <NAME> often uses `liblinear` and `libsvm`. In practical application, you should use one of these libraries rather than rewrite the functions. In practical application, the choices you *do* need to make are: - Choice of parameter $C$ - Choice of kernel (similarity function) - No kernel ("linear" kernel) -- gives standard linear classifier. Choose when $n$ is **large** and when $m$ is **small** - Gaussian Kernel (above) -- need to choose $\sigma^2$. Choose when $n$ is **small** and $m$ is **large** The library may ask you to provide the kernel function. **Note**: do perform feature scaling before using the Gaussian Kernel. **Note**: not all similarity functions are valid kernels. They must satisfy **Mercer's Theorem**, which guarantees that the SVM package's optimizations run correctly and do not diverge. You want to train $C$ and the parameters for the kernel function using the **training** and **cross-validation** datasets. ### Multi-class Classification Many SVM libraries have multi-class classification built-in. You can use the *one-vs-all* method just like we did for logistic regression, where $y \in 1,2,3,\dots,K$ with $(\Theta^{(1)},\Theta^{()2},\dots,\Theta^{(K)}$. We pick class $i$ with the largest $(\Theta^{(i)})^Tx$. ### Logistic Regression vs. SVMs - If $n$ is large (relative to $m$), then use logistic regression, or SVM without a kernel (the "linear kernel") - If $n$ is small and $m$ is intermediate, then use SVM with a Gaussian Kernel - If $n$ is small and $m$ is large, then manually create/add more features, then use logistic regression or SVM without a kernel. In the first case, we don't have enough examples to need a complicated polynomial hypothesis. In the second example, we have enough examples that we may need a complex non-linear hypothesis. In the last case, we want to increase our features so that logistic regression becomes applicable. **Note**: a neural network is likely to work well for any of these situations, but may be slower to train.<file_sep>/scripts/useStyles.ts import { processCSS } from './utils/processCSS'; import { stringHash } from './utils/miscUtils'; /** * This function must be used as the first */ export async function useStyles(css: string): Promise<Record<string, string>> { if (!module.parent) { throw new Error('useStyles should not be invoked directly!'); } const hash = stringHash(css, 'md5', 'hex'); if (useStyles.stylesMap.has(hash)) { const data = useStyles.stylesMap.get(hash); return data!.exports; } const data = await processCSS(css); useStyles.stylesMap.set(hash, data!); return data!.exports; } useStyles.stylesMap = new Map<string, { css: string; exports: Record<string, string> }>(); useStyles.resetMap = () => (useStyles.stylesMap = new Map()); <file_sep>/scripts/StaticSiteBuilder.ts import * as path from 'path'; import globby from 'globby'; import chalk from 'chalk'; import { parseFragment, serialize } from 'parse5'; import fs from 'fs-extra'; import { isBefore } from 'date-fns'; import { partition } from 'lodash'; import chokidar from 'chokidar'; import { PageType, AllFileContent, PostContents, PageContents, TSFileContents, MDFileContents, RenderArgs, FileType } from '../typings/common'; import { readFile } from './utils/readFile'; import { processCSS } from './utils/processCSS'; import { fileLoader } from './utils/fileLoader'; import { walkParse5, stringHash, isProduction as isPROD, validatePostAttributes } from './utils/miscUtils'; import { useStyles } from './useStyles'; import options from './options.json'; export class StaticSiteBuilder { private css: string = ''; private posts: Map<string, PostContents> = new Map(); private pages: Map<string, PageContents> = new Map(); private assest: RenderArgs['assets'] = { css: [], js: [] }; private mainTemplate!: TSFileContents; private blogPageTemplate!: TSFileContents; private addCSS = (css: string) => { this.css = this.css + `\n${css}`; }; private processAssets(html: string, rawPath: string) { const htmlAST = parseFragment(html); const newAST = walkParse5(htmlAST as any, node => { if (node.tagName === 'img') { const src = node.attrs.find(attr => attr.name === 'src'); if (!src) return node; const srcPath = src.value; const newPath = fileLoader(srcPath, rawPath); src.value = newPath; return node; } return node; }); return serialize(newAST); } private processContent = async (file: AllFileContent) => { console.log(chalk.yellow(`Processing: ${file.rawPath}`)); switch (file.type) { case FileType.MD: const content = this.processAssets(file.content, file.rawPath); if (file.isPost) { const test = validatePostAttributes(file.attributes!); if (typeof test === 'string') { console.log(chalk.red.bold(test)); console.log(chalk.yellow.bold(file.rawPath)); process.exit(1); } this.posts.set(file.url, { type: PageType.POST, content, attributes: file.attributes!, slug: path.basename(file.url), url: file.url, rawPath: file.rawPath, writtenToDisk: false }); } else { this.pages.set(file.url, { type: PageType.PAGE, content, attributes: file.attributes!, url: file.url, rawPath: file.rawPath, writtenToDisk: false }); } break; case FileType.TS: await this.processTSFile(file); break; } }; private processTSFile = async (file: TSFileContents) => { let pageBody = await file.render({ posts: [...this.posts.values()], assets: this.assest, content: '', slug: '', attributes: file.attributes, url: file.url, rawPath: file.rawPath, isPost: false, isProduction: isPROD() }); if (typeof pageBody === 'string') { this.pages.set(file.url, { content: this.processAssets(pageBody, file.rawPath), type: PageType.PAGE, attributes: file.attributes, url: file.url, rawPath: file.rawPath, writtenToDisk: false }); } else if (Array.isArray(pageBody)) { pageBody.forEach(page => { this.pages.set(page.url, { content: this.processAssets(page.content, file.rawPath), type: PageType.PAGE, attributes: file.attributes, url: page.url, rawPath: file.rawPath, writtenToDisk: false }); }); } else { this.pages.set(pageBody.url, { url: pageBody.url, content: this.processAssets(pageBody.content, file.rawPath), type: PageType.PAGE, attributes: file.attributes, rawPath: file.rawPath, writtenToDisk: false }); } }; private buildCSS = async () => { /** * Read and build main CSS */ const mainCSS = await processCSS( fs.readFileSync(path.join(process.cwd(), 'styles/main.scss'), 'utf8') ); this.addCSS(mainCSS!.css); useStyles.stylesMap.forEach(data => this.addCSS(data.css)); /** * Write CSS file */ const cssFileHash = isPROD() ? `.${stringHash(this.css, 'sha1', 'hex').slice(0, 6)}` : ''; const cssFilePath = path.join(options.outPath, 'styles', `styles${cssFileHash}.css`); console.log(chalk.magenta(`Writing: ${cssFilePath}`)); fs.outputFileSync(cssFilePath, this.css, 'utf8'); this.assest.css.push(`/styles/styles${cssFileHash}.css`); }; private renderAndWritePages = async () => { const writeFilePromises: Array<Promise<any>> = []; const isProduction = isPROD(); /** * Render and Write Pages */ for (const [url, page] of this.pages) { if (page.writtenToDisk) continue; console.log(chalk.cyan(`Rendering: ${url}`)); const html = '<!DOCTYPE html>' + (await this.mainTemplate.render({ posts: [], content: page.content, assets: this.assest, url, attributes: page.attributes, rawPath: page.rawPath, isProduction, slug: '', isPost: false })); const writePath = path.join(options.outPath, page.url, 'index.html'); console.log(chalk.magenta(`Writing: ${writePath}`)); writeFilePromises.push(fs.outputFile(writePath, html, 'utf8')); page.writtenToDisk = true; } await Promise.all(writeFilePromises); }; private renderAndWritePosts = async () => { const writeFilePromises: Array<Promise<any>> = []; const isProduction = isPROD(); /** * Render and Write Posts */ for (const [url, post] of this.posts) { if (post.writtenToDisk) continue; console.log(chalk.cyan(`Rendering: ${url}`)); const postContent = await this.blogPageTemplate.render({ attributes: post.attributes, posts: [...this.posts.values()], content: post.content, assets: this.assest, url, rawPath: post.rawPath, slug: post.slug, isProduction, isPost: true }); const html = '<!DOCTYPE html>' + (await this.mainTemplate.render({ attributes: post.attributes, posts: [], content: postContent.toString(), assets: this.assest, url, slug: post.slug, rawPath: post.rawPath, isProduction, isPost: true })); const writePath = path.join(options.outPath, post.url, 'index.html'); console.log(chalk.magenta(`Writing: ${writePath}`)); writeFilePromises.push(fs.outputFile(writePath, html, 'utf8')); post.writtenToDisk = true; } await Promise.all(writeFilePromises); }; private handleChange = async (path: string) => { console.log(chalk.yellow.bold(`${path} changed`)); if (path.startsWith('pages')) { const content = await readFile(path); await this.processContent(content); await this.buildCSS(); if ((content as MDFileContents).isPost) { await this.renderAndWritePosts(); } else { await this.renderAndWritePages(); } } else if (path.startsWith('templates')) { await this.build(); } else if (path.startsWith('styles')) { await this.buildCSS(); } }; public async watch() { if (isPROD()) { console.log(chalk.red('--watch can be run only in development mode!')); return; } await this.build(); const watcher = chokidar.watch([ 'pages/**/*.{md,tsx,json}', 'styles/**/*.scss', 'templates/**/*.{tsx,json}' ]); console.log(chalk.yellow.bold('My watch has started')); watcher.on('change', this.handleChange); } public async build() { useStyles.resetMap(); const isProduction = isPROD(); const filePaths = await globby(path.join(options.srcPath, options.srcGlob)); this.mainTemplate = (await readFile(options.mainTemplatePath)) as TSFileContents; this.blogPageTemplate = (await readFile(options.blogPageTemplatePath)) as TSFileContents; /** * Process All files */ const files = await Promise.all(filePaths.map(readFile)); let [posts, pages] = partition(files, file => (file as MDFileContents).isPost); posts = (posts as MDFileContents[]) .filter(post => !post.attributes!.isDraft) .sort((a, b) => (isBefore(a.attributes!.date, b.attributes!.date) ? 1 : -1)); // this.pages = pages as Array<TSFileContents | MDFileContents>; // First process posts await Promise.all(posts.map(this.processContent)); // Then process pages await Promise.all(pages.map(this.processContent)); // render template with no content to extract CSS await this.mainTemplate.render({ posts: [], content: '', assets: this.assest, isProduction, isPost: false, slug: '', attributes: {} as any, url: '', rawPath: '' }); // render template with no content to extract CSS await this.blogPageTemplate.render({ posts: [], content: '', assets: this.assest, isProduction, isPost: true, slug: '', attributes: { author: { name: '', site: '' }, date: new Date(), description: '', title: '', tag: [] }, url: '', rawPath: '' }); await this.buildCSS(); await this.renderAndWritePages(); await this.renderAndWritePosts(); const includesPath = path.join(process.cwd(), options.includesPath); fs.readdirSync(includesPath).map(file => { const src = path.join(includesPath, file); const dest = path.join(process.cwd(), options.outPath, file); console.log(chalk.magenta(`Copying ${file}`)); fs.copyFileSync(src, dest); }); } } <file_sep>/pages/blog/2016/machine-learning/neural-networks-representation.md --- title: "Neural Networks: Representation" author: name: <NAME> site: http://vkbansal.me date: 2016-05-12 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- # Neural Networks: Representation ## Non-linear Hypothesis Performing linear regression with a complex set of data with many features is very unwieldy. Say you wanted to create a hypothesis from three features that included all the quadratic terms: $$ g(\theta_0+\theta_1x^2_1+\theta_2x_1x_2+\theta_3x_1x_3+\theta_4x_2^2+\theta_5x_2x_3+\theta_6x^2_3) $$ That gives us $6$ features. For $100$ features, if we wanted to make them quadratic we would get $5050$ resulting new features. We can approximate the growth of the number of new features we get with all quadratic terms with $O(n^2/2)$. And if you wanted to include all cubic terms in your hypothesis, the features would grow asymptotically at $O(n^3)$. These are very steep growths, so as the number of our features increase, the number of quadratic or cubic features increase very rapidly and becomes quickly impractical. Example: let our training set be a collection of $50 \times 50$ pixel black-and-white photographs, and our goal will be to classify which ones are photos of cars. Our feature set size is then $n=2500$, if we compare every pair of pixels. Now let's say we need to make a quadratic hypothesis function. With quadratic features, our growth is $O(n^2/2)$. So our total features will be about $2500^2/2=3125000$, which is very impractical. Neural networks offers an alternate way to perform machine learning when we have complex hypotheses with many features. ## Neurons and the Brain Neural networks are limited imitations of how our own brains work. At a very simple level, neurons are basically computational units that take input (**dendrites**) as electrical input (called **spikes**) that are channeled to outputs (**axons**). ![Neurons](./images/neuron_2.png) <!--{.img-center}--> ![Neurons](./images/neuron_1.png) <!--{.img-center}--> ## Model Representation I Let's examine how we will represent a hypothesis function using neural networks. In our model, our dendrites are like the input features $(x_1 \cdots x_n)$, and the output is the result of our hypothesis function: Visually, a simplistic representation looks like: $$ \begin{align} \begin{bmatrix} x_0 \\ x_1 \\ x_2 \end{bmatrix} \rightarrow [ \hspace{1em}] \rightarrow h_\Theta(x) \end{align} $$ In this model our $x_0$ input node is sometimes called the **bias unit**. It is always equal to 1. In neural networks, we use the same logistic function as in classification: $\frac{1}{1+e^{−θ^Tx}}$, however we sometimes call it a sigmoid (logistic) **activation** function and the **theta** parameters are sometimes instead called **weights**. Our input nodes (layer 1) go into another node (layer 2), and are output as the hypothesis function. The first layer is called the **input layer** and the final layer the **output layer**, which gives the final value computed on the hypothesis. We can have intermediate layers of nodes between the input and output layers called the **hidden layer**. We label these intermediate or **hidden** layer nodes as $a^{(2)}_0 \cdots a^{(2)}_n$ and call them **activation units**. $$ \begin{align*} & a^{(j)}_i = \text{activation of unit }i \text { in layer } j \\ & \Theta^j = \text{matrix of weights controlling function mapping from layer } j \text{ to layer } j+1 \end{align*} $$ If we had one hidden layer, it would look visually something like: $$ \begin{align*} \begin{bmatrix} x_0 \\ x_1 \\ x_2 \\ x_3 \end{bmatrix} \rightarrow \begin{bmatrix} a^{(2)}_1 \\ a^{(2)}_2 \\ a^{(2)}_3 \\ \end{bmatrix} \rightarrow h_\Theta(x) \end{align*} $$ The values for each of the **activation** nodes is obtained as follows: $$ \begin{align*} & a^{(2)}_1 = g(\Theta^{(1)}_{1,0} x_0 + \Theta^{(1)}_{1,1} x_1 + \Theta^{(1)}_{1,2} x_2 +\Theta^{(1)}_{1,3} x_3) \\ & a^{(2)}_2 = g(\Theta^{(1)}_{2,0} x_0 + \Theta^{(1)}_{2,1} x_1 + \Theta^{(1)}_{2,2} x_2 +\Theta^{(1)}_{2,3} x_3) \\ & a^{(2)}_3 = g(\Theta^{(1)}_{3,0} x_0 + \Theta^{(1)}_{3,1} x_1 + \Theta^{(1)}_{3,2} x_2 +\Theta^{(1)}_{3,3} x_3) \\ \end{align*} $$ And Our hypothesis output is calculated as follows: $$ h_\Theta(x) = g(\Theta^{(2)}_{1,0} a^{(2)}_0 + \Theta^{(2)}_{1,1} a^{(2)}_1 + \Theta^{(2)}_{1,2} a^{(2)}_2 +\Theta^{(2)}_{1,3} a^{(2)}_3) $$ Each layer ($j$) gets its own matrix of weights, $\Theta^{(j)}$. The dimensions of these matrices of weights is determined as follows: If network has $s_j$ units in layer $j$ and $s_{j+1}$ units in layer $j+1$, then $\Theta(j)$ will be of dimension $s_{j+1} \times (s_j+1)$. The $+1$ comes from the addition of **bias nodes**, $x_0$ and $\Theta(j)$,in $\Theta(j)$. In other words the output nodes will not include the bias nodes while the inputs will. Example: if layer 1 has $2$ input nodes and layer 2 has $4$ activation nodes, the dimension of $\Theta{(^1)}$ is going to be $4 \times 3$ where $s_j=2$ and $s_{j+1}=4$, so $s_{j+1} \times (s_j+1)=4 \times 3$. ## Model Representation II In this section we'll do a vectorized implementation of the above functions. We're going to define a new variable $z^{(j)}_k$ so that we have encompasses the parameters inside our $g$ function. In our previous example if we replaced the variable $z$ for all the parameters we would get: $$ \begin{align*} a^{(2)}_1 &= g(z^{(2)}_1) \\ a^{(2)}_2 &= g(z^{(2)}_2) \\ a^{(2)}_3 &= g(z^{(2)}_3) \\ \\ \text{where :} \\ z^{(2)}_1 &= \Theta^{(1)}_{1,0} x_0 + \Theta^{(1)}_{1,1} x_1 + \Theta^{(1)}_{1,2} x_2 +\Theta^{(1)}_{1,3} x_3 \\ z^{(2)}_2 &= \Theta^{(1)}_{2,0} x_0 + \Theta^{(1)}_{2,1} x_1 + \Theta^{(1)}_{2,2} x_2 +\Theta^{(1)}_{2,3} x_3 \\ z^{(2)}_3 &= \Theta^{(1)}_{3,0} x_0 + \Theta^{(1)}_{3,1} x_1 + \Theta^{(1)}_{3,2} x_2 +\Theta^{(1)}_{3,3} x_3 \end{align*} $$ These $z$ values are just a weighted linear combination of input values $x_0$, $x_1$, $x_2$, $x_3$ that go into particular neuron. Let's define vector $x$ and $z^{(2)}$ as follows: $$ \begin{align*} &x = \begin{bmatrix} x_0 \\ x_1 \\ x_2 \\ x_3 \\ \end{bmatrix} \hspace{1em} z^{(2)} = \begin{bmatrix} z^{(2)}_1 \\ z^{(2)}_2 \\ z^{(2)}_3 \\ \end{bmatrix} \\ \\ &\text{ where } x_0 = 1 \end{align*} $$ Now we can vectorize the computation of $a^{(2)}_1$, $a^{(2)}_2$, $a^{(2)}_3$ as follows: $$ a^{(2)} = g(z^{(2)}) $$ where our function $g$ can be applied element-wise to our vector $ z^{(2)}$. We can compute $z^{(2)}$ by setting $x=a^{(1)}$ as: $$ z^{(2)} = \Theta^{(1)}a^{(1)} $$ We can then **add a bias unit** $a^{(2)}_0 = 1$ and compute $z^{(3)}$ as: $$ z^{(3)} = \Theta^{(2)} a^{(2)} $$ We then get our final result with: $$ h_\Theta(x) = a^{(3)} = g(z^{(3)}) $$ This process is also called **Forward Propagation**. We are doing **exactly the same thing** as we did in logistic regression. Adding all these intermediate layers in neural networks allows us to more elegantly produce interesting and more complex non-linear hypotheses. ## Examples and Intuitions I A simple example of applying neural networks is by predicting $x_1 \text{ AND } x_2$, which is the logical `and` operator and is only true if both $x_1$ and $x_2$ are $1$. The graph of our functions will look like: $$ \begin{align*} \begin{bmatrix} x_0 \\ x_1 \\ x_2 \end{bmatrix} \rightarrow \begin{bmatrix} g(z^{(2)}) \end{bmatrix} \rightarrow h_\Theta(x) \end{align*} $$ Remember that $x_0$ is our bias variable and is always $1$. Let's set our first theta matrix as: $$ \begin{align*} &\Theta^{(1)} = \begin{bmatrix} -30 \hspace{1em} 20 \hspace{1em} 20 \end{bmatrix} \\ \\ \implies &h_\Theta(x) = -30+20x_1 + 20x_2 \end{align*} $$ This will cause the output of our hypothesis to only be positive if both $x_1$ and $x_2$ are $1$. | $x_1$ | $x_2$ | $h_\Theta(x)$ | | :---: | :---: | :-----------------: | | $0$ | $0$ | $g(-30) \approx 0$ | | $0$ | $1$ | $g(-10) \approx 0$ | | $1$ | $0$ | $g(-10) \approx 0$ | | $1$ | $1$ | $g(10) \approx 1$ | So we have constructed one of the fundamental operations in computers by using a small neural network rather than using an actual AND gate. Neural networks can also be used to simulate all the other logical gates. Similarly, $\Theta^{(1)}$ for other operations are $$ \begin{align*} x_1 \space AND \space x_2: \\ \Theta_1 &= \begin{bmatrix}-30 & 20 & 20\end{bmatrix} \\ x_1 \space OR \space x_2: \\ \Theta_1 &= \begin{bmatrix}-10 & 20 & 20\end{bmatrix} \\ NOT \space x_1: \\ \Theta_1 &= \begin{bmatrix}10 &- 20 \end{bmatrix} \\ x_1 \space NOR \space x_2: \\ \Theta_1 &= \begin{bmatrix}10 & -20 & -20\end{bmatrix} \end{align*} $$ We can combine these to get the XNOR logical operator (which gives $1$ if neither  $x_1$ nor $x_2$ are both $0$ or both $1$). $$ \begin{bmatrix} x_0 \\ x_1 \\ x_2 \end{bmatrix} \rightarrow \begin{bmatrix} a^{(2)}_0 \\ a^{(2)}_1 \\ a^{(2)}_2 \\ \end{bmatrix} \rightarrow \begin{bmatrix} a^{(3)}_0 \\ a^{(3)}_1 \\ \end{bmatrix} \rightarrow h_\Theta(x) $$ For the transition between the first and second layer, we'll use a $\Theta^{(1)}$ matrix that combines the values for AND and NOR: $$ \begin{align*} \Theta^{(1)} = \begin{bmatrix} -30 & 20 & 20 \\ 10 & -20 & -20 \end{bmatrix} \end{align*} $$ For the transition between the second and third layer, we'll use a $\Theta^{(2)}$ matrix that uses the value for OR: $$ \begin{align*} \Theta^{(2)} = \begin{bmatrix} -10 & 20 & 20 \end{bmatrix} \end{align*} $$ Let's write out the values for all our nodes: $$ \begin{align*} a^{(2)} &= g(\Theta^{(1)} \cdot x) \\ h_\Theta & = a^{(3)} = g(\Theta^{(2)} \cdot a^{(2)}) \end{align*} $$ The result will be as follows: | $x_1$ | $x_2$ | $a^{(2)}_1$ | $a^{(2)}_2$ | $h_\Theta(x)$ | | :---: | :---: | :----------------: | :----------------: | :----------------: | | $0$ | $0$ | $g(-30) \approx 0$ | $g(10) \approx 1$ | $g(10) \approx 1$ | | $0$ | $1$ | $g(-10) \approx 0$ | $g(-10) \approx 0$ | $g(-10) \approx 0$ | | $1$ | $0$ | $g(-10) \approx 0$ | $g(-10) \approx 0$ | $g(-10) \approx 0$ | | $1$ | $1$ | $g(10) \approx 1$ | $g(-30) \approx 0$ | $g(10) \approx 1$ | And thus we have the XNOR operator using one hidden layer! ## Multiclass Classification To classify data into multiple classes, we let our hypothesis function **return a vector of values**. Say we wanted to classify our data into one of four final resulting classes, our final layer of nodes, will be a vector of size $4$: $$ \begin {bmatrix} x_0 \\ x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} \rightarrow \begin {bmatrix} a^{(2)}_0 \\ a^{(2)}_1 \\ a^{(2)}_2 \\ \vdots \\ \end{bmatrix} \rightarrow \begin {bmatrix} a^{(3)}_0 \\ a^{(3)}_1 \\ a^{(3)}_2 \\ \vdots \\ \end{bmatrix} \rightarrow \cdots \rightarrow \begin {bmatrix} h_\Theta(x)_1 \\ h_\Theta(x)_2 \\ h_\Theta(x)_3 \\ h_\Theta(x)_4 \\ \end{bmatrix} $$ Our resulting hypothesis for one set of inputs may look like: $$ h_\Theta(x) = \begin{bmatrix} 0 \\ 0 \\ 1 \\ 0 \end{bmatrix} $$ In which case our resulting class is the third one down, or $h_\Theta(x)_3$. We can define our set of resulting classes as $y$:  $$ y^{(i)} = \begin{bmatrix}1 \\ 0 \\ 0 \\ 0 \end{bmatrix} \text{ or } \begin{bmatrix}0 \\ 1 \\ 0 \\ 0 \end{bmatrix} \text{ or } \begin{bmatrix}0 \\ 0 \\ 1 \\ 0 \end{bmatrix} \text{ or } \begin{bmatrix}0 \\ 0 \\ 0 \\ 1 \end{bmatrix} $$ Our final value of our hypothesis for a set of inputs will be one of the elements in $y$. <file_sep>/pages/blog/2016/machine-learning/recommender-systems.md --- title: "Recommender Systems" author: name: <NAME> site: http://vkbansal.me date: 2016-07-26 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" draft: true math: true --- ## Problem Formulation Recommendation is currently a very popular application of machine learning. Say we are trying to recommend movies to customers. We can use the following definitions > nu= number of users > > nm= number of movies > > r(i,j)=1 if user j has rated movie i > > y(i,j)= rating given by user j to movie i (defined only if r(i,j)=1) ## Content Based Recommendations We can introduce two features, x1 and x2 which represents how much romance or how much action a movie may have (on a scale of 0−1). One approach is that we could do linear regression for every single user. For each user j, learn a parameter θ(j)∈R3. Predict user j as rating movie i with (θ(j))Tx(i) stars. > θ(j)= parameter vector for user j > > x(i)= feature vector for movie i > > For user j, movie i, predicted rating: (θ(j))T(x(i)) > > m(j)= number of movies rated by user j To learn θ(j), we do the following minθ(j)=12∑i:r(i,j)=1((θ(j))T(x(i))−y(i,j))2+λ2∑k=1n(θ(j)k)2 This is our familiar linear regression. The base of the first summation is choosing all i such that r(i,j)=1. To get the parameters for all our users, we do the following: minθ(1),…,θ(nu)=12∑j=1nu∑i:r(i,j)=1((θ(j))T(x(i))−y(i,j))2+λ2∑j=1nu∑k=1n(θ(j)k)2 We can apply our linear regression gradient descent update using the above cost function. The only real difference is that we **eliminate the constant 1m**. ## Collaborative Filtering It can be very difficult to find features such as "amount of romance" or "amount of action" in a movie. To figure this out, we can use *feature finders*. We can let the users tell us how much they like the different genres, providing their parameter vector immediately for us. To infer the features from given parameters, we use the squared error function with regularization over all the users: minx(1),…,x(nm)12∑i=1nm∑j:r(i,j)=1((θ(j))Tx(i)−y(i,j))2+λ2∑i=1nm∑k=1n(x(i)k)2 You can also **randomly guess** the values for theta to guess the features repeatedly. You will actually converge to a good set of features. ## Collaborative Filtering Algorithm To speed things up, we can simultaneously minimize our features and our parameters: J(x,θ)=12∑(i,j):r(i,j)=1((θ(j))Tx(i)−y(i,j))2+λ2∑i=1nm∑k=1n(x(i)k)2+λ2∑j=1nu∑k=1n(θ(j)k)2 It looks very complicated, but we've only combined the cost function for theta and the cost function for x. Because the algorithm can learn them itself, the bias units where x0=1 have been removed, therefore x∈Rn and θ∈Rn. These are the steps in the algorithm: 1. Initialize x(i),...,x(nm),θ(1),...,θ(nu) to small random values. This serves to break symmetry and ensures that the algorithm learns featuresx(i),...,x(nm) that are different from each other. 2. Minimize J(x(i),...,x(nm),θ(1),...,θ(nu)) using gradient descent (or an advanced optimization algorithm). Minimize J(x(i),...,x(nm),θ(1),...,θ(nu)) using gradient descent (or an advanced optimization algorithm). E.g. for every j=1,...,nu,i=1,...nm: Minimize J(x(i),...,x(nm),θ(1),...,θ(nu)) using gradient descent (or an advanced optimization algorithm). E.g. for every j=1,...,nu,i=1,...nm: x(i)k :=x(i)k−α⎛⎝∑j:r(i,j)=1((θ(j))Tx(i)−y(i,j))θ(j)k+λx(i)k⎞⎠ Minimize J(x(i),...,x(nm),θ(1),...,θ(nu)) using gradient descent (or an advanced optimization algorithm). E.g. for every j=1,...,nu,i=1,...nm: x(i)k :=x(i)k−α⎛⎝∑j:r(i,j)=1((θ(j))Tx(i)−y(i,j))θ(j)k+λx(i)k⎞⎠ θ(j)k :=θ(j)k−α⎛⎝∑i:r(i,j)=1((θ(j))Tx(i)−y(i,j))x(i)k+λθ(j)k⎞⎠ 3. For a user with parameters θ and a movie with (learned) features x, predict a star rating of θTx. ## Vectorization: Low Rank Matrix Factorization Given matrices X (each row containing features of a particular movie) and Θ (each row containing the weights for those features for a given user), then the full matrix Y of all predicted ratings of all movies by all users is given simply by: Y=XΘT. Predicting how similar two movies i and j are can be done using the distance between their respective feature vectors x. Specifically, we are looking for a small value of ||x(i)−x(j)||. ## Implementation Detail: Mean Normalization If the ranking system for movies is used from the previous lectures, then new users (who have watched no movies), will be assigned new movies incorrectly. Specifically, they will be assigned θ with all components equal to zero due to the minimization of the regularization term. That is, we assume that the new user will rank all movies 0, which does not seem intuitively correct. We rectify this problem by normalizing the data relative to the mean. First, we use a matrix Y to store the data from previous ratings, where the ith row of Y is the ratings for the ith movie and the jth column corresponds to the ratings for the jth user. We can now define a vector μ=[μ1,μ2,…,μnm] such that μi=∑j:r(i,j)=1Yi,j∑jr(i,j) Which is effectively the mean of the previous ratings for the ith movie (where only movies that have been watched by users are counted). We now can normalize the data by subtracting u, the mean rating, from the actual ratings for each user (column in matrix Y): As an example, consider the following matrix Y and mean ratings μ: Y=⎡⎣⎢⎢54005 ?000 ?550040⎤⎦⎥⎥,μ=⎡⎣⎢⎢2.522.251.25⎤⎦⎥⎥ The resulting Y′ vector is: Y′=⎡⎣⎢⎢2.52−.2.25−1.252.5 ?−2.25−1.25−2.5 ?3.753.75−2.5−21.25−1.25⎤⎦⎥⎥ Now we must slightly modify the linear regression prediction to include the mean normalization term: (θ(j))Tx(i)+μi Now, for a new user, the initial predicted values will be equal to the μ term instead of simply being initialized to zero, which is more accurate. <file_sep>/typings/markdown-it/index.d.ts declare module 'markdown-it' { interface MarkdownOptions { /** * Enable HTML tags in source */ html?: boolean; /** * Use '/' to close single tags (<br />). * This is only for full CommonMark compatibility. */ xhtmlOut?: boolean; /** * Convert '\n' in paragraphs into <br> */ breaks?: boolean; /** * CSS language prefix for fenced blocks. Can be * useful for external highlighters. */ langPrefix?: string; /** * Autoconvert URL-like text to links */ linkify?: boolean; /** * Enable some language-neutral replacement + quotes beautification */ typographer?: boolean; /** Double + single quotes replacement pairs, when typographer enabled, * and smartquotes on. Could be either a String or an Array. * * For example, you can use '«»„“' for Russian, '„“‚‘' for German, * and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). */ quotes?: string; /** * Highlighter function. Should return escaped HTML, * or '' if the source string is not changed and should be escaped externally. * If result starts with <pre... internal wrapper is skipped. */ highlight?(str: string, lang: string): string; } interface Markdown { render(input: string): string; use(...arsg: any[]): Markdown; } const markdownIt: (options: MarkdownOptions | string) => Markdown; export default markdownIt; } <file_sep>/netlify.toml [build] command = "yarn build" publish = "public" [build.environment] NODE_VERSION = "v11.13.0" [[redirects]] from = "/sqlite-wasm-demo/*" to = "https://vkbansal.github.io/sqlite-wasm-demo/:splat" status = 200 force = true <file_sep>/pages/blog/2016/machine-learning/anomaly-detection.md --- title: "Anomaly Detection" author: name: <NAME> site: http://vkbansal.me date: 2016-07-02 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Problem Motivation Just like in other learning problems, we are given a dataset $x^{(1)},x^{(2)}, \dots ,x^{(m)}$. We are then given a new example, $x_{test}$, and we want to know whether this new example is abnormal/anomalous. We define a **model** $p(x)$ that tells us the probability the example is not anomalous. We also use a threshold $\epsilon$ (epsilon) as a dividing line so we can say which examples are anomalous and which are not. A very common application of anomaly detection is detecting fraud: $$ \begin{align*} & x^{(i)} = \text{features of user } i\text{'s activities} \newline & \text{Model } p(x) \text{ from the data} \newline & \text{Identify unusual users by checking which have } p(x) < \epsilon \\ \end{align*} $$ If our anomaly detector is flagging **too many** anomalous examples, then we need to **decrease** our threshold $\epsilon$. ## Anamoly Detection vs Supervised Learning | Anamoly Detection | Supervised Learning | | :--------------------------------------: | :--------------------------------------: | | Very small no. of $+ve$ examples $(y = 1)$ (anamoly). Large number of $-ve$ $(y=0)$ examples (nomaly) | Large number of $+ve$ and $-ve$ examples | | Many different "types" of anomalies. Hard for any algorithm to learn from $+ve$ examples what anomalies look like. | Enough $+ve$ examples for the alogrithm to get a sense of what $+ve$(s) are like | | Future anomalies may look nothing like any of the anomalous examples we've seen so far. | Future $+ve$ examples likely to be similar to ones in training set | | Examples: Fraud Detection, Manufacturing, Monitoring machines in data centers | Examples: Email Spam Classification, Weather Prediction, Cancer Classification | ## Gaussian Distribution The Gaussian Distribution is a familiar bell-shaped curve that can be described by a function $\mathcal{N}(\mu,\sigma^2)$ Let $x \in R$. If the probability distribution of $x$ is Gaussian with mean $\mu$, variance $\sigma^2$, then: $$ x \sim \mathcal{N}(\mu, \sigma^2) $$ The little $\sim$ or 'tilde' can be read as **distributed as**. The Gaussian Distribution is parameterized by a mean and a variance. Mu, or $\mu$, describes the center of the curve, called the mean. The width of the curve is described by sigma, or $\sigma$, called the standard deviation. The full function is as follows: $$ \large p(x; \mu, \sigma^2) = \dfrac{1}{\sigma\sqrt{2\pi}}e^{-\dfrac{1}{2}(\dfrac{x - \mu}{\sigma})^2} $$ We can estimate the parameter $\mu$ from a given dataset by simply taking the average of all the examples: $$ \mu = \frac{1}{m} \sum_{i =1}^{m} x^{(i)} $$ We can estimate the other parameter, $\sigma^2$, with our familiar squared error formula: $$ \sigma^2 = \frac{1}{m} \sum_{i = 1}{m}(x^{(i)} - \mu)^2 $$ ## Algorithm Given a training set of examples $\{x^{(1)}, \dots ,x^{(m)}\}$ where each example is a vector, $x \in R^n$. $$ p(x) = p(x_1;\mu_1, \sigma^2_1) p(x_2;\mu_2, \sigma^2_2) \dots p(x_n;\mu_n, \sigma^2_n) $$ In statistics, this is called an **independence assumption** on the values of the features inside training example $x$. $$ = \prod_{j=1}^n(x_j; \mu_j, \sigma_j) $$ **The algorithm** Choose features $x_i$ that you think might be indicative of anomalous examples. Fit parameters $\mu_1,\dots,\mu_n$, $\sigma^2_1, \dots, \sigma^2_n$. Calculate $μ_j=\frac{1}{m}\sum_{i=1}^mx^{(i)}_j$ Calculate $\sigma^2_j = \frac{1}{m} \sum_{i=1}^m (x^{(i)}_j - \mu_j)^2$ Given a new example $x$, compute $p(x)$: $$ p(x) = \prod_{j=1}^n p(x_j; \mu_j, \sigma^2_j) = \prod_{j=1}^n $$ Anomaly if $p(x)< \epsilon$ A vectorized version of the calculation for $\mu$ is $μ=\frac{1}{m}\sum_{i=1}^{m}x^{(i)}$. You can vectorize $\sigma^2$ similarly. ## Developing and Evaluating an Anomaly Detection System To evaluate our learning algorithm, we take some labeled data, categorized into anomalous and non-anomalous examples ($y=0$ if normal, $y=1$ if anomalous). Among that data, take a large proportion of **good**, non-anomalous data for the training set on which to train $p(x)$. Then, take a smaller proportion of mixed anomalous and non-anomalous examples (you will usually have many more non-anomalous examples) for your cross-validation and test sets. For example, we may have a set where 0.2% of the data is anomalous. We take 60% of those examples, all of which are good (y=0) for the training set. We then take 20% of the examples for the cross-validation set (with 0.1% of the anomalous examples) and another 20% from the test set (with another 0.1% of the anomalous). In other words, we split the data $60/20/20$ training/CV/test and then split the anomalous examples $50/50$ between the CV and test sets. **Algorithm evaluation:** Fit model $p(x)$ on training set $\{ x^{(1)}, \dots, x^{(m)}\} \\$ On a cross validation/test example $x$, predict: $$ \begin{align*} & \text{If } p(x) < \epsilon \text{ (anomaly), then } y=1 \\ & \text{If } p(x) \ge \epsilon \text{ (normal), then } y=0 \\ \end{align*} $$ Possible evaluation metrics (see [Machine Learning System Design](../machine-learning-system-design/)): - True positive, false positive, false negative, true negative. - Precision/recall - F1 score > Note that we use the cross-validation set to choose parameter $ϵ$ ## Choosing What Features to Use The features will greatly affect how well your anomaly detection algorithm works. We can check that our features are **gaussian** by plotting a histogram of our data and checking for the bell-shaped curve. Some **transforms** we can try on an example feature x that does not have the bell-shaped curve are: - $log(x)$ - $log(x+1)$ - $log(x+c)$ for some constant - $\sqrt{x}$ - $x^{1/3}$ We can play with each of these to try and achieve the gaussian shape in our data. There is an **error analysis procedure** for anomaly detection that is very similar to the one in supervised learning. Our goal is for $p(x)$ to be large for normal examples and small for anomalous examples. One common problem is when $p(x)$ is similar for both types of examples. In this case, you need to examine the anomalous examples that are giving high probability in detail and try to figure out new features that will better distinguish the data. In general, choose features that might take on unusually large or small values in the event of an anomaly. ## Multivariate Gaussian Distribution The multivariate gaussian distribution is an extension of anomaly detection and may (or may not) catch more anomalies. Instead of modeling $p(x_1) ,p(x_2),\dots$ separately, we will model $p(x)$ all in one go. Our parameters will be: $\mu \in \mathbb{R}^n$ and $\Sigma \in \mathbb{R}^{n \times n}$ $$ p(x; \mu, \Sigma) = \frac{1}{(2\pi)^{n/2} |{\Sigma}|^{1/2}}exp\left( -\frac{1}{2}(x - \mu)^T \Sigma^{-1}(x - \mu)\right) $$ The important effect is that we can model oblong gaussian contours, allowing us to better fit data that might not fit into the normal circular contours. Varying $\Sigma$ changes the shape, width, and orientation of the contours. Changing $\mu$ will move the center of the distribution. ## Anomaly Detection using the Multivariate Gaussian Distribution When doing anomaly detection with multivariate gaussian distribution, we compute $\mu$ and  $\Sigma$ normally. We then compute $p(x)$ using the new formula in the previous section and flag an anomaly if $p(x)<\epsilon$. The original model for $p(x)$ corresponds to a multivariate Gaussian where the contours of $p(x;\mu,\Sigma)$ are axis-aligned. The multivariate Gaussian model can automatically capture correlations between different features of $x$. However, the original model maintains some advantages: it is computationally cheaper (no matrix to invert, which is costly for large number of features) and it performs well even with small training set size (in multivariate Gaussian model, it should be greater than the number of features for $\Sigma$ to be invertible). <file_sep>/scripts/build.ts import chalk from 'chalk'; import yargs from 'yargs'; const argv = yargs.parse(); import { StaticSiteBuilder } from './StaticSiteBuilder'; try { (async function() { const builder = new StaticSiteBuilder(); console.log(chalk.green('Starting Build...')); if ('watch' in argv) { await builder.watch(); } else { await builder.build(); console.log(chalk.green('Build completed!')); } })(); } catch (e) { console.log(chalk.red('Build failed!')); console.log(e); } <file_sep>/pages/blog/2016/machine-learning/machine-learning-system-design.md --- title: "Machine Learning System Design" author: name: <NAME> site: http://vkbansal.me date: 2016-05-30 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Prioritizing What to Work On Different ways we can approach a machine learning problem: - Collect lots of data. - Develop sophisticated features (for example: using email header data in spam emails). - Develop algorithms to process your input in different ways (recognizing misspellings in spam). It is difficult to tell which of the options will be helpful. ## Error Analysis The recommended approach to solving machine learning problems is: - Start with a simple algorithm, implement it quickly, and test it early. - Plot learning curves to decide if more data, more features, etc. will help - Error analysis: manually examine the errors on examples in the cross validation set and try to spot a trend. It's important to get error results as a single, numerical value. Otherwise it is difficult to assess your algorithm's performance. You may need to process your input before it is useful. For example, if your input is a set of words, you may want to treat the same word with different forms (fail/failing/failed) as one word, so must use **stemming software** to recognize them all as one. ## Error Metrics for Skewed Classes It is sometimes difficult to tell whether a reduction in error is actually an improvement of the algorithm. - For example: In predicting a cancer diagnoses where 0.5% of the examples have cancer, we find our learning algorithm has a 1% error. However, if we were to simply classify every single example as a $0$, then our error would reduce to 0.5% even though we did not improve the algorithm. This usually happens with **skewed classes**; that is, when the ratio of *positive* to *negative* examples is very clode to one of the two extremes. For this we can use **Precision/Recall**. ![Precision-Recall](./images/precision-recall.png) **Precision**: (of all patients we predicted where y=1, what fraction actually has cancer?) $$ \frac{\text{True Positives}}{\text{Total number of predicted positives}}=\frac{\text{True Positives}}{\text{True Positives}+ \text{False positives}} $$ **Recall**: (Of all the patients that actually have cancer, what fraction did we correctly detect as having cancer?) $$ \frac{\text{True Positives}}{\text{Number of actual positives}}= \frac{\text{True Positives}}{\text{True Positives}+ \text{False negatives}} $$ These two metrics give us a better sense of how our classifier is doing. We want both precision and recall to be high. In the example at the beginning of the section, if we classify all patients as $0$, then our **recall** will be $\frac{0}{0+f}=0$, so despite having a lower error percentage, we can quickly see it has worse recall. ## Trading Off Precision and Recall We might want a **confident** prediction of two classes using logistic regression. One way is to increase our threshold: Predict $1$ if: $h_{\theta}(x) \ge 0.7$ Predict $0$ if: $h_{\theta}(x) < 0.7$ This way, we only predict cancer if the patient has a $70%$ chance. Doing this, we will have **higher precision** but **lower recall**. In the opposite example, we can lower our threshold: Predict $1$ if: $h_{\theta}(x) \ge 0.3$ Predict $0$ if: $h_{\theta}(x) < 0.3$ That way, we get a very **safe** prediction. This will cause **higher recall** but **lower precision**. > The greater the threshold, the greater the precision and the lower the recall. > > The lower the threshold, the greater the recall and the lower the precision. In order to turn these two metrics into one single number, we can take the **F value**. One way is to take the **average**: $$ \frac{F + R}{2} $$ This does not work well. If we predict all $y=0$ then that will bring the average up despite having $0$ recall. If we predict all examples as $y=1$, then the very high recall will bring up the average despite having $0$ precision. A better way is to compute the **F Score** (or F1 score): $$ \frac{2PR}{P + R} $$ In order for the F Score to be large, both precision and recall must be large. We want to train precision and recall on the **cross validation set** so as not to bias our test set. ## Data for Machine Learning How much data should we train on? In certain cases, an "inferior algorithm," if given enough data, can outperform a superior algorithm with less data. We must choose our features to have **enough** information. A useful test is: Given input $x$, would a human expert be able to confidently predict $y$? **Rationale for large data**: if we have a **low bias** algorithm (many features or hidden units making a very complex function), then the larger the training set we use, the less we will have overfitting (and the more accurate the algorithm will be on the test set). <file_sep>/pages/blog/2016/machine-learning/unsupervised-learning-clustering.md --- title: "Unsupervised Learning: Clustering" author: name: <NAME> site: http://vkbansal.me date: 2016-06-20 description: My notes from Machine Learning Course by Andrew Ng. tag: - notes - "machine-learning" math: true --- ## Introduction Unsupervised learning is contrasted from supervised learning because it uses an **unlabeled** training set rather than a labeled one. In other words, we don't have the vector y of expected results, we only have a dataset of features where we can find structure. Clustering is good for: - Market segmentation - Social network analysis - Organizing computer clusters - Astronomical data analysis ## K-Means Algorithm The K-Means Algorithm is the most popular and widely used algorithm for automatically grouping data into coherent subsets. 1. Randomly initialize two points in the dataset called the *cluster centroids*. 2. Cluster assignment: assign all examples into one of two groups based on which cluster centroid the example is closest to. 3. Move centroid: compute the averages for all the points inside each of the two cluster centroid groups, then move the cluster centroid points to those averages. 4. Re-run (2) and (3) until we have found our clusters. Our main variables are: $$ K = \text{number of clusters} \\ \text{Training set } x^{(1)}, x^{(2)},\dots, x^{(m)} \text{ where } x^{(i)} \in R^n $$ Note that we **will not use** the $x_0=1$ convention. **The algorithm:** Randomly initialize $K$ cluster centroids $\mu_1, \mu_2, \dots, \mu_k$. $$ \begin{align*} & \text{Repeat:} \\ & \hspace{2em} \text{for } i=1 \text{ to } m: \\ & \hspace{4em} c^{(i)} := \text{index (from } 1 \text{ to } K \text {) of cluster centroid to } x^{(i)} \\ & \hspace{2em} \text{for } k=1 \text{ to } K: \\ & \hspace{4em} \mu_k := \text{average (mean) of points assigned to cluster } k \end{align*} $$ The **first for-loop** is the 'Cluster Assignment' step. We make a vector $c$ where $c^{(i)} $represents the centroid assigned to example $x^{(i)}$. We can write the operation of the Cluster Assignment step more mathematically as follows: $$ c^{(i)} = \min_k ||x^{(i)} - \mu_k||^2 $$ c(i)=argmink ||x(i)−μk||2 That is, each $c^{(i)}$ contains the index of the centroid that has minimal distance to $x^{(i)}$. By convention, we square the right-hand-side, which makes the function we are trying to minimize more sharply increasing. It is mostly just a convention. The **second for-loop** is the 'Move Centroid' step where we move each centroid to the average of its group. More formally, the equation for this loop is as follows: $$ \mu_k = \frac{1}{n} [x^{(k_1)} + x^{(k_2)} + \dots + x^{(k_n)}] \in R^n $$ Where each of $x^{(k_1)},x^{(k_2)},\dots,x^{(k_n)}$ are the training examples assigned to group $μ_k$. If you have a cluster centroid with **0 points** assigned to it, you can randomly **re-initialize** that centroid to a new point. You can also simply **eliminate** that cluster group. After a number of iterations the algorithm will **converge**, where new iterations do not affect the clusters. Note on non-separated clusters: some datasets have no real inner separation or natural structure. K-means can still evenly segment your data into K subsets, so can still be useful in this case. ## Optimization Objective Recall some of the parameters we used in our algorithm: $$ \begin{align*} c^{(i)} &=  \text{index of cluster } (1,2,\dots,K) \text{ to which example } x^{(i)} \text{ is currently assigned}\\ μ_k &= \text{cluster centroid } k  \space (μ_k \in R^n) \\ μ_c^{(i)} &= \text{cluster centroid of cluster to which example } x^{(i)} \text{ has been assigned} \end{align*} $$ Using these variables we can define our **cost function**: $$ J(c^{(1)},\dots,c^{(m)}, \mu_1, \dots, \mu_k) = \frac{1}{m} \sum_{i=1}^m ||x^{(i)} - \mu_{(c^{(i)})}||^2 $$ Our **optimization objective** is to minimize all our parameters using the above cost function: $$ \min_{c,\mu} J(c, \mu) $$ That is, we are finding all the values in sets $c$, representing all our clusters, and $\mu$, representing all our centroids, that will minimize **the average of the distances** of every training example to its corresponding cluster centroid. The above cost function is often called the **distortion** of the training examples. In the **cluster assignment step**, our goal is to: $$ \text{Minimize } J(\dots) \text{ with } c^{(1)}, \dots, c^{(m)} \text{ holding } \mu_1, \mu_2, \dots, \mu_k \text{ fixed} $$ In the **move centroid** step, our goal is to: $$ \text{Minimize } J(\dots) \text{ with } \mu_1, \mu_2, \dots, \mu_k $$ With k-means, it is **not possible for the cost function to sometimes increase**. It should always descend. ## Random Initialization There's one particular recommended method for randomly initializing your cluster centroids. 1. Have $K<m$. That is, make sure the number of your clusters is less than the number of your training examples. 2. Randomly pick $K$ training examples. (Also be sure the selected examples are unique). 3. Set $μ_1,\dots,μ_k$ equal to these $K$ examples. K-means **can get stuck in local optima**. To decrease the chance of this happening, you can run the algorithm on many different random initializations. $$ \begin{align*} &\text{for } i = 1 \text{ to } 100 :\\ & \hspace{2em} \text{randomly initialize k-means} \\ & \hspace{2em} \text{run k-means to get } c \text{ and } m \\ & \hspace{2em} \text{compute the cost function (distortion) } J(c,m) \\ & \hspace{2em} \text{pick the clustering that gave us the lowest cost} \end{align*} $$ ## Choosing the Number of Clusters Choosing $K$ can be quite arbitrary and ambiguous. **The elbow method**: plot the cost $J$ and the number of clusters $K$. The cost function should reduce as we increase the number of clusters, and then flatten out. Choose K at the point where the cost function starts to flatten out. However, fairly often, the curve is **very gradual**, so there's no clear elbow. **Note:** $J$ will **always** decrease as $K$ is increased. The one exception is if k-means gets stuck at a bad local optimum. Another way to choose $K$ is to observe how well k-means performs on a **downstream purpose**. In other words, you choose $K$ that proves to be most useful for some goal you're trying to achieve from using these clusters.<file_sep>/typings/markdown-it-decorate/index.d.ts declare module 'markdown-it-decorate' { const plugin: any; export default plugin; } <file_sep>/scripts/utils/fileLoader.ts import * as path from 'path'; import * as fs from 'fs-extra'; import { fileHash, isProduction } from './miscUtils'; import options from '../options.json'; const IMAGE_EXT_REGEX = /\.(jpe?g|png|svg|gif)/i; const outputPath = path.join(process.cwd(), options.outPath); export function fileLoader(srcPath: string, filePath: string) { const actualSrcPath = path.join(path.dirname(filePath), srcPath); const parsedPath = path.parse(srcPath); if (!fs.existsSync(actualSrcPath)) { throw new Error(`${actualSrcPath} does not exists`); } const hash = isProduction() ? fileHash(actualSrcPath).substr(0, 12) : parsedPath.name; if (IMAGE_EXT_REGEX.test(parsedPath.ext)) { const newPath = `/images/${hash}${parsedPath.ext}`; const newDiskPath = path.join(outputPath, `./${newPath}`); fs.ensureDirSync(path.dirname(newDiskPath)); fs.copyFileSync(actualSrcPath, newDiskPath); return newPath; } return ''; }
a42bdaddbffc55041035a47c87fcddfa3c01ea26
[ "Markdown", "TOML", "TypeScript", "JavaScript" ]
34
TypeScript
eSlider/vkbansal.me
e120ddaa1ba1ab4e1134ca25066a426297d426a7
5ba928ee4ba441044942c4c72ccd88b84dff5cff
refs/heads/main
<file_sep>let minutesToWalk; let theSiteID; let timeAtDestination; let savedInput; let timeAtDestinationMinutes; function handleEnterPress(e){ if(e.keyCode === 13){ let theInput = document.getElementById('userInput').value; savedInput = theInput; e.preventDefault(); // Ensure it is only this code that runs getCoords(theInput); getData(theInput); let emptyTheBox = document.getElementById('stationName'); emptyTheBox.innerHTML = ''; var elmnt = document.getElementById('takemehere'); elmnt.scrollIntoView(); } } function getData(searchData) { const url = `http://api.sl.se/api2/typeahead.json?key=<KEY>&searchstring=${searchData}&stationsonly=true`; fetch(url) .then((resp) => resp.json()) .then(function (data) { let stationName = document.getElementById('stationName') stationName.appendChild(document.createTextNode(searchData.charAt(0).toUpperCase() + searchData.slice(1))); let getSiteId = data.ResponseData[0].SiteId; theSiteID = getSiteId; useSiteID(getSiteId); }) .catch(function (error) { console.log(error); }); } //======================================= //UPDATE TABLE setInterval(async function(){ await useSiteID(theSiteID), console.log("SIDAN UPPDATERAS FÖR => " + "(" + theSiteID + ")"+ minutesToWalk + "min") },60000); //====================================== async function useSiteID(siteID) { document.getElementById('time-grid').innerHTML = ""; const url = `http://api.sl.se/api2/realtimedeparturesv4.json?key=f04c1a44d6294242a1bfa0f41d73270e&siteid=${siteID}&timewindow=30`; await fetch(url) .then((resp) => resp.json()) .then(function (data) { let grid = document.getElementById('time-grid'); let respData = data.ResponseData; if (document.getElementById('bus').checked) { if (respData.Buses.length > 0) { respData.Buses.forEach(element => { let displayTimeNumber = element.DisplayTime; let countChars = displayTimeNumber.length; let oneOrTwoChars; if (countChars >= 6) { oneOrTwoChars = displayTimeNumber.slice(0, 2); } else{ oneOrTwoChars = displayTimeNumber.charAt(0); if(oneOrTwoChars === "N") { oneOrTwoChars = 0; } } let unsliced = element.ExpectedDateTime; //2021-09-02T14:20:00 const dateStr = unsliced, [yyyy,mm,dd,hh,mi,sec] = dateStr.split(/[/:\-T]/) let minutesAfterSliced = mi; let sliced = calculate(`${hh}:${mi}:${sec}`); if (timeAtDestination <= sliced && oneOrTwoChars >= minutesToWalk) { console.log("Du HINNER!" + sliced + ">=" + timeAtDestination + "\nFramme: " + timeAtDestinationMinutes + "\nAvgång: " + minutesAfterSliced); var line = document.createElement('div'); var name = document.createElement('div'); var minutesToGo = document.createElement('div'); line.className = "a1"; name.className = "a2"; minutesToGo.className = "a3"; line.innerHTML = element.LineNumber; name.innerHTML = element.Destination; minutesToGo.innerHTML = element.DisplayTime; grid.appendChild(line); grid.appendChild(name); grid.appendChild(minutesToGo); } else { console.log("Du hinner INTE!" + sliced + "<" + timeAtDestination); } }); } else { let message = document.createElement('div'); message.className = "no-departures"; message.innerHTML = "Det finns inga avgångar för bussar på vald hållplats."; grid.appendChild(message); } } if (document.getElementById('train').checked) { if (respData.Trains.length > 0) { respData.Trains.forEach(element => { let displayTimeNumber = element.DisplayTime; let countChars = displayTimeNumber.length; let oneOrTwoChars; if (countChars >= 6) { oneOrTwoChars = displayTimeNumber.slice(0, 2); } else{ oneOrTwoChars = displayTimeNumber.charAt(0); if(oneOrTwoChars === "N") { oneOrTwoChars = 0; } } let unsliced = element.ExpectedDateTime; //2021-09-02T14:20:00 const dateStr = unsliced, [yyyy,mm,dd,hh,mi,sec] = dateStr.split(/[/:\-T]/) let sliced = calculate(`${hh}:${mi}:${sec}`); if(timeAtDestination <= sliced && oneOrTwoChars >= minutesToWalk) { console.log("Du HINNER!" + sliced +">=" + timeAtDestination); var line = document.createElement('div'); var name = document.createElement('div'); var minutesToGo = document.createElement('div'); line.className = "a1"; name.className = "a2"; minutesToGo.className = "a3"; line.innerHTML = element.LineNumber; name.innerHTML = element.Destination; minutesToGo.innerHTML = element.DisplayTime; grid.appendChild(line); grid.appendChild(name); grid.appendChild(minutesToGo); } else{ console.log("Du hinner INTE!" + sliced +"<" + timeAtDestination); } }); } else { let message = document.createElement('div'); message.className = "no-departures"; message.innerHTML = "Det finns inga avgångar för tåg på vald hållplats."; grid.appendChild(message); } } if (document.getElementById('metro').checked) { if (respData.Metros.length > 0) { respData.Metros.forEach(element => { let displayTimeNumber = element.DisplayTime; let countChars = displayTimeNumber.length; let oneOrTwoChars; if (countChars >= 6) { oneOrTwoChars = displayTimeNumber.slice(0, 2); } else{ oneOrTwoChars = displayTimeNumber.charAt(0); if(oneOrTwoChars === "N") { oneOrTwoChars = 0; } } let unsliced = element.ExpectedDateTime; //2021-09-02T14:20:00 const dateStr = unsliced, [yyyy,mm,dd,hh,mi,sec] = dateStr.split(/[/:\-T]/) let sliced = calculate(`${hh}:${mi}:${sec}`); if (timeAtDestination <= sliced && oneOrTwoChars >= minutesToWalk) { var line = document.createElement('div'); var name = document.createElement('div'); var minutesToGo = document.createElement('div'); line.className = "a1"; name.className = "a2"; minutesToGo.className = "a3"; line.innerHTML = element.LineNumber; name.innerHTML = element.Destination; minutesToGo.innerHTML = element.DisplayTime; grid.appendChild(line); grid.appendChild(name); grid.appendChild(minutesToGo); } else{ console.log("Du hinner INTE!" + sliced +"<" + timeAtDestination); } }); } else { let message = document.createElement('div'); message.className = "no-departures"; message.innerHTML = "Det finns inga avgångar för metros på vald hållplats."; grid.appendChild(message); } } }) .catch(function (error) { console.log(error); }); } function getCoords(input) { const url = `https://api.resrobot.se/v2/location.name.json?key=<KEY>&input=${input}`; fetch(url) .then((resp) => resp.json()) .then(function (data) { let startlongitude = 18.05811; let startlatitude = 59.32000; let stoplongitude = data.StopLocation[0].lon; let stoplatitud = data.StopLocation[0].lat; useCoords(startlatitude, startlongitude, stoplatitud, stoplongitude); }) .catch(function (error) { console.log(error); }); } function useCoords(startlat, startlon, stoplat, stoplon) { const url = `https://api.resrobot.se/v2/trip?key=<KEY>&originCoordLat=${startlat}&originCoordLong=${startlon}&destCoordLat=${stoplat}&destCoordLong=${stoplon}&format=json`; fetch(url) .then((resp) => resp.json()) .then(function (data) { let originTime = data.Trip[0].LegList.Leg[0].Origin.time; let destinationTime = data.Trip[0].LegList.Leg[0].Destination.time; console.log(originTime); console.log(destinationTime); const seconds = calculate(originTime); const seconds2 = calculate(destinationTime); console.log(seconds); timeAtDestination = seconds2; timeAtDestinationMinutes = (seconds2/60); console.log(seconds2); let subraction = (seconds2 - seconds)/60; console.log(subraction); minutesToWalk = subraction; console.log("useCoords-metoden:" + minutesToWalk); }) .catch(function (error) { console.log(error); }); } function calculate(time){ const arr = time.split(":"); const seconds = arr[0] * 3600 + arr[1] * 60 + (+arr[2]); return seconds; }<file_sep># SL-App-Website
7416c24a5a8bc4fc853ec944921f754e24c84860
[ "JavaScript", "Markdown" ]
2
JavaScript
ro-ed/SL-App-Website
c761c8868f243ee1dcde7e938248ed63f09890ef
9274124781ef3eb9c609f548c5c9a08832a1df86
refs/heads/master
<repo_name>bobosui/chortle<file_sep>/test.py from chortle import ExtensionBuilder if __name__ == '__main__': builder = ExtensionBuilder('testplg', verbose=True) builder.add_function('rot13', 'test_fns.rot13') builder.add_function('product', 'test_fns.product') builder.build() <file_sep>/chortle.py import inspect import importlib import os import pathlib import shutil import attr import cffi import jinja2 def import_attr(dotted_path): try: module_path, attr_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path raise ImportError(msg) module = importlib.import_module(module_path) try: return getattr(module, attr_name) except AttributeError: msg = 'Module "%s" does not define "%s"' % ( module_path, attr_name) raise ImportError(msg) @attr.s class Function: name = attr.ib() path = attr.ib() num_args = attr.ib() @property def namespaced_name(self): return f'__chortle_{self.name}' @attr.s class ExtensionBuilder: name = attr.ib() verbose = attr.ib(default=False) functions = attr.ib(default=attr.Factory(list)) def add_function(self, name, path): fn = import_attr(path) sig = inspect.signature(fn) params = sig.parameters.values() if any(p.kind.name in ['KEYWORD_ONLY', 'VAR_KEYWORD'] for p in params): raise ValueError('Cannot create function with keyword arguments') if any(p.kind.name == 'VAR_POSITIONAL' for p in params): num_args = -1 else: num_args = len(params) self.functions.append(Function(name, path, num_args)) def load_template(self, name): ctx = { 'extension_name': self.name, 'functions': self.functions, } with open(self.templates_path / (name + '.tpl')) as f: tpl = jinja2.Template(f.read()) rendered = tpl.render(ctx) with open(self.debug_path / name, 'w') as f: f.write(rendered) return rendered @property def debug_path(self): return pathlib.Path('debug') @property def templates_path(self): return pathlib.Path('templates') def build(self): shutil.rmtree(self.debug_path, ignore_errors=True) os.makedirs(self.debug_path) ffibuilder = cffi.FFI() ffibuilder.embedding_api(self.load_template('plugin_api.h')) ffibuilder.embedding_init_code(self.load_template('plugin.py')) ffibuilder.set_source(self.name, self.load_template('plugin.c')) ffibuilder.compile(verbose=self.verbose) os.rename(self.name + '.c', self.debug_path / (self.name + '.c')) os.rename(self.name + '.o', self.debug_path / (self.name + '.o'))
ee87a619cd062f0fa62353bfbacea31b1e06e975
[ "Python" ]
2
Python
bobosui/chortle
aa8d2be7d649f64f80917350f5dae4ea988e044a
836e0a73fa10a989f48426d570faa35f138a82ff
refs/heads/master
<file_sep>resolution = { 'x' : 128, 'y' : 128 } baseline = 88 gravity = { 'downforce' : 1.5 } actor_jump = 35 actor_speed = 2 title = 'Pypega' actor_hp = 200 gachi_hp = 50 <file_sep>NAME = "Pypega" VERSION = "0.1" DESCRIPTION = "FOR SAAAN." MAIN_FILE = "main.py" ########################################### import sys,os from cx_Freeze import setup,Executable additional_library = ['numpy.core._methods','numpy.lib.format'] PYTHON_PATH = os.path.dirname(sys.executable) os.environ['TCL_LIBRARY'] = r'{}\tcl\tcl8.6'.format(PYTHON_PATH) os.environ['TK_LIBRARY'] = r'{}\tcl\tcl8.6'.format(PYTHON_PATH) setup( name=NAME, version=VERSION, description=DESCRIPTION, executables=[Executable(MAIN_FILE,base = "Win32GUI")], options={ 'build_exe': { 'includes': additional_library, 'packages': ['OpenGL'] } } ) <file_sep>from playsound import playsound as player import os import pyxel import constants as c from game.characters.actor import Actor from game.levels.level import Levels as lvl from game.characters.enemy import Gachi class App: def __init__(self): pyxel.init(c.resolution['x'], c.resolution['y'], caption=c.title) pyxel.load('game/assets/pypega.pyxres') self.x = 0;self.y = 0;self.virtual_x = 0 self.level = lvl() self.actor = Actor(2, c.baseline) self.gachi = Gachi(110, c.baseline - 55) self.gachi_on = False pyxel.run(self.update, self.draw) def update(self): if True: print(f"Current Position: {self.actor.get_position()}") #print(f"Jumping: {self.actor.is_jumping()}") print(f"Virtual X: {self.virtual_x}") self.x, self.y = self.actor.get_position() if pyxel.btnp(pyxel.KEY_ESCAPE) or pyxel.btnp(pyxel.KEY_Q): pyxel.quit() if pyxel.btn(pyxel.KEY_DOWN) and self.y < c.resolution['y'] - 40: self.actor.move(0, c.actor_speed) if pyxel.btnp(pyxel.KEY_SPACE) and self.y > 2 and self.actor.is_jumping() == False: self.actor.jump(c.actor_jump, self.y) if pyxel.btn(pyxel.KEY_LEFT): if self.x > 2: self.actor.move(-c.actor_speed, 0) if self.virtual_x > 0: self.virtual_x = self.virtual_x - c.actor_speed if pyxel.btn(pyxel.KEY_RIGHT): if self.x < c.resolution['x'] - 28: self.actor.move(c.actor_speed, 0) if self.virtual_x < 1920: self.virtual_x = self.virtual_x + c.actor_speed if self.actor.is_in_limit(): self.actor.applygravity(c.gravity['downforce']) def draw(self): pyxel.cls(0) if pyxel.btn(pyxel.KEY_RIGHT): self.level.move('right', self.virtual_x) elif pyxel.btn(pyxel.KEY_LEFT) and self.virtual_x > 0: self.level.move('left', self.virtual_x) else: self.level.draw() #if self.gachi_on: #self.actor.draw_hands() # else: self.actor.draw() self.actor.draw_hp_bar() self.draw_attack() self.draw_shield() if self.virtual_x > 150 and self.virtual_x < 550 or self.gachi_on: self.gachi.draw() if not self.gachi_on: self.gachi_on = True player(os.getcwd()+r'\game\assets\music\assclap.mp3', False) def draw_attack(self): if pyxel.btn(pyxel.KEY_F) or pyxel.btn(pyxel.KEY_F) and pyxel.btn(pyxel.KEY_SPACE): if self.actor.get_direction() == 'Right': self.actor.attack('right') else: self.actor.attack('left') else: pass def draw_shield(self): if pyxel.btn(pyxel.KEY_E) or pyxel.btn(pyxel.KEY_E) and pyxel.btn(pyxel.KEY_SPACE): if self.actor.get_direction() == 'Right': self.actor.shield('right') else: self.actor.shield('left') else: pass if __name__ == '__main__': App()<file_sep>import pyxel class App: def __init__(self): pyxel.init(160, 120) self.x = 0 pyxel.load('game/assets/pypega.pyxres') pyxel.run(self.update, self.draw) def update(self): self.x = (self.x + 1) % pyxel.width def draw(self): pyxel.cls(0) pyxel.blt(16, 16, 0, 64, 32, 16, 16) App()<file_sep>import pyxel import constants as c class Actor: def __init__(self, x, y): self.x = x self.y = y self.direction = '' self.is_attacking = False self.hp = c.actor_hp def __del__(self): pass def move(self, x, y): if x > 0 and y == 0: self.x = self.x + x self.direction = 'Right' if x < 0 and y == 0: self.x = self.x + x self.direction = 'Left' if y > 0 and x == 0 or y < 0 and x == 0: self.y = self.y + y def get_position(self): return self.x, self.y def get_direction(self): return self.direction def is_attacking(self): return self.is_attacking def draw_hp_bar(self): pyxel.text(17, 10, self.get_hp(), 8) pyxel.blt(2, 10, 0, 48, 48, 16, 16, 0) pyxel.blt(18, 10, 0, 48+16, 48, 16, 16, 0) pyxel.blt(34, 10, 0, 48+32, 48, 16, 16, 0) pyxel.blt(50, 10, 0, 48+48, 48, 16, 16, 0) def get_hp(self): return (f"{self.hp}") def attack(self, direction): if direction == 'right': pyxel.blt(self.x+15, self.y, 0, 64, 32, 16, 16, 0) else: pyxel.blt(self.x-15, self.y, 0, 64, 32, -16, 16, 0) def shield(self, direction): if direction == 'right': pyxel.blt(self.x+12, self.y, 0, 80, 32, 16, 16, 0) else: pyxel.blt(self.x-12, self.y, 0, 80, 32, -16, 16, 0) def draw(self): if self.is_jumping() and self.direction == 'Left': pyxel.blt(self.x, self.y, 0, 0, 48, -16, -16, 0) elif self.is_jumping(): pyxel.blt(self.x, self.y, 0, 0, 48, 16, -16, 0) elif self.direction == 'Right': pyxel.blt(self.x, self.y, 0, 0, 48, 16, 16, 0) elif self.direction == 'Left': pyxel.blt(self.x, self.y, 0, 0, 48, -16, 16, 0) else: pyxel.blt(self.x, self.y, 0, 0, 48, 16, 16, 0) def draw_hands(self): if self.is_jumping() and self.direction == 'Left': pyxel.blt(self.x, self.y, 0, 16, 64, -16, -16, 0) pyxel.blt(self.x-15, self.y, 0, 0, 64, -16, -16, 0) pyxel.blt(self.x+15, self.y, 0, 32, 64, -16, -16, 0) elif self.is_jumping(): pyxel.blt(self.x, self.y, 0, 16, 64, 16, -16, 0) pyxel.blt(self.x-15, self.y, 0, 0, 64, 16, -16, 0) pyxel.blt(self.x+15, self.y, 0, 32, 64, 16, -16, 0) elif self.direction == 'Right': pyxel.blt(self.x, self.y, 0, 16, 64, 16, 16, 0) pyxel.blt(self.x-10, self.y, 0, 0, 64, 16, 16, 0) pyxel.blt(self.x+12, self.y, 0, 32, 64, 16, 16, 0) elif self.direction == 'Left': pyxel.blt(self.x-15, self.y, 0, 0, 64, -16, 16, 0) pyxel.blt(self.x+15, self.y, 0, 32, 64, -16, 16, 0) pyxel.blt(self.x, self.y, 0, 16, 64, -16, 16, 0) else: pyxel.blt(self.x, self.y, 0, 0, 64, 16, 16, 0) pyxel.blt(self.x-10, self.y, 0, 32, 64, 16, 16, 0) pyxel.blt(self.x+12, self.y, 0, 16, 64, 16, 16, 0) def is_in_limit(self): if self.y < c.baseline: return True return False def is_jumping(self): try: if int(self.y) < int(self.previous_y) and self.y < c.baseline - 2: return True except AttributeError: pass self.previous_y = self.y return False def applygravity(self, intensity): self.y = self.y + intensity def jump(self, intensity, startpoint): self.startpoint = startpoint self.y = self.y - intensity <file_sep>import pyxel import constants as c class Levels: def __init__(self): self.virtual_x = 0 self.virtual_y = 0 def draw(self): pyxel.bltm(self.virtual_x, self.virtual_y, 0, 0, 0, 256, 16, 0) def move(self, direction, x): if direction == 'right': self.virtual_x = -x pyxel.bltm(self.virtual_x, self.virtual_y, 0, 0, 0, 256, 16, 0) #print(f"blitting tilemap at: {self.virtual_x}") if direction == 'left': self.virtual_x = -x pyxel.bltm(self.virtual_x, self.virtual_y, 0, 0, 0, 256, 16, 0) #print(f"blitting tilemap at: {self.virtual_x}")<file_sep># pypega Pypega the game ![Gameplay](https://j.gifs.com/vl7jXn.gif) <file_sep>import pyxel import constants as c import random class Gachi: def __init__(self, x, y): self.x = x self.y = y self.x_side = [-16, 16, 16, 16, 16, 16] self.y_side = [16, -16, 16, 16, 16, 16, 16, 16, 16, 16] self.hp = c.gachi_hp def draw(self): pyxel.blt(self.x, self.y, 0, 16, 48, self.x_side[random.randint(0,len(self.x_side) - 1)] , self.y_side[random.randint(0,len(self.y_side) - 1)] , 0) def draw_hp_bar(self): pyxel.text(17, 10, self.get_hp(), 8) pyxel.blt(-2, 10, 0, 48, 48, 16, 16, 0) pyxel.blt(-18, 10, 0, 48+16, 48, 16, 16, 0) pyxel.blt(-34, 10, 0, 48+32, 48, 16, 16, 0) pyxel.blt(-50, 10, 0, 48+48, 48, 16, 16, 0) def get_hp(self): return (f"{self.hp}")
89739080d468cfc6195ae1fe3786e1676cfd88bd
[ "Markdown", "Python" ]
8
Python
FilippoLeone/pypega
8dd3eee22dcac063d5de430a4c1e3e34a5cc5b85
bc2714c308e68daf124d3f9b00aa1bd47d1a3d95
refs/heads/master
<repo_name>tcompart/influxdb<file_sep>/influxql/result.go package influxql import ( "encoding/json" "errors" ) // Result represents a resultset returned from a single statement. type Result struct { // StatementID is just the statement's position in the query. It's used // to combine statement results if they're being buffered in memory. StatementID int `json:"-"` Series Rows Err error } // MarshalJSON encodes the result into JSON. func (r *Result) MarshalJSON() ([]byte, error) { // Define a struct that outputs "error" as a string. var o struct { Series []*Row `json:"series,omitempty"` Err string `json:"error,omitempty"` } // Copy fields to output struct. o.Series = r.Series if r.Err != nil { o.Err = r.Err.Error() } return json.Marshal(&o) } // UnmarshalJSON decodes the data into the Result struct func (r *Result) UnmarshalJSON(b []byte) error { var o struct { Series []*Row `json:"series,omitempty"` Err string `json:"error,omitempty"` } err := json.Unmarshal(b, &o) if err != nil { return err } r.Series = o.Series if o.Err != "" { r.Err = errors.New(o.Err) } return nil } <file_sep>/cluster/config.go package cluster import ( "time" "github.com/influxdb/influxdb/toml" ) const ( // DefaultShardWriterTimeout is the default timeout set on shard writers. DefaultShardWriterTimeout = 5 * time.Second ) // Config represents the configuration for the the clustering service. type Config struct { ShardWriterTimeout toml.Duration `toml:"shard-writer-timeout"` } // NewConfig returns an instance of Config with defaults. func NewConfig() Config { return Config{ ShardWriterTimeout: toml.Duration(DefaultShardWriterTimeout), } }
9ad067d2613a75f0ead0f8d5efca94a5d0421035
[ "Go" ]
2
Go
tcompart/influxdb
357b6585c1474bb8de0b6685bf157399667c17cd
23ea24a8d0ca15d5a91e3b1de841bb752cff880a
refs/heads/master
<file_sep>export const aboutme: string; export const content: string; export const footerShared: string; <file_sep>/// <reference types="react" /> import './AboutMe.css'; export interface IProps { content: string; img: string; textUppercase: string; } export declare const AboutMeComponent: (props: IProps) => JSX.Element; <file_sep>export * from './aboutMe';
b3da534b034bd9436f9c9dab0dc71ea166759f1c
[ "TypeScript" ]
3
TypeScript
joaquinicolas/widget-about-me
1dc948b5107541e327e35c49a70c44105ef4442b
92f500aa38ea73e3bcfbf3bac82538d0e9d93ab7
refs/heads/master
<repo_name>nikola-m4/popularis<file_sep>/core/src/com/popularis/entity/EntityTree.java package com.popularis.entity; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Vector3; import com.popularis.gfx.Model; import com.popularis.gfx.ModelBuilder; import com.popularis.world.World; public class EntityTree extends Entity { public EntityTree(World world) { super(world); } @Override public String getTexture() { return "tree.png"; } @Override public Model buildModel(ModelBuilder builder, ShaderProgram shader) { return builder.quad(0, (3 * 76f / 48f) / 2f, 0, 3, 3 * 76f / 48f, 0, 0, 48, 76, 128, 128).build(shader); } @Override public EntityType getType() { return EntityType.TREE; } @Override public Vector3 getHitboxSize() { return new Vector3(3, 5, 3); } } <file_sep>/core/src/com/popularis/ui/GuiImageButton.java package com.popularis.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class GuiImageButton extends GuiButton { private TextureRegion image; private String tooltip = null; private GlyphLayout layout = new GlyphLayout(); public GuiImageButton(int id, int x, int y, int width, int height, TextureRegion image, String tooltip) { super(id, x, y, width, height); image.flip(false, true); this.image = image; this.tooltip = tooltip; } public GuiImageButton(int id, int x, int y, int width, int height, TextureRegion image) { this(id, x, y, width, height, image, null); } @Override public void render() { Color color = isHovered() ? Color.YELLOW : Color.WHITE; super.drawRect(color, x, y, width, height, 4); batch.setColor(color); batch.draw(image, x + 8, y + 8, width - 16, height - 16); batch.setColor(Color.WHITE); } @Override public void renderTop() { if (tooltip != null && isHovered()) { layout.setText(font, tooltip); super.fillRect(Color.DARK_GRAY, Gdx.input.getX(), Gdx.input.getY() - layout.height - 8, layout.width + 8, layout.height + 8); font.draw(batch, tooltip, Gdx.input.getX() + 4, Gdx.input.getY() - layout.height - 4); } } } <file_sep>/core/src/com/popularis/entity/EntityType.java package com.popularis.entity; public enum EntityType { TREE, UNIT; } <file_sep>/core/src/com/popularis/event/events/AddTaskEvent.java package com.popularis.event.events; import java.util.Collection; import com.popularis.entity.EntityUnit; import com.popularis.event.api.CancellableEvent; import com.popularis.gameplay.Colony; import com.popularis.gameplay.tasks.Task; /** * Triggered whenever a task is added to a colony, i.e. whenever the player clicks somewhere * to assign the task with some units selected. This event happens before the colony decides * what unit to assign the task to. After the colony decided the unit to assign the task to, * an {@link AssignTaskEvent} is triggered. */ public class AddTaskEvent extends CancellableEvent { public static final AddTaskEvent INSTANCE = new AddTaskEvent(); private Colony colony; private Task task; private Collection<EntityUnit> allowedUnits; public AddTaskEvent set(Colony colony, Task task, Collection<EntityUnit> allowedUnits) { this.colony = colony; this.task = task; this.allowedUnits = allowedUnits; return this; } public Colony getColony() { return colony; } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } public Collection<EntityUnit> getAllowedUnits() { return allowedUnits; } public void setAllowedUnits(Collection<EntityUnit> allowedUnits) { this.allowedUnits = allowedUnits; } } <file_sep>/core/src/com/popularis/util/Mathf.java package com.popularis.util; import java.util.List; import java.util.Random; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; /** * A collection of useful math operations using floats so I don't need to cast from doubles every time. */ public class Mathf { public static final float PI = 3.1415927f; /** Useful pythagorean stuff so I don't have to calculate at runtime */ public static final float ROOT_2 = 1.4142135f, ROOT_05 = 1 / ROOT_2; // lookup table for 2^n (useful for noise) public static final int[] LOOKUP_2_TO_N = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048}; public static final Matrix4 IDENTITY = new Matrix4(); private static Random random = new Random(); public static float toRadians(float degrees) { return degrees / 180.0f * PI; } public static float toDegrees(float radians) { return radians * 180.0f / PI; } public static float clamp(float x, float min, float max) { if (x < min) return min; if (x > max) return max; return x; } public static float random() { return random.nextFloat(); } public static int randint(int bounds) { return random.nextInt(bounds); } public static int randint() { return random.nextInt(); } public static float sin(float x) { return (float) Math.sin(toRadians(x)); } public static float cos(float x) { return (float) Math.cos(toRadians(x)); } public static float tan(float x) { return (float) Math.tan(toRadians(x)); } public static float asin(float x) { return toDegrees((float) Math.asin(x)); } public static float acos(float x) { return toDegrees((float) Math.acos(x)); } public static float atan(float x) { return toDegrees((float) Math.atan(x)); } public static float atan2(float y, float x) { return toDegrees((float) Math.atan2(y, x)); } public static int floor(float x) { return (int) Math.floor(x); } public static float sqrt(float x) { return (float) Math.sqrt(x); } public static int ceil(float x) { return (int) Math.ceil(x); } public static int round(float x) { return (int) Math.round(x); } public static final float exp2toN(int exp) { if (exp <= 8) { return LOOKUP_2_TO_N[exp]; } else { return pow(2, exp); } } public static float pow(float base, float exp) { return (float) Math.pow(base, exp); } public static float pow(float base, int exp) { float r = 1; for (int i = 0; i < exp; i++) r *= base; return r; } public static float minimumX(Vector2... vectors) { float x = Float.MAX_VALUE; for (Vector2 v : vectors) if (v.x < x) x = v.x; return x; } public static float minimumY(Vector2... vectors) { float y = Float.MAX_VALUE; for (Vector2 v : vectors) if (v.y < y) y = v.y; return y; } public static boolean isWhole(float x) { return x == (int) x; } public static float lerp(float a, float b, float t) { return a + t * (b - a); } public static float[] toFloatArray(List<Float> list) { float[] arr = new float[list.size()]; int i = 0; for (Float f : list) { arr[i++] = (f != null ? f : Float.NaN); } return arr; } public static int[] toIntArray(List<Integer> list) { int[] arr = new int[list.size()]; int i = 0; for (Integer f : list) { arr[i++] = (f != null ? f : 0); } return arr; } public static short[] toShortArray(List<Short> list) { short[] arr = new short[list.size()]; int i = 0; for (Short f : list) { arr[i++] = (f != null ? f : 0); } return arr; } public static short[] intsToShortArray(List<Integer> list) { short[] arr = new short[list.size()]; int i = 0; for (Integer f : list) { arr[i++] = (f != null ? f.shortValue() : 0); } return arr; } public static float noiseOctaves(float x, float y, int octaves, int offsetX, int offsetY) { float ampl = 1; float freq = 1; float n = 0; for (int i = 0; i < octaves; i++) { n += SimplexNoise.noise(x * freq + offsetX, y * freq + offsetY) * ampl; ampl *= 0.5f; freq *= 2; } return n; } public static boolean isAllFalse(boolean[] arr) { for (boolean b : arr) { if (b) return false; } return true; } public static Vector3 surfaceNormal(Vector3 v1, Vector3 v2, Vector3 v3) { Vector3 v = new Vector3(v2).sub(v1); Vector3 w = new Vector3(v3).sub(v1); return v.crs(w).nor(); } public static float abs(float a) { return Math.abs(a); } public static int mostSignificantAxis(Vector3 v) { if (abs(v.y) >= abs(v.x) && abs(v.y) >= abs(v.z)) return 1; else if (abs(v.x) >= abs(v.z)) return 0; else return 2; } } <file_sep>/core/src/com/popularis/event/events/CancelTaskEvent.java package com.popularis.event.events; import com.popularis.entity.EntityUnit; import com.popularis.event.api.Event; import com.popularis.gameplay.Colony; import com.popularis.gameplay.tasks.Task; public class CancelTaskEvent extends Event { public static final CancelTaskEvent INSTANCE = new CancelTaskEvent(); private Colony colony; private Task task; private EntityUnit cancellingUnit; public CancelTaskEvent set(Colony colony, Task task, EntityUnit cancellingUnit) { this.colony = colony; this.task = task; this.cancellingUnit = cancellingUnit; return this; } public Colony getColony() { return colony; } public Task getTask() { return task; } public EntityUnit getCancellingUnit() { return cancellingUnit; } } <file_sep>/core/src/com/popularis/event/api/Listener.java package com.popularis.event.api; public interface Listener {} <file_sep>/core/src/com/popularis/world/Chunk.java package com.popularis.world; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.utils.Disposable; import com.popularis.blocks.Block; import com.popularis.gameplay.Colony; import com.popularis.gfx.CameraController; import com.popularis.gfx.ChunkModelBuilder; import com.popularis.gfx.Model; import com.popularis.util.Mathf; public class Chunk implements Disposable { public final int x, z; private final World world; private ChunkModelBuilder modelBuilder; private byte[] blocks; private Matrix4 transform; // because chunks are 16 x 128 x 16, and I only want 16 x 16 x 16 models, // I need 8 models per chunk private Model[] models = new Model[8]; public boolean[] dirty = new boolean[8]; public Chunk(World world, int x, int z) { this.world = world; this.x = x; this.z = z; blocks = new byte[16 * 128 * 16]; transform = new Matrix4().translate(x * 16, 0, z * 16); modelBuilder = new ChunkModelBuilder(); } public void generate(int offsetX1, int offsetZ1, int offsetX2, int offsetZ2) { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { int height = (int) (Mathf.noiseOctaves((this.x * 16 + x) * 0.02f, (this.z * 16 + z) * 0.02f, 4, offsetX1, offsetZ1) * 1 + 80); boolean cliff = Mathf.noiseOctaves((this.x * 16 + x) * 0.02f, (this.z * 16 + z) * 0.02f, 1, offsetX2, offsetZ2) > 0.3f; if (cliff) height += 3; for (int y = 0; y < height; y++) { if (y == height - 1) { setBlock(Block.grass, x, y, z); } else { setBlock(Block.stone, x, y, z); } } } } } public Block getBlock(int x, int y, int z) { if (!inBounds(x, y, z)) { return world.getBlock(this.x * 16 + x, y, this.z * 16 + z); } return Block.blocks[blocks[x | y << 4 | z << 11]]; } public Block getBlockClampedToEdge(int x, int y, int z) { if (x < 0) return getBlockClampedToEdge(x + 1, y, z); else if (z < 0) return getBlockClampedToEdge(x, y, z + 1); else return getBlock(x, y, z); } public void setBlock(Block b, int x, int y, int z) { if (!inBounds(x, y, z)) { world.setBlock(b, this.x * 16 + x, y, this.z * 16 + z); return; } // updates all the chunks and sections adjacent to this block int my = y / 16; for (int zz = -1; zz <= 1; zz++) { for (int yy = -1; yy <= 1; yy++) { if (yy + my < 0 || yy + my >= 8) continue; for (int xx = -1; xx <= 1; xx++) { Chunk c = world.getChunk(this.x + xx, this.z + zz); if (c == null) continue; c.dirty[my + yy] = true; } } } byte id = b == null ? 0 : b.id; blocks[x | y << 4 | z << 11] = id; } public boolean inBounds(int x, int y, int z) { return x >= 0 && y >= 0 && z >= 0 && x < 16 && y < 128 && z < 16; } public void buildModel(ShaderProgram shader, CameraController controller, Colony colony) { for (int i = 0; i < 8; i++) { buildModel(shader, i, controller, colony); } } public void buildModel(ShaderProgram shader, int i, CameraController controller, Colony colony) { models[i] = modelBuilder.makeModel(shader, this, i, controller, colony); dirty[i] = false; } public boolean faceVisible(int x, int y, int z, int f) { switch (f) { default: case 0: return isBlockTransparent(x, y, z + 1); case 1: return isBlockTransparent(x, y, z - 1); case 2: return isBlockTransparent(x - 1, y, z); case 3: return isBlockTransparent(x + 1, y, z); case 4: return isBlockTransparent(x, y - 1, z); case 5: return isBlockTransparent(x, y + 1, z); } } public boolean isBlockTransparent(int x, int y, int z) { return getBlock(x, y, z) == null; } public boolean[] visibleFaces(boolean[] arr, int x, int y, int z) { for (int i = 0; i < 6; i++) { arr[i] = faceVisible(x, y, z, i); } return arr; } public boolean crash = true; public void render(ShaderProgram shader, CameraController controller, Colony colony) { shader.setUniformMatrix("transformMatrix", transform); for (int i = 0; i < 8; i++) { if (dirty[i]) buildModel(shader, i, controller, colony); if (models[i] != null) models[i].render(); } } @Override public void dispose() { for (Model m : models) if (m != null) m.dispose(); } } <file_sep>/core/src/com/popularis/input/Input.java package com.popularis.input; import com.badlogic.gdx.InputProcessor; import com.popularis.event.api.EventBus; import com.popularis.event.events.InputEvent.KeyPressEvent; import com.popularis.event.events.InputEvent.KeyReleaseEvent; import com.popularis.event.events.InputEvent.MousePressEvent; import com.popularis.event.events.InputEvent.MouseReleaseEvent; import com.popularis.event.events.InputEvent.ScrollEvent; public class Input implements InputProcessor { @Override public boolean keyDown(int keycode) { EventBus.trigger(new KeyPressEvent(keycode)); return true; } @Override public boolean keyUp(int keycode) { EventBus.trigger(new KeyReleaseEvent(keycode)); return true; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { EventBus.trigger(new MousePressEvent(button, screenX, screenY)); return true; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { EventBus.trigger(new MouseReleaseEvent(button, screenX, screenY)); return true; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { EventBus.trigger(new ScrollEvent(amount)); return true; } } <file_sep>/core/src/com/popularis/gfx/CameraController.java package com.popularis.gfx; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.Ray; import com.popularis.blocks.Block; import com.popularis.event.api.EventBus; import com.popularis.event.api.Intercept; import com.popularis.event.api.Listener; import com.popularis.event.api.Monitor; import com.popularis.event.events.InputEvent.KeyPressEvent; import com.popularis.event.events.InputEvent.ScrollEvent; import com.popularis.gameplay.Colony; import com.popularis.gameplay.tasks.Task; import com.popularis.gameplay.tasks.TaskBuild; import com.popularis.ui.CitizenGui; import com.popularis.util.Coordinate; import com.popularis.util.Mathf; import com.popularis.world.World; public class CameraController implements Listener { private static final float MIN_ZOOM = 0.25f, MAX_ZOOM = 3; private Coordinate hoveredBlock; private World world; private OrthographicCamera camera; private Colony colony; private Vector3 tmp = new Vector3(), tmp2 = new Vector3(); private Coordinate pivotPoint = null; private int lastRotationX = -1; public int maximumVisibleLevel = 85; public CitizenGui citizenGui; public CameraController(World world, Colony colony) { this.world = world; this.colony = colony; float aspect = (float) Gdx.graphics.getWidth() / (float) Gdx.graphics.getHeight(); camera = new OrthographicCamera(24 * aspect, 24); camera.near = 0.1f; camera.far = 500; camera.position.set(-60, 160, -60); camera.lookAt(0, 128, 0); camera.position.y = 128; EventBus.register(this); } public void update(float delta) { float s = 50 * delta; boolean v = Gdx.input.isKeyPressed(Keys.W) ^ Gdx.input.isKeyPressed(Keys.S); boolean h = Gdx.input.isKeyPressed(Keys.A) ^ Gdx.input.isKeyPressed(Keys.D); if (v && h) s *= Mathf.ROOT_05; // MOVING WITH ARROW KEYS if (Gdx.input.isKeyPressed(Keys.W)) { tmp.set(camera.direction); tmp.y = 0; tmp.nor().scl(2 * s); camera.position.add(tmp); } if (Gdx.input.isKeyPressed(Keys.S)) { tmp.set(camera.direction); tmp.y = 0; tmp.nor().scl(-2 * s); camera.position.add(tmp); } if (Gdx.input.isKeyPressed(Keys.A)) { tmp.set(camera.direction).crs(camera.up); tmp.y = 0; tmp.nor().scl(-s); camera.position.add(tmp); } if (Gdx.input.isKeyPressed(Keys.D)) { tmp.set(camera.direction).crs(camera.up); tmp.y = 0; tmp.nor().scl(s); camera.position.add(tmp); } if (Gdx.input.isKeyPressed(Keys.LEFT)) { pivotPoint = getAnchorBlock(Gdx.input.getX(), Gdx.input.getY()); float angleY = 180 * delta; camera.rotateAround(pivotPoint.toVector3(tmp), tmp2.set(0, 1, 0), -angleY); } if (Gdx.input.isKeyPressed(Keys.RIGHT)) { pivotPoint = getAnchorBlock(Gdx.input.getX(), Gdx.input.getY()); float angleY = 180 * delta; camera.rotateAround(pivotPoint.toVector3(tmp), tmp2.set(0, 1, 0), angleY); } // ROTATING WITH RIGHT-CLICK if (Gdx.input.isButtonPressed(1)) { // for some reason, Gdx.input.getDeltaX() doesn't work on HTML so I have to do this int dx; if (lastRotationX == -1) { dx = 0; } else { dx = Gdx.input.getX() - lastRotationX; } lastRotationX = Gdx.input.getX(); float angleY = -2 * dx; if (pivotPoint == null) { pivotPoint = getPickedBlock(Gdx.input.getX(), Gdx.input.getY(), false); if (pivotPoint == null) { pivotPoint = getAnchorBlock(Gdx.input.getX(), Gdx.input.getY()); } } else { camera.rotateAround(pivotPoint.toVector3(tmp), tmp2.set(0, 1, 0), angleY); } } else { pivotPoint = null; } hoveredBlock = getPickedBlock(Gdx.input.getX(), Gdx.input.getY(), true); camera.update(); } public Coordinate getHoveredBlock() { return hoveredBlock; } public Coordinate getPivotPoint() { return pivotPoint; } @Monitor public void onKeyPress(KeyPressEvent e) { switch (e.getKeycode()) { case Keys.EQUALS: changeVisibleLevel(1); break; case Keys.MINUS: changeVisibleLevel(-1); break; case Keys.B: world.setBlock(Block.stone, hoveredBlock.x, hoveredBlock.y, hoveredBlock.z); break; } } private void changeVisibleLevel(int change) { maximumVisibleLevel += change; if (maximumVisibleLevel < 5) maximumVisibleLevel = 5; if (maximumVisibleLevel > 90) maximumVisibleLevel = 90; world.buildModelsFromYLevel(maximumVisibleLevel); } public Coordinate getPickedBlock(float screenX, float screenY, boolean goInBlock) { Ray ray = camera.getPickRay(screenX, screenY); float step = 0.1f; tmp2.set(ray.direction).scl(step); tmp.set(ray.origin).add(0.5f, 0.5f, 0.5f); int ix, iy, iz; for (int i = 0; i < (int) (500 / step); i++) { tmp.add(tmp2); ix = (int) (tmp.x); iy = (int) (tmp.y); iz = (int) (tmp.z); if (isBlockAt(ix, iy, iz) && iy <= maximumVisibleLevel) { if (!goInBlock) { tmp.sub(tmp2); ix = (int) (tmp.x); iy = (int) (tmp.y); iz = (int) (tmp.z); } if (iy == maximumVisibleLevel + 1) return null; return new Coordinate(ix, iy, iz); } } return null; } private boolean isBlockAt(int x, int y, int z) { if (world.getBlock(x, y, z) != null) return true; for (Task task : colony.getTasks()) { if (task instanceof TaskBuild) { TaskBuild b = (TaskBuild) task; if (b.getBlock() != null && b.getTarget().x == x && b.getTarget().y == y && b.getTarget().z == z) { return true; } } } return false; } /** * Fires a ray from the given screen coordinates and returns the position it hits on the y = maximumVisibleLevel plane.<br /> * Functionally equivalent to {@link #getPickedBlock(float, float)} if the entire world was one layer at y = maximumVisibleLevel. */ private Coordinate getAnchorBlock(float screenX, float screenY) { Ray ray = camera.getPickRay(screenX, screenY); float step = 0.01f; tmp2.set(ray.direction).scl(step); tmp.set(ray.origin).add(0.5f, 0.5f, 0.5f); int ix, iy, iz; for (int i = 0; i < (int) (500 / step); i++) { tmp.add(tmp2); ix = (int) (tmp.x); iy = (int) (tmp.y); iz = (int) (tmp.z); if (iy < maximumVisibleLevel) { return new Coordinate(ix, iy, iz); } } return null; } @Intercept public void onScroll(ScrollEvent e) { if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT)) { changeVisibleLevel(-e.getAmount()); world.buildModelsFromYLevel(maximumVisibleLevel); } else { camera.zoom += camera.zoom * e.getAmount() * 0.25f; if (camera.zoom < MIN_ZOOM) camera.zoom = MIN_ZOOM; if (camera.zoom > MAX_ZOOM) camera.zoom = MAX_ZOOM; } } public OrthographicCamera getCamera() { return camera; } } <file_sep>/core/src/com/popularis/gfx/postprocessing/PostProcessing.java package com.popularis.gfx.postprocessing; import static com.badlogic.gdx.Gdx.gl; import static com.badlogic.gdx.graphics.GL20.*; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.popularis.gfx.CameraController; import com.popularis.gfx.Framebuffer; import com.popularis.gfx.Model; public class PostProcessing { private List<PostProcessingEffect> effects = new ArrayList<PostProcessingEffect>(); private Model basicQuad; public PostProcessing(AssetManager assets) { short[] ind = { 2, 1, 0, 2, 0, 3 }; float[] vert = { -1, -1, -1, 1, 1, 1, 1, -1 }; basicQuad = new Model(ind, vert); // creates a basic quad int w = Gdx.graphics.getWidth(); int h = Gdx.graphics.getHeight(); effects.add(new EntityXrayEffect(assets, new Framebuffer(w, h, false))); effects.add(new OutlineEffect(assets, new Framebuffer(w, h, false), w, h)); effects.add(new PostProcessingEffect(assets, "basicVertex.glsl", "contrastFragment.glsl", null)); // the last effect, so it's null } public void doPostProcessing(CameraController camera, int colorAttachment, int depthAttachment, int entityColor, int entityDepth) { int lastColor = colorAttachment; for (PostProcessingEffect effect : effects) { if (effect.fbo != null) effect.fbo.bind(); effect.shader.begin(); effect.updateShader(camera); gl.glActiveTexture(GL_TEXTURE0); gl.glBindTexture(GL_TEXTURE_2D, lastColor); gl.glActiveTexture(GL_TEXTURE1); gl.glBindTexture(GL_TEXTURE_2D, depthAttachment); gl.glActiveTexture(GL_TEXTURE2); gl.glBindTexture(GL_TEXTURE_2D, entityColor); gl.glActiveTexture(GL_TEXTURE3); gl.glBindTexture(GL_TEXTURE_2D, entityDepth); gl.glActiveTexture(GL_TEXTURE0); basicQuad.renderBasic(); effect.shader.end(); if (effect.fbo != null) { // update the last color, so that this effect's output // will be fed as the color input into the next effect lastColor = effect.fbo.getColourTexture(); effect.fbo.unbind(); } else { break; } } } } <file_sep>/desktop/src/com/popularis/desktop/DesktopLauncher.java package com.popularis.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.popularis.Popularis; import com.popularis.util.Platform; public class DesktopLauncher { public static void main(String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = 1080; config.height = 540; config.samples = 2; Platform.platform = Platform.DESKTOP; Platform.crossPlatform = new DesktopPlatform(); new LwjglApplication(Popularis.instance, config); } } <file_sep>/core/src/com/popularis/util/AABB.java package com.popularis.util; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Pool.Poolable; public class AABB implements Poolable { private Vector3 position = new Vector3(); private Vector3 size = new Vector3(); public AABB() {} public void setSize(Vector3 s) { size.set(s); } public void setSize(float x, float y, float z) { size.set(x, y, z); } public void updatePosition(Vector3 pos) { position.set(pos); } public void updatePosition(float x, float y, float z) { position.set(x, y, z); } public float minX() { return position.x - size.x / 2f; } public float maxX() { return position.x + size.x / 2f; } public float minZ() { return position.z - size.z / 2f; } public float maxZ() { return position.z + size.z / 2f; } public float minY() { return position.y - 0.5f; } public float maxY() { return position.y + size.y - 0.5f; } public boolean containsPoint(Vector3 point) { return minX() < point.x && maxX() > point.x && minY() < point.y && maxY() > point.y && minZ() < point.z && maxZ() > point.z; } public boolean collidesX(AABB other) { if (maxY() <= other.minY()) return false; if (maxZ() <= other.minZ()) return false; if (minY() >= other.maxY()) return false; if (minZ() >= other.maxZ()) return false; return minX() < other.maxX() && maxX() > other.minX(); } public boolean collidesY(AABB other) { if (maxX() <= other.minX()) return false; if (maxZ() <= other.minZ()) return false; if (minX() >= other.maxX()) return false; if (minZ() >= other.maxZ()) return false; return minY() < other.maxY() && maxY() > other.minY(); } public boolean collidesZ(AABB other) { if (maxY() <= other.minY()) return false; if (maxX() <= other.minX()) return false; if (minY() >= other.maxY()) return false; if (minX() >= other.maxX()) return false; return minZ() < other.maxZ() && maxZ() > other.minZ(); } public boolean collidesGround(AABB other) { if (maxX() < other.minX()) return false; if (maxZ() < other.minZ()) return false; if (minX() > other.maxX()) return false; if (minZ() > other.maxZ()) return false; return minY() < other.maxY() && minY() > other.minY(); } public boolean collides(AABB other) { return collidesX(other) && collidesY(other) && collidesZ(other); } public boolean collidesX(Iterable<AABB> others) { for (AABB other : others) if (collidesX(other)) return true; return false; } public boolean collidesY(Iterable<AABB> others) { for (AABB other : others) if (collidesY(other)) return true; return false; } public boolean collidesGround(Iterable<AABB> others) { for (AABB other : others) if (collidesGround(other)) return true; return false; } public boolean collidesZ(Iterable<AABB> others) { for (AABB other : others) if (collidesZ(other)) return true; return false; } public boolean collides(Iterable<AABB> others) { for (AABB other : others) if (collides(other)) return true; return false; } @Override public void reset() { position.setZero(); size.setZero(); } } <file_sep>/html/src/com/popularis/client/HtmlLauncher.java package com.popularis.client; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.popularis.Popularis; import com.popularis.util.Platform; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() { GwtApplicationConfiguration config = new GwtApplicationConfiguration(1080, 540); return config; } @Override public ApplicationListener createApplicationListener() { Platform.platform = Platform.HTML; Platform.crossPlatform = new HtmlPlatform(); return Popularis.instance; } }<file_sep>/core/src/com/popularis/gameplay/tasks/TaskType.java package com.popularis.gameplay.tasks; public enum TaskType { NONE, MOVE, BUILD, DESTROY, MOVE_AWAY; } <file_sep>/README.md # Popularis This was an old project I worked on for about three months. It was a very ambitious idea for a real-time strategy game, and uses the [libGDX](https://libgdx.badlogicgames.com) Java game engine. However, most of the rendering code is written from scratch using pure OpenGL. It would have been a game where you can control units, and have them gather resources, build towns, and survive in the wilderness, maybe fighting AI-generated civilizations. I know, ambitious. ## Currently in the game You can... * Move the camera around and select units * Be in an isometric randomly-generated world with some cool graphics effects * Order the units to move, build, or destroy ## Screenshots ![The world](https://i.imgur.com/TqpSra9.png) ![Selecting units](https://i.imgur.com/M4xdK6j.png) ![Destroying a cliffside](https://i.imgur.com/xcsHU8d.png) ## Building Clone the repository and run `./gradlew desktop:run`. The build will be in `desktop/build/libs`. You need Java, and probably a specific version of it too. See [this](https://github.com/libgdx/libgdx/wiki/Gradle-on-the-Commandline) for more info. <file_sep>/core/src/com/popularis/util/CrossPlatform.java package com.popularis.util; public interface CrossPlatform { void setWireframe(boolean wireframe); void initializeDepthTextureBuffers(); } <file_sep>/core/src/com/popularis/ui/GuiTextButton.java package com.popularis.ui; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.utils.Align; public class GuiTextButton extends GuiButton { private String text; public GuiTextButton(int id, int x, int y, int width, int height, String text) { super(id, x, y, width, height); this.text = text; } @Override public void render() { Color color = isHovered() ? Color.YELLOW : Color.WHITE; super.drawRect(color, x, y, width, height, 4); font.setColor(color); font.draw(batch, text, x, y + height / 2 - 8, width, Align.center, true); font.setColor(Color.WHITE); } public String getText() { return text; } public void setText(String text) { this.text = text; } } <file_sep>/core/src/com/popularis/gfx/postprocessing/PostProcessingEffect.java package com.popularis.gfx.postprocessing; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.popularis.gfx.CameraController; import com.popularis.gfx.Framebuffer; import com.popularis.util.ShaderSourceFile; public class PostProcessingEffect { protected ShaderProgram shader; protected Framebuffer fbo; public PostProcessingEffect(AssetManager assets, String vertexShader, String fragmentShader, Framebuffer fbo) { this.fbo = fbo; shader = ShaderSourceFile.createShader(assets, vertexShader, fragmentShader); } public void updateShader(CameraController camera) { } } <file_sep>/core/src/com/popularis/event/api/Event.java package com.popularis.event.api; import com.popularis.event.api.Intercept.Ordering; public abstract class Event { Ordering currentOrdering = null; boolean propagationStopped = false; public boolean isPropagationStopped() { return propagationStopped; } /** * Will stop the event from propagating into later Orders or into Monitor * methods. Calling this method from a method with {@code @Monitor} will throw * an {@code IllegalStateException}. * <p> * This differs slightly from just cancelling the event if it is * {@link Cancellable}. This stops any monitoring methods from receiving the * event but does not cancel it. For example, whenever a block is changed in the * world, the world sends out a {@code BlockChangeEvent}. It then checks if this * event is not cancelled--if it is, the block will not be changed. Stopping * propagation will stop other listeners from getting this event but will still * allow the event to happen. */ public void stopPropagation() throws IllegalStateException { if (currentOrdering == Ordering.MONITOR) throw new IllegalStateException("Cannot stop propagation from Monitor!"); propagationStopped = true; } } <file_sep>/core/src/com/popularis/world/World.java package com.popularis.world; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.Pool; import com.popularis.blocks.Block; import com.popularis.entity.Entity; import com.popularis.event.api.EventBus; import com.popularis.event.events.BlockChangeEvent; import com.popularis.gameplay.Colony; import com.popularis.gfx.CameraController; import com.popularis.util.AABB; import com.popularis.util.Mathf; public class World implements Disposable { private Chunk[] chunks; private int length, width; private List<Entity> entities = new ArrayList<Entity>(); private List<AABB> aabbs = new ArrayList<AABB>(); private Pool<AABB> aabbPool = new Pool<AABB>() { @Override protected AABB newObject() { return new AABB(); } }; public World(int length, int width) { chunks = new Chunk[length * width]; this.length = length; this.width = width; for (int z = 0; z < width; z++) { for (int x = 0; x < length; x++) { chunks[x + z * length] = new Chunk(this, x, z); } } Random rand = new Random(); int offsetX1 = rand.nextInt(1000); int offsetZ1 = rand.nextInt(1000); int offsetX2 = rand.nextInt(1000); int offsetZ2 = rand.nextInt(1000); for (int z = 0; z < width; z++) { for (int x = 0; x < length; x++) { getChunk(x, z).generate(offsetX1, offsetZ1, offsetX2, offsetZ2); } } } public Block getBlock(int x, int y, int z) { if (!inBounds(x, y, z)) return null; int cx = Mathf.floor(x / 16f); int cz = Mathf.floor(z / 16f); return getChunk(cx, cz).getBlock(x % 16, y, z % 16); } public void setBlock(Block block, int x, int y, int z) { if (!inBounds(x, y, z)) return; BlockChangeEvent e = BlockChangeEvent.INSTANCE.set(getBlock(x, y, z), block, x, y, z); EventBus.trigger(e); int cx = Mathf.floor(e.getX() / 16f); int cz = Mathf.floor(e.getZ() / 16f); getChunk(cx, cz).setBlock(e.getNewBlock(), e.getX() % 16, e.getY(), e.getZ() % 16); } public void updateChunkAtBlock(int x, int y, int z) { if (!inBounds(x, y, z)) return; int cx = Mathf.floor(x / 16f); int cy = Mathf.floor(y / 16f); int cz = Mathf.floor(z / 16f); getChunk(cx, cz).dirty[cy] = true; } public boolean inBounds(int x, int y, int z) { return x >= 0 && y >= 0 && z >= 0 && x < length * 16 && y < 128 && z < width * 16; } public void buildModels(ShaderProgram shader, CameraController controller, Colony colony) { shader.begin(); for (Chunk c : chunks) { c.buildModel(shader, controller, colony); } shader.end(); } public void buildModelsFromYLevel(int yLevel) { int section = yLevel / 16; if (section < 0 || section >= 8) return; for (Chunk c : chunks) { c.dirty[section] = true; if (yLevel % 16 <= 1 && section > 0) c.dirty[section - 1] = true; if (yLevel % 16 >= 14 && section < 7) c.dirty[section + 1] = true; } } public Chunk getChunk(int x, int z) { if (x < 0 || z < 0 || x >= length || z >= width) return null; return chunks[x + z * length]; } public int getLength() { return length; } public int getWidth() { return width; } public void render(ShaderProgram shader, CameraController controller, Colony colony) { for (Chunk c : chunks) { c.render(shader, controller, colony); } } public void addEntity(Entity entity) { entities.add(entity); } public List<Entity> getEntities() { return entities; } /** * Gets the AABBs of all the blocks around the given hitbox */ public List<AABB> getAABBsAround(AABB aabb) { freeAABBs(); int minX = Mathf.floor(aabb.minX()); int minY = Mathf.floor(aabb.minY()); int minZ = Mathf.floor(aabb.minZ()); int maxX = Mathf.ceil(aabb.maxX()); int maxY = Mathf.ceil(aabb.maxY()); int maxZ = Mathf.ceil(aabb.maxZ()); for (int z = minZ; z <= maxZ; z++) { for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { if (getBlock(x, y, z) != null) { aabbs.add(getAABBOf(x, y, z)); } } } } return aabbs; } private void freeAABBs() { for (AABB a : aabbs) { aabbPool.free(a); } aabbs.clear(); } public AABB getAABBOf(int x, int y, int z) { AABB block = aabbPool.obtain(); block.setSize(1, 1, 1); block.updatePosition(x, y, z); return block; } @Override public void dispose() { for (Chunk c : chunks) c.dispose(); for (Entity e : entities) e.dispose(); } } <file_sep>/html/src/com/popularis/client/HtmlPlatform.java package com.popularis.client; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Field; import com.badlogic.gdx.utils.reflect.ReflectionException; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.webgl.client.WebGLRenderingContext; import com.popularis.util.CrossPlatform; public class HtmlPlatform implements CrossPlatform { @Override public void setWireframe(boolean wireframe) { // not supported in GWT } @Override public void initializeDepthTextureBuffers() { try { Gdx.app.log("HtmlPlatform", "Initializing depth texture extension..."); // I have to use reflection because the WebGLRenderingContext // field is not public, which kind of sucks Field field = ClassReflection.getDeclaredField(Gdx.gl.getClass(), "gl"); field.setAccessible(true); WebGLRenderingContext gl = (WebGLRenderingContext) field.get(Gdx.gl); JavaScriptObject ext = gl.getExtension("WEBGL_depth_texture"); if (ext == null) { Gdx.app.log("HtmlPlatform", "WEBGL_depth_texture was null, trying WEBKIT..."); gl.getExtension("WEBKIT_WEBGL_depth_texture"); } if (ext == null) { Gdx.app.log("HtmlPlatform", "WEBKIT_WEBGL_depth_texture was null, trying MOZ..."); gl.getExtension("MOZ_WEBGL_depth_texture"); } if (ext == null) { Gdx.app.error("HtmlPlatform", "MOZ__WEBGL_depth_texture was null, could not load depth texture extension."); } else { Gdx.app.log("HtmlPlatform", "Depth texture extension loaded successfully!"); } } catch (ReflectionException e) { Gdx.app.error("HtmlPlatform", "A reflection exception occured.", e); } } } <file_sep>/core/src/com/popularis/gfx/ModelBuilder.java package com.popularis.gfx; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.popularis.util.Mathf; public class ModelBuilder { private List<Float> vertices, textures, colours, normals; private List<Integer> indices; private int[] lastAO = new int[4]; private int aoIndex = 0; private float u = 0, v = 0; public float r = 1, g = 1, b = 1, a = 1, nx = 0, ny = 0, nz = 0; public int faceIndex = 0; public boolean debug = false; public ModelBuilder() { vertices = new ArrayList<Float>(); colours = new ArrayList<Float>(); textures = new ArrayList<Float>(); normals = new ArrayList<Float>(); indices = new ArrayList<Integer>(); } public ModelBuilder texture(float u, float v) { this.u = u; this.v = v; return this; } public ModelBuilder vertex(float x, float y, float z) { vertices.add(x); vertices.add(y); vertices.add(z); colours.add(r); colours.add(g); colours.add(b); colours.add(a); textures.add(u); textures.add(v); normals.add(nx); normals.add(ny); normals.add(nz); return this; } private void setNormal(float x, float y, float z) { nx = x; ny = y; nz = z; } private float aoIntensity = 0.75f; public ModelBuilder vertex(int aoValue, float x, float y, float z) { float shading = (aoValue / 3.0f) * aoIntensity + (1 - aoIntensity); vertices.add(x); vertices.add(y); vertices.add(z); colours.add(r * shading); colours.add(g * shading); colours.add(b * shading); colours.add(a); textures.add(u); textures.add(v); lastAO[aoIndex] = aoValue; aoIndex++; if (aoIndex >= 4) { aoIndex = 0; } return this; } public ModelBuilder colour(float r, float g, float b, float a) { this.r = r; this.g = g; this.b = b; this.a = a; return this; } public ModelBuilder colour(float r, float g, float b) { return colour(r, g, b, 1); } public ModelBuilder applyLighting(int face) { if (face == 0 || face == 1) colour(0.75f, 0.75f, 0.75f); else if (face == 2 || face == 3) colour(0.5f, 0.5f, 0.5f); else if (face == 4 || face == 5) colour(1, 1, 1); else System.err.println("Invalid face " + face); return this; } public ModelBuilder applyLighting(int face, float tintR, float tintG, float tintB) { return applyLighting(face, tintR, tintG, tintB, 1); } public ModelBuilder applyLighting(int face, float tintR, float tintG, float tintB, float tintA) { if (face == 0 || face == 1) colour(0.75f * tintR, 0.75f * tintG, 0.75f * tintB, tintA); else if (face == 2 || face == 3) colour(0.5f * tintR, 0.5f * tintG, 0.5f * tintB, tintA); else if (face == 4 || face == 5) colour(tintR, tintG, tintB, tintA); else System.err.println("Invalid face " + face); return this; } public ModelBuilder applyLighting(int face, Color tint) { return applyLighting(face, tint.r, tint.g, tint.b, tint.a); } public void faceIndices() { if (lastAO[0] + lastAO[3] > lastAO[1] + lastAO[2]) { indicesOffset(faceIndex, 0, 3, 2, 0, 1, 3); } else { indicesOffset(faceIndex, 0, 1, 2, 2, 1, 3); } faceIndex += 4; } public void triangleIndices() { indicesOffset(faceIndex, 0, 1, 2); faceIndex += 3; } public ModelBuilder indices(int... ind) { for (int i : ind) { indices.add(i); } return this; } public ModelBuilder indicesOffset(int offset, int... ind) { for (int i : ind) { indices.add(offset + i); } return this; } private void face(int face, float x, float y, float z, float sx, float sy, float sz, float u1, float v1, float u2, float v2) { // float minX = -sx + fx; // float maxX = sx + fx; // float minY = -sy + fy; // float maxY = sy + fy; // float minZ); = -sz + fz; // float maxZ); = sz + fz; float minX = x - sx / 2; float maxX = x + sx / 2; float minY = y - sy / 2; float maxY = y + sy / 2; float minZ = z - sz / 2; float maxZ = z + sz / 2; texture(u1, v1); switch (face) { case 0: // FrontFace setNormal(0, 0, 1); texture(u1, v1); vertex(minX, minY, maxZ); texture(u2, v1); vertex(maxX, minY, maxZ); texture(u1, v2); vertex(minX, maxY, maxZ); texture(u2, v2); vertex(maxX, maxY, maxZ); faceIndices(); break; case 1: // BackFace setNormal(0, 0, -1); texture(u2, v2); vertex(minX, minY, minZ); texture(u2, v1); vertex(minX, maxY, minZ); texture(u1, v2); vertex(maxX, minY, minZ); texture(u1, v1); vertex(maxX, maxY, minZ); faceIndices(); break; case 2: // LeftFace setNormal(-1, 0, 0); texture(u1, v2); vertex(minX, minY, minZ); texture(u2, v2); vertex(minX, minY, maxZ); texture(u1, v1); vertex(minX, maxY, minZ); texture(u2, v1); vertex(minX, maxY, maxZ); faceIndices(); break; case 3: // Right Face setNormal(1, 0, 0); vertex(maxX, minY, minZ); vertex(maxX, maxY, minZ); vertex(maxX, minY, maxZ); vertex(maxX, maxY, maxZ); faceIndices(); break; case 4: // BottomFace setNormal(0, -1, 0); vertex(minX, minY, minZ); vertex(maxX, minY, minZ); vertex(minX, minY, maxZ); vertex(maxX, minY, maxZ); faceIndices(); break; case 5: // TopFace setNormal(0, 1, 0); texture(u2, v2); vertex(minX, maxY, minZ); texture(u2, v1); vertex(minX, maxY, maxZ); texture(u1, v2); vertex(maxX, maxY, minZ); texture(u1, v1); vertex(maxX, maxY, maxZ); faceIndices(); break; default: System.err.println("Invalid face " + face); break; } } public ModelBuilder face(int face, float x, float y, float z, float sx, float sy, float sz, int rx, int ry, int rw, int rh, int texW, int texH) { float u1 = rx / (float) texW; float v1 = ry / (float) texH; float u2 = (rx + rw) / (float) texW; float v2 = (ry + rh) / (float) texH; face(face, x, y, z, sx, sy, sz, u1, v1, u2, v2); return this; } public ModelBuilder quad(float x, float y, float z, float width, float height, int rx, int ry, int rw, int rh, int texW, int texH) { float scaledWidth = width * Mathf.ROOT_05; float minX = x - scaledWidth / 2; float maxX = x + scaledWidth / 2; float minY = y - height / 2; float maxY = y + height / 2; float minZ = z - scaledWidth / 2; float maxZ = z + scaledWidth / 2; float u1 = rx / (float) texW; float v1 = ry / (float) texH; float u2 = (rx + rw) / (float) texW; float v2 = (ry + rh) / (float) texH; setNormal(-Mathf.ROOT_05, 0, -Mathf.ROOT_05); texture(u2, v2); vertex(minX, minY, maxZ); texture(u2, v1); vertex(minX, maxY, maxZ); texture(u1, v2); vertex(maxX, minY, minZ); texture(u1, v1); vertex(maxX, maxY, minZ); faceIndices(); return this; } public ModelBuilder cube(float x, float y, float z, float sx, float sy, float sz, int rx, int ry, int rw, int rh, int texW, int texH) { for (int i = 0; i < 6; i++) { applyLighting(i); face(i, x, y, z, sx, sy, sz, rx, ry, rw, rh, texW, texH); } return this; } public Model build(ShaderProgram shader) { if (indices.isEmpty() || vertices.isEmpty()) { return null; } shader.begin(); Model model = new Model(shader, Mathf.intsToShortArray(indices), Mathf.toFloatArray(vertices), Mathf.toFloatArray(colours), Mathf.toFloatArray(textures), Mathf.toFloatArray(normals)); shader.end(); return model; } } <file_sep>/core/src/com/popularis/ui/Gui.java package com.popularis.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public abstract class Gui { public static Texture guiTexture; private static BitmapFont guiFont; private static OrthographicCamera guiCamera; private static SpriteBatch guiBatch; public static void init() {} static { guiCamera = new OrthographicCamera(Gdx.graphics.getWidth(), -Gdx.graphics.getHeight()); guiCamera.translate(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2); guiCamera.update(); guiBatch = new SpriteBatch(); guiBatch.setProjectionMatrix(guiCamera.combined); guiFont = new BitmapFont(Gdx.files.internal("font.fnt"), true); } protected SpriteBatch batch; protected BitmapFont font; protected Texture texture; public Gui() { batch = guiBatch; font = guiFont; texture = guiTexture; } /** * Called every frame. The GUI renders its elements to the screen using the * spritebatch. */ public abstract void render(); /** * Called every frame, after every GUI has done its render method. */ public void renderTop() {} protected void fillRect(Color color, float x, float y, float width, float height) { batch.setColor(color); batch.draw(guiTexture, x, y, width, height, 8 / 256f, 8 / 256f, 16 / 256f, 16 / 256f); batch.setColor(Color.WHITE); } protected void drawRect(Color color, float x, float y, float width, float height, float b) { batch.setColor(color); // CORNERS batch.draw(guiTexture, x, y, b, b, 0 / 256f, 0 / 256f, 8 / 256f, 8 / 256f); batch.draw(guiTexture, x + width - b, y, b, b, 8 / 256f, 0 / 256f, 0 / 256f, 8 / 256f); batch.draw(guiTexture, x + width - b, y + height - b, b, b, 8 / 256f, 8 / 256f, 0 / 256f, 0 / 256f); batch.draw(guiTexture, x, y + height - b, b, b, 0 / 256f, 8 / 256f, 8 / 256f, 0 / 256f); // EDGES batch.draw(guiTexture, x + b, y, width - 2 * b, b, 8 / 256f, 0 / 256f, 16 / 256f, 8 / 256f); batch.draw(guiTexture, x + b, y + height - b, width - 2 * b, b, 8 / 256f, 8 / 256f, 16 / 256f, 0 / 256f); batch.draw(guiTexture, x, y + b, b, height - 2 * b, 0 / 256f, 8 / 256f, 8 / 256f, 16 / 256f); batch.draw(guiTexture, x + width - b, y + b, b, height - 2 * b, 8 / 256f, 8 / 256f, 0 / 256f, 16 / 256f); batch.setColor(Color.WHITE); } } <file_sep>/core/src/com/popularis/gfx/Framebuffer.java package com.popularis.gfx; import static com.badlogic.gdx.Gdx.gl; import static com.badlogic.gdx.graphics.GL20.*; import com.badlogic.gdx.Gdx; public class Framebuffer { private int width, height, fbo, colourTexture, depthTexture; private boolean hasDepth; public Framebuffer(int width, int height, boolean hasDepth) { this.width = width; this.height = height; this.hasDepth = hasDepth; fbo = gl.glGenFramebuffer(); bind(); //gl.glDrawBuffer(GL_COLOR_ATTACHMENT0); gl.glActiveTexture(GL_TEXTURE0); colourTexture = gl.glGenTexture(); gl.glBindTexture(GL_TEXTURE_2D, colourTexture); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); gl.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, null); gl.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colourTexture, 0); if (hasDepth) { depthTexture = gl.glGenTexture(); gl.glBindTexture(GL_TEXTURE_2D, depthTexture); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); gl.glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, null); gl.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0); } unbind(); } public int getFbo() { return fbo; } public int getColourTexture() { return colourTexture; } public int getDepthTexture() { return depthTexture; } public boolean hasDepth() { return hasDepth; } public void bind() { gl.glBindFramebuffer(GL_FRAMEBUFFER, fbo); gl.glViewport(0, 0, width, height); } public void unbind() { gl.glBindFramebuffer(GL_FRAMEBUFFER, 0); gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } public void dispose() { gl.glDeleteFramebuffer(fbo); } } <file_sep>/core/src/com/popularis/entity/EntityMob.java package com.popularis.entity; import java.util.List; import com.badlogic.gdx.math.Vector3; import com.popularis.util.AABB; import com.popularis.world.World; public abstract class EntityMob extends Entity { private Vector3 tmp = new Vector3(); public EntityMob(World world) { super(world); } public abstract float getMoveSpeed(); public abstract float getJumpPower(); public void jump() { if (grounded) { this.velocity.y = getJumpPower(); grounded = false; } } public boolean moveTowards(Vector3 target, float minimumDistance) { Vector3 direction = tmp.set(target).sub(position); if (direction.len() < minimumDistance) return true; direction.y = 0; direction.nor().scl(getMoveSpeed()); move(direction); return false; } public boolean moveAway(Vector3 target, float minimumDistance) { Vector3 direction = tmp.set(target).sub(position); if (direction.len() > minimumDistance) return true; if (direction.isZero()) { direction.setToRandomDirection(); } direction.set(-direction.x, 0, -direction.z); move(direction); return false; } public void move(Vector3 direction) { direction.y = 0; direction.nor().scl(getMoveSpeed()); position.x += direction.x; aabb.updatePosition(position); List<AABB> worldAABB = world.getAABBsAround(aabb); if (aabb.collidesX(worldAABB)) { position.x -= direction.x; jump(); } position.z += direction.z; aabb.updatePosition(position); worldAABB = world.getAABBsAround(aabb); if (aabb.collidesZ(worldAABB)) { position.z -= direction.z; jump(); } } } <file_sep>/core/src/com/popularis/event/api/Intercept.java package com.popularis.event.api; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Tells the event bus to invoke this method every time there is an event. */ @Retention(RUNTIME) @Target(METHOD) public @interface Intercept { /** * The order that the event should fire in. See {@link Ordering} and its values. */ public Ordering order() default Ordering.MIDDLE; /** * If true, the method will not invoke if the event has been cancelled by an earlier method. */ public boolean ignoreCancelled() default false; public enum Ordering { /** The event fires before any other */ FIRST, /** The event fires early, but after the FIRST ones */ SECOND, /** The default order. Most events fire here. */ MIDDLE, /** The event fires after the MIDDLE ones. */ SECOND_LAST, /** The event fires last. */ LAST, /** * The event fires after every event has happened. Events in this category should * never change the actual event, only log or act upon it. For example, a logger * could listen for a BlockPlaceEvent and log its location, or a sound engine could * listen for a PlaySoundEvent and play the actual sound. */ MONITOR; } } <file_sep>/core/src/com/popularis/util/ShaderSourceFile.java package com.popularis.util; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Array; public class ShaderSourceFile { private String text; public ShaderSourceFile(String text) { if (Platform.platform == Platform.HTML) { text = "precision mediump float;\n\n" + text; } this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } public static ShaderProgram createShader(AssetManager assets, String vertex, String fragment) { ShaderProgram shader = new ShaderProgram(assets.get(vertex, ShaderSourceFile.class).getText(), assets.get(fragment, ShaderSourceFile.class).getText()); if (!shader.isCompiled()) { Gdx.app.error("ShaderLog", "ERROR in shader program " + vertex + " and " + fragment); Gdx.app.error("ShaderLog", shader.getLog()); } return shader; } public static class ShaderSourceFileLoader extends SynchronousAssetLoader<ShaderSourceFile, AssetLoaderParameters<ShaderSourceFile>> { public ShaderSourceFileLoader(FileHandleResolver resolver) { super(resolver); } @Override public ShaderSourceFile load(AssetManager assetManager, String fileName, FileHandle file, AssetLoaderParameters<ShaderSourceFile> parameter) { String text = file.readString(); return new ShaderSourceFile(text); } @SuppressWarnings("rawtypes") @Override public Array<AssetDescriptor> getDependencies(String fileName, FileHandle file, AssetLoaderParameters<ShaderSourceFile> parameter) { return null; } } } <file_sep>/core/src/com/popularis/util/Platform.java package com.popularis.util; public enum Platform { DESKTOP, HTML; public static Platform platform; public static CrossPlatform crossPlatform; } <file_sep>/core/src/com/popularis/gameplay/tasks/TaskMoveAwayFrom.java package com.popularis.gameplay.tasks; import com.badlogic.gdx.math.Vector3; import com.popularis.entity.EntityUnit; import com.popularis.world.World; public class TaskMoveAwayFrom extends Task { private float minimumDistance; public TaskMoveAwayFrom(Vector3 target, float minimumDistance) { super(target); this.minimumDistance = minimumDistance; } @Override public boolean tick(EntityUnit unit, World world) { return unit.moveAway(target, minimumDistance); } @Override public TaskType getType() { return TaskType.NONE; } @Override public String getStatusText() { return "getting out of the way"; } }
aaf53b0b2fe077df12f836c5040babf9b4a72983
[ "Markdown", "Java" ]
30
Java
nikola-m4/popularis
ddfb71b91854cb8da97b1820866d1d23c03d9348
8ff361d8bb2d629318afa4d37fd34c3f65f1fd6f
refs/heads/main
<file_sep>#!/usr/bin/env bash SRC_BUCKET=gs://tbd-project READS_PATH=data/reads/ TARGETS_PATH=data/targets/ : "${TF_VAR_project_name:?ERROR: TF_VAR_project_name !!!}" PATH_DEST=gs://${TF_VAR_project_name}/data/ gsutil cp -R ${SRC_BUCKET}/${READS_PATH} ${PATH_DEST} && \ gsutil cp -R ${SRC_BUCKET}/${TARGETS_PATH} ${PATH_DEST} if [ $? -eq 0 ]; then echo "Reads data copied to gs://${TF_VAR_project_name}" else echo "Failed to copy test data to gs://${TF_VAR_project_name}" fi gsutil ls gs://${TF_VAR_project_name}/data/<file_sep>FROM gcr.io/spark-operator/spark:v3.0.0-gcs-prometheus ARG SPARK_VERSION=3.0.1 ARG HADOOP_VERSION=2.7 ARG GCS_CONNECTOR_VERSION=hadoop2-1.9.17 ARG GCS_NIO_VERSION=0.120.0-alpha RUN rm -rf /opt/spark RUN apt update && apt install wget -y # Spark installation WORKDIR /tmp # Using the preferred mirror to download Spark # hadolint ignore=SC2046 RUN wget -q https://archive.apache.org/dist/spark/spark-${SPARK_VERSION}/spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}.tgz RUN tar xzf "spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}.tgz" -C /opt --owner root --group root --no-same-owner && \ rm "spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}.tgz" WORKDIR /opt RUN mv spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}/* spark/ && rm -rf spark-${SPARK_VERSION}-bin-hadoop${HADOOP_VERSION}/ # Configure Spark ENV SPARK_HOME=/opt/spark RUN cd $SPARK_HOME/jars && wget https://repo1.maven.org/maven2/com/google/cloud/bigdataoss/gcs-connector/${GCS_CONNECTOR_VERSION}/gcs-connector-${GCS_CONNECTOR_VERSION}-shaded.jar && \ wget https://repo1.maven.org/maven2/com/google/cloud/google-cloud-nio/${GCS_NIO_VERSION}/google-cloud-nio-${GCS_NIO_VERSION}-shaded.jar <file_sep>#!/usr/bin/env bash [ $# -eq 0 ] && { echo "Usage: $0 [app_name] [build|deploy|run|delete|logs]"; exit 1; } # check required env variables before proceeding PARAM_1=$1 PARAM_2=$2 : "${PARAM_1:?ERROR: APP_NAME not provided !!!}" : "${PARAM_2:?ERROR: MODE not provided !!!}" export APP_NAME=$1 export MODE=$2 if [ $MODE == "logs" ]; then sparkctl log -f $APP_NAME elif [ $MODE == "delete" ]; then sparkctl delete $APP_NAME elif [ $MODE == "build" ]; then echo "Packaging assembly..." sbt assembly elif [ $MODE == "deploy" ]; then echo "Copying assembly jar to GCS..." export JAR_FILE=$(find target/ -name "*assembly*.jar") #cleanup gsutil rm gs://${TF_VAR_project_name}/jars/baseline/$JAR_FILE rm -rf ~/.gsutil/tracker-files/upload* gsutil cp $JAR_FILE gs://${TF_VAR_project_name}/jars/baseline/ elif [ $MODE == "run" ]; then echo "Deploying Spark app to Kubernetes..." kubectl label servicemonitor/prometheus-pushgateway release=prometheus-community --overwrite kubectl apply -f manifests/servicemonitor-spark.yaml sparkctl delete $APP_NAME #cleanup old Spark driver service if exists kubectl get svc --no-headers -o custom-columns=":metadata.name" | grep $APP_NAME-[[:alnum:]]*-driver-svc | xargs -I {} kubectl delete svc {} kubectl apply -f manifests/$APP_NAME.yaml sparkctl list while [ $(kubectl get svc --no-headers -o custom-columns=":metadata.name" | grep $APP_NAME-[[:alnum:]]*-driver-svc | wc -l) -lt 1 ]; do echo "Service does not exists yet, waiting 1s" sleep 1 done kubectl get svc --no-headers -o custom-columns=":metadata.name" | grep $APP_NAME-[[:alnum:]]*-driver-svc | xargs -I {} kubectl label svc {} sparkSvc=driver fi<file_sep># tbd-example-project ## How to setup a new project https://github.com/MrPowers/spark-sbt.g8 ``` sbt new MrPowers/spark-sbt.g8 ``` ## Core technologies - OpenJDK: 11.0.10.hs-adpt - Scala: 2.12.10 - Spark: 3.0.1 - sbt: 1.3.13 # Using a docker helper image You can use the same docker image to build and deploy your app to GKE. The only difference is that you need to mount 2 volumes : - the one pointed by $PROJECT_DIR where you store your IaC - the other one pointed by $APP_DIR where you have your sbt-based Spark app You can clone your git repo into $APP_DIR and develop in your favourite IDE and only using container for deployment. ``` export IMAGE_TAG=0.1.3 export SEMESTER=2021l export GROUP_ID=${SEMESTER}-999 ##Watch out ! Please use the group id provided by lecturers!!! export PROJECT_DIR=$HOME/tbd/project export APP_DIR=/Users/mwiewior/research/git/tbd-example-project ### change it so that it points to your cloned project repo export TF_VAR_billing_account=011D36-51D2BA-441848 ### copied from billing tab export TF_VAR_location=europe-west1 ### St. Ghislain, Belgium export TF_VAR_zone=europe-west1-b export TF_VAR_machine_type=e2-standard-2 mkdir -p $PROJECT_DIR cd $PROJECT_DIR docker run --rm -it \ --name tbd \ -p 9090:9090 \ -p 9091:9091 \ -p 3000:3000 \ -v $PROJECT_DIR:/home/tbd \ -v $APP_DIR:/home/app \ -e GROUP_ID=$GROUP_ID \ -e TF_VAR_billing_account=$TF_VAR_billing_account \ -e TF_VAR_location=$TF_VAR_location \ -e TF_VAR_zone=$TF_VAR_zone \ -e TF_VAR_machine_type=$TF_VAR_machine_type \ biodatageeks/tbd-os:$IMAGE_TAG bash ``` ## GCP deployment Login to GKE: ``` gcp-login.sh ``` ### Copy data to GCS ```bash bin/prepare-test-data.sh ``` ### appctl tool ``` bash-3.2$ bin/appctl.sh Usage: bin/appctl.sh [app_name] [build|deploy|run|delete|logs] ``` ## Performance testing Valid apps are : intervaljoin-spark and intervaljoin-sequila ### Build/ship ``` bin/appctl.sh intervaljoin-sequila build ``` ### Deploy ``` bin/appctl.sh intervaljoin-sequila deploy ``` ### Run ``` bin/appctl.sh intervaljoin-sequila run ``` ## Prepare data ```bash sdk use spark 3.0.1 spark-shell \ --driver-memory 8g \ --num-executors 4 \ --packages org.biodatageeks:sequila_2.12:0.6.5 -v ``` ```scala import org.apache.spark.sql.{SequilaSession, SparkSession} import org.biodatageeks.sequila.utils.SequilaRegister val tableName = "reads" val bamPath = "/Users/mwiewior/research/data/NA12878.proper.wes.md.bam" sql( s""" |CREATE TABLE IF NOT EXISTS $tableName |USING org.biodatageeks.sequila.datasources.BAM.BAMDataSource |OPTIONS(path "$bamPath") | """.stripMargin) val df = spark .sql(s"SELECT sample_id,contig,pos_start,pos_end,cigar,seq FROM $tableName") df.coalesce(32).write .partitionBy("sample_id","contig") .saveAsTable("reads_part") ``` ### Spark image ```bash cd docker docker build -t biodatageeks/spark:v3.0.1-gcs-prometheus . ``` ### Troubleshooting Problems with not resolving deps in Spark Shell ``` rm -rf ~/.ivy2/cache rm -rf ~/.m2/repository ``` ## Results ```bash +---------+ | count(1)| +---------+ |132403544| +---------+ ``` # Prepare dataset ``` gsutil mb -l europe-west1 gs://tbd-project gsutil cp -R spark-warehouse/reads_part/* gs://tbd-project/data/reads/ gsutil cp -R /Users/mwiewior/research/data/targets/tgp_exome_hg18.bed gs://tbd-project/data/targets/ gsutil iam ch allAuthenticatedUsers:objectViewer gs://tbd-project/ ```
6318962c08cdd3cf0d7ccb3bb2783166bc134c2c
[ "Markdown", "Dockerfile", "Shell" ]
4
Shell
bdg-tbd/tbd-example-pub
b70c43344dc86efe82310bb10ad7bef5cbb212e5
bb83023d5e529f4f6a417245ea8c748ee6a70e61
refs/heads/master
<repo_name>icshwi/fimscb<file_sep>/simulator/simulator.bash #!/bin/bash # # Copyright (c) 2018 - Present European Spallation Source ERIC # # The program is free software: you can redistribute # it and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, either version 2 of the # License, or any newer version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see https://www.gnu.org/licenses/gpl-2.0.txt # # # author : <NAME> # email : <EMAIL> # date : Thursday, July 19 16:56:13 CEST 2018 # version : 0.0.1 declare -gr SC_SCRIPT="$(realpath "$0")" declare -gr SC_SCRIPTNAME=${0##*/} declare -gr SC_TOP="${SC_SCRIPT%/*}" KAM_TOP=${SC_TOP}/kameleon # We have to go the toplevel of the working tree. pushd ${SC_TOP}/../ git submodule update --init --recursive ; git submodule update --remote ; popd python ${KAM_TOP}/kameleon.py --host="127.0.0.1" --file=${SC_TOP}/atomki_scb_monitor.kam <file_sep>/fimscbApp/src/Makefile TOP=../.. include $(TOP)/configure/CONFIG #---------------------------------------- # ADD MACRO DEFINITIONS AFTER THIS LINE #============================= #============================= # Build the IOC application PROD_IOC = fimscb # fimscb.dbd will be created and installed DBD += fimscb.dbd # fimscb.dbd will be made up from these files: fimscb_DBD += base.dbd fimscb_DBD += devIocStats.dbd fimscb_DBD += stream.dbd fimscb_DBD += asyn.dbd fimscb_DBD += drvAsynSerialPort.dbd fimscb_DBD += drvAsynIPPort.dbd # Include dbd files from all support applications: #fimscb_DBD += xxx.dbd # Add all the support libraries needed by this IOC fimscb_LIBS += stream asyn fimscb_LIBS += devIocStats # fimscb_registerRecordDeviceDriver.cpp derives from fimscb.dbd fimscb_SRCS += fimscb_registerRecordDeviceDriver.cpp # Build the main IOC entry point on workstation OSs. fimscb_SRCS_DEFAULT += fimscbMain.cpp fimscb_SRCS_vxWorks += -nil- # Add support from base/src/vxWorks if needed #fimscb_OBJS_vxWorks += $(EPICS_BASE_BIN)/vxComLibrary # Finally link to the EPICS Base libraries fimscb_LIBS += $(EPICS_BASE_IOC_LIBS) #=========================== include $(TOP)/configure/RULES #---------------------------------------- # ADD RULES AFTER THIS LINE <file_sep>/README.md # fimscb [![Build Status](https://travis-ci.org/icshwi/fimscb.svg?branch=master)](https://travis-ci.org/icshwi/fimscb) ## Simulator * Start the simulator ``` fimscb (master)$ bash simulator/simulator.bash ~/epics_env/epics-Apps/fimscb ~/epics_env/epics-Apps/fimscb ~/epics_env/epics-Apps/fimscb **************************************************** * * * Kameleon v1.5.0 (2017/SEP/14 - Production) * * * * * * (C) 2015-2017 European Spallation Source (ESS) * * * **************************************************** [17:25:48.489] Using file '/home/jhlee/epics_env/epics-Apps/fimscb/simulator/atomki_scb_monitor.kam' (contains 19 commands and 19 statuses). [17:25:48.489] Start serving from hostname '127.0.0.1' on port '9999'. ``` ## EPICS IOC * Start IOC ``` fimscb (master)$ cd iocBoot/iocfimscb iocfimscb (master)$ ./st.cmd #!../../bin/linux-x86_64/fimscb < envPaths epicsEnvSet("IOC","iocfimscb") epicsEnvSet("TOP","/home/jhlee/epics_env/epics-Apps/fimscb") epicsEnvSet("STREAM_PROTOCOL_PATH", ".:/home/jhlee/epics_env/epics-Apps/fimscb/db") epicsEnvSet(P, FIMSCB) epicsEnvSet(R, KAM) epicsEnvSet("IOCST", "FIMSCB-KAM:IocStats") cd "/home/jhlee/epics_env/epics-Apps/fimscb" dbLoadDatabase "dbd/fimscb.dbd" fimscb_registerRecordDeviceDriver pdbbase epicsEnvSet("PORT", "FIMSCB") drvAsynIPPortConfigure(FIMSCB, "127.0.0.1:9999", 0, 0, 0) # <0x0d> \r # <0x0a> \n asynOctetSetInputEos(FIMSCB, 0, "\n") asynOctetSetOutputEos(FIMSCB, 0, "\r\n") dbLoadRecords("db/iocAdminSoft.db", "IOC=FIMSCB-KAM:IocStats") dbLoadRecords("db/fimscb.db", "P=FIMSCB-KAM:,PORT=FIMSCB") #dbLoadRecords("db/stream_raw.db", "P=$(P)-$(R):,PORT=FIMSCB") cd "/home/jhlee/epics_env/epics-Apps/fimscb/iocBoot/iocfimscb" iocInit Starting iocInit ############################################################################ ## EPICS R3.16.1 ## EPICS Base built Jun 26 2018 ############################################################################ iocRun: All initialization complete dbl > "/home/jhlee/epics_env/epics-Apps/fimscb/iocfimscb_PVs.list" epics> ^C jhlee@kaffee:~/epics_env/epics-Apps/fimscb/iocBoot/iocfimscb$ ./st.cmd #!../../bin/linux-x86_64/fimscb < envPaths epicsEnvSet("IOC","iocfimscb") epicsEnvSet("TOP","/home/jhlee/epics_env/epics-Apps/fimscb") epicsEnvSet("STREAM_PROTOCOL_PATH", ".:/home/jhlee/epics_env/epics-Apps/fimscb/db") epicsEnvSet(P, FIMSCB) epicsEnvSet(R, KAM) epicsEnvSet("IOCST", "FIMSCB-KAM:IocStats") cd "/home/jhlee/epics_env/epics-Apps/fimscb" dbLoadDatabase "dbd/fimscb.dbd" fimscb_registerRecordDeviceDriver pdbbase epicsEnvSet("PORT", "FIMSCB") drvAsynIPPortConfigure(FIMSCB, "127.0.0.1:9999", 0, 0, 0) # <0x0d> \r # <0x0a> \n asynOctetSetInputEos(FIMSCB, 0, "\n") asynOctetSetOutputEos(FIMSCB, 0, "\r\n") dbLoadRecords("db/iocAdminSoft.db", "IOC=FIMSCB-KAM:IocStats") dbLoadRecords("db/fimscb.db", "P=FIMSCB-KAM:FimSCB:,PORT=FIMSCB") #dbLoadRecords("db/stream_raw.db", "P=$(P)-$(R):,PORT=FIMSCB") cd "/home/jhlee/epics_env/epics-Apps/fimscb/iocBoot/iocfimscb" iocInit Starting iocInit ############################################################################ ## EPICS R3.16.1 ## EPICS Base built Jun 26 2018 ############################################################################ iocRun: All initialization complete dbl > "/home/jhlee/epics_env/epics-Apps/fimscb/iocfimscb_PVs.list" ``` One may see the following log in the simulator ``` [16:32:40.961] Client connection opened. [16:32:41.464] Command 'I?<0x0d><0x0a>' (Get IP Address) received from client. [16:32:41.465] Status '192.168.1.100<0x0a>' (Get IP Address) sent to client. [16:32:41.466] Command 'S?<0x0d><0x0a>' (Get Subnet Mask) received from client. [16:32:41.466] Status '255.255.255.0<0x0a>' (Get Subnet Mask) sent to client. [16:32:41.467] Command 'G?<0x0d><0x0a>' (Get Gateway Address) received from client. [16:32:41.467] Status '192.168.1.1<0x0a>' (Get Gateway Address) sent to client. [16:32:41.468] Command 'G?<0x0d><0x0a>' (Get Gateway Address) received from client. [16:32:41.468] Status '192.168.1.1<0x0a>' (Get Gateway Address) sent to client. [16:32:41.470] Command 'P?<0x0d><0x0a>' (Get TCP Port) received from client. [16:32:41.470] Status '6666<0x0a>' (Get TCP Port) sent to client. [16:32:41.471] Command 'C?<0x0d><0x0a>' (Read Configuration) received from client. [16:32:42.473] Command 'F?<0x0d><0x0a>' (Get Firmware Version) received from client. [16:32:42.474] Status '20180720180000<0x0a>' (Get Firmware Version) sent to client. [16:32:42.475] Command 'N?<0x0d><0x0a>' (Get Name) received from client. [16:32:42.475] Status 'ESS FIM SCB Mon. v1 #0<0x0a>' (Get Name) sent to client. ``` One can check its PVs through tools/caget_pvs.bash with iocfimscb_PVs.list ``` $ bash tools/caget_pvs.bash iocfimscb_PVs.list "FimSCB" >> Unset ... EPICS_CA_ADDR_LIST and EPICS_CA_AUTO_ADDR_LIST Set ... EPICS_CA_ADDR_LIST and EPICS_CA_AUTO_ADDR_LIST >> Print ... EPICS_CA_ADDR_LIST : 10.0.6.172 EPICS_CA_AUTO_ADDR_LIST : YES >> Get PVs .... FIMSCB-KAM:FimSCB:FW-RB 20180720180000 FIMSCB-KAM:FimSCB:MODEL-RB ESS FIM SCB Mon. v1 #0 FIMSCB-KAM:FimSCB:UPTIME-RB 196758 FIMSCB-KAM:FimSCB:IP-RB 192.168.1.100 FIMSCB-KAM:FimSCB:Subnet-RB 255.255.255.0 FIMSCB-KAM:FimSCB:Gateway-RB 192.168.1.1 FIMSCB-KAM:FimSCB:DNSServer-RB 192.168.1.1 FIMSCB-KAM:FimSCB:TCPPort-RB 6666 FIMSCB-KAM:FimSCB:U-RB 24266 FIMSCB-KAM:FimSCB:IDI-RB 240 FIMSCB-KAM:FimSCB:IDO-RB 243 FIMSCB-KAM:FimSCB:IA1-RB 257 FIMSCB-KAM:FimSCB:IA2-RB 245 FIMSCB-KAM:FimSCB:Temperature-RB 10841 FIMSCB-KAM:FimSCB:Pressure-RB 100620 FIMSCB-KAM:FimSCB:Humidity-RB 42141 FIMSCB-KAM:FimSCB:WriteConf-RB 0 FIMSCB-KAM:FimSCB:IP-SET 192.168.1.100 FIMSCB-KAM:FimSCB:IPUpdate-RB_ 192.168.1.100 FIMSCB-KAM:FimSCB:Subnet-SET 255.255.255.0 FIMSCB-KAM:FimSCB:SubnetUpdate-RB_ 255.255.255.0 FIMSCB-KAM:FimSCB:Gateway-SET 192.168.1.1 FIMSCB-KAM:FimSCB:GatewayUpdate-RB_ 192.168.1.1 FIMSCB-KAM:FimSCB:DNSServer-SET 192.168.1.1 FIMSCB-KAM:FimSCB:DNSServerUpdate-RB_ 192.168.1.1 FIMSCB-KAM:FimSCB:InfoUpdate-Cmd Revert FIMSCB-KAM:FimSCB:TCPPort-SET 6666 FIMSCB-KAM:FimSCB:WriteConf-SET 0 FIMSCB-KAM:FimSCB:InfoUpdate:1-Fout_ 0 FIMSCB-KAM:FimSCB:TCPPortUpdate-RB_ 6666 FIMSCB-KAM:FimSCB:WriteConf-RB_ 0 ```
e46fb54f1ca0009ce42479f25fd355c60bf28f37
[ "Markdown", "Makefile", "Shell" ]
3
Shell
icshwi/fimscb
19c81607972e8a586271022f7e98ce78c7d32f18
6678a9b42dec8948d3fdea85310f7108c8ee2971
refs/heads/master
<file_sep>import { StyleSheet } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ffb961', alignItems: 'center', justifyContent: 'center', }, flex: { flexDirection: 'row', }, flextext: { fontSize: 22, margin: 10, }, totaltext: { fontSize: 22, marginTop: 10, }, gameBtn: { marginTop: 35, fontSize: 20, color: 'black', borderWidth: 2, paddingVertical: 8, paddingHorizontal: 40, borderRadius: 5, borderColor: 'black' }, image: { height: 90, width: 90, margin: 10, } }); export { styles };
e9d5c04f92120da3cd611c90e69a0805061bad2c
[ "JavaScript" ]
1
JavaScript
kinoodaphne/dice-roller
8f5d57851473fc8b50df48e2266a75392ee03f8b
9de49a0b9e6d06d9093892906149bc020084d4cd
refs/heads/master
<file_sep># FernandoOtavioApp aplicativo de tcc do eefo <file_sep>app.controller('galeriaCtrl' , function($scope){ $scope.imagens = [ { url:"http://www.obmep.org.br/images/capas-apostilas-03.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-14-Eureka.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-03.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-03.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-14-Eureka.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-03.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-14-Eureka.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-03.png" }, { url:"http://www.obmep.org.br/images/capas-apostilas-14-Eureka.png" }, ]; $scope.al = "alllll"; });<file_sep>app.controller('mainCtrl',function($scope){ $scope.estaLogado = false; });
0ddb8a611b96d790bb3b8de359327ee67f396676
[ "Markdown", "JavaScript" ]
3
Markdown
WizardCedric/FernandoOtavioApp
fc51180b9cb6cb8cb935089f224a9cbfc3de72fb
d9e6ac53432de490d28198cbaf829765f51d42fd
refs/heads/master
<file_sep>// // AaptConfig.h // AaptExt // // Created by BunnyBlue on 6/25/15. // Copyright © 2015 BunnyBlue. All rights reserved. // #ifndef __ACDD__AaptConfig_h #define __ACDD__AaptConfig_h #include <stdio.h> #include <iostream> #include <string> #include <sstream> #include <fstream> #include <stdlib.h> #include <map> using namespace std; #define ACDD_AAPT_CONFIG_SHARED_RESOURCES_SYMBOL "shared-resources-symbol"//prebuild Shared Package Resouces #define ACDD_AAPT_CONFIG_PKG_GROUP_ID "pkgGroupId"// plugin package group id #define ACDD_AAPT_CONFIG_PKG_VERSION_NAME "versionName"//plugin package versionName #define ACDD_AAPT_CONFIG_TYPE_PACKAGE_GROUP_ID 1 #define ACDD_AAPT_CONFIG_TYPE_SHARED_RESOURCE_TABLE 2 class ACDDAaptConfig { size_t packageGroupId; std::string mSharedResourcePackageName; std::string mSharedResourcePath; std::string versionName; bool updateVersion; public: static ACDDAaptConfig* getInstance() { static ACDDAaptConfig instance; return &instance; } //config bool initACDDConig(std::string config,int configType); // std::string getConfigByKey(const std::string key); size_t getPackageGroupId(); std::string getSharedResourcePackageName(); std::string getSharedResourcePath(); std::string getVersionName(); bool isUpdateVersion(); int getSharedResource(std::string type,std::string name); protected: struct Object_Creator { Object_Creator() { ACDDAaptConfig::getInstance(); } }; static Object_Creator _object_creator; std::string _conFilePath; std::map<std::string, std::string> options; bool read_file(std::istream& is); ACDDAaptConfig() { updateVersion=false; packageGroupId=0x7f; } ~ACDDAaptConfig() {} }; #endif /* AaptConfig_cpp */ /* config should be pkg=io.github.bunnyblue.pkg preBuildJarPath=/Users/Downloads/prebuild.jar pkgGroupId=0x1a unusedkey=unusedvalue */ <file_sep>// // AaptConfig.cpp // AaptExt // // Created by BunnyBlue on 6/25/15. // Copyright © 2015 BunnyBlue. All rights reserved. // #include <androidfw/acdd/ACDDAaptConfig.h> #include <androidfw/acdd/ACDDResourceBridge.h> #include <iostream> #include <string> using namespace std; ACDDAaptConfig::Object_Creator ACDDAaptConfig::_object_creator; std::string inline delSpaces(std::string &str) { for (size_t i = 0; i < str.length(); i++) { if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') { str.erase(i, 1); i--; } } return str; } // std::string ACDDAaptConfig::getConfigByKey(const std::string key){ // map<string,string>::iterator itr=options.find(key); // if (itr==options.end()) { // return NULL; // } // return itr->second; // // } bool ACDDAaptConfig::initACDDConig(std::string config,int configType){ fprintf(stdout, "***ACDD*** initACDDConig %s \n",config.c_str()); if (configType==ACDD_AAPT_CONFIG_TYPE_PACKAGE_GROUP_ID) { const char * pkgGroup=config.c_str(); fprintf(stderr, "***ACDD*** ACDD Shared Resource pkgGroup %s \n",pkgGroup); if(pkgGroup[0]=='0'&&pkgGroup[1]=='x') { packageGroupId=strtol(pkgGroup,NULL,16); } }else if (configType==ACDD_AAPT_CONFIG_TYPE_SHARED_RESOURCE_TABLE) { mSharedResourcePath=config; } return true; // std::ifstream ifs( path.c_str()); // if(!ifs.good()) { // ifs.close(); // fprintf(stderr, "***ACDD*** ACDD Config File %s Not accessable \n",path.c_str()); // return false; // } // return read_file(ifs); } std::string ACDDAaptConfig::getSharedResourcePackageName(){ return mSharedResourcePackageName; } std::string ACDDAaptConfig::getSharedResourcePath(){ return mSharedResourcePath; } size_t ACDDAaptConfig::getPackageGroupId(){ // fprintf(stdout, "***ACDD*** ACDD PackgeID %02x \n",(unsigned int)packageGroupId); return packageGroupId; } bool ACDDAaptConfig::isUpdateVersion(){ return updateVersion; } std::string ACDDAaptConfig::getVersionName(){ return versionName; } int ACDDAaptConfig::getSharedResource(std::string type,std::string name){ return ACDDResourceBridge::getInstance()->getResourceId(type,name);; } <file_sep>// // Copyright 2006 The Android Open Source Project // // Build resource files from raw assets. // #include "ACDDResourceImpl.h" void acdd_parseResourceTable(){ std::string sharedResourceSymbol=ACDDAaptConfig::getInstance()->getSharedResourcePath(); if(access(sharedResourceSymbol.c_str(),F_OK)==-1) { fprintf(stderr, "PreDefine Resource Symbol file not access ,process abort!!! \n"); exit(-0x01010000); }else{ fprintf(stderr, "PreDefine Resource Symbol found \n"); sp<XMLNode> root = XMLNode::parse(sharedResourceSymbol.c_str()); Vector<sp<XMLNode> >mChildrenNodes= root->getChildren(); for (size_t i=0; i<mChildrenNodes.size(); i++) { sp<XMLNode> mCurrntNode= mChildrenNodes.itemAt(i); // <public type="attr" name="theme" id="0x01010000" /> Vector<XMLNode::attribute_entry> mAttributes=mCurrntNode->getAttributes(); std::string type; std::string name; int value=0; for (size_t i=0; i<mAttributes.size(); i++) { const XMLNode::attribute_entry& ae(mAttributes.itemAt(i)); // String8(attr->string).string() if(!ae.name.compare(android::String16("type"))){ type= String8(ae.string).string(); }else if (!ae.name.compare(android::String16("name"))) { name= String8(ae.string).string(); }else if(!ae.name.compare(android::String16("id"))){ value= strtol(String8(ae.string).string(),NULL,16); } } ACDDResourceBridge::getInstance()->addResourceSymbol(type,name,value); } } } // void ACDD_old_injectmanifest(Bundle* bundle){ // // // String8 srcFile(bundle->getAndroidManifestFile()); // // AaptFile *mAaptFile=new AaptFile(srcFile.getPathLeaf(), AaptGroupEntry(), srcFile.getPathDir()); // // const sp<AaptFile> manifestFile(mAaptFile); // // String8 manifestPath(bundle->getAndroidManifestFile()); // fprintf(stderr, "ResourceShareOld dump info ..get default versionName%s\n",manifestPath.string()); // // // Generate final compiled manifest file. // //manifestFile->clearData(); // sp<XMLNode> root = XMLNode::parse(bundle->getAndroidManifestFile()); // // if (root == NULL) { // if(!access(bundle->getAndroidManifestFile(),0)) {}else{ // fprintf(stderr, "ResourceShareOld found \n"); // } // fprintf(stderr, "no node \n"); // return; // } // hack_massageManifest(root); // // // fprintf(stderr, "ResourceShareOld version ibundle->getAndroidManifestFile()7\n"); // // } // void hack_massageManifest( sp<XMLNode> root) // { // root = root->searchElement(String16(), String16("manifest")); // // const XMLNode::attribute_entry* attrlocal = root->getAttribute( // String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName")); // if (attrlocal != NULL) { // fprintf(stderr, "ResourceShareOld version dump info ..get default versionName%s\n",strdup(String8(attrlocal->string).string())); // char * versionNameMisc=strdup(String8(attrlocal->string).string()); //bunny // if(access(versionNameMisc,F_OK)!=-1) { // fprintf(stdout, "WARNING ACDD you should use shared resoures!!!!!!!!!\n"); // ACDDAaptConfig::getInstance()->initConfigFile(versionNameMisc); // fprintf(stdout, "update ACDD shared resoures in old modle%s\n"); // } // // // // } // // // // // }
b98bde6f1fd6b3afeebc3205dd8d6f9730821e2a
[ "C++" ]
3
C++
longpenghn/ACDDExtension
3a711fbae57f0899ea8dcd5abce57b48586c497e
b7b15842a753b306c8a46a83b1454da49ecb6ab9
refs/heads/master
<file_sep><?php require_once "templates/page_setup.php"; include "templates/header.php"; if (isset($_GET['ing'])){ //&& $_GET['team']) $db = new Database(); $ing = trim($_GET['ing'],'"'); $team = trim($_GET['team'],'"'); $page_name = $ing; $title = $ing; } else{ header('location: index.php'); } include 'templates/jumbotron.php'; ?> <script type="text/javascript" src="food_page.js"></script> <div class = "container-fluid product-details" id ="product_details"> <div class="row"> <div class="col-md-3" id = "productImgCol"> <img id = "product_image" src = "" alt="product_image" style="height:300px;width:300px;"> </div> <div class = "col-md-3" id="productDetailsCol"> <?php ?> <h3 class="name"><?php echo $ing?></h3> <h3 class="debug"></h3> <!--<h3 id="masterstatus"></h3>--> <p class="desc">Ingredient description</p> <?php //echo $dbh->getRatingStars($dbh->averageRating($ingredient));?> <span class =""><a href="#reviewList"><?php// echo $reviewCount;?> Reviews</a></span> <?php if (isset($_SESSION['username']) and $_SESSION['username']!="Guest"): //adds a cart option if user is signed in ?> <h4 id = "cart"></h4> <?php endif;?> $<span class="price"></span> per <span class = "unit"></span> </div> <div class = "col-md-3" id=productPurchaseCol> </div> </div> <hr> <div class = "row"> <div class = "col-sm-6" id="reviewList" style="margin-left:20px;"> <?php ?> </div> </div> </div> <?php require 'templates/footer.php';?> <file_sep><?php header ( 'Content-Type: text/json' ); header ( "Access-Control-Allow-Origin: *" ); $n = $_REQUEST ["a"]; switch ($n) { case "open" : $s = "green"; break; case "closed" : $s = "red"; break; default : $s = "yellow"; break; } echo json_encode($s); ?> <file_sep>#!/bin/bash chmod -R 755 * find . -iname "*.php" | xargs chmod 644 echo "Permissions granted." <file_sep>$(document).ready(function() { var jqxhr = $.post("https://www.cs.colostate.edu/~ct310/yr2017sp/more_assignments/project03masterlist.php", function(data, status) { parseData(data); }) .fail(function(){ $("#masterstatus").html("Failed to open"); $("#masterstatus").css("background-color", "red"); }) }); function parseData(lst) { var rt = ""; var tab = document.getElementById("ingredients"); var len = lst.length; for (j = 0; j < len; j++) { getStatus(lst[j]);//call in initial loop else there be dragons! } } function getStatus(lst){ var url = lst.baseURL; url = url + "ajax_status.php"; jQuery.post(url,function(data,status){ if(typeof data.status !== undefined){ if(data.status == "open"){ getIngs(lst.baseURL, lst.nameShort, lst.Team); } } }) .fail(function(data,status){ }); } var ingredients=[]; function getIngs(baseurl,nameShort,team){ var url = baseurl + "ajax_listing.php"; if(url != "ajax_listing.php"){ $.post(url,function(data,status){ for(var j=0;j<data.length;j++){ if(typeof data[j].name !== typeof undefined){ var x = {name: data[j].name, short: data[j].short, unit: data[j].unit, cost: data[j].cost}; ingredients.push(x); } } fillData(ingredients,baseurl,nameShort,team); }); } } var z =0; function fillData(ings,base,nameShort,team){ var details = ""; var len = ings.length; for (j = z; j < len; j++) { var y = ings[j]; if((typeof y.name !== undefined)&&(y.name !='') && (y.name)){ details = '<div class = "col-sm-3 col-md-3 col-xs-3 product-listing">'; details += '<div class="thumbnail">'; details += "<a href=\"food_page.php?ing="+y.name+"&team="+nameShort+"\">"; details += "<img id = \""+team+"_"+y.name.replace(/ /g,'')+"\" src = \"\" alt = \"thumbnail\" style = \"height:200px;width:200px;\">"; details += "</a>"; details += "<div class= \"caption\">"; details += "<h4 class = \"pull-right\">$"+y.cost+" per "+y.unit +"</h4>"; details += "<h4><a href=\"food_page.php?ing="+y.name+"&team="+nameShort+"\">"+y.name+"</a></h4>"; details += "<p>Site: <a href=\""+base+"\">"+nameShort+"</a></p>"; details += "<p>"+y.short+"</p>"; details += "</div></div></div>"; getImage(y,base,team); $("#dis").append(details); z++; } } } function getImage(ing,base,team){ if(ing.name!=""){ var str =ing.name.replace(/\s/g,''); $.get(base+"ajax_ingrimage.php?ing="+ing.name,function(data,status){ $("#"+team+"_"+str).attr('src','data:image/jpeg;base64,'+data); }).fail(function(){ $("#"+team+"_"+str).attr('alt',"Failed to load image invalid URL"); }); } } <file_sep>var ing = getUrlVars()["ing"]; var team = getUrlVars()["team"]; function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars; } $(document).ready(function() { var jqxhr = $.post("https://www.cs.colostate.edu/~ct310/yr2017sp/more_assignments/project03masterlist.php", function(data, status) { $("#masterstatus").html("master status open " + ing + " " + team); findShortName(data, ing, team); }) .fail(function(){ $("#masterstatus").html("Failed to open"); $("#masterstatus").css("background-color", "red"); }) }); function findShortName(lst, ing, team) { var len = lst.length; for (j = len - 1; j >= 0; j--) { if(lst[j].nameShort == team){ getInfo(lst[j].baseURL, ing); getImage(lst[j].baseURL, ing); } } } function getInfo(baseURL,ing){ jQuery.post(baseURL + "ajax_ingredient.php?ing="+ing, function(data, status) { jQuery(".name").html(data.name); jQuery(".price").html(data.cost); jQuery(".unit").html(data.unit); jQuery(".desc").html(data.desc); var cart = "<a href=\"cart.php?name="+data.name+"&team="+baseURL+"&cost="+data.cost+"\">Add to cart</a>"; $("#cart").html(cart); }); } function getImage(baseURL, ing){ jQuery.get(baseURL + "ajax_ingrimage.php?ing="+ing, function(data, status) { jQuery('#product_image').attr('src', 'data:image/jpg;base64,' + data); }).fail(function(){ }); } <file_sep><?php header('Content-Type: text/json'); header("Access-Control-Allow-Origin: *"); echo json_encode(array('status'=>'open')); ?> <file_sep><?php include "templates/page_setup.php"; header('Content-Type: text/json'); header("Access-Control-Allow-Origin: *"); if (isset($_GET['ing'])){ $db = new Database(); $ing = trim($_GET['ing'],'"'); $ingredient = $db->getIngredientbyName($ing); $ingarray = array("name"=>$ingredient['i_name'], "short"=>$ingredient['description'], "unit"=>$ingredient['unit'],"cost"=>$ingredient['price'],"time"=>$ingredient['time'], "desc"=>$ingredient['longdescription']); //redient['i_name'] echo json_encode($ingarray); } ?> <file_sep><?php require_once "templates/page_setup.php"; $page_name = "checkout"; include "templates/header.php"; include "templates/jumbotron.php"; ?> <?php if (isset($_POST['check'])){ $users = User::readUsers(); //get users from users.csv foreach ($users as $u){ if ($u->status == 'Admin'){ $to = $u->email; $t=0; if(!empty($_GET['total'])) $t = doubleval($_GET['total']); $subject = 'CT310 Empo Team -- Customer Purchase: $'.number_format((float)$t,2,'.','').' has been billed to your account.'; $message = 'This is an email from www.cs.colostate.edu/~mjrerle/p3/ and is not an actual bill. This is for testing purposes only.'; mail($to,$subject,$message); } } clear_cart(); //header('Location: cart.php'); echo '<h2 align="center">Thanks for Shopping With Us!</h2>'; echo '<p align="center"><a href="food.php">Back To Shopping</a></p>'; include 'templates/footer.php'; die(); } function clear_cart(){ unset($_SESSION['array']); unset($_SESSION['items']); } $total; $str = '<h1 align="center">Your Total is $0.00</h1> <h2 align="center">Are You Sure You Want To Checkout?</h2> <form action="#" method="post"> <input type="submit" name="check" value="Checkout"> </form> </div>'; if(!empty($_GET['total'])){ $total = doubleval($_GET['total']); $str = '<div class="checkout"> <h1 align="center">Your Total is $'. number_format((float)$total, 2 , '.' , '').'</h1> <h2 align="center">Are You Sure You Want To Checkout?</h2> <form action="#" method="post"> <input type="submit" name="check" value="Checkout"> </form> </div>'; echo $str; } else{ echo $str; } ?> <?php require 'templates/footer.php';?> <file_sep>Hosted on http://www.cs.colostate.edu/~mjrerle/p3/index.php https://www.git-tower.com/blog/git-cheat-sheet/ <file_sep><?php require_once "templates/page_setup.php"; $_final; $page_name = "cart"; include "templates/header.php"; include "templates/jumbotron.php"; ?> <?php class cart{ public $name; public $cost; public $teamURL; public function __construct($name="",$cost=0,$teamURL=""){ $this->name=$name; $this->cost=$cost; $this->teamURL=$teamURL; } } ?> <?php function total (){ $total = 0.0; $row = $_SESSION['array']; foreach ($row as $ing){ $total += $_SESSION['items'][$ing->name]['Total']; } return $total; } ?> <?php function view_cart(){ $row = $_SESSION['array']; echo '<table class="table">'; echo '<tr> <th>Name</th> <th>Price</th> <th>Quantity</th> <th>Site</th> </tr> '; foreach ($row as $ing){ $price = number_format((float)$_SESSION['items'][$ing->name]['Total'], 2 , '.' , ''); // formatted to 2 decimals $quant = $_SESSION['items'][$ing->name]['Quantity']; //quantity echo '<tr>'; echo "<td>$ing->name</td>"; echo "<td>$price</td>"; echo "<td>$quant</td>"; echo "<td><a href=".$ing->teamURL.">$ing->teamURL</a></td>"; echo "<td><a href=\"cart.php?remove=yes&name=$ing->name&cost=$ing->cost&team=$ing->teamURL\">Remove from Cart</a></td>"; echo '</tr>'; } echo '</table>'; } function remove_item($name){ foreach($_SESSION['array'] as $itemsKey => $items){ foreach($items as $valueKey => $value){ if($valueKey == 'name' && $value == $name){ //delete this particular object from the $array unset($_SESSION['array'][$itemsKey]); } } } if (empty($_SESSION['array'])) unset($_SESSION['array']); } ?> <?php if (isset($_GET['remove'])): $name = strip_tags($_GET['name']); $cost = strip_tags($_GET['cost']); $team = strip_tags($_GET['team']); $sing = new cart($name,$cost,$team); $quant = $_SESSION['items'][$name]['Quantity']; if ($quant <= 1): unset($_SESSION['items'][$name]); //remove remove_item($name);//unset($_SESSION['array']); unset($_GET['name']); else: $_SESSION['items'][$name]['Quantity']--; //remove only 1 $_SESSION['items'][$name]['Total'] -= $sing->cost; endif; header('Location: cart.php'); die(); endif; ?> <?php if (!isset($_SESSION['array']) and !isset($_GET['name'])): echo '<h3 align="center">Your Cart is Empty</h3>'; echo '<p align="center"><a href="food.php">Continue Shopping</a></p>'; require 'templates/footer.php'; die(); endif; ?> <?php if (isset($_GET['name'])): $name = strip_tags($_GET['name']); $team = strip_tags($_GET['team']); $cost = doubleval($_GET['cost']); $sing = new cart($name,$cost,$team); if (!isset($_SESSION['array'])): $row = array(); //stores ingredients in cart $row[] = $sing; $_SESSION['array'] = $row; $_SESSION['items'] = array(); $_SESSION['items'][$name] = array('Quantity' => 1, 'Total' => $row[0]->cost); else: $row = $_SESSION['array']; if (isset($_SESSION['items'][$name])): //item exists already $_SESSION['items'][$name]['Quantity']++; $price = $sing->cost; $_SESSION['items'][$name]['Total'] += $price; else: //create a new item $_SESSION['items'][$name] = array('Quantity' => 1, 'Total' => $sing->cost); $row[] = $sing; //add to cart $_SESSION['array'] = $row; endif; endif; endif; ?> <div class="cart"> <h2 align="center">My Cart</h2> <?php view_cart(); ?> <h3 align="center">Your Total is: $<?php $_final = total(); echo number_format((float)$_final, 2 , '.' , '');?></h3> <p align="center"><a href="checkout.php?total=<?php echo $_final;?>">Checkout</a></p> <p align="center"><a href="products.php">Continue Shopping</a></p> </div> <?php require 'templates/footer.php';?> <file_sep><?php header('Content-Type: text/json'); header("Access-Control-Allow-Origin: *"); include "templates/page_setup.php"; require_once "create.php"; if(!$dbh=setupProductConnection()) die; dropTableByName("ingredient"); dropTableByName("comment"); dropTableByName("images"); createTableIngredient(); createTableImage(); createTableComment(); loadProductsIntoEmptyDatabase(); $db = new Database(); $ingredients = $db->getIngredients(); $count = $db->getNumberOfIngredients(); $array = array(); $i=0; while($i<$count){ $array[$i] = array("name"=>$ingredients[$i]->name, "short"=>$ingredients[$i]->description, "unit"=>$ingredients[$i]->unit,"cost"=>$ingredients[$i]->price); $i++; } echo json_encode($array); ?> <file_sep><?php class Ingredient{ public $name; public $unit; public $id; public $price; public $description; public $longdescription; public $time; public $imgURL; function __construct($name="",$unit="",$id=0,$description="", $longdescription="",$time="",$price=0, $imgURL =""){ $this->name = $name; $this->unit = $unit; $this->id = $id; $this->description=$description; $this->price=$price; $this->longdescription=$longdescription; $this->time=$time; $this->imgURL=$imgURL; } public static function getIngredientFromRow($row){ $ingredient = new Ingredient(); $ingredient->name = $row['i_name']; $ingredient->unit = $row['unit']; $ingredient->id = $row['id']; $ingredient->price = $row['price']; $ingredient->description = $row['description']; $ingredient->longdescription=$row['longdescription']; $ingredient->time=$row['time']; $ingredient->imgURL = $row['imgURL']; return $ingredient; } function __toString(){ return $this->name; } } <file_sep><?php include "templates/page_setup.php"; header('Content-Type: text/json'); header("Access-Control-Allow-Origin: *"); if(isset($_GET['ing'])){ $db = new Database(); $ing = strip_tags($_GET['ing']); $ingredient = $db->getIngredientbyName($ing); $path = (dirname(__FILE__)) ."/assets/img/". $ingredient['imgURL']; $type = pathinfo($path, PATHINFO_EXTENSION); $data = file_get_contents($path); echo json_encode(base64_encode($data)); } else header('location: index.php'); ?> <file_sep><?php include "templates/page_setup.php"; include "templates/header.php"; include "templates/jumbotron.php"; ?> <script src = "display.js"></script> <div class = "container-fluid product-list" id="content" style =""> <div class = "row"> <div class = "col-md-12"> <?php if(isset($_SESSION['status']) and $_SESSION['status']=='Admin'){ echo '<a href = "ingredient_form.php?action=new" class = "btn bth-default btn-sm">Add new ingredient to database<span class = "glyphicon glyphicon-plus"></a><br>'; } ?> <div class="row" id = "dis"> </div> </div> </div> <div id="debug"></div> </div> <?php include "templates/footer.php";?>
7ce19a6ac5ac53817f2c18bd039bc16037147670
[ "JavaScript", "Markdown", "PHP", "Shell" ]
14
PHP
mjrerle/webdevp3
39d348f9f6d77c2966d1a2f0c4234679a5e98a2b
ae435ac630b4015df58734c5209a6ca98d8e953a
refs/heads/master
<file_sep>- Plan app prototype - Set up server routes - Set up APIs/Controllers - Set up DB - Set up login/authentication - Set up front end<file_sep>module.exports = (app, passport) => { app.get('/', (req, res) => { // evt: check if logged in res.render('home'/* HOME TPL*/); }); app.get('/signup', (req, res) => { res.render('signup'); }); app.get('/login', (req, res) => { res.render('login') }); app.get('/create', (req, res) => { res.render('new-family'); }); app.get('/families/:familyname', (req, res) => { // evt: db/cache lookup res.render('memorial', { name: req.params.familyname }); }); }<file_sep>// config/db.js module.exports = { 'url' : 'mongodb://localhost:27017/requiem' };
45d6e61d4fc8a7dea83c0995e91343b875a349b1
[ "JavaScript", "Text" ]
3
Text
brycepj/requiem
135b28b1e697e2db3600727543cb918fdc7d0c0b
86413f1a5ff5b230477d0822d9f90e2187464d8e
refs/heads/main
<file_sep>package breakoutGame; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class gameMenu extends JFrame { private JPanel menuPanel = new JPanel(); private static JButton playButton = new JButton("Play"); private static JButton scoreBoardButton = new JButton("Scoreboard"); private static JButton exitButton = new JButton("Exit"); public static final CardLayout switchScreens = new CardLayout(); public static final JPanel parentPanel = new JPanel(); public gameMenu() { playButton.addActionListener(new ButtonHandler(this)); scoreBoardButton.addActionListener(new ButtonHandler(this)); exitButton.addActionListener(new ButtonHandler(this)); menuPanel.add(playButton); menuPanel.add(scoreBoardButton); menuPanel.add(exitButton); scoreboardMenu scoreBoard = new scoreboardMenu(); parentPanel.setLayout(switchScreens); switchScreens.show(parentPanel, "parent"); parentPanel.add(menuPanel, "menu"); parentPanel.add(scoreBoard, "scoreboard"); add(parentPanel); setTitle("Breakout"); setSize(500, 800); setVisible(true); setResizable(false); setLocationRelativeTo(null); setLayout(new BorderLayout()); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } class ButtonHandler implements ActionListener { gameMenu theGame; public ButtonHandler(gameMenu thisGame) { theGame = thisGame; } public void actionPerformed(ActionEvent e) { if (e.getSource() == playButton) { gamePlay game = new gamePlay(); game.setVisible(true); setVisible(false); } if (e.getSource() == scoreBoardButton) { switchScreens.show(parentPanel, "scoreboard"); } if (e.getSource() == exitButton) { System.exit(0); } } } public static void main(String[] args) { new gameMenu(); } }<file_sep>package chatroom_GUI; import java.io.*; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Calendar; public class clientHandler extends Thread { private Socket socket; private server server; private PrintWriter sentToClient; private BufferedReader reader; private InputStream receivedFromClient; private String clientMessage; private SimpleDateFormat df; private Calendar cal; public clientHandler(Socket socket, server server) { this.socket = socket; this.server = server; } public void run() { try { System.out.println("Connection found!"); receivedFromClient = socket.getInputStream(); reader = new BufferedReader(new InputStreamReader(receivedFromClient)); OutputStream os = socket.getOutputStream(); sentToClient = new PrintWriter(os, true); String userName = reader.readLine(); System.out.println("New user connection from " + userName); cal = Calendar.getInstance(); df = new SimpleDateFormat("HH:mm"); String serverMessage = "--- " + userName + " has entered the chatroom ---"; server.addName(userName); server.broadCast(serverMessage); do { clientMessage = reader.readLine(); server.broadCast("[" + df.format(cal.getTime()) + "]" + userName + ": " + clientMessage); } while (!clientMessage.equals("QUIT")); String clientLeft = "--- " + userName + " has left the chat ---"; server.broadCast(clientLeft); server.remove(this, userName); socket.close(); } catch (Exception e) { System.out.println("Lost connection - " + e); } } public void sendMessage(String message) { sentToClient.println(message); } }<file_sep>package breakoutGame; import java.awt.*; public class paddle extends objects { int units = 15; public paddle(int yPos, int xPos, int width, int height) { super(yPos, xPos, width, height); } @Override public void paintComponents(Graphics g) { g.setColor(Color.BLUE); g.fillRect(yCoords, xCoords, width, height); } public void moveLeft() { if (yCoords < 5) { yCoords = 5; } yCoords -= units; } public void moveRight() { if (yCoords > 400) { yCoords = 400; } yCoords += units; } }<file_sep>package chatroom_GUI; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; public class readThread extends Thread { private Socket socket; private chatroom chatroom; private InputStream receiveFromServer; private BufferedReader reader; static String message; public readThread(Socket socket, chatroom chatroom) { this.socket = socket; this.chatroom = chatroom; try { receiveFromServer = socket.getInputStream(); reader = new BufferedReader(new InputStreamReader(receiveFromServer)); } catch (Exception e) { e.printStackTrace(); } } public void run() { while (true) { try { message = reader.readLine(); System.out.println(message); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>package gp_surgery; public abstract class person { private String title; private String forename; private String surname; public person(String title, String forename, String surname) { this.title = title; this.forename = forename; this.surname = surname; } @Override public String toString() { return title + " " + forename + " " + surname; }; }<file_sep>package calculator_app; import java.awt.event.*; import java.util.regex.*; import static calculator_app.myapp.*; class numberButton implements ActionListener { private String value; public numberButton(String buttonValue) { this.value = buttonValue; } public void actionPerformed(ActionEvent e) { if (calculatorValue.length() == 1 && calculatorValue.equals("0")) { multipleDigits = false; numberButtons[9].setEnabled(false); } if (multipleDigits == true) { calculatorValue += value; text.setText(calculatorValue); } if (multipleDigits == false) { numberButtons[9].setEnabled(true); multipleDigits = true; calculatorValue = value; text.setText(calculatorValue); } } } class operationsListener implements ActionListener { private String operator; public operationsListener(String buttonValue) { this.operator = buttonValue; } public void actionPerformed(ActionEvent e) { if (operator == "BACK") { calculatorValue = calculatorValue.substring(0, calculatorValue.length() - 1); text.setText(calculatorValue); if (!calculatorValue.contains(".")) { operationButtons[7].setEnabled(true); } if (calculatorValue.length() == 0) { calculatorValue = "0"; text.setText(calculatorValue); } } if (operator == "+" | operator == "-" | operator == "*" | operator == "/") { calculatorValue += operator; text.setText(calculatorValue); } if (operator == "(") { if (calculatorValue.equals("0")) { calculatorValue = operator; text.setText(calculatorValue); } else { calculatorValue += operator; text.setText(calculatorValue); } } if (operator == ")") { Pattern pattern = Pattern.compile("[(]"); Matcher matcher = pattern.matcher(calculatorValue); int count = 0; int clicks = 0; while (matcher.find()) { count++; } if (calculatorValue.contains("(")) { if (clicks == count) { operationButtons[1].setEnabled(false); } calculatorValue += operator; text.setText(calculatorValue); clicks++; } } if (operator == ".") { calculatorValue += operator; text.setText(calculatorValue); if (calculatorValue.contains(".")) { operationButtons[7].setEnabled(false); } } if (operator == "C") { calculatorValue = "0"; text.setText(calculatorValue); operationButtons[7].setEnabled(true); } if (operator == "=") { String subString = ""; int total = 0; if (calculatorValue.length() > 1) { if (calculatorValue.startsWith("(")) { int endsWithBracket = calculatorValue.lastIndexOf(")") + 1; subString += calculatorValue.substring(0, endsWithBracket); } System.out.println(subString); } } } }<file_sep>package chatroom_GUI; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.util.Set; public class server { private int port; private clientHandler userClient; private Set<String> allUsers = new HashSet<>(); private Set<clientHandler> allClientHandlers = new HashSet<>(); static ServerSocket serverSocket; public server(int port) { this.port = port; } public void run() { try { serverSocket = new ServerSocket(port); System.out.println("Searching for connections..."); while (true) { Socket socket = serverSocket.accept(); clientHandler userClient = new clientHandler(socket, this); allClientHandlers.add(userClient); userClient.start(); } } catch (IOException e) { System.out.println("Unable to connect to client - " + e); } } public void broadCast(String message) { System.out.println("Sending message to all users: " + message); for (clientHandler clientNo : allClientHandlers) { clientNo.sendMessage(message); } } public void addName(String name) { allUsers.add(name); } public void remove(clientHandler userClient, String clientName) { allClientHandlers.remove(userClient); allUsers.remove(clientName); } public static void main(String[] args) { server server = new server(8888); server.run(); } }<file_sep>package chatroom_GUI; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class clientGUI extends JFrame { private JPanel parentPanel, addressPanel, bottomPanel, middlePanel, topPanel; private JLabel nameLabel, IPLabel, PortLabel, label, message; private JTextField nameField, IPField, PortField; private JButton button; private CardLayout switchScreens; private GridLayout gridLayout; private chatroom chatroom; static String name; private Font font; private int fontSize = 20; public clientGUI() throws Exception { font = new Font("Railway Extra Bold", Font.PLAIN, fontSize); switchScreens = new CardLayout(); nameLabel = new JLabel("Username: "); IPLabel = new JLabel("IP Address: "); PortLabel = new JLabel("Port Address: "); label = new JLabel("Enter IP address and Port Number"); nameLabel.setFont(font); IPLabel.setFont(font); PortLabel.setFont(font); label.setFont(font); message = new JLabel(); nameField = new JTextField(1); IPField = new JTextField(1); PortField = new JTextField(1); button = new JButton("Go!"); button.setFont(font); IPField.addActionListener(new ButtonHandler(this)); PortField.addActionListener(new ButtonHandler(this)); button.addActionListener(new ButtonHandler(this)); topPanel = new JPanel(); middlePanel = new JPanel(); bottomPanel = new JPanel(); parentPanel = new JPanel(); addressPanel = new JPanel(); //chatroom = new chatroom(); gridLayout = new GridLayout(4, 2); topPanel.add(label); middlePanel.add(message); bottomPanel.setLayout(gridLayout); bottomPanel.add(nameLabel); bottomPanel.add(nameField); bottomPanel.add(IPLabel); bottomPanel.add(IPField); bottomPanel.add(PortLabel); bottomPanel.add(PortField); bottomPanel.add(button); bottomPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); topPanel.setBorder(BorderFactory.createEmptyBorder(20, 30, 30, 30)); addressPanel.add(topPanel); addressPanel.add(middlePanel); addressPanel.add(bottomPanel); parentPanel.setLayout(switchScreens); parentPanel.add(addressPanel, "menu"); //parentPanel.add(chatroom, "chatroom"); switchScreens.show(parentPanel, "menu"); add(parentPanel); setTitle("Chat Room"); setVisible(true); setResizable(false); setSize(400, 600); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) throws Exception { new clientGUI(); } class ButtonHandler implements ActionListener { clientGUI theapp; public ButtonHandler(clientGUI thisApp) { this.theapp = thisApp; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { name = nameField.getText(); String IPAddress = IPField.getText(); String getPort = PortField.getText(); if (IPAddress == "127.0.0.1" && getPort == "8888") { switchScreens.show(parentPanel, "chatroom"); } } } } }<file_sep>package breakoutGame; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class gamePlay extends JFrame implements ActionListener, KeyListener { Timer gameInterval = new Timer(5, this); repaint paint = new repaint(); static ball ball = new ball(100,600,20, 500, 800); static paddle paddle = new paddle(250,600,80,20); public gamePlay() { gameInterval.start(); add(paint); addKeyListener(this); setTitle("Breakout"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setResizable(false); setSize(500,800); } @Override public void actionPerformed(ActionEvent e) { ball.move(); ball.checkPaddleCollision(); repaint(); } static void repaint(Graphics g) { ball.paintComponents(g); paddle.paintComponents(g); } @Override public void keyTyped(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_A) { paddle.moveLeft(); } if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) { paddle.moveLeft(); } if (keyEvent.getKeyCode() == KeyEvent.VK_D) { paddle.moveRight(); } if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) { paddle.moveRight(); } } @Override public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_A) { paddle.moveLeft(); } if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) { paddle.moveLeft(); } if (keyEvent.getKeyCode() == KeyEvent.VK_D) { paddle.moveRight(); } if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) { paddle.moveRight(); } } @Override public void keyReleased(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_A) { paddle.moveLeft(); } if (keyEvent.getKeyCode() == KeyEvent.VK_LEFT) { paddle.moveLeft(); } if (keyEvent.getKeyCode() == KeyEvent.VK_D) { paddle.moveRight(); } if (keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) { paddle.moveRight(); } } }
911467d4bcd9691f4c8c46fdd2744fb45d2ce853
[ "Java" ]
9
Java
brandonwklee/java
a6eaac1419f82aee2c516adbaa5f5da1f8f425a8
d06fb9037bfdcd6be686d755988c62d6e4e12246
refs/heads/master
<file_sep># weiboPro Based on scrapy-redis Crawl the weibo content and store it in mongodb <file_sep>from scrapy import Request, Spider import json from weiboPro.items import * class WeiboSpider(Spider): name = 'weibo' # allowed_domains = ['www.xxx.com'] # start_urls = ['http://www.xxx.com/'] user_url = 'https://weibo.com/ajax/profile/info?uid={uid}' # 用户详情 weibo_url = 'https://weibo.com/ajax/statuses/mymblog?uid={uid}&page={page}&feature=0' # 微博列表 follow_url = 'https://weibo.com/ajax/friendships/friends?page={page}&uid={uid}' # 关注列表 start_users = ['1227368500'] def start_requests(self): for uid in self.start_users: yield Request(self.user_url.format(uid=uid), callback=self.parse_user) def parse_user(self, response): result = json.loads(response.text) user_info = result.get('data').get('user') field_map = { 'description': 'description', 'id': 'id', 'followers_count': 'followers_count', 'friends_count': 'friends_count', 'location': 'location', 'screen_name': 'screen_name', 'verified_reason': 'verified_reason' } if user_info: item = UserItem() for key, value in field_map.items(): item[key] = user_info.get(value) yield item uid = user_info.get('id') yield Request(self.follow_url.format(page=1, uid=uid), callback=self.parse_follows, meta={'page': 1, 'uid': uid}) yield Request(self.weibo_url.format(uid=uid, page=1), callback=self.parse_weibos, meta={'page': 1, 'uid': uid}) def parse_follows(self, response): result = json.loads(response.text) follow_info = result.get('users') # 获得一个列表 dic = {} if result.get('next_cursor') != 0: for user_dict in follow_info: dic[user_dict.get('idstr')] = user_dict.get('name') if user_dict.get('idstr'): uid = user_dict.get('idstr') yield Request(self.user_url.format(uid=uid), callback=self.parse_user) uid = response.meta.get('uid') item = UserRelationItem() item['id'] = uid item['follows'] = list(dic) yield item page = response.meta.get('page') + 1 yield Request(self.follow_url.format(uid=uid, page=page), callback=self.parse_follows, meta={'page':page, 'uid':uid}) def parse_weibos(self, response): result = json.loads(response.text) weibo_info = result.get('data').get('list') # 获得一个列表 field_map = { 'id':'id', 'attitudes_count': 'attitudes_count', 'comments_count': 'comments_count', 'create_at': 'create_at', 'reposts_count': 'reposts_count', 'text_raw': 'text_raw' } if result.get('data').get('bottom_tips_visible') == False: for weibo in weibo_info: item = WeiboItem() # item['id'] = response.meta.get('uid') for key, value in field_map.items(): item[key] = weibo.get(value) yield item uid = response.meta.get('uid') page = response.meta.get('page') + 1 yield Request(self.weibo_url.format(uid=uid, page=page), callback=self.parse_weibos, meta={'uid': uid, 'page': page}) else: print('-------------------此人微博已全部爬取------------------------') <file_sep># Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class UserItem(scrapy.Item): collection = 'users' description = scrapy.Field() id = scrapy.Field() followers_count = scrapy.Field() friends_count = scrapy.Field() location = scrapy.Field() screen_name = scrapy.Field() verified_reason = scrapy.Field() class UserRelationItem(scrapy.Item): collection = 'users' id = scrapy.Field() follows = scrapy.Field() class WeiboItem(scrapy.Item): collection = 'weibo' id = scrapy.Field() attitudes_count = scrapy.Field() comments_count = scrapy.Field() create_at = scrapy.Field() reposts_count = scrapy.Field() text_raw = scrapy.Field()
1dbbe5d75d8f7573f09de40623208fbc62a15a9c
[ "Markdown", "Python" ]
3
Markdown
IvanLeezj/weiboPro
fce26eb6a4b4f283db3adf1543081e3b38ae4df4
d99944be0862887088a1f1d843917c7a3e37aa9e
refs/heads/master
<file_sep>try{ let tabCreated = null; chrome.tabs.onRemoved.addListener(() => { chrome.tabs.query({currentWindow: true}, (tabs) => { console.log(tabs); if( tabs.length === 1 ){ chrome.tabs.create({ url: 'chrome://newtab/', active: false, }, function(tab){ tabCreated = tab; console.log("newly created tab is: ", tabCreated); }) } }) }) chrome.tabs.onCreated.addListener((tab) => { if(tabCreated !== null && tab.id !== tabCreated.id){ if(tabCreated.url === 'chrome://newtab/'){ chrome.tabs.remove(tabCreated.id, () => console.log("removed tab")); } } }); chrome.tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => { if(tabId === tabCreated.id) tabCreated = tabInfo; }); }catch(error){ console.log(error); }
04f10163203a9c61314fa25ae671b306175973a0
[ "JavaScript" ]
1
JavaScript
HARSH-SHETH/LastTabStanding
e6a8b027163ae96fb44cbf5e94e6225b6e62b379
e30129d3d41f3e08c343eac8b1362d24f68b9127
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular'; import {RestaurantService} from "../../providers/restaurant-service-rest"; import * as firebase from "firebase"; /** * Generated class for the EventAddPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name: 'page-event-add', segment: 'event-add' }) @Component({ selector: 'page-event-add', templateUrl: 'event-add.html', }) export class EventAddPage { noticeTitle: string; noticeContent: string; favorites: Array<any> = []; public db = firebase.firestore(); date : any; constructor(public navCtrl: NavController, public service: RestaurantService, private alertCtrl: AlertController) { // this.getFavorites(); // console.log(this.favorites); } addReview(){ var success = this.addReviewAsync().then(()=> this.presentAlert()).then(()=>{this.navCtrl.push('page-home');}).catch(); //console.log("result:",success); } async addReviewAsync(){ let review = await this._addreview(); return review; } _addreview():Promise<any>{ return new Promise<any>(resolve => { var success = "success"; this.date = new Date().toUTCString(); var addDoc = this.db.collection('event').add({ title : this.noticeTitle, content : this.noticeContent, timeStamp: this.date }).then(ref=>{ resolve(success); console.log('Added document'); }) // resolve(store); }) } presentAlert() { let alert = this.alertCtrl.create({ title: "Event added", buttons: ['OK'] }); alert.present(); } } <file_sep>import {Component} from '@angular/core'; import { IonicPage, Config, NavController, NavParams, ToastController, ModalController, AlertController, Platform } from 'ionic-angular'; import {RestaurantService} from '../../providers/restaurant-service-mock'; import leaflet from 'leaflet'; import * as firebase from "firebase"; import 'firebase/firestore'; import {HttpClient, HttpHeaders} from "@angular/common/http"; @IonicPage({ name: 'page-restaurant-list', segment: 'restaurant-list' }) @Component({ selector: 'page-restaurant-list', templateUrl: 'restaurant-list.html' }) export class RestaurantListPage { orders: Array<any> = []; public store : string=''; public table: any; public menuCollection: any; public db = firebase.firestore(); waitingNumber=0; owner:string=''; order:string=''; total:number=0; names:string=''; date:string=''; num2:number=0; user:string=''; restaurants: Array<any>; searchKey: string = ""; viewMode: string = "list"; proptype: string; from: string; map; markersGroup; public storeCollection: any; constructor(public navCtrl: NavController, public navParams: NavParams, public service: RestaurantService, public platform : Platform, public toastCtrl: ToastController, public modalCtrl: ModalController, public config: Config, private alertCtrl: AlertController, private http: HttpClient) { this.platform.ready().then(() => {var store_a = this.storeAsync().then(store=> this.store = store).then(()=>{this.start();})}); // console.log(this.proptype); } async storeAsync(){ let val = await this._store(); return val; } _store():Promise<any> { return new Promise<any>(resolve => { var store1: any; this.storeCollection=this.db.collection('store'); this.storeCollection.where("owner", "==", firebase.auth().currentUser.email) .onSnapshot(function (querySnapshot) { querySnapshot.forEach(function (doc) { store1 = doc.data().code; } ) resolve(store1); } ); }) } start(){ var abc =this.startAsync().then(num2 => { this.waitingNumber = num2}); } async startAsync(){ let check = await this._start(); return check; } _start():Promise<any>{ return new Promise<any>(resolve => { this.db.collection(this.store).get().then(function(querySnapshot) { let a : number = querySnapshot.size; resolve(a); }); }) } waiting(){ if(this.waitingNumber!=0){ var abc =this.checkoutAsync().then(num => { this.num2=num; var wait = this.waitAsync(this.num2).then(wm => { this.waitingNumber=wm; }) }); } } async checkoutAsync(){ let check = await this._check(); return check; } _check():Promise<any>{ return new Promise<any>(resolve => { let wm = 9999999; this.db.collection(this.store).get().then(function(querySnapshot) { querySnapshot.forEach(doc => { console.log(doc.data().order) wm = doc.data().order; }); resolve(wm); }); }); } notification(){ let body = { "notification": { "title": "Waiting is done! Come to the restaurant!", "body": "Waiting is done! Come to the restaurant!", "sound": "default", "click_action": "FCM_PLUGIN_ACTIVITY", "icon": "fcm_push_icon" }, "data": {}, "to": "/topics/" + this.user.replace('@','').replace('.',''), "priority": "high", "restricted_package_name": "" } let options = new HttpHeaders().set('Content-Type', 'application/json'); this.http.post("https://fcm.googleapis.com/fcm/send", body, { headers: options.set('Authorization', 'key=<KEY>'), }) .subscribe(); } async waitAsync(num : number){ let wait = await this._wait(num); return wait; } _wait(num : number):Promise<any>{ return new Promise<any>(resolve => { var orderRef = this.db.collection(this.store).where("order", "==", num).onSnapshot(querySnapshot => { if(querySnapshot.size>0) { querySnapshot.docChanges.forEach(change => { const fooId = change.doc.id const fooUser = change.doc.data().user this.user=fooUser; this.db.collection(this.store).doc(fooId).delete().then(success => { let wm = this.waitingNumber-1; this.waitingNumber=this.waitingNumber-1; this.notification(); resolve(wm); }); }); }else{ resolve(this.waitingNumber); } }); }); } } <file_sep>import {Component, ViewChild} from '@angular/core'; import {Nav, Platform} from 'ionic-angular'; import {StatusBar} from '@ionic-native/status-bar'; import {SplashScreen} from '@ionic-native/splash-screen'; import * as firebase from 'firebase'; import { FCM } from '@ionic-native/fcm'; import {GlobalvarsProvider} from "../providers/globalvars/globalvars"; export interface MenuItem { title: string; component: any; icon: string; } // Initialize Firebase var config = { apiKey: "<KEY>", authDomain: "easyordercustomer.firebaseapp.com", databaseURL: "https://easyordercustomer.firebaseio.com", projectId: "easyordercustomer", storageBucket: "easyordercustomer.appspot.com", messagingSenderId: "1063191754261" }; // var secondaryAppConfig = { // apiKey: "<KEY>", // authDomain: "easyorderbusiness.firebaseapp.com", // projectId: "easyorderbusiness", // databaseURL: "https://easyordercustomer.firebaseio.com", // storageBucket: "easyordercustomer.appspot.com" // }; @Component({ templateUrl: 'app.html' }) export class foodIonicApp { @ViewChild(Nav) nav: Nav; tabsPlacement: string = 'bottom'; tabsLayout: string = 'icon-top'; rootPage: any = 'page-auth'; showMenu: boolean = true; homeItem: any; initialItem: any; messagesItem: any; settingsItem: any; appMenuItems: Array<MenuItem>; yourRestaurantMenuItems: Array<MenuItem>; accountMenuItems: Array<MenuItem>; helpMenuItems: Array<MenuItem>; public secondary :any; public secondaryDatabase : any; public storeCollection: any; public storeCode: any; email:string=''; public db :any; constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private fcm: FCM, public global : GlobalvarsProvider) { firebase.initializeApp(config); firebase.auth().onAuthStateChanged((user)=>{ if(user){ this.rootPage = 'page-home'; this.email=user.email; this.platform.ready().then(() => { this.db=firebase.firestore(); this.fcm.getToken().then(token => { // Your best bet is to here store the token on the user's profile on the // Firebase database, so that when you want to send notifications to this // specific user you can do it from Cloud Functions. }); var store_a = this.storeAsync().then(store_a=> this.storeCode = store_a).then(()=>{this.fcm.subscribeToTopic(this.storeCode);}); this.fcm.onNotification().subscribe(data => { if (data.wasTapped) { console.log("Received in background"); } else { console.log("Received in foreground"); } }); this.fcm.onTokenRefresh().subscribe(token => { console.log(token); }); this.statusBar.overlaysWebView(false); this.splashScreen.hide(); }); if (!this.platform.is('mobile')) { this.tabsPlacement = 'top'; this.tabsLayout = 'icon-left'; } }else{ this.rootPage = 'page-auth'; } }); // this.initializeApp(); this.homeItem = { component: 'page-home' }; this.messagesItem = { component: 'page-message-list'}; this.appMenuItems = [ // {title: 'Restaurants', component: 'page-restaurant-list', icon: 'home'}, {title: 'Reviews', component: 'page-dish-list', icon: 'camera'}, // {title: 'Nearby', component: 'page-nearby', icon: 'compass'}, {title: 'Waiting', component: 'page-restaurant-list', icon: 'albums'}, // {title: 'Latest Orders', component: 'page-orders', icon: 'list-box'}, {title: 'Register Menu', component: 'page-create-menu', icon: 'log-in'}, {title: 'Edit Menu', component: 'page-edit-menu', icon: 'refresh'}, {title: 'Events', component: 'page-event', icon: 'albums'}, {title: 'Notice', component: 'page-notice', icon: 'list-box'}, // {title: 'Favorite Restaurants', component: 'page-favorite-list', icon: 'heart'} ]; this.yourRestaurantMenuItems = [ {title: 'Register Restaurant', component: 'page-your-restaurant', icon: 'clipboard'} ]; this.accountMenuItems = [ {title: 'Login', component: 'page-auth', icon: 'log-in'}, {title: 'My Account', component: 'page-my-account', icon: 'contact'}, {title: 'Logout', component: 'page-auth', icon: 'log-out'}, ]; this.helpMenuItems = [ {title: 'About', component: 'page-about', icon: 'information-circle'}, {title: 'Support', component: 'page-support', icon: 'call'}, // {title: 'App Settings', component: 'page-settings', icon: 'cog'}, // {title: 'Walkthrough', component: 'page-walkthrough', icon: 'photos'} ]; } logout(){ firebase.auth().signOut().then(function() { // Sign-out successful. console.log("logout"); }).catch(function(error) { // An error happened. console.log("error"); }); } async storeAsync(){ let val = await this._store(); return val; } _store():Promise<any> { return new Promise<any>(resolve => { var store=''; this.storeCollection=this.db.collection('store'); this.storeCollection.where("owner", "==", this.email) .onSnapshot(function (querySnapshot) { querySnapshot.forEach(function (doc) { store = doc.data().code //.log(store); resolve(store); } ) } ); }) } initializeApp() { this.platform.ready().then(() => { console.log(this.email) this.fcm.subscribeToTopic('abc'); this.fcm.onNotification().subscribe(data => { if (data.wasTapped) { console.log("Received in background"); } else { console.log("Received in foreground"); } }); this.fcm.onTokenRefresh().subscribe(token => { console.log(token); }); this.statusBar.overlaysWebView(false); this.splashScreen.hide(); }); if (!this.platform.is('mobile')) { this.tabsPlacement = 'top'; this.tabsLayout = 'icon-left'; } } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } } <file_sep>import { Component, OnInit} from '@angular/core'; import { IonicPage, NavController, NavParams , LoadingController, ToastController} from 'ionic-angular'; import { AlertController } from 'ionic-angular'; import * as firebase from "firebase"; import 'firebase/firestore'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import {NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderOptions, NativeGeocoderForwardResult} from "@ionic-native/native-geocoder"; /** * Generated class for the RegisterServicePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name :'page-register-service' }) @Component({ selector: 'page-register-service', templateUrl: 'register-service.html', }) export class RegisterServicePage implements OnInit{ date : any; email : any; name: any; phone: any; location: Array<any>=[]; address: any; business_hours: any; public db = firebase.firestore(); public onYourRestaurantForm: FormGroup; constructor(public loadingCtrl: LoadingController, public toastCtrl: ToastController, private _fb: FormBuilder,private nativeGeocoder: NativeGeocoder, public navCtrl: NavController, public navParams: NavParams,private alertCtrl: AlertController) { this.email = this.navParams.get("email"); } ngOnInit() { this.onYourRestaurantForm = this._fb.group({ restaurantTitle: ['', Validators.compose([ Validators.required ])], restaurantAddress: ['', Validators.compose([ Validators.required ])], restaurantPhone: ['', Validators.compose([ Validators.required ])], restaurantHours: ['', Validators.compose([ Validators.required ])] }); } RegisterService(){ // var success = this.RegisterAsync().then(()=> this.presentAlert()).then(()=>{this.navCtrl.push('page-home');}).catch(); var success = this.RegisterAsync().then(()=> this.presentToast()).catch(); } async RegisterAsync(){ let reg = await this._addservice(); return reg; } presentAlert() { let alert = this.alertCtrl.create({ title: "Register Applied", buttons: ['OK'] }); alert.present(); } presentToast() { // send booking info let loader = this.loadingCtrl.create({ content: "Please wait..." }); // show message let toast = this.toastCtrl.create({ showCloseButton: true, cssClass: 'profiles-bg', message: 'Your restaurant was registered!', duration: 3000, position: 'bottom' }); loader.present(); setTimeout(() => { loader.dismiss(); toast.present(); // back to home page this.navCtrl.setRoot('page-home'); }, 3000) } _addservice():Promise<any>{ return new Promise<any>(resolve => { var success = "success"; this.date = new Date().toUTCString(); //this.id = this.id.toString(); let options: NativeGeocoderOptions = { useLocale: true, maxResults :5 }; console.log(this.business_hours, this.address, this.phone); this.nativeGeocoder.forwardGeocode(this.address, options) .then((coordinates: NativeGeocoderForwardResult[]) => this.location= coordinates) .catch((error: any) => console.log(error)); var addDoc = this.db.collection('owner').add({ email : this.email, status : '1', phone : this.phone }). then(()=>{ var addStore = this.db.collection('store').add({ code:"", address: this.address, hours: this.business_hours, location: this.location[0].latitude+","+this.location[0].longitude, name : this.name, owner: this.email, phone: this.phone, service_status: '1' }).then(()=>{ resolve(success) }) }) // resolve(store); }) } } <file_sep>import {Component} from "@angular/core"; import {IonicPage, NavController, ViewController, NavParams} from "ionic-angular"; @IonicPage({ name: 'page-notifications' }) @Component({ selector: 'page-notifications', templateUrl: 'notifications.html' }) export class NotificationsPage { content: any; title: any; timeStamp: any; constructor(public navParams: NavParams,public navCtrl: NavController, public viewCtrl: ViewController) { this.content= this.navParams.get("content"); this.title = this.navParams.get("title"); this.timeStamp = this.navParams.get("timeStamp"); } close() { this.viewCtrl.dismiss(); } messages () { this.navCtrl.push('page-message-list'); } } <file_sep>import {Component} from '@angular/core'; import { IonicPage, NavController, ModalController, NavParams, AlertController, LoadingController, ToastController } from 'ionic-angular'; import {RestaurantService} from '../../providers/restaurant-service-mock'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import leaflet from 'leaflet'; import * as firebase from "firebase"; @IonicPage({ name: 'page-nearby', segment: 'nearby' }) @Component({ selector: 'page-nearby', templateUrl: 'nearby.html' }) export class NearbyPage { restaurants: Array<any>; map; markersGroup; noticeTitle : any; noticeContent : any; timeStamp:any; orders: Array<any> = []; public noticeCollection: any; public db = firebase.firestore(); public onYourRestaurantForm: FormGroup; constructor(public loadingCtrl: LoadingController, public toastCtrl: ToastController, private _fb: FormBuilder,public navCtrl: NavController, private alertCtrl: AlertController,public service: RestaurantService, public navParams: NavParams) { this.noticeTitle= this.navParams.get("title"); this.noticeContent= this.navParams.get("content"); this.timeStamp=this.navParams.get('timeStamp'); console.log(this.timeStamp) } ngOnInit() { this.onYourRestaurantForm = this._fb.group({ restaurantTitle: ['', Validators.compose([ Validators.required ])], restaurantAddress: ['', Validators.compose([ Validators.required ])], }); } presentToast() { // send booking info let loader = this.loadingCtrl.create({ content: "Please wait..." }); // show message let toast = this.toastCtrl.create({ showCloseButton: true, cssClass: 'profiles-bg', message: 'Your Event was changed!', duration: 3000, position: 'bottom' }); loader.present(); setTimeout(() => { loader.dismiss(); toast.present(); // back to home page this.navCtrl.setRoot('page-home'); }, 3000) } presentAlert() { let alert = this.alertCtrl.create({ title: "Review edited", buttons: ['OK'] }); alert.present(); } addReview(){ var success = this.editReviewAsync().then(()=> this.presentToast()).catch(); //console.log("result:",success); } async editReviewAsync(){ let review = await this._editreview(); return review; } _editreview():Promise<any>{ return new Promise<any>(resolve => { var success = "success"; var reviewRef = this.db.collection('event').where("timeStamp", "==", this.timeStamp).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { console.log(change) const reviewid = change.doc.id; this.db.collection('event').doc(reviewid).update({title: this.noticeTitle, content : this.noticeContent}); // do something with foo and fooId resolve(); }) }) // resolve(store); }) } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import * as firebase from "firebase"; /** * Generated class for the NoticePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name: 'page-notice', segment: 'notice' }) @Component({ selector: 'page-notice', templateUrl: 'notice.html', }) export class NoticePage { orders: Array<any> = []; public noticeCollection: any; public db = firebase.firestore(); title:any; content:any; constructor(public navCtrl: NavController, public navParams: NavParams) { this.getOrders(); } getOrders(){ var menu_a = this.orderAsync().then(menu_a=> this.orders= menu_a) .then(()=>console.log(this.orders)); console.log(this.orders); } async orderAsync(){ let menu = await this._order(); return menu; } _order():Promise<any>{ return new Promise<any>(resolve => { var order: Array<any>=[]; this.noticeCollection = this.db.collection("notice"); var orderInfo = this.noticeCollection.get() .then(snapshot => { snapshot.forEach(doc => { order.push({ title : doc.data().title, timeStamp : doc.data().timeStamp, content : doc.data().content }); }); console.log("####", order); resolve(order); }) .catch(err => { console.log('Error getting documents', err); }); }) } ionViewDidLoad() { console.log('ionViewDidLoad NoticePage'); } readmore(id){ this.navCtrl.push('page-notifications', {'content': this.orders[id].content,'title':this.orders[id].title, 'timeStamp':this.orders[id].timeStamp }); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, AlertController, MenuController, ToastController, PopoverController, ModalController, IonicModule, Platform, } from 'ionic-angular'; import {RestaurantService} from '../../providers/restaurant-service-mock'; import * as firebase from "firebase"; import 'firebase/firestore'; import {GlobalvarsProvider} from "../../providers/globalvars/globalvars"; import {FCM} from "@ionic-native/fcm"; import {catchError} from "rxjs/operators"; import {_catch} from "rxjs/operator/catch"; import { IamportService } from 'iamport-ionic-kcp'; import { InAppBrowser } from '@ionic-native/in-app-browser'; import { HttpClient, HttpHeaders} from "@angular/common/http"; var secondaryAppConfig = { apiKey: "<KEY>", authDomain: "easyorderbusiness.firebaseapp.com", projectId: "easyorderbusiness", databaseURL: "https://easyordercustomer.firebaseio.com", storageBucket: "easyordercustomer.appspot.com" }; var config = { apiKey: "<KEY>", authDomain: "easyorderbusiness.firebaseapp.com", databaseURL: "https://easyorderbusiness.firebaseio.com", projectId: "easyorderbusiness", storageBucket: "easyorderbusiness.appspot.com", messagingSenderId: "448152825562" }; @IonicPage({ name: 'page-home', segment: 'home', priority: 'high' }) @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { restaurants: Array<any>; searchKey: string = ""; yourLocation: string = "Gongreung 58 130, Seoul"; email:string=''; store:string=''; public storeCollection: any; public secondary : any; public secondaryDatabase :any; public orders : Array<any>=[]; public orderCollection: any; public db = firebase.firestore(); status = '0'; //private buttonColor: string = "primary"; //private disableButton =false; constructor(public iamport: IamportService, private theInnAppBrowser : InAppBrowser,public http: HttpClient, public navCtrl: NavController, public platform : Platform,private fcm: FCM,public menuCtrl: MenuController, public popoverCtrl: PopoverController, public locationCtrl: AlertController, public modalCtrl: ModalController, public toastCtrl: ToastController, public service: RestaurantService) { this.menuCtrl.swipeEnable(true, 'authenticated'); this.menuCtrl.enable(true); firebase.auth().onAuthStateChanged((user)=>{ if(user){ this.email=user.email; console.log("%%email", this.email); }else{ } }); // this.getOrder(); // this.findAll(); this.getregister(); // this.initializeApp(); // this.platform.ready().then(() => { // // this.secondaryDatabase = firebase.firestore(firebase.app('secondary')); // this.storeCollection = this.secondaryDatabase.collection("store"); // var store_a = this.storeAsync().then(store_a => this.store = store_a); // this.getOrder(); // }); } pay(event) { this.iamport.payment("imp94907252", { pay_method : "card", merchant_uid : this.email + new Date().getTime(), name : "주문명:결제테스트", amount : 50000, app_scheme : "ionickcp" //플러그인 설치 시 사용한 명령어 "ionic cordova plugin add cordova-plugin-iamport-kcp --variable URL_SCHEME=ionickcp" 의 URL_SCHEME 뒤에 오는 값을 넣으시면 됩니다. }).then((response)=> { // console.log(response); if ( response.isSuccess() ) { //TODO : 결제성공일 때 처리 var res = this.updateownerAsync(this.email).then(status => this.status= status ).then(()=>this.presentAlert()).then(()=> this.navCtrl.setRoot('page-home')); // .then(()=>this.updatestoreAsync(this.email)).then( // status => this.status = status // ).then(()=>this.presentAlert()) // .then(()=>this.navCtrl.push('page-home')) // // console.log(response); }else{ } }) .catch((err)=> { alert(err) }) ; } presentAlert() { let alert = this.locationCtrl.create({ title: "Payment Success", buttons: ['OK'] }); console.log(this.status); alert.present(); } async updateownerAsync(email){ let val = await this._updateowner(email); return val; } _updateowner(email):Promise<any> { return new Promise<any>(resolve => { var status ='2' var orderRef = this.db.collection('owner').where("email", "==", this.email).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { const fooId = change.doc.id this.db.collection('owner').doc(fooId).update({status:'2'}); // do something with foo and fooId }) resolve(status); }); }) } async updatestoreAsync(email){ let val = await this._updatestore(email); return val; } _updatestore(email):Promise<any> { return new Promise<any>(resolve => { var status ='2' var orderRef = this.db.collection('owner').where("email", "==", email).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { const fooId = change.doc.id this.db.collection('owner').doc(fooId).update({status:'2'}); // do something with foo and fooId }) resolve(status); }); }) } getregister(){ this.platform.ready().then(()=>{ var res = this.resAsync().then(status=> this.status = status).then(()=> { if(this.status=='2'){ this.order() } } ) }) } async resAsync(){ let val = await this._res(); return val; } _res():Promise<any> { return new Promise<any>(resolve => { var res:any; var t_status; // var orderRef = this.db.collection('owner').where("email", "==", this.email).onSnapshot(querySnapshot => { // querySnapshot.docChanges.forEach(change => { // // const fooId = change.doc.id // this.db.collection('store').doc(fooId).update({service_status:'2'}); // // do something with foo and fooId // // }) // resolve(status); // }); var resRef = this.db.collection('owner').where("email","==", this.email).onSnapshot(function (querySnapshot) { querySnapshot.forEach(function (doc) { t_status = doc.data().status; console.log(t_status); } ); if(t_status==null){ t_status = '0'; resolve(t_status) }else{ resolve(t_status) } } ); }) } register_service(){ this.navCtrl.push('page-register-service', {email : this.email}); } order() { console.log("what the status", this.status); console.log("status22222") var store_a = this.storeAsync().then(store_a => this.store = store_a).then(() => { this.getOrder(); }) // } async storeAsync(){ let val = await this._store(); return val; } _store():Promise<any> { return new Promise<any>(resolve => { var store:Array<any>=[]; this.storeCollection=this.db.collection('store'); this.storeCollection.where("owner", "==", this.email) .onSnapshot(function (querySnapshot) { querySnapshot.forEach(function (doc) { store.push(doc.data().code); resolve(store); } ) } ); }) } getOrder(){ var menu_a = this.orderAsync().then(menu_a=> this.orders= menu_a) .then(()=>console.log(this.orders)); console.log(this.orders); } async orderAsync(){ let menu = await this._order(); return menu; } _order():Promise<any>{ return new Promise<any>(resolve => { var order: Array<any>=[]; this.orderCollection = this.db.collection("order"); console.log(this.store); var orderRef = this.orderCollection.where("store_code", "==", this.store[0]); console.log(orderRef) var button_col = "primary" var disablebtn= false; var orderInfo = orderRef.get() .then(snapshot => { snapshot.forEach(doc => { if(doc.data().status==false){ button_col="light" disablebtn= true; }else{ button_col ="primary" disablebtn = false; } order.push({ menu : doc.data().menu, totalPrice : doc.data().totalprice, status : doc.data().status, tableNum : doc.data().table_num, timeStamp : doc.data().timestamp, user : doc.data().user, store_code:doc.data().store_code, buttonColor :button_col, disableButton : disablebtn }); }); console.log("####", order); resolve(order); }) .catch(err => { console.log('Error getting documents', err); }); }) } confirm(index : any){ this.orders[index].status=false; this.orders[index].buttonColor = "light"; this.orders[index].disableButton = true; var orderRef = this.orderCollection.where("timestamp", "==", this.orders[index].timeStamp).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { //if (change.type === 'added' && change.doc._document.hasLocalMutations) { const fooId = change.doc.id this.orderCollection.doc(fooId).update({status : false}); // do something with foo and fooId //} }) }); // console.log(orderRef); // var a = orderRef.update({status:false}); } ///get doc // const usersRef = db.collection('users').doc('id') // // usersRef.get() // .then((docSnapshot) => { // if (docSnapshot.exists) { // usersRef.onSnapshot((doc) => { // // do stuff with the data // }); // } else { // usersRef.set({...}) // create the document // } // }); openRestaurantListPage(proptype) { this.navCtrl.push('page-restaurant-list', proptype); } openRestaurantFilterPage() { let modal = this.modalCtrl.create('page-restaurant-filter'); modal.present(); } openNearbyPage() { this.navCtrl.push('page-nearby'); } openOrders() { this.navCtrl.push('page-orders'); } openCart() { this.navCtrl.push('page-cart'); } openRestaurantDetail(restaurant: any) { this.navCtrl.push('page-restaurant-detail', { 'id': restaurant.id }); } openSettingsPage() { this.navCtrl.push('page-settings'); } openNotificationsPage() { this.navCtrl.push('page-notifications'); } openCategoryPage() { this.navCtrl.push('page-restaurant-list'); } onInput(event) { this.service.findByName(this.searchKey) .then(data => { this.restaurants = data; }) .catch(error => alert(JSON.stringify(error))); } onCancel(event) { this.findAll(); } findAll() { this.service.findAll() .then(data => this.restaurants = data) .catch(error => alert(error)); } alertLocation() { let changeLocation = this.locationCtrl.create({ title: 'Change Location', message: "Type your Address to change restaurant list in that area.", inputs: [ { name: 'location', placeholder: 'Enter your new Location', type: 'text' }, ], buttons: [ { text: 'Cancel', handler: data => { console.log('Cancel clicked'); } }, { text: 'Change', handler: data => { console.log('Change clicked', data); this.yourLocation = data.location; let toast = this.toastCtrl.create({ message: 'Location was change successfully', duration: 3000, position: 'top', closeButtonText: 'OK', showCloseButton: true }); toast.present(); } } ] }); changeLocation.present(); } presentNotifications(myEvent) { console.log(myEvent); let popover = this.popoverCtrl.create('page-notifications'); popover.present({ ev: myEvent }); } ionViewWillEnter() { this.navCtrl.canSwipeBack(); } } <file_sep>import { Component } from '@angular/core'; import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular'; import {RestaurantService} from "../../providers/restaurant-service-rest"; import * as firebase from "firebase"; /** * Generated class for the EventModPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name: 'page-event-mod', segment: 'event-mod' }) @Component({ selector: 'page-event-mod', templateUrl: 'event-mod.html', }) export class EventModPage { restaurants: Array<any>; map; markersGroup; noticeTitle : any; noticeContent : any; timeStamp:any; orders: Array<any> = []; public noticeCollection: any; public db = firebase.firestore(); constructor(public navCtrl: NavController, private alertCtrl: AlertController,public service: RestaurantService, public navParams: NavParams) { this.noticeTitle= this.navParams.get("title"); this.noticeContent= this.navParams.get("content"); this.timeStamp=this.navParams.get('timeStamp'); console.log(this.timeStamp) } presentAlert() { let alert = this.alertCtrl.create({ title: "Review edited", buttons: ['OK'] }); alert.present(); } addReview(){ var success = this.editReviewAsync().then(()=> this.presentAlert()).then(()=>{this.navCtrl.push('page-home');}).catch(); //console.log("result:",success); } async editReviewAsync(){ let review = await this._editreview(); return review; } _editreview():Promise<any>{ return new Promise<any>(resolve => { var success = "success"; var reviewRef = this.db.collection('event').where("timeStamp", "==", this.timeStamp).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { console.log(change) const reviewid = change.doc.id; this.db.collection('event').doc(reviewid).update({title: this.noticeTitle, content : this.noticeContent}); // do something with foo and fooId resolve(); }) }) // resolve(store); }) } } <file_sep>import {Component} from '@angular/core'; import { IonicPage, ActionSheetController, ActionSheet, NavController, NavParams, ToastController, AlertController, LoadingController } from 'ionic-angular'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; import {RestaurantService} from '../../providers/restaurant-service-mock'; import leaflet from 'leaflet'; import * as firebase from "firebase"; @IonicPage({ name: 'page-restaurant-detail' }) @Component({ selector: 'page-restaurant-detail', templateUrl: 'restaurant-detail.html' }) export class RestaurantDetailPage { noticeTitle: string; noticeContent: string; favorites: Array<any> = []; public db = firebase.firestore(); date : any; public onYourRestaurantForm: FormGroup; email: string; constructor(public loadingCtrl: LoadingController, public toastCtrl: ToastController, private _fb: FormBuilder,public navCtrl: NavController, public service: RestaurantService, private alertCtrl: AlertController) { // this.getFavorites(); // console.log(this.favorites); firebase.auth().onAuthStateChanged((user)=> { if (user) { this.email = user.email; console.log("%%email", this.email); } else { } }); } ngOnInit() { this.onYourRestaurantForm = this._fb.group({ restaurantTitle: ['', Validators.compose([ Validators.required ])], restaurantAddress: ['', Validators.compose([ Validators.required ])], }); } presentToast() { // send booking info let loader = this.loadingCtrl.create({ content: "Please wait..." }); // show message let toast = this.toastCtrl.create({ showCloseButton: true, cssClass: 'profiles-bg', message: 'Your event was registered!', duration: 3000, position: 'bottom' }); loader.present(); setTimeout(() => { loader.dismiss(); toast.present(); // back to home page this.navCtrl.setRoot('page-home'); }, 3000) } addReview(){ var success = this.addReviewAsync().then(()=> this.presentToast()).catch(); //console.log("result:",success); } async addReviewAsync(){ let review = await this._addreview(); return review; } _addreview():Promise<any>{ return new Promise<any>(resolve => { var success = "success"; this.date = new Date().toUTCString(); var addDoc = this.db.collection('event').add({ title : this.noticeTitle, content : this.noticeContent, timeStamp: this.date, owner: this.email }).then(ref=>{ resolve(success); console.log('Added document'); }) // resolve(store); }) } presentAlert() { let alert = this.alertCtrl.create({ title: "Event added", buttons: ['OK'] }); alert.present(); } } <file_sep>import { Component } from '@angular/core'; import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular'; import * as firebase from "firebase"; @IonicPage({ name: 'page-event', segment: 'event' }) @Component({ selector: 'page-event', templateUrl: 'event.html', }) export class EventPage { orders: Array<any> = []; public noticeCollection: any; public db = firebase.firestore(); title:any; content:any; email : any; sameowner : true; constructor(public navCtrl: NavController, public navParams: NavParams, public alert:AlertController) { this.getOrders(); firebase.auth().onAuthStateChanged((user)=> { if (user) { this.email = user.email; console.log("%%email", this.email); } else { } }); } getOrders(){ var menu_a = this.orderAsync().then(menu_a=> this.orders= menu_a) .then(()=>console.log(this.orders)); console.log(this.orders); } async orderAsync(){ let menu = await this._order(); return menu; } _order():Promise<any>{ return new Promise<any>(resolve => { var order: Array<any>=[]; this.noticeCollection = this.db.collection("event"); var orderInfo = this.noticeCollection.get() .then(snapshot => { snapshot.forEach(doc => { var same = false; if(this.email== doc.data().owner){ same = true; } order.push({ title : doc.data().title, timeStamp : doc.data().timeStamp, content : doc.data().content, valid : same }); }); console.log("####", order); resolve(order); }) .catch(err => { console.log('Error getting documents', err); }); }) } presentAlert(id) { let alert = this.alert.create({ title: "Do you really want to delete the event?", buttons: [ { text: 'No', handler: () => { console.log('Disagree clicked'); } }, { text: 'YES', handler: () => { this.deleteReview(id) } } ] }); alert.present(); } deleteReview(id){ var orderdoc_id = this.orders[id].timeStamp; var reviewRef = this.db.collection('event').where("timeStamp", "==", orderdoc_id).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { const reviewid = change.doc.id; this.db.collection('event').doc(reviewid).delete().then(()=>this.presentAlert2()).then(()=>this.navCtrl.setRoot('page-home')).catch(err=> console.log("error")); // do something with foo and fooId //resolve(); }) }) } updateOrder(id) { var orderdoc_id = this.orders[id].timeStamp; this.navCtrl.push('page-nearby', {'content':this.orders[id].content, 'title':this.orders[id].title, 'timeStamp':orderdoc_id}); } presentAlert2() { let alert = this.alert.create({ title: "Deletion is completed", buttons: ["OK"] }); alert.present(); } openCategoryPage() { this.navCtrl.push('page-restaurant-detail'); } readmore(id){ this.navCtrl.push('page-checkout', {'content': this.orders[id].content,'title':this.orders[id].title, 'timeStamp':this.orders[id].timeStamp }); } } <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { AlertController } from 'ionic-angular'; import * as firebase from "firebase"; import 'firebase/firestore'; /** * Generated class for the EditMenuPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name:'page-edit-menu' }) @Component({ selector: 'page-edit-menu', templateUrl: 'edit-menu.html', }) export class EditMenuPage { store : any; menu: any; time: any; date : any; code : any; id: any; //menuDoc_id menus :Array<any>=[]; public db = firebase.firestore(); constructor(public navCtrl: NavController, public navParams: NavParams, private alert: AlertController) { this.id = this.navParams.get("id"); this.openMenus() } getstorename(){ for(let i=0; i<this.menus.length; i++){ var menu_a= this.storeAsync(this.menus[i].code).then(name => this.menus[i].store= name).then(()=> console.log(this.menus[i].store)) } // var menu_a = this.storeAsync().then(menu_a=> this.store= menu_a) // .then(()=>console.log(this.store)).catch(); } async storeAsync(code){ let menu = await this._store(code); return menu; } _store(code):Promise<any>{ return new Promise<any>(resolve => { var store:any; this.db.collection("store").where("code", "==",code).get() .then(snapshot => { snapshot.forEach(doc => { store = doc.data().name }); resolve(store); }) .catch(err => { console.log('Error getting documents', err); }); // resolve(store); }) } async getMenuAsync(){ let text = await this._getMenu(); return text; } _getMenu():Promise<any>{ return new Promise<any>(resolve => { var text:Array<any>=[]; var menuRef = this.db.collection('menu').where("owner_id", "==", firebase.auth().currentUser.email); var menuinfo = menuRef.get() .then(snapshot => { snapshot.forEach(doc => { text.push({ price : doc.data().price, name : doc.data().menu, code: doc.data().store_code, id : doc.data().id }) }); console.log(text); resolve(text); }) .catch(err => { console.log('Error getting documents', err); }); // resolve(store); }) } openMenus(){ var review_a = this.getMenuAsync().then(text=> this.menus= text).then(()=>this.getstorename()); } editMenu(id){ this.navCtrl.push('page-write-edit-menu',{ 'name': this.menus[id].name, 'price': this.menus[id].price, 'id': this.menus[id].id }) } presentAlert(id) { let alert = this.alert.create({ title: "Do you really want to delete the Menu?", buttons: [ { text: 'No', handler: () => { console.log('Disagree clicked'); } }, { text: 'YES', handler: () => { this.deleteMenu(id) } } ] }); alert.present(); } deleteMenu(id){ var docid = this.menus[id].id var reviewRef = this.db.collection('menu').where("id", "==", docid).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { const reviewid = change.doc.id; console.log(id,"$$$$$$$$$$$$$$$$$$"); this.db.collection('menu').doc(reviewid).delete().then(()=>this.navCtrl.push('page-home')).catch(err=> console.log("error")); }) }) } // presentAlert2() { // // let alert = this.alert.create({ // title: "Deleted Menu", // buttons: ["OK"] // }); // alert.present(); // } ionViewDidLoad() { console.log('ionViewDidLoad EditMenuPage'); } } <file_sep>import {Component} from '@angular/core'; import {IonicPage, NavController} from 'ionic-angular'; import {DishService} from '../../providers/dish-service-mock'; import * as firebase from "firebase"; import 'firebase/firestore'; @IonicPage({ name: 'page-dish-list', segment: 'dish-list' }) @Component({ selector: 'page-dish-list', templateUrl: 'dish-list.html' }) export class DishListPage { dishes: Array<any>=[]; orders: Array<any>=[]; stores: Array<any>=[]; code : Array<any>=[]; public reviewCollection :any; public storeCollection : any; public db = firebase.firestore(); public user:any; store_code : any; reviews : Array<any>=[]; constructor(public navCtrl: NavController, public dishService: DishService) { //this.dishes = this.dishService.findAll(); this.openReviewList(); } // async storeAsync(){ let storelist = await this._codelist(); return storelist; } _codelist():Promise<any>{ return new Promise<any>(resolve => { var store_code: any; this.user = firebase.auth().currentUser.email; this.storeCollection = this.db.collection("store"); this.user = this.user.toString(); var orderRef = this.storeCollection.where("owner", "==", this.user); var orderinfo = orderRef.get() .then(snapshot => { snapshot.forEach(doc => { store_code = doc.data().code; }); resolve(store_code); }) .catch(err => { console.log('Error getting documents', err); }); // resolve(store); }) } async reviewListAsync(code){ let reviewlist = await this._reviewlist(code); return reviewlist; } _reviewlist(code):Promise<any>{ return new Promise<any>(resolve => { var reviews: Array<any>=[]; // var store_code : any; //this.user = firebase.auth().currentUser.email; //this.storeCollection = this.db.collection("store"); //this.user = this.user.toString(); // console.log(code); var reviewRef = this.db.collection("review").where("store_code", "==", code); var storeinfo = reviewRef.get() .then(snapshot => { snapshot.forEach(doc => { reviews.push({ content : doc.data().content, menu : doc.data().menu, star : doc.data().star, time : doc.data().time, user_id : doc.data().user_id }) }); //console.log(store); resolve(reviews); }) .catch(err => { console.log('Error getting documents', err); }); // resolve(); // resolve(store); } ) } openReviewList(){ var menu_a = this.storeAsync().then(code=> this.store_code= code) .then(()=>this.reviewListAsync(this.store_code)) .then((reviews)=> this.reviews = reviews) .catch(); // this.user = firebase.auth().currentUser.email; // console.log(this.user); } // openDishDetail(dish) { // // this.navCtrl.push('page-dish-detail', { // // 'id': dish.id // // }); // } } <file_sep>import { Component } from '@angular/core'; import {IonicPage, LoadingController, NavController, NavParams, ToastController} from 'ionic-angular'; import { AlertController } from 'ionic-angular'; import * as firebase from "firebase"; import 'firebase/firestore'; import { FormGroup, Validators, FormBuilder } from '@angular/forms'; /** * Generated class for the WriteEditMenuPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name:'page-write-edit-menu' }) @Component({ selector: 'page-write-edit-menu', templateUrl: 'write-edit-menu.html', }) export class WriteEditMenuPage { store : any; menu: any; time: any; date : any; name : any; price : any; id: any; public db = firebase.firestore(); menu_price : any; menu_name: any; code : any; public onYourRestaurantForm: FormGroup; constructor(public loadingCtrl: LoadingController, public toastCtrl: ToastController, private _fb: FormBuilder,public navCtrl: NavController, public navParams: NavParams ,private alertCtrl: AlertController) { this.name = this.navParams.get("name"); this.price = this.navParams.get("price"); this.id = this.navParams.get("id") } ngOnInit() { this.onYourRestaurantForm = this._fb.group({ restaurantTitle: ['', Validators.compose([ Validators.required ])], restaurantAddress: ['', Validators.compose([ Validators.required ])], }); } presentToast() { // send booking info let loader = this.loadingCtrl.create({ content: "Please wait..." }); // show message let toast = this.toastCtrl.create({ showCloseButton: true, cssClass: 'profiles-bg', message: 'Your Menu was changed!', duration: 3000, position: 'bottom' }); loader.present(); setTimeout(() => { loader.dismiss(); toast.present(); // back to home page this.navCtrl.setRoot('page-home'); }, 3000) } onModelChange(event){ console.log(event); } async editMenuAsync(){ let menus = await this._editmenu(); return menus; } _editmenu():Promise<any>{ return new Promise<any>(resolve => { var success = "success"; this.date = new Date().toUTCString(); //var orderid = this.id; var code = this.code; var reviewRef = this.db.collection('menu').where("id", "==", this.id).onSnapshot(querySnapshot => { querySnapshot.docChanges.forEach(change => { const reviewid = change.doc.id; this.db.collection('menu').doc(reviewid).update({menu: this.menu_name, price : this.menu_price}); // do something with foo and fooId resolve(); }) }) // resolve(store); }) } presentAlert() { let alert = this.alertCtrl.create({ title: "Menu edited", buttons: ['OK'] }); alert.present(); } addReview(){ var success = this.editMenuAsync().then(()=> this.presentToast()).catch(); console.log("result:",success); } ionViewDidLoad() { console.log('ionViewDidLoad WriteEditMenuPage'); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { WriteEditMenuPage } from './write-edit-menu'; import {EditMenuPage} from "../edit-menu/edit-menu"; @NgModule({ declarations: [ WriteEditMenuPage, ], imports: [ IonicPageModule.forChild(WriteEditMenuPage), ], exports: [ WriteEditMenuPage ] }) export class WriteEditMenuPageModule {} <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { RestaurantListPage } from './restaurant-list'; import { PipesModule } from '../../pipes/pipes.module'; @NgModule({ declarations: [ RestaurantListPage ], imports: [ IonicPageModule.forChild(RestaurantListPage), PipesModule ], exports: [ RestaurantListPage ] }) export class RestaurantListPageModule { } <file_sep>import { Component ,OnInit} from '@angular/core'; import {IonicPage, LoadingController, NavController, NavParams, ToastController} from 'ionic-angular'; import { AlertController } from 'ionic-angular'; import * as firebase from "firebase"; import 'firebase/firestore'; import { FormBuilder, FormArray, FormGroup, Validators } from '@angular/forms'; /** * Generated class for the CreateMenuPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage({ name:'page-create-menu' }) @Component({ selector: 'page-create-menu', templateUrl: 'create-menu.html', }) export class CreateMenuPage { date : any; store : any; menuprice: any; menuname : any; storecode : any; code : any; id: any; public db = firebase.firestore(); public menuform : FormGroup; constructor(public loadingCtrl: LoadingController, public toastCtrl: ToastController,private _fb: FormBuilder,public navCtrl: NavController, public navParams: NavParams ,private alertCtrl: AlertController) { this.code = this.navParams.get("code"); this.menuform = this._fb.group({ storecode: ['', Validators.required ], menus : this._fb.array([ this.initmenu() ]) }); } initmenu():FormGroup { return this._fb.group( { menuName :['', Validators.required], menuPrice :['', Validators.required] } ); } addNewMenufield():void { const control =<FormArray>this.menuform.controls.menus; control.push(this.initmenu()); } removeMenufield(i: number) : void { const control =<FormArray>this.menuform.controls.menus; control.removeAt(i); } manage(val : any) : void { console.dir(val); } onModelChange(event){ console.log(event); } async addMenuAsync(data){ let menus = await this._addmenu(data); return menus; } _addmenu(data):Promise<any>{ return new Promise<any>(resolve => { var success = "success"; let menuvalue = data; this.date = new Date().toUTCString(); // this.id = this.id.toString(); var addDoc = this.db.collection('menu').add({ // orderDoc_id : this.id, menu : menuvalue.menuName, price : parseInt(menuvalue.menuPrice), time: this.date, owner_id : firebase.auth().currentUser.email, // store_name:this.store, store_code : this.storecode, id:"", status :0 }).then(function(docRef) { console.log("Document written with ID: ", docRef.id); // var docid = docRef.id.toString() var setid = docRef.update({ id: docRef.id.toString() }) resolve(success); console.log('Added document'); }); // resolve(store); }) } // updateMenu() { // // var orderRef = this.db.collection('order').where("id", "==", this.id).onSnapshot(querySnapshot => { // querySnapshot.docChanges.forEach(change => { // // const fooId = change.doc.id // this.db.collection('order').doc(fooId).update({review: true}); // // do something with foo and fooId // // }) // }); // } presentAlert() { let alert = this.alertCtrl.create({ title: "Menu added", buttons: ['OK'] }); alert.present(); } presentToast() { // send booking info let loader = this.loadingCtrl.create({ content: "Please wait..." }); // show message let toast = this.toastCtrl.create({ showCloseButton: true, cssClass: 'profiles-bg', message: 'Your menus are registered!', duration: 3000, position: 'bottom' }); loader.present(); setTimeout(() => { loader.dismiss(); toast.present(); // back to home page this.navCtrl.setRoot('page-home'); }, 3000) } addMenu(){ // var success = this.addMenuAsync().then(()=> this.presentAlert()).then(()=>{this.navCtrl.push('page-home');}).catch(); for(let i=0; i<this.menuform.controls.menus.value.length;i++ ){ console.log("&&&&&", this.menuform.controls.menus.value[i]); var menuadd = this.addMenuAsync(this.menuform.controls.menus.value[i]) } return this.presentToast(); } ionViewDidLoad() { console.log('ionViewDidLoad CreateMenuPage'); } }
a3ded068a2b34912140841a3b588d71b8cd91d9d
[ "TypeScript" ]
17
TypeScript
Juyounglee95/easyOrderBusiness
6ffe6385c2042f5b3c2023009312dd29e012a3a5
db95da5c74b9599daa0b8904b7e6ad5aec67b272
refs/heads/main
<file_sep>import axios, { AxiosInstance } from 'axios'; import { createError } from './errors'; import { EVERY_NODE_VERSION } from './version'; export enum EverifyApiError { 'InvalidBodyError' = 'InvalidBodyError', 'NoProjectFoundError' = 'NoProjectFoundError', 'InternalVerificationStartError' = 'InternalVerificationStartError', 'NoCurrentlyActiveVerificationError' = 'NoCurrentlyActiveVerificationError', } export interface EverifyConstructorArgs { sandbox?: boolean; baseUrl?: string; } export interface EverifyStartVerificationArgs { phoneNumber: string; method?: 'SMS'; locale?: string; sandbox?: boolean; } export interface EverifyCheckVerificationArgs { phoneNumber: string; code: string; } export type EverifyStartVerificationResponse = { locale: string; phoneNumber: string; sandbox?: boolean; id: string; createdAt: string; expiresAt: string; status: 'PENDING'; }; export type EverifyCheckVerificationResponse = { status: 'PENDING' | 'SUCCESS'; }; const getAxiosInstance = ({ baseUrl, apiKey, }: { baseUrl: string; apiKey: string; }) => { const instance = axios.create({ baseURL: baseUrl, timeout: 5000, headers: { 'X-Everify-Client': `everify-node@${EVERY_NODE_VERSION}`, Authorization: `Bearer ${apiKey}`, }, }); instance.interceptors.response.use( (res) => res, (err) => { const contentType = err.response?.headers?.['content-type']; if (!contentType || !contentType.includes('application/json')) { if (err.response) { throw new Error( `Invalid Server response. Status ${err.response.status}. Data: ${err.response.data}` ); } throw err; } throw createError(err.response.data); } ); return instance; }; export class Everify { private sandboxEnabled: boolean; private axiosClient: AxiosInstance; constructor( apiKey: string, { sandbox = false, baseUrl = 'https://everify.dev/api', }: EverifyConstructorArgs | undefined = {} ) { this.sandboxEnabled = sandbox; this.axiosClient = getAxiosInstance({ baseUrl, apiKey }); } public sandbox(on: boolean | undefined = true) { this.sandboxEnabled = on; } public async startVerification({ phoneNumber, method = 'SMS', locale, sandbox: forceSandbox, }: EverifyStartVerificationArgs) { const body = { phoneNumber, method, locale, sandbox: forceSandbox ?? this.sandboxEnabled, }; const response = await this.axiosClient.post<EverifyStartVerificationResponse>( 'verifications/start', body ); return response.data; } public async checkVerification({ phoneNumber, code, }: EverifyCheckVerificationArgs) { const body = { phoneNumber, code, }; const response = await this.axiosClient.post<EverifyCheckVerificationResponse>( 'verifications/check', body ); return response.data; } } <file_sep># Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### [0.0.8](https://github.com/everify/everify-node/compare/v0.0.7...v0.0.8) (2021-02-17) ### [0.0.7](https://github.com/everify/everify-node/compare/v0.0.6...v0.0.7) (2021-02-16) ### [0.0.6](https://github.com/everify/everify-node/compare/v0.0.5...v0.0.6) (2021-02-11) ### [0.0.5](https://github.com/everify/everify-node/compare/v0.0.4...v0.0.5) (2021-02-11) ### [0.0.4](https://github.com/everify/everify-node/compare/v0.0.3...v0.0.4) (2021-02-11) ### [0.0.3](https://github.com/everify/everify-node/compare/v0.0.2...v0.0.3) (2021-02-10) ### 0.0.2 (2021-02-10) <file_sep>export const EVERY_NODE_VERSION = '0.0.1'; <file_sep>export * from './lib/client'; import { Everify } from './lib/client'; export default Everify; <file_sep>export const createError = ({ name, message, ...rest }: { name: string; message: string; [key: string]: string; }) => { function EverifyError(this: any, name: string, message: string, rest = {}) { if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = name; this.message = message; Object.assign(this, rest); } EverifyError.prototype = Object.create(Error.prototype); EverifyError.prototype.constructor = EverifyError; EverifyError.prototype.name = name; // @ts-ignore return new EverifyError(name, message, rest); }; <file_sep># everify-node Node client for the Everify API - secure SMS verification made simple
ff90021eaa34dfaf83f3bde2c14308505492ff25
[ "Markdown", "TypeScript" ]
6
TypeScript
everify/everify-node
d71765f5376080a85998061a2b1458e85d591c19
b53c02a5ede5fac8252bb4244de33aef24ecc5a0
refs/heads/main
<repo_name>Mehulrastogi101/Student-Leaderboard<file_sep>/AlmaBetter____Student Leaderboard/Student_Records/Student_Portal/migrations/0003_auto_20210523_0028.py # Generated by Django 3.1 on 2021-05-22 18:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Student_Portal', '0002_auto_20210522_1305'), ] operations = [ migrations.AddField( model_name='addstudent', name='Percentage', field=models.FloatField(default=35), preserve_default=False, ), migrations.AddField( model_name='addstudent', name='Tmarks', field=models.IntegerField(default=150), preserve_default=False, ), ] <file_sep>/AlmaBetter____Student Leaderboard/Student_Records/Student_Portal/migrations/0001_initial.py # Generated by Django 3.1 on 2021-05-22 06:59 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AddStudent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Name', models.IntegerField()), ('Rollno', models.IntegerField()), ('Math', models.IntegerField()), ('Physics', models.IntegerField()), ('Chemistry', models.IntegerField()), ], ), ] <file_sep>/AlmaBetter____Student Leaderboard/Student_Records/Student_Portal/models.py from django.db import models from django.conf import settings class AddStudent(models.Model): Name = models.CharField(max_length=50) Rollno = models.IntegerField() Math = models.IntegerField() Physics = models.IntegerField() Chemistry = models.IntegerField() Tmarks = models.IntegerField() Percentage = models.FloatField() <file_sep>/AlmaBetter____Student Leaderboard/Student_Records/Student_Portal/views.py from django.shortcuts import render from django.contrib import messages from Student_Portal.models import AddStudent from django.db.models import Sum # Create your views here. def home(request): return render(request, "Home.html") def add(request): return render(request, "Add-student-record.html") def leaderboard(request): addstudent = AddStudent.objects.all() return render(request, "Student-Leaderboard.html",{'addstudent':addstudent}) def added(request): if request.method == "POST": Tmarks = [] Name = request.POST['Name'] Rollno = request.POST['Rollno'] Math = int(request.POST['Math']) print(Math) Physics = int(request.POST['Physics']) Chemistry = int(request.POST['Chemistry']) Tmarks = Math + Physics + Chemistry print(Tmarks) Percentage = round((Tmarks/300)*100,2) print(Percentage) clog = AddStudent(Chemistry = Chemistry,Physics = Physics, Math = Math,Rollno= Rollno,Name=Name,Tmarks=Tmarks,Percentage=Percentage) clog.save() return render(request, "Add-student-record.html") <file_sep>/AlmaBetter____Student Leaderboard/Student_Records/Student_Portal/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('add', views.add, name='add'), path('added',views.added,name ='added'), path('leaderboard',views.leaderboard,name ='leaderboard') ] <file_sep>/README.md # This is an assignment for Full Stack Developer Internship (AlmaBetter) ## Stack Technology:- 1.)Frontend- HTML & CSS 2.)Backend- Python (Django Framework) 3.)Database- MySQL 4.)Deployed on- Heroku ## LIVE SERVER LINK:- Application Link=>https://student125643.herokuapp.com/
4e52045767b96b83b7ac9d07182c12d57f035f87
[ "Markdown", "Python" ]
6
Python
Mehulrastogi101/Student-Leaderboard
59d571e5a40891bb91e09ba90c9cbc661b8d094e
52442e78ee384346a73f456b0ce1fe76909e2321
refs/heads/master
<file_sep>package ru.job4j.chess.figures.black; import ru.job4j.chess.behaviors.NoMove; import ru.job4j.chess.figures.Cell; import ru.job4j.chess.figures.Figure; public class QueenBlack extends Figure { /** * Constructs QueenBlack with specified position. * @param position position on board */ public QueenBlack(Cell position) { super(position, new NoMove()); } } <file_sep>package ru.job4j.sqltoxml; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class ConfigTest { @Test public void whenInitThenLoadsPropertiesFromSpecifiedFile() { Config config = new Config(); config.init(); String url = config.get("url"); assertThat(url, startsWith("jdbc:sqlite:")); } } <file_sep>package ru.job4j.tracker; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; /** * Contains all actions available to users. */ public class MenuTracker { /** * Input system. */ private final Input input; /** * Tracker of items. */ private final ITracker tracker; /** * Link to object that manages the program cycle. * It should be used to exit the program. */ private StartUI startUI; /** * Consumer used for output of messages. */ private final Consumer<String> console; /** * List af actions available in the menu. */ private final List<UserAction> actions = new ArrayList<>(); /** * Constructs menu. * @param input input system * @param tracker tracker of items */ public MenuTracker(Input input, ITracker tracker, Consumer<String> console) { this.input = input; this.tracker = tracker; this.console = console; initializeActions(); } /** * Initializes the menu with available actions. */ private void initializeActions() { actions.add(new AddItem(0, "Add new Item")); actions.add(new ShowAllItems(1, "Show all items")); actions.add(new MenuTracker.EditItem(2, "Edit item", this)); actions.add(new MenuTracker.DeleteItem(3, "Delete item", this)); actions.add(new FindItemById(4, "Find item by Id", this)); actions.add(new FindItemsByName(5, "Find items by name", this)); actions.add(new ExitApp(6, "Exit Program")); } /** * Sets the object managing the program cycle. * @param startUI managing object */ public void setUI(StartUI startUI) { this.startUI = startUI; } /** * Gets the range corresponding to menu keys. * @return range of keys */ public int[] getKeyRange() { int[] range = new int[actions.size()]; for (int i = 0; i < range.length; i++) { range[i] = actions.get(i).key(); } return range; } /** * Selects action by specified key. * @param key value of key */ public void select(int key) { actions.get(key).execute(this.input, this.tracker); } /** * Shows the menu. */ public void show() { console.accept(""); console.accept("Menu."); for (UserAction action : actions) { console.accept(action.info()); } } /** * Prints caption using specified text. * @param text text */ public void printCaption(String text) { console.accept(String.format("------------%s------------", text)); } /** * Prints message to console associated with this menu. * @param text message */ public void print(String text) { console.accept(text); } /** * Implements action of exiting application. * Uses {@link MenuTracker#startUI} field of outer class. */ private class ExitApp extends BaseAction { /** * Creates an instance of {@code ExitApp}. * @param key value of key * @param info descriptive information */ public ExitApp(int key, String info) { super(key, info); } @Override public void execute(Input input, ITracker tracker) { MenuTracker.this.startUI.exit(); } } /** * Implements action of adding new item. */ private class AddItem extends BaseAction { /** * Constructs instance of {@code AddItem}. * @param key value of key * @param info descriptive information */ public AddItem(int key, String info) { super(key, info); } @Override public void execute(Input input, ITracker tracker) { printCaption("Creating new item"); String name = input.ask("Enter name: "); String description = input.ask("Enter description: "); Item item = new Item(name, description, System.currentTimeMillis()); item = tracker.add(item); console.accept("Created item:"); console.accept(item.toString()); } } /** * Implements action of displaying all items. */ private class ShowAllItems extends BaseAction { /** * Constructs instance of {@code ShowAllItems}. * @param key value of key * @param info descriptive information */ public ShowAllItems(int key, String info) { super(key, info); } @Override public void execute(Input input, ITracker tracker) { printCaption("List of all items"); List<Item> all = tracker.findAll(); for (Item item : all) { console.accept(item.toString()); } } } /** * Implements action of editing existing item. */ private static class EditItem extends MenuAction { /** * Constructs instance of {@code EditItem}. * @param key value of key * @param info descriptive information * @param menu menu object used as user interface */ public EditItem(int key, String info, MenuTracker menu) { super(key, info, menu); } @Override public void execute(Input input, ITracker tracker) { printCaption("Editing item"); String id = input.ask("Enter id: "); String name = input.ask("Enter new name: "); String description = input.ask("Enter new description: "); if (tracker.replace(id, new Item(name, description, System.currentTimeMillis()))) { print("Item modified."); } else { print("Item not found."); } } } /** * Implements action of deleting existing item. */ private static class DeleteItem extends MenuAction { /** * Constructs instance of {@code DeleteItem}. * @param key value of key * @param info descriptive information * @param menu menu object used as user interface */ public DeleteItem(int key, String info, MenuTracker menu) { super(key, info, menu); } @Override public void execute(Input input, ITracker tracker) { printCaption("Deleting item"); String id = input.ask("Enter id: "); if (tracker.delete(id)) { print("Item deleted."); } else { print("Item not found."); } } } } /** * Implements action of finding existing item by id. */ class FindItemById extends MenuAction { /** * Constructs instance of {@code FindItemById}. * @param key value of key * @param info descriptive information * @param menu menu object used as user interface */ public FindItemById(int key, String info, MenuTracker menu) { super(key, info, menu); } @Override public void execute(Input input, ITracker tracker) { printCaption("Finding item by id"); String id = input.ask("Enter id: "); Item found = tracker.findById(id); if (found != null) { print("Found item:"); print(found.toString()); } else { print("Item not found."); } } } /** * Implements action of finding existing items by name. */ class FindItemsByName extends MenuAction { /** * Constructs instance of {@code FindItemsByName}. * @param key value of key * @param info descriptive information * @param menu menu object used as user interface */ public FindItemsByName(int key, String info, MenuTracker menu) { super(key, info, menu); } @Override public void execute(Input input, ITracker tracker) { printCaption("Finding item by name"); String name = input.ask("Enter name: "); List<Item> items = tracker.findByName(name); if (items.size() > 0) { for (Item item : items) { print(item.toString()); } } else { print("Items not found."); } } } <file_sep>package ru.job4j.collections.queue; import ru.job4j.collections.stack.SimpleStack; /** * Simple implementation of first-in-first-out (FIFO) queue data structure * that uses two stacks as underlying containers. */ public class SimpleQueue<T> { private final SimpleStack<T> stackIn = new SimpleStack<>(); private final SimpleStack<T> stackOut = new SimpleStack<>(); /** * Adds the specified element to the queue. * @param value element to add */ public void push(T value) { stackIn.push(value); } /** * Returns and removes the first element in the queue. * @return first element or null is the queue is empty */ public T poll() { if (stackOut.isEmpty()) { while (!stackIn.isEmpty()) { stackOut.push(stackIn.poll()); } } return stackOut.poll(); } } <file_sep>package ru.job4j.ood.menu; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class MenuTest { private static final String NL = System.lineSeparator(); @Test public void display() { StringBuilder buffer = new StringBuilder(); ToStringRenderer renderer = new ToStringRenderer(" ", buffer::append, NL); Menu menu = new Menu("item_1", renderer); menu.addItem(new SimpleMenuItem("item_1.1")); menu.addItem(new SimpleMenuItem("item_1.2")); Menu subMenu1 = new Menu("item_1.3"); menu.addItem(subMenu1); subMenu1.addItem(new SimpleMenuItem("item_1.3.1")); subMenu1.addItem(new SimpleMenuItem("item_1.3.2")); Menu subMenu2 = new Menu("item_1.4"); menu.addItem(subMenu2); subMenu2.addItem(new SimpleMenuItem("item_1.4.1")); subMenu2.addItem(new SimpleMenuItem("item_1.4.2")); String expected = String.join(NL, "item_1", " item_1.1", " item_1.2", " item_1.3", " item_1.3.1", " item_1.3.2", " item_1.4", " item_1.4.1", " item_1.4.2", "" ); menu.display(); assertThat(buffer.toString(), is(expected)); } } <file_sep>package ru.job4j.ood.carparking; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents parking service that can serve vehicles of different sizes. */ public class Parking { public static final int DEFAULT_CAR_SIZE = 1; public static final int DEFAULT_TRUCK_SIZE = 4; /** Algorithm that finds parking space for any parked vehicle. */ private final SpaceFinder finder; /** Spaces occupied by parked vehicles. */ private final Map<Long, ParkingSpace> occupiedSpaces = new HashMap<>(); /** Vehicles currently parked in this parking. */ private final Map<ParkingSpace, Vehicle> parkedVehicles = new HashMap<>(); /** * Initializes the parking with the specified number of parking spots. * @param numCarPlaces number of car parking spots * @param numTruckPlaces number of truck parking spots * @param finder finder that helps to find free spots */ public Parking(int numCarPlaces, int numTruckPlaces, SpaceFinder finder) { this.finder = finder; this.finder.setSpots(initSpots(numCarPlaces, numTruckPlaces)); } private List<Spot> initSpots(int numCarPlaces, int numTruckPlaces) { List<Spot> spots = new ArrayList<>(); for (int i = 0; i < numCarPlaces; i++) { spots.add(new Spot(DEFAULT_CAR_SIZE)); } for (int i = 0; i < numTruckPlaces; i++) { spots.add(new Spot(DEFAULT_TRUCK_SIZE)); } return spots; } /** * Accepts the parking vehicle. * @param vehicle vehicle to park * @return ticket that should be used for getting the vehicle back */ public Ticket driveIn(Vehicle vehicle) { ParkingSpace space = finder.findSpaceFor(vehicle); if (space == null) { return null; } space.occupyWith(vehicle); occupiedSpaces.put(space.getId(), space); parkedVehicles.put(space, vehicle); return new Ticket(vehicle.getId(), space.getId()); } /** * Gives back the parked vehicle using info from the specified ticket. * @param ticket ticket received when driving in the parking * @return vehicle parked vehicle or null if nothing found */ public Vehicle leave(Ticket ticket) { ParkingSpace space = occupiedSpaces.get(ticket.getParkingSpaceId()); if (space == null) { return null; } Vehicle vehicle = parkedVehicles.get(space); if (vehicle == null) { throw new IllegalStateException("Cannot find vehicle"); } if (!vehicle.getId().equals(ticket.getVehicleId())) { throw new IllegalStateException("Vehicle's IDs do not match"); } space.free(); occupiedSpaces.remove(space.getId()); parkedVehicles.remove(space); return vehicle; } } <file_sep>package ru.job4j.chess.behaviors; import ru.job4j.chess.exceptions.ImpossibleMoveException; import ru.job4j.chess.figures.Cell; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Moving only diagonally. */ public class DiagonalMove implements MovingBehavior { @Override public Cell[] way(Cell source, Cell dest) throws ImpossibleMoveException { if (!isDiagonal(source, dest)) { throw new ImpossibleMoveException(source, dest); } int x = source.x; int y = source.y; Cell[] steps = new Cell[Math.abs(dest.x - x)]; int deltaX = x < dest.x ? 1 : -1; int deltaY = y < dest.y ? 1 : -1; return IntStream.range(1, steps.length + 1) .mapToObj(i -> Cell.findByXY(x + i * deltaX, y + i * deltaY)) .collect(Collectors.toList()).toArray(steps); } private boolean isDiagonal(Cell source, Cell dest) { return Math.abs(source.x - dest.x) == Math.abs(source.y - dest.y); } } <file_sep>package ru.job4j.jmm.gc; /** * Принуждает Garbage Collector выполнить сборку мусора если запустить * с ограничением максимального размера хипа (опция -Xmx).<br> */ public class ForceGarbageCollection { public static void main(String[] args) throws Exception { System.out.println("start"); int numObjects = 64_000; if (args.length == 1) { numObjects = Integer.parseInt(args[0]); } long delay = 1L; if (args.length == 2) { delay = Long.parseLong(args[1]); } for (int i = 0; i < numObjects; i++) { new User(i); if (delay > 0) { Thread.sleep(delay); } } System.out.println("finish"); } } <file_sep>package ru.job4j.ood.calculator; import org.junit.Test; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class SimpleExpressionParserTest { public static final double DELTA = 1e-15; @Test public void whenParseOneNumberThenReturnNumberExpression() { ExpressionParser parser = new SimpleExpressionParser(null, null); Expression actual = parser.parse("32.1"); NumberExpression expected = new NumberExpression(32.1); assertThat(actual, is(expected)); } @Test public void whenParseTwoOperandsThenReturnsArithmeticExpression() { ExpressionParser parser = new SimpleExpressionParser( (op1, operation, op2) -> op1 + op2, null); Expression result = parser.parse("3.0 + 2"); assertThat(result.evaluate(), closeTo(5.0, DELTA)); } @Test public void whenParseFunctionThenReturnsFunctionExpression() { SimpleExpressionParser parser = new SimpleExpressionParser( null, (name, argument) -> Math.sin(Math.toRadians(argument))); Expression result = parser.parse("sin(30)"); assertThat(result.evaluate(), closeTo(0.5, DELTA)); } } <file_sep>package ru.job4j.vacparser.storage; import ru.job4j.vacparser.model.Vacancy; import java.sql.SQLException; import java.util.List; /** * Storage of vacancies that can perform operations of adding and finding vacancies. */ public interface Storage { /** * Adds the specified vacancy to the storage. * @param vacancy vacancy object * @return vacancy object whose id is assigned * @throws SQLException if database error occurs */ Vacancy add(Vacancy vacancy) throws SQLException; /** * Adds all the specified vacancies to the storage. * @param vacancies list of vacancies * @throws SQLException if database error occurs */ void addAll(List<Vacancy> vacancies) throws SQLException; /** * Finds all vacancies in the storage. * @return list of found vacancies * @throws SQLException if database error occurs */ List<Vacancy> findAll() throws SQLException; /** * Tries to find a vacancy the the specified name. * @param name name of the vacancy * @return found vacancy or null * @throws SQLException if database error occurs */ Vacancy findByName(String name) throws SQLException; /** * Tries to find a vacancy the the specified id. * @param id id of the vacancy * @return found vacancy or null * @throws SQLException if database error occurs */ Vacancy findById(int id) throws SQLException; /** * Tries to find last vacancy in the storage. * The vacancy with the last modification time is considered the last vacancy. * @return last vacancy object or null if the storage is empty * @throws SQLException if database error occurs */ Vacancy findLast() throws SQLException; } <file_sep>package ru.job4j.ood.tictac; import java.io.PrintStream; /** * Output that can be used on standard console. */ public class ConsoleOutput implements Output { private final GridFormatter formatter; private final PrintStream printStream; /** Constructs the formatter instance using specified formatter and printStream. */ public ConsoleOutput(GridFormatter formatter, PrintStream printStream) { this.formatter = formatter; this.printStream = printStream; } /** Prints the specified game grid. */ @Override public void printGrid(GridView grid) { printStream.print(formatter.format(grid)); } /** Prints the specified message. */ @Override public void print(String message) { printStream.print(message); } /** Prints the specified message and newline symbol. */ @Override public void println(String message) { printStream.println(message); } } <file_sep>package ru.job4j.vacparser.parsers; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; /** * Parser of date time input. * Examples of allowed formats:<br> * 3 май 19, 19:53<br> * сегодня, 09:03<br> * вчера, 09:03 */ public class DateTimeParser { public static final List<String> MONTHS = List.of( "янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек" ); private static final int YEAR_PREFIX = LocalDate.now().getYear() / 100; /** * Parses the specified date time input. * @param dateTime date time as in the examples in this {@link DateTimeParser} class comment * @return date time without time zone */ public LocalDateTime parse(String dateTime) { String[] tokens = dateTime.split(", "); if (tokens.length != 2) { throw new IllegalArgumentException("Illegal date time format: " + dateTime); } LocalDate date = parseDate(tokens[0]); LocalTime time = LocalTime.parse(tokens[1]); return LocalDateTime.of(date, time); } /** Parses date input. */ private LocalDate parseDate(String dateString) { String[] tokens = dateString.split(" "); if (tokens.length == 3) { int day = Integer.parseInt(tokens[0]); int month = parseMonth(tokens[1]); int year = Integer.parseInt(tokens[2]); year = YEAR_PREFIX * 100 + year; return LocalDate.of(year, month, day); } else if (tokens.length == 1) { if ("вчера".equals(tokens[0])) { return LocalDate.now().minusDays(1); } else if ("сегодня".equals(tokens[0])) { return LocalDate.now(); } else { throw new IllegalArgumentException("Illegal date format: " + dateString); } } throw new IllegalArgumentException("Illegal date format: " + dateString); } /** Parses month input. The month must be one of the strings in {@link #MONTHS} array. */ private int parseMonth(String month) { int idx = MONTHS.indexOf(month); if (idx == -1) { throw new IllegalArgumentException("Invalid month: " + month); } return idx + 1; } } <file_sep>package ru.job4j.io.netw.bot; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Allows to load key-value pairs from a file. */ public class DataLoader { /** Map that represents key-value pairs of data. */ private Map<String, String> map; /** * Loads data from the specified input stream that receives XML data. * @param in input stream * @throws IOException if error occurs when reading data */ public void loadFromXML(InputStream in) throws IOException { Properties data = new Properties(); data.loadFromXML(in); map = new HashMap<>(); for (String key : data.stringPropertyNames()) { map.put(key, data.getProperty(key)); } } /** * @return data represented by key-value pairs */ public Map<String, String> getMap() { return map; } } <file_sep>package ru.job4j.collections.map; import org.junit.Test; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class UserTest { @Test public void whenConstructedThenContainsSpecifiedValues() { Calendar birthday = new GregorianCalendar(1998, Calendar.DECEMBER, 20); User alice = new User("Alice", 1, birthday); assertThat(alice.getName(), is("Alice")); assertThat(alice.getChildren(), is(1)); assertThat(alice.getBirthday(), is(birthday)); } @Test public void whenConvertedToStringThenRepresentsCorrectValues() { Calendar birthday = new GregorianCalendar(1998, Calendar.DECEMBER, 20); User alice = new User("Alice", 1, birthday); assertThat(alice.toString(), is("User{name='Alice', children=1, birthday=20.12.1998}")); } @Test public void whenUsersWithEqualDataThenEqualsReturnTrue() { Calendar birthday1 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); Calendar birthday2 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); User alice1 = new User("Alice", 1, birthday1); User alice2 = new User("Alice", 1, birthday2); assertThat(alice1.equals(alice2), is(true)); } @Test public void whenDifferentUsersThenEqualsReturnsFalse() { Calendar birthday1 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); Calendar birthday2 = new GregorianCalendar(1998, Calendar.DECEMBER, 21); User alice1 = new User("Alice", 1, birthday1); User alice2 = new User("Alice", 1, birthday2); assertThat(alice1.equals(alice2), is(false)); } @SuppressWarnings({"EqualsWithItself", "ConstantConditions", "EqualsBetweenInconvertibleTypes"}) @Test public void whenNullOrNotUserThenEqualsReturnsFalse() { Calendar birthday1 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); User alice1 = new User("Alice", 1, birthday1); assertThat(alice1.equals(alice1), is(true)); assertThat(alice1.equals(null), is(false)); assertThat(alice1.equals("alice1"), is(false)); } @Test public void whenUsersWithEqualDataThenHashcodeReturnEqualValues() { Calendar birthday1 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); Calendar birthday2 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); User alice1 = new User("Alice", 1, birthday1); User alice2 = new User("Alice", 1, birthday2); assertEquals(alice1.hashCode(), alice2.hashCode()); } @Test public void whenEqualsAndHashcodeAreOverriddenThenMapContainsOneObject() { Calendar birthday1 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); Calendar birthday2 = new GregorianCalendar(1998, Calendar.DECEMBER, 20); User alice1 = new User("Alice", 1, birthday1); User alice2 = new User("Alice", 1, birthday2); Map<User, String> map = new HashMap<>(); map.put(alice1, "First"); map.put(alice2, "Second"); assertThat(map.size(), is(1)); assertThat(map.get(alice1), is("Second")); assertThat(map.get(alice2), is("Second")); System.out.println(map.toString()); } } <file_sep>package ru.job4j.ood.calculator; import org.junit.Test; import ru.job4j.calculate.Calculate; import static org.junit.Assert.assertEquals; import static ru.job4j.ood.calculator.ArithmeticOperation.*; public class ArithmeticCalculatorAdapterTest { public static final double DELTA = 1e-15; @Test public void whenCalculateThenUsesCalculator() { ArithmeticCalculatorAdapter adapter = new ArithmeticCalculatorAdapter(new Calculate()); assertEquals(6.0, adapter.calculate(3.0, MULTIPLY, 2.0), DELTA); assertEquals(1.5, adapter.calculate(3.0, DIVIDE, 2.0), DELTA); assertEquals(5.0, adapter.calculate(3.0, ADD, 2.0), DELTA); assertEquals(1.0, adapter.calculate(3.0, SUBTRACT, 2.0), DELTA); } } <file_sep>package ru.job4j.tittactoe; import org.junit.Test; import ru.job4j.tictactoe.Figure3T; import ru.job4j.tictactoe.Logic3T; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class Logic3TTest { @Test public void whenRowHasXWinnerThenTrue() { Figure3T[][] table = stringsToTable("O O", "XOO", "XXX"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerX(), is(true)); } @Test public void whenColumnHasXWinnerThenTrue() { Figure3T[][] table = stringsToTable("OXO", " XO", "OXX"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerX(), is(true)); } @Test public void whenHasNoXWinnerThenFalse() { Figure3T[][] table = stringsToTable("O O", "OXX", "XXO"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerX(), is(false)); } @Test public void whenRowHasOWinnerThenTrue() { Figure3T[][] table = stringsToTable("X X", "XXO", "OOO"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerO(), is(true)); } @Test public void whenColumnHasOWinnerThenTrue() { Figure3T[][] table = stringsToTable("OXO", " OO", "OXO"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerO(), is(true)); } @Test public void whenLeftDiagonalHasXWinnerThenTrue() { Figure3T[][] table = stringsToTable("XO ", "OX ", "OXX"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerX(), is(true)); } @Test public void whenRightDiagonalHasOWinnerThenTrue() { Figure3T[][] table = stringsToTable("XXO", "XO ", "OXO"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerO(), is(true)); } @Test public void whenHasNoOWinnerThenFalse() { Figure3T[][] table = stringsToTable("O O", "OXX", "XXO"); Logic3T logic = new Logic3T(table); assertThat(logic.isWinnerO(), is(false)); } @Test public void whenHasGapThenTrue() { Figure3T[][] table = stringsToTable("OXX", "XOX", "OX "); Logic3T logic = new Logic3T(table); assertThat(logic.hasGap(), is(true)); } @Test public void whenNoGapsThenFalse() { Figure3T[][] table = stringsToTable("OXX", "XOX", "XXO"); Logic3T logic = new Logic3T(table); assertThat(logic.hasGap(), is(false)); } private static Figure3T[][] stringsToTable(String... lines) { Figure3T[][] table = new Figure3T[3][3]; for (int i = 0; i < lines.length; i++) { String[] symbols = lines[i].split(""); for (int j = 0; j < symbols.length; j++) { Figure3T figure; switch (symbols[j]) { case "X": figure = new Figure3T(true); break; case "O": figure = new Figure3T(false); break; case " ": figure = new Figure3T(); break; default: throw new IllegalArgumentException("Invalid symbol: " + symbols[j]); } table[i][j] = figure; } } return table; } } <file_sep>package ru.job4j.jmm.cache; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class TextFileCacheTest { private static final String NL = System.lineSeparator(); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void testGetContents() throws IOException { String names = "Alice" + NL + "Bob"; String address = "Bob's address"; createFile("names.txt", names); createFile("address.txt", address); TextFileCache textCache = new TextFileCache(temporaryFolder.getRoot().toPath()); String namesResult = textCache.getContents("names.txt"); assertThat(namesResult, is(names)); String addressResult = textCache.getContents("address.txt"); assertThat(addressResult, is(address)); } private void createFile(String name, String contents) throws IOException { File f = temporaryFolder.newFile(name); Files.writeString(f.toPath(), contents); } } <file_sep>package ru.job4j.ood.carparking; /** * Represents passenger car. */ public class Car implements Vehicle { private final LicensePlateNumber licensePlate; /** Constructs the car using the specified id. */ public Car(LicensePlateNumber licensePlate) { this.licensePlate = licensePlate; } @Override public String getId() { return licensePlate.getNumber(); } @Override public int size() { return 1; } @Override public String toString() { return "Car{licensePlate=" + licensePlate + '}'; } } <file_sep>package ru.job4j.collections.list; /** * Node of linked list that stores data and link to the next node. * @param <E> type of elements contained in the list */ public class Node<E> { final E data; Node<E> next; Node(E data) { this.data = data; } } <file_sep>package ru.job4j.tracker; import java.util.List; /** * Interface of a repository of items that allows to add, delete, replace and find items. */ public interface ITracker { /** * Adds an item and sets unique id of the item. * @param item new item * @return item with initialized id */ Item add(Item item); /** * Replaces existing item with other item. * @param id id of existing item * @param item new item * @return true if replaced item, false otherwise */ boolean replace(String id, Item item); /** * Deletes item by id. * @param id id of existing item * @return true if item was deleted, false otherwise */ boolean delete(String id); /** * Gets all items in tracker. * @return all items */ List<Item> findAll(); /** * Finds by name. * @param key name of item * @return items with names that equal specified key */ List<Item> findByName(String key); /** * Finds item by specified id. * @param id id of item * @return found item or null if there is no item with specified id */ Item findById(String id); } <file_sep>package ru.job4j.collections.tree; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Represents node that contains value and list of children. * @param <E> type of value */ public class Node<E> { /** Value stored at the node. */ private final E value; /** List of child nodes. */ private final List<Node<E>> children = new ArrayList<>(); /** * Constructs node and initializes with the specified value. * @param value value stored at the node */ public Node(E value) { this.value = Objects.requireNonNull(value); } /** * Adds child node to the list of children. * @param child child node */ public void add(Node<E> child) { children.add(child); } /** * @return value of the node */ public E getValue() { return value; } /** * @return list of child nodes */ public List<Node<E>> getChildren() { return children; } /** * Checks whether the specified value is equals to ' * the node's value. * @param that other value * @return true if other value is equal, otherwise false */ public boolean eqValue(E that) { return this.value.equals(that); } } <file_sep>package ru.job4j.ood.carparking; /** * Ticket that unites information about the parked vehicle and parking space. */ public class Ticket { private final String vehicleId; private final long parkingSpaceId; /** Constructs the ticket and initializes with the specified id and parking space id. */ public Ticket(String vehicleId, long parkingSpaceId) { this.vehicleId = vehicleId; this.parkingSpaceId = parkingSpaceId; } public String getVehicleId() { return vehicleId; } public long getParkingSpaceId() { return parkingSpaceId; } @Override public String toString() { return "Ticket{vehicleId='" + vehicleId + '\'' + ", parkingSpaceId=" + parkingSpaceId + '}'; } } <file_sep>package ru.job4j.ood.menu; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class SimpleMenuItemTest { @Test public void whenDisplayThenOutputUsingIndentation() { StringBuilder builder = new StringBuilder(); ToStringRenderer renderer = new ToStringRenderer("-", builder::append, ""); SimpleMenuItem item = new SimpleMenuItem("Item1", null, renderer, 3); item.display(); assertThat(builder.toString(), is("---Item1")); } @Test public void whenChooseThenExecuteAction() { Action action1 = mock(Action.class); Action action2 = mock(Action.class); SimpleMenuItem item = new SimpleMenuItem("Item1", action1, null, 0); item.choose(); verify(action1, times(1)).execute(); item.setAction(action2); item.choose(); verify(action2, times(1)).execute(); } } <file_sep>/** * 2nd attempt to make a food store. */ package ru.job4j.ood.store;<file_sep>package ru.job4j.vacparser; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.vacparser.model.ForumPage; import ru.job4j.vacparser.model.Vacancy; import ru.job4j.vacparser.parsers.ForumPageParser; import ru.job4j.vacparser.storage.Storage; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; /** * Performs forum page processing. * Uses supplied predicates to filter the vacancies received from the forum page * then submits the filtered vacancies to storage. */ public class ForumPageProcessor { private static final Logger LOG = LoggerFactory.getLogger(ForumPageProcessor.class); private static final int SKIP_ROWS = 4; private final Storage storage; private final Predicate<Vacancy> skipByTime; private final Predicate<String> passByName; private final Consumer<Vacancy> vacancyLoader; private final ForumPageParser pageParser; /** * Initializes the processor. * @param storage vacancy storage * @param pageParser parser that should parse forum page * @param passByName predicate that any vacancy name should pass * @param skipByTime predicate that is used for skipping vacancies by time and stopping the processing * @param vacancyLoader vacancy consumer that will load additional vacancy content */ public ForumPageProcessor(Storage storage, ForumPageParser pageParser, Predicate<String> passByName, Predicate<Vacancy> skipByTime, Consumer<Vacancy> vacancyLoader) { this.storage = storage; this.pageParser = pageParser; this.passByName = passByName; this.skipByTime = skipByTime; this.vacancyLoader = vacancyLoader; } /** * Gets, filters and saves to storage the vacancies from the specified forum page document. * @param forumPageDoc document that represents the forum page * @return optional result that may contain link to next forum page */ public Optional<String> process(Document forumPageDoc) throws SQLException { ForumPage forumPage = pageParser.parse(forumPageDoc, SKIP_ROWS); List<Vacancy> allVacancies = forumPage.getVacancies(); boolean finishOnThisPage = false; List<Vacancy> filtered = new ArrayList<>(); for (Vacancy vacancy : allVacancies) { if (skipByTime.test(vacancy)) { if (!finishOnThisPage) { LOG.trace("Skipping on (and before) vacancy {}", vacancy); finishOnThisPage = true; } } else if (passByName.test(vacancy.getName()) && storage.findByName(vacancy.getName()) == null) { filtered.add(vacancy); } } for (Vacancy vacancy : filtered) { vacancyLoader.accept(vacancy); } storage.addAll(filtered); if (finishOnThisPage) { LOG.info("Finishing processing"); return Optional.empty(); } else { String nextPage = forumPage.getNextPage(); LOG.info("Next page to process: {}", nextPage); return Optional.of(nextPage); } } } <file_sep>package ru.job4j.departments; import org.junit.Test; import java.util.List; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class CodeSorterTest { @Test public void whenSortAscendingUpToThreeLevelsThenSuccessAndSuperCodesAdded() { CodeSorter sorter = new CodeSorter(); List<String> codes = List.of( "K1\\SK1", "K1\\SK2", "K1\\SK1\\SSK1", "K1\\SK1\\SSK2", "K2", "K2\\SK1\\SSK1", "K2\\SK1\\SSK2" ); List<String> sorted = sorter.sortAscending(codes); List<String> expected = List.of( "K1", "K1\\SK1", "K1\\SK1\\SSK1", "K1\\SK1\\SSK2", "K1\\SK2", "K2", "K2\\SK1", "K2\\SK1\\SSK1", "K2\\SK1\\SSK2" ); assertThat(sorted, is(expected)); } @Test public void whenSortDescendingUpToThreeLevelsThenSuccessAndSuperCodesAdded() { CodeSorter sorter = new CodeSorter(); List<String> codes = List.of( "K1\\SK1", "K1\\SK2", "K1\\SK1\\SSK1", "K1\\SK1\\SSK2", "K2", "K2\\SK1\\SSK1", "K2\\SK1\\SSK2" ); List<String> sorted = sorter.sortDescending(codes); List<String> expected = List.of( "K2", "K2\\SK1", "K2\\SK1\\SSK2", "K2\\SK1\\SSK1", "K1", "K1\\SK2", "K1\\SK1", "K1\\SK1\\SSK2", "K1\\SK1\\SSK1" ); assertThat(sorted, is(expected)); } } <file_sep>package ru.job4j.array; import java.util.HashSet; import java.util.Set; /** * Contains method for array checking. */ public class Check { /** * Checks whether all elements of the array are same (all true or all false). * @param data checked arrays * @return true if all elements are the same, false otherwise */ public boolean mono(boolean[] data) { if (data.length == 1) { return true; } boolean result = true; for (int i = 1; i < data.length; i++) { if (data[i - 1] != data[i]) { result = false; break; } } return result; } /** * Checks if array is non-decreasing. * @param array an array * @return true if array is non-decreasing */ public boolean isNonDecreasing(int[] array) { boolean result = true; for (int i = 0; i < array.length - 1; i++) { if (array[i] > array[i + 1]) { result = false; break; } } return result; } /** * Checks if all elements of an array are contained in other array. * @param superArray super array containing all possible elements of sub array * @param subArray array of checked elements * @return true if first array contains all elements of the sub-array */ public boolean isSubArray(int[] superArray, int[] subArray) { Set<Integer> superSet = new HashSet<>(); for (int m : superArray) { superSet.add(m); } for (int n : subArray) { if (!superSet.contains(n)) { return false; } } return true; } } <file_sep>package ru.job4j.ood.carparking; /** * Represents any kind of vehicle in the context of parking service. */ public interface Vehicle { /** Returns ID of the vehicle. */ String getId(); /** Returns size of the vehicle that corresponds to the number of minimal parking spots. */ int size(); } <file_sep>package ru.job4j.ood.carparking; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class SpaceManagerTest { private static final int TRUCK_SIZE = 4; private final SpaceManager manager = new SpaceManager(); @Test public void whenFindSpaceForSmallVehicleThenFindsOneSpot() { Spot busy = new Spot(); busy.occupy(); Spot free = new Spot(); manager.setSpots(List.of(busy, free)); Vehicle car = makeCar(); ParkingSpace space = manager.findSpaceFor(car); assertNotNull(space); assertFalse(free.isOccupied()); space.occupyWith(car); assertTrue(free.isOccupied()); } @Test public void whenFindSpaceForBigVehicleThenFindsOneBigSpot() { Spot busy = new Spot(TRUCK_SIZE); busy.occupy(); Spot free = new Spot(TRUCK_SIZE); manager.setSpots(List.of(busy, free)); Vehicle truck = makeTruck("2", TRUCK_SIZE); ParkingSpace space = manager.findSpaceFor(truck); assertNotNull(space); assertFalse(free.isOccupied()); space.occupyWith(truck); assertTrue(free.isOccupied()); } @Test public void whenFindSpaceForBigVehicleThenFindsSeveralSmallSpots() { Spot busy1 = new Spot(); busy1.occupy(); Spot free1 = new Spot(); Spot busy2 = new Spot(); busy2.occupy(); Spot free2 = new Spot(); Spot free3 = new Spot(); manager.setSpots(List.of(busy1, free1, busy2, free2, free3)); Vehicle truck = makeTruck("3", 2); ParkingSpace space = manager.findSpaceFor(truck); assertNotNull(space); assertFalse(free2.isOccupied()); assertFalse(free3.isOccupied()); space.occupyWith(truck); assertTrue(free2.isOccupied()); assertTrue(free3.isOccupied()); } @Test public void whenFindSpaceForBigVehicleOnSmallSpotThenCannotFind() { Spot busy1 = new Spot(); busy1.occupy(); Spot free1 = new Spot(); Spot busy2 = new Spot(); busy2.occupy(); manager.setSpots(List.of(busy1, free1, busy2)); Vehicle truck = makeTruck("4", 2); ParkingSpace space = manager.findSpaceFor(truck); assertNull(space); } private Car makeCar() { return new Car(new LicensePlateNumber("1")); } private Truck makeTruck(String number, int size) { return new Truck(new LicensePlateNumber(number), size); } } <file_sep>package ru.job4j.ood.kiss; import org.junit.Test; import java.util.Comparator; import java.util.List; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class MaxMinTest { private final MaxMin maxMin = new MaxMin(); private final List<String> values = List.of("aa", "a", "aaa", ""); private final Comparator<String> comparatorByLength = Comparator.comparingInt(String::length); @Test public void whenMaxThenReturnsMaximumElement() { String result = maxMin.max(values, comparatorByLength); assertThat(result, is("aaa")); } @Test public void whenMinThenReturnsMinimumElement() { String result = maxMin.min(values, comparatorByLength); assertThat(result, is("")); } } <file_sep>package ru.job4j.sqltoxml; import org.junit.Test; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class EntryTest { @Test public void whenEntriesAreEqualThenHashCodesAreEqual() { Entry e1 = new Entry(10); Entry e2 = new Entry(10); assertThat(e1, is(e2)); assertThat(e1.hashCode(), is(e2.hashCode())); } @Test public void whenToStringThenReturnsFieldValue() { Entry e = new Entry(20); assertThat(e.toString(), is("Entry{field=20}")); } } <file_sep>baseUrl=jdbc:postgresql://localhost/ user=postgres password= <file_sep>package ru.job4j.sqltoxml; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.xml.sax.SAXException; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.IOException; import java.nio.file.Path; import java.sql.SQLException; import java.util.List; /** * Generates entries, saves entries to XML, transforms XML, and uses SAX parser to parse the result. */ public class EntryProcessor { private static final Logger LOG = LogManager.getLogger(EntryProcessor.class); private final Path xmlPath; private final Path xsltPath; private final int size; /** Initializes processor with the number of entries, path to XML and XSLT files. */ public EntryProcessor(int size, Path xmlPath, Path xsltPath) { this.size = size; this.xmlPath = xmlPath; this.xsltPath = xsltPath; } /** Starts the processing and returns result. */ public long start() { long result = -1L; List<Entry> entries = saveDbAndLoadEntries(); boolean saved = saveToXml(entries); if (saved) { Path converted = convertXml(); if (converted != null) { result = parseXmlSum(converted); } } return result; } /** Generates entries in the db and returns list of entries. */ private List<Entry> saveDbAndLoadEntries() { Config config = new Config(); config.init(); StoreSQL store; try { store = new StoreSQL(config); store.generate(size); LOG.info("Generated {} entries", size); return store.load(); } catch (SQLException e) { LOG.error("Cannot save or load entries", e); return List.of(); } } /** Saves entries to XML file. */ private boolean saveToXml(List<Entry> entries) { StoreXML storeXML = new StoreXML(xmlPath); try { storeXML.save(entries); LOG.info("Saved XML to {}", xmlPath); return true; } catch (JAXBException | IOException e) { LOG.error("Cannot store XML", e); return false; } } /** Converts XML and returns path to the converted XML file. */ private Path convertXml() { String filename = xmlPath.getFileName().toString(); String convertedName = filename.substring(0, filename.indexOf(".xml")) + "_transformed.xml"; Path convertedXml = xmlPath.resolveSibling(convertedName); ConvertXSLT converter = new ConvertXSLT(); try { converter.convert(xmlPath, convertedXml, xsltPath); LOG.info("Converted XML saved to {}", convertedXml); return convertedXml; } catch (IOException | TransformerException e) { LOG.error("Cannot convert XML", e); return null; } } /** Parses XML file and returns result. */ private long parseXmlSum(Path xmlPath) { SAXCalculator calc = new SAXCalculator("entry", "field"); try { return calc.sum(xmlPath); } catch (ParserConfigurationException | SAXException | IOException e) { LOG.error("Cannot parse XML", e); return -1; } } } <file_sep>package ru.job4j.ood.warehouse.foods; import ru.job4j.ood.warehouse.Food; import java.math.BigDecimal; import java.time.LocalDate; /** Represents bread. */ public class Bread extends Food { public Bread(LocalDate createDate, LocalDate expireDate, BigDecimal price) { super("Bread", createDate, expireDate, price, null); } } <file_sep>baseUrl=jdbc:postgresql://localhost:5432/ user=postgres password=<PASSWORD> <file_sep>/** * Tic-Tac-Toe game that uses text interface. */ package ru.job4j.ood.tictac; <file_sep>site.url=https://www.sql.ru/forum/job-offers jdbc.url=jdbc:postgresql://localhost:5432/test_vacparser jdbc.user=postgres jdbc.password= cron.time=0 0 12 * * ? <file_sep>package ru.job4j.io.netw.bot; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static ru.job4j.io.netw.bot.Constants.*; public class ClientTest { @Test public void whenStartThenReceivesResponses() throws IOException { testClientReception( new Questionnaire("Hi, Bob!", "bye"), String.join(NL, "Hi, Alice!", "", "Bye!", "", ""), List.of("Hi, Alice!", "Bye!") ); } @Test public void whenStartThenCanReceiveMultilineMessages() throws IOException { testClientReception( new Questionnaire("Hi, Bob!", "How are you?", "bye"), String.join(NL, "Hi, Alice!", "", "I'm fine!", "Thanks!", "", "Bye!", "", ""), List.of("Hi, Alice!", String.join(NL, "I'm fine!", "Thanks!"), "Bye!") ); } private void testClientReception(Supplier<String> questions, String responses, List<String> expected) throws IOException { Socket socket = mock(Socket.class); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); when(socket.getOutputStream()).thenReturn(buffer); when(socket.getInputStream()).thenReturn(new ByteArrayInputStream(responses.getBytes())); List<String> received = new ArrayList<>(); Client client = new Client(socket, questions, received::add); client.start(); assertThat(received, is(expected)); } private static class Questionnaire implements Supplier<String> { private final List<String> responses; private int index; public Questionnaire(String... responses) { this.responses = List.of(responses); } @Override public String get() { return responses.get(index++); } } } <file_sep>package ru.job4j.collections.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * The implementation of iterator that returns only even numbers. */ public class EvenIterator implements Iterator<Integer> { /** Indicates that there is no valid index. */ private static final int NO_ELEMENT = -1; /** Iterated values. */ private final int[] values; /** Index that points to the next even value. */ private int nextIndex; /** * Constructs instance initialized with specified values. * @param values array of iterated values */ public EvenIterator(int[] values) { this.values = values; nextIndex = findNext(NO_ELEMENT); } /** * @return true if the iteration has more even elements, false otherwise */ @Override public boolean hasNext() { return nextIndex != NO_ELEMENT; } /** * @return next even number in the iteration * @throws NoSuchElementException if the iteration has no more even numbers */ @Override public Integer next() throws NoSuchElementException { if (nextIndex == NO_ELEMENT) { throw new NoSuchElementException(); } int value = values[nextIndex]; nextIndex = findNext(nextIndex); return value; } /** * Finds next index that points to an even value. * @param previousEven index of the previous even value * @return next index of even value */ private int findNext(int previousEven) { int found = NO_ELEMENT; for (int i = previousEven + 1; i < values.length; i++) { if (values[i] % 2 == 0) { found = i; break; } } return found; } } <file_sep>Задания ======= В порядке от последних к первым. ## Раздел "Middle" ### 3.4 Spring ### 3.3 Hibernate ### 3.2 Servlets, JSP ### 3.1 Многопоточность ## Раздел "Junior" ### 2.5 Garbage Collection ## 2.4 ООД ### 2.3 SQL, JDBC ### 2.2 Ввод-Вывод ### 2.1 Collections.Pro ## Раздел "Стажер" ### 1.4 FP, Lambda, Stream API ### 1.3 Collections ### 1.2 ООП ### 1.1 Базовый синтаксис <file_sep>site.url=site-url jdbc.url=db-url jdbc.user=user jdbc.password=123 cron.time=0 1 2 * * ? crawl.delay=1234 <file_sep>package ru.job4j.ood.tictac; /** * Represents grid that can be changed. */ public interface GameGrid extends GridView { /** Changes mark of the grid cell at the specified position. */ void changeCell(Position position, Mark mark); /** * Tries to find a winner having the specified number of adjacent marks. * @param lineLength number of adjacent marks that should be on one line. * @return mark of the winner or null if there is no winner yet */ Mark findWinningMark(int lineLength); } <file_sep>package ru.job4j.ood.tictac; /** * Helper used for getting input from playing human. */ public class HumanPlayer implements Player { private final Mark mark; private final Input input; /** Constructs the player using the specified mark and input. */ public HumanPlayer(Mark mark, Input input) { this.mark = mark; this.input = input; } /** Make the next move in the game using the specified grid view. */ @Override public Position makeMove(GridView view) { return input.requestPosition("Enter row and column for next " + mark + ": "); } /** Returns mark used by this player. */ @Override public Mark getMark() { return mark; } } <file_sep>package ru.job4j.ood.tictac; /** * Represents grid view containing only methods that do not change the grid. */ public interface GridView { /** Returns mark at the specified position. */ Mark markAt(Position position); /** Checks whether the cell the specified position is free or busy. */ boolean isFreeAt(Position position); /** Returns true if all cells in the grid are busy, false otherwise. */ boolean isFull(); /** Returns size of the grid. */ int size(); } <file_sep>package ru.job4j.chess.behaviors; import ru.job4j.chess.figures.Cell; /** * Moving one cell in all directions. */ public class OneCellMove implements MovingBehavior { @Override public Cell[] way(Cell source, Cell dest) { throw new UnsupportedOperationException(); } } <file_sep>-- create database test_items_db; -- Connect to test_items_db before creating tables create table permission ( id serial primary key, name varchar(20) ); create table role ( id serial primary key, name varchar(20) ); create table role_permission ( role_id int references role (id), permission_id int references permission (id), primary key (role_id, permission_id) ); create table "user" ( id serial primary key, login varchar(30) not null, password varchar(30) not null, role_id int not null references role (id) ); create table category ( id serial primary key, name varchar(30) not null ); create table state ( id serial primary key, name varchar(30) not null ); create table item ( id serial primary key, title varchar(128) not null, body text not null, created timestamp not null default now(), creator_id int not null references "user" (id), category_id int references category (id), state_id int references state (id) ); create table attachment ( id serial primary key, name varchar(128) not null, body bytea, created timestamp not null default now(), creator_id int not null references "user" (id) ); create table comment ( id serial primary key, body text, created timestamp not null default now(), author_id int not null references "user" (id) ); insert into role (name) values ('admin'); insert into role (name) values ('guest'); insert into permission (name) values ('read'); insert into permission (name) values ('comment'); insert into permission (name) values ('attach'); insert into role_permission (role_id, permission_id) values (1, 1); insert into role_permission (role_id, permission_id) values (1, 2); insert into role_permission (role_id, permission_id) values (1, 3); insert into role_permission (role_id, permission_id) values (2, 1); insert into "user" (login, password, role_id) values ('admin', 'admin', 1); insert into category (name) values ('development'); insert into category (name) values ('testing'); insert into state (name) values ('state1'); insert into attachment (name, body, created, creator_id) values ('attachment-name', '\x54455354', now(), 1); insert into comment (body, created, author_id) values ('comment-body', now(), 1); insert into item (title, body, created, creator_id, category_id, state_id) values ('title1', 'body1', now(), 1, 1, 1); <file_sep>package ru.job4j.io.find; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Supporting settings for I/O tests. */ public class TestingSettings { private static final Properties PROPERTIES = new Properties(); static { try (InputStream in = TestingSettings.class.getResourceAsStream("/test.properties")) { PROPERTIES.load(in); } catch (IOException e) { e.printStackTrace(); } } private TestingSettings() { } public static String testDirProvider() { return PROPERTIES.getProperty("testDirProvider"); } } <file_sep>/** * First attempt to make a food store. */ package ru.job4j.ood.warehouse;<file_sep>package ru.job4j.loop; import java.util.function.BiPredicate; /** * Contains methods of painting geometric shapes. */ public class Paint { private static final String NEW_LINE = System.lineSeparator(); /** * Creates a string representation of pyramid. * @param height height of the pyramid * @return pyramid as string of characters */ public String pyramid(int height) { return this.loopBy(height, 2 * height - 1, (row, col) -> col >= height - 1 - row && col <= height - 1 + row); } /** * Creates a string representation of right triangle. * @param height height of the triangle * @return right triangle as string of characters */ public String rightTrl(int height) { //noinspection SuspiciousNameCombination return this.loopBy(height, height, (row, col) -> col <= row); } /** * Creates a string representation of left triangle. * @param height height of the triangle * @return left triangle as string of characters */ public String leftTrl(int height) { //noinspection SuspiciousNameCombination return this.loopBy(height, height, (row, col) -> col >= (height - row - 1)); } private String loopBy(int height, int width, BiPredicate<Integer, Integer> predicate) { StringBuilder screen = new StringBuilder(); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { if (predicate.test(row, col)) { screen.append("^"); } else { screen.append(" "); } } screen.append(NEW_LINE); } return screen.toString(); } } <file_sep>package ru.job4j.collections.set; import ru.job4j.collections.list.SimpleArrayList; import java.util.Iterator; /** * Simple set that uses dynamic array list as underlying container. * @param <E> type of element */ public class SimpleSet<E> implements Iterable<E> { /** List of elements that serves as container of elements in the set. */ private final SimpleArrayList<E> elements = new SimpleArrayList<>(); /** * Adds the specified element to the set if it is not already present. * @param element element to be added */ public void add(E element) { if (!contains(element)) { elements.add(element); } } /** * Checks that the set contains the specified element. * @param element element whose presence is to be tested * @return true if the set contains the element, false otherwise */ private boolean contains(E element) { boolean found = false; for (E value : elements) { if (value.equals(element)) { found = true; break; } } return found; } /** * @return iterator over the elements in this set */ @Override public Iterator<E> iterator() { return elements.iterator(); } /** * @return string representation of this set */ @Override public String toString() { return elements.toString(); } } <file_sep>create table if not exists vacancy ( id serial primary key, name varchar(256) not null unique, description text not null, link varchar(256) not null, created timestamp not null, modified timestamp not null ); <file_sep>package ru.job4j.ood.store; import org.junit.Before; import org.junit.Test; import ru.job4j.ood.store.foods.Milk; import java.math.BigDecimal; import java.time.LocalDate; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class TrashTest { private final LocalDate now = LocalDate.now(); private Trash trash; @Before public void setup() { Distribution distribution = new Distribution(new SimpleStoreCycleCalculator(25, 75, now)); trash = new Trash(distribution.trashStrategy()); } @Test public void whenFoodUpto100ThenRejects() { Milk milk = new Milk(now.minusDays(4), now, BigDecimal.valueOf(80)); assertThat(trash.accepts(milk), is(false)); } @Test public void whenFoodOver100ThenAccepts() { Milk milk = new Milk(now.minusDays(4), now.minusDays(1), BigDecimal.valueOf(80)); assertThat(trash.accepts(milk), is(true)); } } <file_sep>package ru.job4j.ood.menu; import java.util.function.Consumer; /** * Renders appearance of nested items to any string consumer. */ public class ToStringRenderer implements Renderer { /** Symbol used for indentation of nested items. */ private final String indentationSymbol; /** Destination of rendering. */ private final Consumer<String> out; /** Suffix appended to the end of string representation of nested items. */ private final String suffix; /** * Constructs the renderer using specified indentation symbol, string consumer. * System's line separator will be used as suffix * */ public ToStringRenderer(String indentationSymbol, Consumer<String> out) { this(indentationSymbol, out, System.lineSeparator()); } /** Constructs the renderer using specified indentation symbol, string consumer, and suffix. */ public ToStringRenderer(String indentationSymbol, Consumer<String> out, String suffix) { this.indentationSymbol = indentationSymbol; this.out = out; this.suffix = suffix; } /** Renders appearance of the specified item. */ @Override public void render(NestedItem item) { out.accept(indentationSymbol.repeat(item.getLevel()) + item.name() + suffix); } } <file_sep>package ru.job4j.io.chat; import java.util.function.Consumer; import java.util.function.Supplier; /** * Simulates a conversation between two talkers. * When the first talker sends 'stop' then the second talker stops responding. * When the first talker sends 'continue' the the second talker resumes responding. * When the first talker sends 'quit' then the conversation is over. */ public class Chat { /** The first talker. */ private final Supplier<String> talker1; /** The second talker. */ private final Supplier<String> talker2; /** Output receiving responses from the second talker. */ private final Consumer<String> output; /** Logger that saves the whole conversation. */ private final Consumer<String> logger; /** * Constructs the chat with the specified talkers, output and logger. * @param talker1 the first talker that starts and finishes the conversation * @param talker2 the second talker that gives responses * @param output output receiving responses from the second talker * @param logger logger that saves the whole conversation */ public Chat(Supplier<String> talker1, Supplier<String> talker2, Consumer<String> output, Consumer<String> logger) { this.talker1 = talker1; this.talker2 = talker2; this.output = output; this.logger = logger; } /** * Starts the chat. * The second talker is suspended when the first talker sends 'stop', * and resumed when the first sends 'continue'. * The chat is over when the first talker sends 'quit'. */ public void start() { boolean running = true; boolean responding = true; while (running) { String phrase = talker1.get(); logger.accept(phrase); if ("stop".equals(phrase)) { responding = false; } else if ("continue".equals(phrase)) { responding = true; } else if ("quit".equals(phrase)) { running = false; } else if (responding) { String response = talker2.get(); output.accept(response); logger.accept(response); } } } } <file_sep>package ru.job4j.ood.calculator; /** Parser of string expressions. */ public interface ExpressionParser { /** Parses the specified string expression to {@link Expression} object. */ Expression parse(String expression); } <file_sep>package ru.job4j.vacparser; import org.jsoup.nodes.Document; import org.junit.Before; import org.junit.Test; import ru.job4j.vacparser.model.ForumPage; import ru.job4j.vacparser.model.Vacancy; import ru.job4j.vacparser.parsers.ForumPageParser; import ru.job4j.vacparser.storage.Storage; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class ForumPageProcessorTest { private static final int SKIP_ROWS = 4; private static final LocalDateTime TODAY = LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0)); private static final LocalDateTime YESTERDAY = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.of(0, 0)); private ForumPage forumPage; private Vacancy vacJava1; private Vacancy vacJava2; @Before public void setupPage() { forumPage = new ForumPage(); vacJava1 = new Vacancy("Java", "link1", TODAY); Vacancy vacJs = new Vacancy("JavaScript", "link2", TODAY); vacJava2 = new Vacancy("Java", "link3", YESTERDAY); forumPage.setVacancies(List.of(vacJava1, vacJs, vacJava2)); forumPage.setNextPage("nextPageUrl"); } @Test public void whenProcessDocumentThenAddsFilteredByNameVacanciesToStorage() throws SQLException { Document fakeDoc = mock(Document.class); ForumPageParser pageParser = mock(ForumPageParser.class); when(pageParser.parse(fakeDoc, SKIP_ROWS)).thenReturn(forumPage); Storage storage = mock(Storage.class); when(storage.findByName(anyString())).thenReturn(null); ForumPageProcessor processor = new ForumPageProcessor(storage, pageParser, "Java"::equals, vac -> false, vac -> { }); List<Vacancy> expectedFiltered = List.of(vacJava1, vacJava2); Optional<String> result = processor.process(fakeDoc); assertThat(result.orElse("other"), is("nextPageUrl")); verify(pageParser).parse(fakeDoc, SKIP_ROWS); verify(storage).addAll(expectedFiltered); } @Test public void whenProcessDocumentThenAddsFilteredByDateVacanciesToStorage() throws SQLException { Document fakeDoc = mock(Document.class); ForumPageParser pageParser = mock(ForumPageParser.class); when(pageParser.parse(fakeDoc, SKIP_ROWS)).thenReturn(forumPage); Storage storage = mock(Storage.class); when(storage.findByName(anyString())).thenReturn(null); Predicate<Vacancy> skipByTime = vac -> vac.getModified().equals(YESTERDAY); ForumPageProcessor processor = new ForumPageProcessor(storage, pageParser, "Java"::equals, skipByTime, vac -> { }); List<Vacancy> expectedFiltered = List.of(vacJava1); Optional<String> result = processor.process(fakeDoc); assertThat(result.isPresent(), is(false)); verify(pageParser).parse(fakeDoc, SKIP_ROWS); verify(storage).addAll(expectedFiltered); } } <file_sep>package ru.job4j.collections.list; import java.util.StringJoiner; /** * Simple list implemented as single-linked list. * @param <E> type of the contained elements */ public class SimpleLinkedList<E> { /** Link that points to the first node of this list. */ private Node<E> first; /** Number of elements in the list. */ private int size; /** * @return number of elements in the list */ public int getSize() { return size; } /** * Adds the specified element as first element of the list. * @param element element to add */ public void add(E element) { Node<E> node = new Node<>(element); node.next = first; first = node; size++; } /** * Deletes the first element of the list. * @return first element or null if the list is empty */ public E delete() { Node<E> node = first; if (node == null) { return null; } else { first = first.next; size--; return node.data; } } /** * Gets element at the specified index in this list * @param index index of the element * @return element at index * @throws IndexOutOfBoundsException if index is out of range */ public E get(int index) throws IndexOutOfBoundsException { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } Node<E> node = first; for (int i = 0; i < index; i++) { node = node.next; } return node.data; } /** * @return string representation of the list */ @Override public String toString() { StringJoiner joiner = new StringJoiner(", ", "[", "]"); Node<E> current = first; while (current != null) { joiner.add(current.data.toString()); current = current.next; } return joiner.toString(); } } <file_sep>package ru.job4j.collections.tree; import org.junit.Test; import java.util.*; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class SimpleTreeImplTest { private final SimpleTreeImpl<Integer> tree = new SimpleTreeImpl<>(1); @Test public void whenAdd6ElementsThenFindLastReturns6() { tree.add(1, 2); tree.add(1, 3); tree.add(1, 4); tree.add(4, 5); tree.add(5, 6); var found = tree.findBy(6); assertThat(found.isPresent(), is(true)); assertThat(found.get().getValue(), is(6)); } @Test public void whenFindNonExistingThenNotPresent() { tree.add(1, 2); assertThat(tree.findBy(6).isPresent(), is(false)); } @Test public void whenIteratorThenIteratesAllElements() { tree.add(1, 2); tree.add(1, 3); tree.add(1, 4); tree.add(2, 5); tree.add(2, 6); tree.add(3, 7); tree.add(3, 8); tree.add(7, 9); int expected = 1; for (Integer value : tree) { assertThat(value, is(expected++)); } } @Test public void whenAddDuplicateThenDoesNotContainDuplicates() { assertThat(tree.add(1, 2), is(true)); assertThat(tree.add(1, 2), is(false)); Node<Integer> parent = tree.findBy(1).orElseThrow(); assertThat(parent.getChildren().size(), is(1)); assertThat(tree.getSize(), is(2)); } @Test public void whenAddToNonExistingParentThenDoesNotAdd() { assertThat(tree.add(22, 3), is(false)); Node<Integer> parent = tree.findBy(1).orElseThrow(); assertThat(parent.getChildren().size(), is(0)); assertThat(tree.getSize(), is(1)); } @Test(expected = ConcurrentModificationException.class) public void whenIterateAfterModificationThenException() { Iterator<Integer> it = tree.iterator(); tree.add(1, 2); it.next(); } @Test(expected = NoSuchElementException.class) public void whenIterateBeyondElementsThenException() { Iterator<Integer> it = tree.iterator(); it.next(); it.next(); } @Test public void whenIsBinaryInvokedOnBinaryTreeThenReturnsTrue() { tree.add(1, 2); tree.add(1, 3); tree.add(2, 4); tree.add(2, 5); tree.add(3, 6); tree.add(3, 7); assertThat(tree.isBinary(), is(true)); } @Test public void whenIsBinaryInvokedOnNonBinaryTreeThenReturnsFalse() { tree.add(1, 2); tree.add(1, 3); tree.add(2, 4); assertThat(tree.isBinary(), is(false)); } } <file_sep>package ru.job4j.collections.list; /** * Contains methods that inspect linked lists. */ public class LinkedListChecker { /** * Checks if the linked list starting with the specified first node has a cycle. * @param first first node of the list * @param <T> type of list elements * @return true if has cycle, false otherwise */ public static <T> boolean hasCycle(Node<T> first) { Node<T> fast = first; Node<T> slow = first; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { return true; } } return false; } } <file_sep>package ru.job4j.professions; public class Doctor extends Profession { public Doctor(String name) { super(name, "Doctor"); } public void heal(Patient patient) { } } <file_sep>package ru.job4j.ood.calculator; import org.junit.Before; import org.junit.Test; import ru.job4j.calculate.Calculate; import java.util.Scanner; import java.util.StringJoiner; import java.util.function.Supplier; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class InteractCalcTest { private static final String NL = System.lineSeparator(); private InteractCalc calc; private StringBuilder buffer; @Before public void setup() { buffer = new StringBuilder(); calc = new InteractCalc( new SimpleExpressionEvaluator(new SimpleExpressionParser( new ArithmeticCalculatorAdapter(new Calculate()), new TrigonometricFunctionCalculator()) ), buffer::append ); } @Test public void whenStartsAndExitThenPrintsPromptOnly() { calc.setInput(prepareUserInput("exit")); calc.start(); assertOutput("Enter expression:"); } @Test public void whenEnterTwoTimesThreeThenOutputsSix() { calc.setInput(prepareUserInput("2 * 3", "exit")); calc.start(); assertOutput("Enter expression:", "6.0"); } @Test public void whenEmptyInputThenStartFromTheBeginning() { calc.setInput(prepareUserInput("2 * 3", "", "3 / 2", "exit")); calc.start(); assertOutput("Enter expression:", "6.0", "Enter expression:", "1.5"); } @Test public void whenAddNumberToResultThenOutputsSum() { calc.setInput(prepareUserInput("3 * 4", " + 7", "exit")); calc.start(); assertOutput("Enter expression:", "12.0", "19.0"); } @Test public void whenSubtractAndDivideAndMultiplyThenOutputsResult() { calc.setInput(prepareUserInput("19 - 7", " / 5", " * 10.0", "exit")); calc.start(); assertOutput("Enter expression:", "12.0", "2.4", "24.0"); } @Test public void whenSinusThenCalculatesSinus() { calc.setInput(prepareUserInput("sin(90)", "exit")); calc.start(); assertOutput("Enter expression:", "1.0"); } private Supplier<String> prepareUserInput(String... userInput) { StringJoiner joiner = new StringJoiner(NL); for (String input : userInput) { joiner.add(input); } Scanner in = new Scanner(joiner.toString()); return in::nextLine; } private void assertOutput(String... lines) { StringBuilder builder = new StringBuilder(); for (String line : lines) { builder.append(line); builder.append(" "); } assertThat(buffer.toString(), is(builder.toString())); } } <file_sep>package ru.job4j.ood.store; import ru.job4j.ood.store.cycle.Expirable; import java.time.LocalDate; /** Contains helper methods for testing purposes. */ public class TestHelpers { /** Creates stub instance of {@link ru.job4j.ood.warehouse.quality.Expirable} . */ public static Expirable stubExpirable(int creationDay, int expirationDay) { return new Expirable() { @Override public LocalDate created() { return stubDate(creationDay); } @Override public LocalDate expires() { return stubDate(expirationDay); } }; } /** Creates stub local date. */ public static LocalDate stubDate(int day) { return LocalDate.of(2020, 1, day); } } <file_sep>package ru.job4j.sqltoxml; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; /** * Stores entries in an XML file using JAXB. */ public class StoreXML { private final Path target; public StoreXML(Path target) { this.target = target; } /** * Saves entries to the target file. * @param entries list of entries */ public void save(List<Entry> entries) throws JAXBException, IOException { JAXBContext jaxbContext = JAXBContext.newInstance(Entries.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Entries wrapper = new Entries(entries); try (BufferedWriter out = Files.newBufferedWriter(target)) { marshaller.marshal(wrapper, out); } } } <file_sep>package ru.job4j.io.chat; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class ChatTest { private final Listener output = new Listener(); private final Listener logger = new Listener(); @Test public void whenTypeMessageThenResponseIsReceivedAndConversationIsLogged() { Talker human = new Talker(List.of("1-Hello", "quit")); Talker bot = new Talker(List.of("2-Goodbye")); new Chat(human, bot, output, logger).start(); var botResponse = List.of("2-Goodbye"); var conversation = List.of("1-Hello", "2-Goodbye", "quit"); assertThat(output.getPhrases(), is(botResponse)); assertThat(logger.getPhrases(), is(conversation)); } @Test public void whenStoppedThenNoResponse() { Talker human = new Talker(List.of("1-Hello", "stop", "1-Quiet", "continue", "1-Loud", "quit")); Talker bot = new Talker(List.of("2-Hi", "2-Bye")); new Chat(human, bot, output, logger).start(); var botResponse = List.of("2-Hi", "2-Bye"); var conversation = List.of("1-Hello", "2-Hi", "stop", "1-Quiet", "continue", "1-Loud", "2-Bye", "quit"); assertThat(output.getPhrases(), is(botResponse)); assertThat(logger.getPhrases(), is(conversation)); } private static class Talker implements Supplier<String> { private final List<String> phrases; private int index; public Talker(List<String> phrases) { this.phrases = phrases; } @Override public String get() { return phrases.get(index++); } } private static class Listener implements Consumer<String> { private final List<String> phrases = new ArrayList<>(); @Override public void accept(String s) { phrases.add(s); } public List<String> getPhrases() { return phrases; } } } <file_sep>package ru.job4j.tools; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; /** * Contains utility methods for handling files in the {@code resources} folder. */ public class Resources { /** * Gets path to the specified resource. * @param name name of the resource * @return path */ public static Path getPath(String name) { URL url = Resources.class.getClassLoader().getResource(name); if (url == null) { throw new IllegalArgumentException("Can not locate resource: " + name); } try { return Paths.get(url.toURI()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Can not get path to resource: " + name, e); } } } <file_sep>package ru.job4j.ood.tictac; /** * Represents player participating in the game. */ public interface Player { /** * Returns position for the next move in the game using the specified grid view * or null if the grid is full. */ Position makeMove(GridView view); /** Returns mark used by this player. */ Mark getMark(); } <file_sep>package ru.job4j.vacparser; import org.jsoup.nodes.Document; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.vacparser.model.Vacancy; import ru.job4j.vacparser.parsers.ForumPageParser; import ru.job4j.vacparser.parsers.VacancyPageParser; import ru.job4j.vacparser.storage.DbHelper; import ru.job4j.vacparser.storage.DbStorage; import ru.job4j.vacparser.storage.Storage; import ru.job4j.vacparser.util.AppSettings; import ru.job4j.vacparser.util.DocumentLoader; import java.sql.Connection; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Optional; import java.util.function.Predicate; /** * This class implements the job that will be performed by the scheduler. */ public class VacanciesScraper implements Job { private static final Logger LOG = LoggerFactory.getLogger(VacanciesScraper.class); /** Contains the main logic of page loading and processing cycle. */ @Override public void execute(JobExecutionContext context) { AppSettings settings = (AppSettings) context.getJobDetail().getJobDataMap().get("appSettings"); Connection connection = null; try { connection = DbHelper.getConnection(settings); Storage storage = new DbStorage(connection); String pageUrl = settings.siteUrl(); LocalDateTime temporalBoundary = calculateDateTimeLimit(storage); LOG.info("Using temporal boundary {}", temporalBoundary); Predicate<Vacancy> skipByTime = vacancy -> { boolean afterBoundary = vacancy.getModified().isAfter(temporalBoundary); return !afterBoundary; }; Predicate<String> passByName = name -> name.contains("Java") && !name.toLowerCase().contains("script"); DocumentLoader loader = new DocumentLoader(settings.crawlDelay()); VacancyPageParser vacParser = new VacancyPageParser(); ForumPageProcessor processor = new ForumPageProcessor(storage, new ForumPageParser(), passByName, skipByTime, new VacancyContentLoader(loader, vacParser)); Optional<Document> loadedDoc = loader.apply(pageUrl); if (loadedDoc.isPresent()) { Document forumPage = loadedDoc.get(); Optional<String> parsedLink = processor.process(forumPage); while (parsedLink.isPresent()) { pageUrl = parsedLink.get(); loadedDoc = loader.apply(pageUrl); if (loadedDoc.isPresent()) { forumPage = loadedDoc.get(); parsedLink = processor.process(forumPage); } else { LOG.warn("Scraping interrupted because this page could not loaded: " + pageUrl); break; } } } } catch (SQLException e) { LOG.error("Database error", e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { LOG.error("Error Closing connection", e); } } } } /** * Calculates time limit based on on the fact whether the storage contains any records. * If the storage contains no records then time limit is the start of the previous year, * otherwise the time limit is the modification time of the last vacancy. * @param storage the storage * @return date time limit after which no scraping should be performed * @throws SQLException if db access error occurs */ private static LocalDateTime calculateDateTimeLimit(Storage storage) throws SQLException { LocalDateTime temporalBoundary; Vacancy lastVacancy = storage.findLast(); if (lastVacancy == null) { int previousYear = LocalDate.now().minusYears(1L).getYear(); temporalBoundary = LocalDateTime.of(previousYear, 12, 31, 23, 59, 59); } else { temporalBoundary = lastVacancy.getCreated(); } return temporalBoundary; } } <file_sep>package ru.job4j.ood.calculator; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ArithmeticExpressionTest { @Test public void whenEvaluateThenUsesCalculator() { ArithmeticExpression expr = new ArithmeticExpression( new NumberExpression(3D), new NumberExpression(2D), ArithmeticOperation.MULTIPLY, (op1, operation, op2) -> (operation == ArithmeticOperation.MULTIPLY) ? (op1 * op2) : -1 ); assertEquals(6.0, expr.evaluate(), 1e-15); } } <file_sep>package ru.job4j.collections.generic; /** * Store of roles. */ public class RoleStore extends AbstractStore<Role> { /** * Initializes store with the specified maximum capacity. * @param maxSize maximum number of stored roles */ public RoleStore(int maxSize) { super(maxSize); } } <file_sep>package ru.job4j.ood.store; import org.junit.Before; import org.junit.Test; import ru.job4j.ood.store.foods.Milk; import java.math.BigDecimal; import java.time.LocalDate; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class WarehouseTest { private final LocalDate now = LocalDate.now(); private Warehouse warehouse; @Before public void setup() { Distribution distribution = new Distribution(new SimpleStoreCycleCalculator(25, 75, now)); warehouse = new Warehouse(distribution.warehouseStrategy()); } @Test public void testAdd() { Milk milk = new Milk(now.minusDays(1), now.plusDays(4), BigDecimal.valueOf(80)); warehouse.add(milk); assertThat(warehouse.takeAll().contains(milk), is(true)); } @Test public void whenFoodBelow25ThenAccepts() { Milk milk = new Milk(now.minusDays(1), now.plusDays(4), BigDecimal.valueOf(80)); assertThat(warehouse.accepts(milk), is(true)); } @Test public void whenFoodFrom25ThenRejects() { Milk milk = new Milk(now.minusDays(1), now.plusDays(1), BigDecimal.valueOf(80)); assertThat(warehouse.accepts(milk), is(false)); } } <file_sep>package ru.job4j.stream9; import org.junit.Test; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class StudentTest { @Test public void testCompareTo() { Student bob1 = new Student("Bob", 1); Student bob5 = new Student("Bob", 5); assertTrue(bob5.compareTo(bob1) > 0); assertTrue(bob1.compareTo(bob5) < 0); assertThat(bob1.compareTo(new Student("Bob", 1)), is(0)); assertTrue(new Student("Alice", 1).compareTo(bob1) < 0); } @Test public void testEquals() { Student bob1 = new Student("Bob", 42); Student bob2 = new Student("Bob", 42); assertEquals(bob1, bob2); } @SuppressWarnings("UnnecessaryLocalVariable") @Test public void whenSameInstanceThenEqualsReturnsTrue() { Student bob1 = new Student("Bob", 42); Student bob2 = bob1; assertEquals(bob1, bob2); } @Test public void whenOtherTypeThenEqualsReturnsFalse() { assertNotEquals("Bob", new Student("Bob", 42)); } @Test public void whenEqualsThenSameHashCodes() { Student bob1 = new Student("Bob", 42); Student bob2 = new Student("Bob", 42); assertEquals(bob1.hashCode(), bob2.hashCode()); } @Test public void testToString() { Student bob = new Student("Bob", 42); assertThat(bob.toString(), is("Student{name='Bob', score=42}")); } } <file_sep>package ru.job4j.chess; import ru.job4j.chess.exceptions.FigureNotFoundException; import ru.job4j.chess.exceptions.ImpossibleMoveException; import ru.job4j.chess.exceptions.OccupiedWayException; import ru.job4j.chess.figures.Cell; import ru.job4j.chess.figures.Figure; import java.util.stream.IntStream; import java.util.stream.Stream; /** * The class is responsible for the movement of chess figures. */ public class Logic { /** * Arrays of all figures involved in the game. */ private final Figure[] figures = new Figure[32]; /** * Index used when adding figures. */ private int index = 0; /** * Adds figure. * @param figure figure */ public void add(Figure figure) { this.figures[this.index++] = figure; } /** * Moves the figure from the specified source cell to the destination cell. * @param source source cell * @param dest destination cell * @return true if the movement was successful, false otherwise * @throws ImpossibleMoveException throws when the destination can not be reached in one move * @throws FigureNotFoundException throws when there is no figure in source cell * @throws OccupiedWayException throws when the route to destination is occupied */ public boolean move(Cell source, Cell dest) throws ImpossibleMoveException, FigureNotFoundException, OccupiedWayException { int index = this.findBy(source); if (index == -1) { throw new FigureNotFoundException(); } Cell[] steps = this.figures[index].way(source, dest); if (!routeIsFree(steps)) { throw new OccupiedWayException(); } boolean rst = false; if (steps.length > 0) { this.figures[index] = this.figures[index].copy(dest); rst = true; } return rst; } /** * Removes all figures. */ public void clean() { IntStream.range(0, this.figures.length).forEach(i -> this.figures[i] = null); this.index = 0; } /** * Checks whether all cells on the route are not occupied. * @param steps cells on the route including destination * @return true if the route is free, false otherwise */ private boolean routeIsFree(Cell[] steps) { return Stream.of(steps).noneMatch(cell -> findBy(cell) != -1); } /** * Finds the index in the {@link Logic#figures} array of a figure which occupies the specified cell. * @param cell cell * @return index of -1 if cell is not occupied */ private int findBy(Cell cell) { return IntStream.range(0, this.figures.length) .filter(index -> this.figures[index] != null && this.figures[index].position().equals(cell)) .findFirst().orElse(-1); } } <file_sep>package ru.job4j.list; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Contains method for converting two-dimensional array to list. */ public class ConvertMatrix2List { /** * Converts two-dimensional array to list of integers. * @param array two-dimensional array * @return list containing all values of input array */ public List<Integer> toList(int[][] array) { return Stream.of(array) .map(IntStream::of) .flatMap(IntStream::boxed) .collect(Collectors.toList()); } } <file_sep>package ru.job4j.array; /** * Contains method for merging sorted arrays. */ public class MergeArrays { /** * Merges two sorted arrays into one. * @param a first sorted array * @param b second sorted array * @return sorted array containing all elements of source arrays */ public int[] merge(int[] a, int[] b) { int[] result = new int[a.length + b.length]; int ai = 0, bi = 0; for (int i = 0; i < result.length; i++) { if (ai < a.length && bi < b.length) { result[i] = a[ai] < b[bi] ? a[ai++] : b[bi++]; } else if (ai < a.length) { result[i] = a[ai++]; } else if (bi < b.length) { result[i] = b[bi++]; } } return result; } } <file_sep>package ru.job4j.array; /** * Contains method for creating array of squared numbers. */ public class Square { /** * Creates array filled with numbers squared. * @param bound upper bound (inclusive) * @return arrays of numbers squared */ public int[] calculate(int bound) { int[] result = new int[bound]; for (int i = 1; i <= bound; i++) { result[i - 1] = i * i; } return result; } } <file_sep>package ru.job4j.array; /** * Contains method for checking diagonals of matrix. */ public class MatrixCheck { /** * Checks whether every diagonal is mono that is it contains only same elements * (all true, all false, or left diagonal true and right false, or left false and right true). * @param data 2d array of elements * @return true if all diagonals are mono or false otherwise */ public boolean mono(boolean[][] data) { boolean result = true; int size = data.length, i, j, k; boolean left = data[0][0]; boolean right = data[0][size - 1]; for (i = 1, j = 1, k = size - 2; i < size; i++, j++, k--) { if (data[i][j] != left || data[i][k] != right) { result = false; break; } } return result; } } <file_sep>package ru.job4j.tracker; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Helps to read sql statements. */ public class SqlReader { private static final String SQL_STATEMENT_SEPARATOR = ";\\s*"; /** * Reads sql statements that are separated by a semicolon. * @param in input stream * @return list of strings where each string represents a separate sql statement */ public List<String> readSqlStatements(InputStream in) { List<String> statements = new ArrayList<>(); try (Scanner scanner = new Scanner(new BufferedInputStream(in))) { scanner.useDelimiter(SQL_STATEMENT_SEPARATOR); while (scanner.hasNext()) { statements.add(scanner.next()); } return statements; } } } <file_sep>package ru.job4j.vacparser.util; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class AppSettingsTest { @Test public void whenLoadedThenReturnCorrectSettings() { AppSettings settings = new AppSettings("test_vacparser_settings_app.properties"); assertThat(settings.siteUrl(), is("site-url")); assertThat(settings.jdbcUrl(), is("db-url")); assertThat(settings.jdbcUser(), is("user")); assertThat(settings.jdbcPassword(), is("123")); assertThat(settings.cronTime(), is("0 1 2 * * ?")); assertThat(settings.crawlDelay(), is(1234)); } } <file_sep>package ru.job4j.tracker; public abstract class MenuAction extends BaseAction { /** * Menu which is used as user interface element * outputting info messages. */ private final MenuTracker menu; /** * Initializes fields of base class. * @param key unique key * @param info descriptive information * @param menu menu object used as user interface */ public MenuAction(int key, String info, MenuTracker menu) { super(key, info); this.menu = menu; } /** * Prints info message. * @param text message */ public void print(String text) { menu.print(text); } /** * Prints caption of the action. * @param text text for the caption */ public void printCaption(String text) { menu.printCaption(text); } } <file_sep>package ru.job4j.vacparser.parsers; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.Test; import ru.job4j.vacparser.model.ForumPage; import ru.job4j.vacparser.model.Vacancy; import ru.job4j.vacparser.util.ResourceReader; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class ForumPageParserTest { private static final String TEST_PAGE = "html/forum_page_test.html"; private static final LocalDate TODAY = LocalDate.now(); @Test public void whenParseThenCanFindAllVacancies() throws IOException { Document doc = Jsoup.parse(ResourceReader.readWin1251(TEST_PAGE)); ForumPageParser parser = new ForumPageParser(); ForumPage forumPage = parser.parse(doc, 0); List<Vacancy> vacancies = forumPage.getVacancies(); assertThat(vacancies.size(), is(2)); Vacancy vacancy1 = vacancies.get(0); assertThat(vacancy1.getName(), is("SQL разработчик в отчетность (Москва)")); assertThat(vacancy1.getLink(), is("https://www.sql.ru/forum/1317171/sql-razrabotchik-v-otchetnost-moskva")); assertThat(vacancy1.getModified(), is(LocalDateTime.of(TODAY, LocalTime.of(16, 5)))); Vacancy vacancy2 = vacancies.get(1); assertThat(vacancy2.getName(), is("DBA mariaDB Москва")); assertThat(vacancy2.getLink(), is("https://www.sql.ru/forum/1317271/dba-mariadb-moskva")); assertThat(vacancy2.getModified(), is(LocalDateTime.of(TODAY, LocalTime.of(15, 40)))); } @Test public void whenNextPageUrlThenReturnsLinkToPageAfterCurrent() throws IOException { Document doc = Jsoup.parse(ResourceReader.readWin1251(TEST_PAGE)); ForumPageParser parser = new ForumPageParser(); ForumPage forumPage = parser.parse(doc, 0); String nextPageLink = forumPage.getNextPage(); String expected = "https://www.sql.ru/forum/job-offers/2"; assertThat(nextPageLink, is(expected)); } } <file_sep>package ru.job4j.ood.tictac; /** * Represents output for game. */ public interface Output { /** Prints the specified game grid. */ void printGrid(GridView grid); /** Prints the specified message. */ void print(String message); /** Prints the specified message and newline symbol. */ void println(String message); } <file_sep>package ru.job4j.ood.carparking; /** * Represents parking spot. */ public class Spot { private static final int DEFAULT_CAR_SIZE = 1; private final int size; private boolean occupied; /** Constructs the spot using the default car size. */ public Spot() { this(DEFAULT_CAR_SIZE); } /** Constructs the spot using the specified size. */ public Spot(int size) { this.size = size; } /** Returns size of the spot in units where one unit corresponds to the smallest parking spot. */ public int size() { return size; } /** Returns true is the spot is occupied, false otherwise. */ public boolean isOccupied() { return occupied; } /** Occupies the spot. */ public void occupy() { occupied = true; } /** Set the spot free. */ public void free() { occupied = false; } } <file_sep>package ru.job4j.ood.warehouse.foods; import ru.job4j.ood.warehouse.Food; import java.math.BigDecimal; import java.time.LocalDate; /** Represents milk. */ public class Milk extends Food { public Milk(LocalDate createDate, LocalDate expireDate, BigDecimal price) { super("Milk", createDate, expireDate, price, null); } } <file_sep>package ru.job4j.pseudo; /** * Triangle shape. */ public class Triangle implements Shape { /** * Height of the triangle. */ private final int height; /** * Constructs instance of {@code Triangle} of specified height. * @param height height of the triangle */ public Triangle(int height) { this.height = height; } /** * Returns a pseudo-graphic representation of the triangle. * @return pseudo-graphic triangle */ @Override public String draw() { StringBuilder builder = new StringBuilder(); int width = height * 2 - 1; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { builder.append(col >= height - 1 - row && col <= height - 1 + row ? "*" : " "); } builder.append(NEW_LINE); } return builder.toString(); } } <file_sep>package ru.job4j.io.pack; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.file.*; import java.util.*; import java.util.zip.*; import static org.hamcrest.core.Is.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class FolderArchiverTest { private static final String PROJECT_NAME = "project1"; private static final String SOURCE_FOLDER = PROJECT_NAME; private static final String OUTPUT_FILE = PROJECT_NAME + ".zip"; private final Map<String, Long> expectedInZip = new HashMap<>(); private Path source; private Path dir1; private Path dir11; @Before public void setUp() throws IOException { Path testDir = Jimfs.newFileSystem(Configuration.unix()).getPath("testDir"); Files.createDirectory(testDir); source = Files.createDirectory(testDir.resolve(SOURCE_FOLDER)); dir1 = Files.createDirectory(source.resolve("dir1")); dir11 = Files.createDirectory(dir1.resolve("dir11")); } @Test public void whenCompressWithoutLimitationsThenArchiveContainsAllFiles() throws IOException { makeFile(expectedInZip, source, "File1.java", "public class File1 { public void bar() {} }"); makeFile(expectedInZip, dir1, "file11.xml", "<xml><content>content 11</content></xml>"); makeFile(expectedInZip, dir11, "File111.java", "public class File111 { public void bar() {} }"); makeFile(expectedInZip, dir11, "file112.txt", "A quick brown fox jumps over a lazy dog. A quick brown fox jumps over a lazy dog."); Path zipArchive = new FolderArchiver().compress(source, source.resolveSibling(OUTPUT_FILE), null); assertThat(Files.exists(zipArchive), is(true)); Map<String, Long> zippedFiles = putZipEntriesInfoToMap(zipArchive); assertThat(zippedFiles, is(expectedInZip)); } @Test public void whenCompressExcludingByExtensionThenArchiveDoesNotContainExcludedFiles() throws IOException { makeFile(expectedInZip, source, "File1.java", "public class File1 { public void bar() {} }"); makeFile(null, dir1, "file11.xml", "<xml><content>content 11</content></xml>"); makeFile(expectedInZip, dir11, "File111.java", "public class File111 { public void bar() {} }"); makeFile(null, dir11, "file112.txt", "A quick brown fox jumps over a lazy dog. A quick brown fox jumps over a lazy dog."); Path zipArchive = new FolderArchiver().compress(source, source.resolveSibling(OUTPUT_FILE), List.of("xml", "txt")); assertThat(Files.exists(zipArchive), is(true)); Map<String, Long> zippedFiles = putZipEntriesInfoToMap(zipArchive); assertThat(zippedFiles, is(expectedInZip)); } @Test(expected = FolderArchiver.WrappedIOException.class) public void whenWriteEntryToZipAndIOExceptionThenThrowWrappedIOException() throws IOException { ZipOutputStream out = mock(ZipOutputStream.class); doThrow(new IOException()).when(out).putNextEntry(any(ZipEntry.class)); new FolderArchiver().writeEntryToZip(out, source, source.resolve("test.txt")); } private static Map<String, Long> putZipEntriesInfoToMap(Path zipFile) throws IOException { Map<String, Long> info = new HashMap<>(); try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(zipFile))) { ZipEntry entry; Checker checker = new Checker(); while ((entry = zin.getNextEntry()) != null) { info.put(entry.getName(), checker.crc32(zin)); zin.closeEntry(); } } return info; } private void makeFile(Map<String, Long> map, Path parent, String name, String content) throws IOException { Path file = parent.resolve(name); Files.writeString(file, content); if (map != null) { Checker checker = new Checker(); map.put(source.relativize(file).toString(), checker.crc32(file)); } } private static class Checker { private final byte[] bytes = new byte[128]; public long crc32(InputStream in) throws IOException { Checksum checksum = new CRC32(); CheckedInputStream checkedIn = new CheckedInputStream(in, checksum); int n; do { n = checkedIn.read(bytes); } while (n != -1); return checksum.getValue(); } public long crc32(Path file) throws IOException { Checksum checksum = new CRC32(); checksum.update(Files.readAllBytes(file)); return checksum.getValue(); } } } <file_sep>package ru.job4j.ood.store; import org.junit.Before; import org.junit.Test; import ru.job4j.ood.store.foods.Bread; import ru.job4j.ood.store.foods.Cheese; import ru.job4j.ood.store.foods.Meat; import ru.job4j.ood.store.foods.Milk; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class ControlQualityTest { private static final BigDecimal DISCOUNT = BigDecimal.valueOf(0.2); public static final int WAREHOUSE_LIMIT = 25; public static final int SALE_LIMIT = 75; private final LocalDate now = LocalDate.now(); private Store warehouse; private Store shop; private Store trash; private Distribution distribution; private ControlQuality control; @Before public void setup() { distribution = new Distribution(new SimpleStoreCycleCalculator(WAREHOUSE_LIMIT, SALE_LIMIT, now)); warehouse = new Warehouse(distribution.warehouseStrategy()); shop = new Shop(distribution.shopStrategy(), distribution.discountStrategy(), DISCOUNT); trash = new Trash(distribution.trashStrategy()); control = new ControlQuality(List.of(warehouse, shop, trash)); } @Test public void whenShelfLifeLessThan25ThenMoveToWarehouse() { Milk milk = makeFood(Milk.class, 1, 4); control.sort(List.of(milk)); assertThat(warehouse.takeAll(), contains(milk)); assertThat(shop.takeAll(), not(contains(milk))); assertThat(trash.takeAll(), not(contains(milk))); } @Test public void whenShelfLife25To75ThenMoveToShop() { Milk milk = makeFood(Milk.class, 2, 2); control.sort(List.of(milk)); assertThat(warehouse.takeAll(), not(contains(milk))); assertThat(shop.takeAll(), contains(milk)); assertThat(trash.takeAll(), not(contains(milk))); } @Test public void whenShelfLifeGreaterThan75ThenDiscountAndMoveToShop() { Milk milk = makeFood(Milk.class, 4, 1); assertNull(milk.getDiscount()); control.sort(List.of(milk)); assertThat(warehouse.takeAll(), not(contains(milk))); assertThat(shop.takeAll(), contains(milk)); assertThat(trash.takeAll(), not(contains(milk))); assertThat(milk.getDiscount(), is(DISCOUNT)); } @Test public void whenShelfLifeExpiresThenMoveToTrash() { Milk milk = makeFood(Milk.class, 4, -1); control.sort(List.of(milk)); assertThat(warehouse.takeAll(), not(contains(milk))); assertThat(shop.takeAll(), not(contains(milk))); assertThat(trash.takeAll(), contains(milk)); } @Test public void whenResortAfterSomeDaysPassedThenFoodIsRedistributed() { Milk milk = makeFood(Milk.class, 0, 5); Bread bread = makeFood(Bread.class, 2, 3); Cheese cheese = makeFood(Cheese.class, 4, 1); Meat meat = makeFood(Meat.class, 5, -1); control.sort(List.of(milk, bread, cheese, meat)); assertTrue(warehouse.contains(milk)); assertTrue(shop.contains(bread)); assertTrue(shop.contains(cheese)); assertThat(cheese.getDiscount(), is(DISCOUNT)); assertTrue(trash.contains(meat)); LocalDate twoDaysHavePassed = now.plusDays(2); distribution.setCycleCalculator(new SimpleStoreCycleCalculator(WAREHOUSE_LIMIT, SALE_LIMIT, twoDaysHavePassed)); control.resort(); assertTrue(warehouse.isEmpty()); assertThat(shop.takeAll(), containsInAnyOrder(milk, bread)); assertThat(bread.getDiscount(), is(DISCOUNT)); assertThat(trash.takeAll(), containsInAnyOrder(cheese, meat)); } @Test public void whenFoodAcceptedByTwoStoresThenOnlyOneReceivesIt() { trash = new Trash(distribution.warehouseStrategy()); control = new ControlQuality(List.of(warehouse, shop, trash)); Milk milk = makeFood(Milk.class, 0, 5); control.sort(List.of(milk)); assertTrue(warehouse.contains(milk)); assertTrue(shop.isEmpty()); assertTrue(trash.isEmpty()); } private <T extends Food> T makeFood(Class<T> clazz, int createdBefore, int expiresAfter) { try { Constructor<T> constructor = clazz.getConstructor(LocalDate.class, LocalDate.class, BigDecimal.class); LocalDate created = now.minusDays(createdBefore); LocalDate expires = now.plusDays(expiresAfter); return constructor.newInstance(created, expires, null); } catch (Exception e) { throw new RuntimeException("Failed to make food", e); } } } <file_sep>package ru.job4j.ood.calculator; /** Represents arithmetic expression than can be evaluated. */ public class ArithmeticExpression implements Expression { /** First operand. */ private final Expression first; /** Second operand. */ private final Expression second; /** Arithmetic operation. */ private final ArithmeticOperation operation; /** Calculator used for evaluation. */ private final ArithmeticCalculator calculator; /** * Constructs expression using the specified operands, operation and calculator. * @param first first operand * @param second second operand * @param operation used operation * @param calculator used calculator */ public ArithmeticExpression(Expression first, Expression second, ArithmeticOperation operation, ArithmeticCalculator calculator) { this.first = first; this.second = second; this.operation = operation; this.calculator = calculator; } /** Evaluates the expression and returns result. */ @Override public double evaluate() { return calculator.calculate(first.evaluate(), operation, second.evaluate()); } } <file_sep>package ru.job4j.ood.warehouse.quality; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; /** * Distributes entities into destinations using an external sorting strategy * represented by {@link DestinationSorter} instance. */ public class ControlQuality<T extends Expirable & Discountable> { private static final Logger LOG = LogManager.getLogger(ControlQuality.class); /** Maps destination id to real destinations. */ private final Map<DestId, Consumer<T>> destinations = new EnumMap<>(DestId.class); /** Strategy used for determining destination of sorted entities. */ private DestinationSorter<T> sortingStrategy; /** Initializes instance with the specified sorting strategy. * @param sortingStrategy strategy used for determining destination of sorted entities */ public ControlQuality(DestinationSorter<T> sortingStrategy) { this.sortingStrategy = sortingStrategy; } /** Sets sorting strategy. * @param sortingStrategy strategy used for determining destination of sorted entities */ public void setSortingStrategy(DestinationSorter<T> sortingStrategy) { this.sortingStrategy = sortingStrategy; } /** * Adds destination for sorted entities. * @param id destination id * @param destination destination that should receive sorted entities */ public void addDestination(DestId id, Consumer<T> destination) { destinations.put(id, destination); } /** * Distributes the specified entities to destinations using current sorting strategy algorithm. * @param entityList list of entities to distribute */ public void sort(List<T> entityList) { for (T entity : entityList) { DestId id = sortingStrategy.sort(entity); Consumer<T> consumer = destinations.get(id); if (consumer != null) { LOG.trace("{} goes to {}", entity, consumer); consumer.accept(entity); } } } } <file_sep>package ru.job4j.bank; /** * Thrown when expected account not found. */ public class AccountNotFoundException extends RuntimeException { } <file_sep>package ru.job4j.search; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class SearchTest { private final List<File> expectedFiles = new ArrayList<>(); private File testDir; /** Allows creation of files and folders that will be deleted when the test finishes. */ @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() throws IOException { testDir = temporaryFolder.newFolder("testDir"); File dir1 = makeDir(testDir, "dir1"); File dir2 = makeDir(testDir, "dir2"); File dir3 = makeDir(testDir, "dir3"); File dir34 = makeDir(dir3, "dir34"); makeFileExpected(dir1, "txt"); makeFileExpected(dir2, "java"); makeFile(dir2, "bak"); makeFileExpected(dir3, "java"); makeFile(dir3, "class"); makeFileExpected(dir34, "java"); makeFile(dir34, "doc"); } @Test public void whenSearchFilesWithGivenExtensionsThenReturnsCorrectList() { List<File> result = new Search().files(testDir.getAbsolutePath(), List.of("txt", "java")); assertThat(result, is(expectedFiles)); } @SuppressWarnings("ResultOfMethodCallIgnored") private static File makeDir(File parent, String name) { File d = new File(parent, name); d.mkdir(); return d; } private static File makeFile(File parent, String ext) throws IOException { return File.createTempFile("test", "." + ext, parent); } private void makeFileExpected(File parent, String ext) throws IOException { expectedFiles.add(makeFile(parent, ext)); } } <file_sep>package ru.job4j.sqltoxml; import org.junit.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class StoreXMLTest { @Test public void whenSaveThenWritesXml() throws IOException, JAXBException { Path testDir = Files.createTempDirectory(StoreXMLTest.class.getName()); Path target = testDir.resolve("store.xml"); StoreXML storeXML = new StoreXML(target); List<Entry> entries = Arrays.asList(new Entry(10), new Entry(20)); String expected = String.join("\n", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", "<entries>", " <entry>", " <field>10</field>", " </entry>", " <entry>", " <field>20</field>", " </entry>", "</entries>", ""); try { storeXML.save(entries); assertThat(Files.exists(target), is(true)); String actual = Files.readString(target); assertThat(actual, is(expected)); } finally { Files.deleteIfExists(target); Files.deleteIfExists(testDir); } } } <file_sep>package ru.job4j.ood.store; import ru.job4j.ood.store.cycle.Expirable; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Objects; /** Represents any kind of food that can be stored in a warehouse and sold in a shop. */ public abstract class Food implements Expirable { /** Name of the food. */ private final String name; /** Date of creation. */ private final LocalDate createDate; /** Date of expiration. */ private final LocalDate expireDate; /** Price of the food. */ private final BigDecimal price; /** Discount of the food. */ private BigDecimal discount; /** Creates food instance and initializes it with the specified name, dates, price and discount. * @param name name of the food * @param createDate date of creation * @param expireDate date of expiration * @param price price of the food * @param discount discount of the food */ public Food(String name, LocalDate createDate, LocalDate expireDate, BigDecimal price, BigDecimal discount) { this.name = name; this.createDate = createDate; this.expireDate = expireDate; this.price = price; this.discount = discount; } /** Returns name of the food. */ public String getName() { return name; } /** Returns price of the food. */ public BigDecimal getPrice() { return price; } /** Returns discount of the food. */ public BigDecimal getDiscount() { return discount; } /** Returns date of creation. */ @Override public LocalDate created() { return createDate; } /** Returns date of expiration. */ @Override public LocalDate expires() { return expireDate; } /** Sets the specified discount. */ public void setDiscount(BigDecimal discount) { this.discount = discount; } @Override public String toString() { return "Food{name='" + name + "', createDate=" + createDate + ", expireDate=" + expireDate + ", price=" + price + ", discount=" + discount + '}'; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Food food = (Food) obj; return Objects.equals(name, food.name) && Objects.equals(createDate, food.createDate) && Objects.equals(expireDate, food.expireDate) && Objects.equals(price, food.price) && Objects.equals(discount, food.discount); } @Override public int hashCode() { return Objects.hash(name, createDate, expireDate, price, discount); } } <file_sep>package ru.job4j.ood.store; import org.junit.Before; import org.junit.Test; import ru.job4j.ood.store.foods.Meat; import ru.job4j.ood.store.foods.Milk; import java.math.BigDecimal; import java.time.LocalDate; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class ShopTest { private static final BigDecimal DISCOUNT = BigDecimal.valueOf(0.3); private final LocalDate now = LocalDate.now(); private Shop shop; @Before public void setup() { Distribution distribution = new Distribution(new SimpleStoreCycleCalculator(25, 75, now)); shop = new Shop(distribution.shopStrategy(), distribution.discountStrategy(), DISCOUNT); } @Test public void whenFoodFrom25To75ThenAcceptsAndAdds() { Milk milk = new Milk(now.minusDays(1), now.plusDays(3), BigDecimal.valueOf(80)); assertThat(shop.accepts(milk), is(true)); shop.add(milk); assertThat(shop.takeAll(), contains(milk)); } @Test public void whenFoodFrom75to100ThenAcceptsAddsAndDiscounts() { Milk milk = new Milk(now.minusDays(3), now.plusDays(1), BigDecimal.valueOf(80)); assertThat(shop.accepts(milk), is(true)); assertNull(milk.getDiscount()); shop.add(milk); assertThat(shop.takeAll(), contains(milk)); assertThat(milk.getDiscount(), is(DISCOUNT)); } @Test public void whenFoodBelow25orOver100ThenRejects() { Milk milk = new Milk(now.minusDays(1), now.plusDays(4), BigDecimal.valueOf(80)); assertThat(shop.accepts(milk), is(false)); Meat meat = new Meat(now.minusDays(4), now.minusDays(1), BigDecimal.valueOf(400)); assertThat(shop.accepts(meat), is(false)); } } <file_sep>package ru.job4j.ood.warehouse.quality; /** * The sorter is used for determining destination of sorted entities according to expiration state. */ public interface DestinationSorter<T extends Expirable & Discountable> { /** * Determines destination ID for the specified entity. */ DestId sort(T entity); } <file_sep>package ru.job4j.io.chat; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Random; import java.util.Scanner; /** * Console chat that allows a user to enter phrases and prints * responses from input file. * The whole conversation is written to a log file. */ public class ConsoleChat { /** Path to a file that contains phrases. */ private final Path inputFile; /** Path to a log file. */ private final Path logFile; /** A random generator that is used to choose response phrases. */ private Random random; /** * Creates and initializes the chat with the specified input and log files. * @param inputFile path to input file * @param logFile path to log file */ public ConsoleChat(Path inputFile, Path logFile) { this.inputFile = inputFile; this.logFile = logFile; random = new Random(); } /** * Starts the chat. * @throws IOException if an I/O error occurs. */ public void start() throws IOException { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); List<String> answers = Files.readAllLines(inputFile); Chat chat = new Chat(scanner::nextLine, () -> answers.get(random.nextInt(answers.size())), System.out::println, new SimpleLogger(logFile)); chat.start(); } /** * Sets random with fixed seed for testing purposes. * @param random random with fixed seed */ void setRandom(Random random) { this.random = random; } } <file_sep>package ru.job4j.collections.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * Contains methods that convert iterators. */ public class Converter { /** * Converts iterator of iterators to iterator of Integer elements. * @param it iterator of iterators * @return iterator of Integer elements */ public Iterator<Integer> convert(Iterator<Iterator<Integer>> it) { return new IntegerIterator(it); } /** * Implements iterator on Integers that uses iterator of iterators * as underlying iterator. */ private static class IntegerIterator implements Iterator<Integer> { private final Iterator<Iterator<Integer>> outer; private Iterator<Integer> inner; /** * Constructs iterator based on the specified iterator of iterators. * @param outer iterator of iterators */ public IntegerIterator(Iterator<Iterator<Integer>> outer) { this.outer = outer; moveToNextInner(); } /** * @return true if the iteration has more Integer elements, false otherwise */ @Override public boolean hasNext() { boolean hasMore = inner.hasNext(); while (!hasMore && outer.hasNext()) { moveToNextInner(); hasMore = inner.hasNext(); } return hasMore; } /** * @return next Integer in the iteration * @throws NoSuchElementException if the iteration has no more elements */ @Override public Integer next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } return inner.next(); } /** * Retrieves next inner iterator from the outer iterator. */ private void moveToNextInner() { inner = outer.next(); } } } <file_sep>package ru.job4j.ood.store; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; /** * Distributes food items into stores. */ public class ControlQuality { private static final Logger LOG = LogManager.getLogger(ControlQuality.class); /** Stores that receive food items. */ private final List<Store> stores; /** Initializes control instance with the specified list of stores. */ public ControlQuality(List<Store> stores) { this.stores = stores; } /** Moves food items to destination stores. */ public void sort(List<Food> foods) { for (Food food : foods) { add(food); } } /** Moves the specified food item to a receiving store. */ public void add(Food food) { for (Store store : stores) { if (store.accepts(food)) { LOG.trace("{} goes to {}", food, store); store.add(food); break; } } } /** Redistributes foods in all stores. */ public void resort() { List<Food> redistributedFood = new ArrayList<>(); for (Store store : stores) { redistributedFood.addAll(store.takeAll()); } redistributedFood.forEach(f -> f.setDiscount(null)); sort(redistributedFood); } } <file_sep>package ru.job4j.ood.calculator; import java.util.Map; /** Represents arithmetic operation. */ public enum ArithmeticOperation { ADD, SUBTRACT, MULTIPLY, DIVIDE; /** Map of symbols to operations. */ private static final Map<String, ArithmeticOperation> OPERATIONS = Map.of( "+", ADD, "-", SUBTRACT, "*", MULTIPLY, "/", DIVIDE ); /** Transforms string representation to operation object. */ public static ArithmeticOperation from(String s) { ArithmeticOperation operation = OPERATIONS.get(s); if (operation == null) { throw new IllegalArgumentException("Can not infer any arithmetic operation from this argument: " + s); } return operation; } } <file_sep>-- 1. Написать запрос получение всех продуктов с типом "СЫР" select p.id, p.name, p.expired_date, p.price from product p inner join type t on p.type_id = t.id where t.name = 'СЫР'; -- 2. Написать запрос получения всех продуктов, у кого в имени есть слово "мороженное" select id, name, expired_date, price from product where name like '%мороженное%'; -- 3. Написать запрос, который выводит все продукты, срок годности которых заканчивается в следующем месяце. select id, name, expired_date, price from product where date_part('month', expired_date) = date_part('month', current_date) + 1; -- 4. Написать запрос, который выводит самый дорогой продукт. select id, name, expired_date, price from product order by price desc limit 1; -- 5. Написать запрос, который выводит количество всех продуктов определенного типа. select count(p.id) from product p inner join type t on t.id = p.type_id where t.name = 'СЫР'; -- 6. Написать запрос получение всех продуктов с типом "СЫР" и "МОЛОКО" select p.id, p.name, p.expired_date, p.price from product p inner join type t on p.type_id = t.id where t.name in ('СЫР', 'МОЛОКО'); -- 7. Написать запрос, который выводит тип продуктов, которых осталось меньше 10 штук. select t.name, p.name from type t inner join product p on t.id = p.type_id where p.quantity < 10; -- 8. Вывести все продукты и их тип. select p.id, p.name, t.name, p.expired_date, p.price from product p inner join type t on p.type_id = t.id; <file_sep>package ru.job4j.io.netw.bot; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Map; import static ru.job4j.io.netw.bot.Constants.*; /** * Application that starts a server for {@link WiseOracle}. */ public class WiseOracleServerApp { /** Path to resource file containing answers of the oracle. */ private static final String XML_FILE = "/oracle_answers.xml"; /** Established application port after the server socket is created. */ private static volatile int establishedAppPort = -1; /** Oracle that can reply to requests. */ private Oracle oracle; /** Server socket that waits for requests from clients. */ private ServerSocket serverSocket; /** Local port on which the server is listening. */ private int localPort; /** * Constructs an instance of the app using any free port. * @param answers collection of keyword-answer pairs * @throws IOException if an I/O error occurs opening the socket, or waiting for the connection */ WiseOracleServerApp(Map<String, String> answers) throws IOException { this(0, answers); } /** * Constructs instance of app using the specified port. * @param port port number * @param answers collection of keyword-answer pairs * @throws IOException if an I/O error occurs opening the socket, or waiting for the connection */ private WiseOracleServerApp(int port, Map<String, String> answers) throws IOException { serverSocket = new ServerSocket(port); localPort = serverSocket.getLocalPort(); oracle = new WiseOracle(answers); } /** * Accepts an incoming connection and starts the server. * @throws IOException if an I/O error occurs */ public void start() throws IOException { try (Socket incoming = serverSocket.accept()) { new Server(incoming, oracle).start(); } } /** * @return local port on which the server is listening */ int getLocalPort() { return localPort; } /** * Main method starting the application. * @param args args[0] - port number (optional) */ public static void main(String[] args) { int port = DEFAULT_PORT; if (args.length == 1) { port = Integer.parseInt(args[0]); } try { DataLoader data = new DataLoader(); data.loadFromXML(WiseOracleServerApp.class.getResourceAsStream(XML_FILE)); Map<String, String> answers = data.getMap(); var app = new WiseOracleServerApp(port, answers); establishedAppPort = app.getLocalPort(); app.start(); } catch (IOException e) { e.printStackTrace(); } } /** * Gets the established application port for testing purposes. * @return number of the port used by the application after the server socket is created */ static int getEstablishedAppPort() { return establishedAppPort; } } <file_sep>package ru.job4j.collections.iterator; import org.junit.Test; import java.util.NoSuchElementException; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class EvenIteratorTest { @Test public void whenNoDataThenHasNextReturnsFalse() { EvenIterator it = new EvenIterator(new int[]{}); assertThat(it.hasNext(), is(false)); } @Test public void whenNoEvenNumbersThenHasNextReturnsFalse() { EvenIterator it = new EvenIterator(new int[]{1, 3}); assertThat(it.hasNext(), is(false)); } @Test public void whenEvenNumberThenHasNextReturnsTrue() { EvenIterator it = new EvenIterator(new int[]{2}); assertThat(it.hasNext(), is(true)); } @Test public void whenEvenSeparatedByOddThenNextReturnsOnlyEven() { EvenIterator it = new EvenIterator(new int[]{2, 1, 4}); assertThat(it.next(), is(2)); assertThat(it.next(), is(4)); } @Test public void whenOddAfterEvenThenHasNextReturnsFalse() { EvenIterator it = new EvenIterator(new int[]{2, 1}); it.next(); assertThat(it.hasNext(), is(false)); } @Test(expected = NoSuchElementException.class) public void whenNoEvenThenNextThrowsException() { EvenIterator it = new EvenIterator(new int[]{3, 1}); it.next(); } } <file_sep>package ru.job4j.chess.figures.white; import ru.job4j.chess.behaviors.OneCellForwardMove; import ru.job4j.chess.figures.Cell; import ru.job4j.chess.figures.Figure; public class PawnWhite extends Figure { public static final int WHITE_PAWN_DELTA_Y = 1; /** * Constructs PawnWhite with specified position. * @param position position on board */ public PawnWhite(final Cell position) { super(position, new OneCellForwardMove(WHITE_PAWN_DELTA_Y)); } } <file_sep>package ru.job4j.ood.tictac; /** Type of player used in configuration. */ public enum PlayerType { HUMAN, COMPUTER } <file_sep>package ru.job4j.io.netw.bot; import java.io.IOException; import java.net.Socket; import java.util.Scanner; import static ru.job4j.io.netw.bot.Constants.*; /** * Allows to enter requests in command line interface (CLI) and receive responses from a server. */ public class ClientCliApp { /** * Main method starting the application. * @param args args[0] - host, args[1] - port number */ public static void main(String[] args) { int port = DEFAULT_PORT; String host = "localhost"; if (args.length == 2) { host = args[0]; port = Integer.parseInt(args[1]); } try { Socket socket = new Socket(host, port); Scanner in = new Scanner(System.in); Client client = new Client(socket, in::nextLine, System.out::println); client.start(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package ru.job4j.tracker; /** * Implements {@link Input} for testing purposes. */ public class StubInput implements Input { /** * Sequence of prepared testing answers. */ private final String[] answers; /** * Index of next answer, it is used and incremented * in {@link StubInput#ask(String) ask} method. */ private int position; /** * Constructs instance of {@code StubInput} and initializes it with array of answers. * @param answers array of answers */ public StubInput(String[] answers) { this.answers = answers; } /** * Retrieves next response to testing question. * @param question not used * @return next response from a sequence of prepared answers */ @Override public String ask(String question) { return answers[position++]; } /** * Retrieves next integer response to testing question. * @param question question * @param range allowable range of responses * @return next integer response from a sequence of prepared answers * @throws MenuOutException when answer is not in specified range */ @Override public int ask(String question, int[] range) { int answer = Integer.parseInt(this.ask(question)); if (ConsoleInput.valueIsNotInRange(answer, range)) { throw new MenuOutException("Out of menu range: " + answer); } return answer; } } <file_sep>create table if not exists item ( id serial primary key, name varchar(128), description varchar(128), created bigint ); <file_sep>package ru.job4j.chess.figures; import ru.job4j.chess.behaviors.MovingBehavior; import ru.job4j.chess.exceptions.ImpossibleMoveException; /** * Base class from which all concrete figures must inherit. */ public abstract class Figure { /** * Current position on chess board. */ private final Cell position; /** * Algorithm which implements moving behavior of concrete type of figure. */ private MovingBehavior movingBehavior; /** * Initializes figure with position and moving behavior. * @param position position on board * @param movingBehavior moving behavior of concrete type of figure */ public Figure(final Cell position, MovingBehavior movingBehavior) { this.position = position; this.movingBehavior = movingBehavior; } /** * Current position on chess board. * @return current position */ public Cell position() { return this.position; } /** * Checks that this figure can move this way and returns cells included in this way. * @param source source position * @param dest destination position * @return array of cells that the figure must pass through * @throws ImpossibleMoveException throws when the destination can not be reached in one move */ public Cell[] way(Cell source, Cell dest) throws ImpossibleMoveException { return movingBehavior.way(source, dest); } /** * Name of the figure's icon file. * @return icon file name */ public String icon() { return String.format( "%s.png", this.getClass().getSimpleName() ); } /** * Creates copy of the figure on destination position. * @param dest destination cell * @return copy of the figure */ public Figure copy(Cell dest) { try { Figure copied = this.getClass().getConstructor(Cell.class).newInstance(dest); copied.movingBehavior = this.movingBehavior; return copied; } catch (Exception e) { throw new RuntimeException("Error copying figure", e); } } } <file_sep>package ru.job4j.calculate; /** * Simple calculator that can add, subtract, divide and multiply. * The result of the last calculation can be obtained using the {@code getResult} * method. */ public class Calculate { private double result; /** * Gets result of the last calculation. * @return result of the last calculation */ public double getResult() { return this.result; } /** * Adds two values. * @param first first value * @param second second value */ public void add(double first, double second) { this.result = first + second; } /** * Subtracts one value from another. * @param first the value from which the other value is subtracted * @param second subtraction value */ public void subtract(double first, double second) { this.result = first - second; } /** * Divides one value by another. * @param dividend dividend value * @param divider divisor value */ public void div(double dividend, double divider) { this.result = dividend / divider; } /** * Multiplies two values. * @param first first value * @param second second value */ public void multiply(double first, double second) { this.result = first * second; } } <file_sep>package ru.job4j.vacparser; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.vacparser.util.AppSettings; /** * Main class that starts the scheduler using application settings. */ public class Main { private static final String DEFAULT_PROP_NAME = "vacparser_app.properties"; private static final Logger LOG = LoggerFactory.getLogger(Main.class); /** * Loads settings and starts scheduler. * @param args first argument may contain name of properties resource file */ public static void main(String[] args) { String propName = DEFAULT_PROP_NAME; if (args.length > 0) { propName = args[0]; } AppSettings settings = new AppSettings(propName); AppScheduler appScheduler = new AppScheduler(VacanciesScraper.class, settings); try { appScheduler.start(); } catch (SchedulerException e) { LOG.error("Scheduler error", e); } } } <file_sep>package ru.job4j.bank; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.hamcrest.core.Is.is; import static org.hamcrest.number.IsCloseTo.closeTo; import static org.junit.Assert.*; public class BankTest { public static final double DELTA = 1e-15; private Bank bank; @Before public void setUp() { bank = new Bank(); } @Test public void whenNonExistingPassportThenHasNoAccounts() { List<Account> list = bank.getUserAccounts("123"); assertThat(list.size(), is(0)); } @Test public void whenAddingUserWithoutAccountThenHasNoAccounts() { User user = new User("Denis", "<PASSWORD>"); bank.addUser(user); List<Account> list = bank.getUserAccounts("pass1"); assertThat(list.size(), is(0)); } @Test public void whenAddingUserAndAccountThenReturnAccount() { bank.addUser(new User("Denis", "<PASSWORD>")); Account account = new Account("requisites", 0); bank.addAccountToUser("pass1", account); List<Account> list = bank.getUserAccounts("pass1"); assertThat(list.get(0), is(account)); } @Test public void whenAddingSameUserThenAccountsNotLost() { User user = new User("Denis", "<PASSWORD>"); bank.addUser(user); Account account = new Account("requisites", 0); bank.addAccountToUser("pass1", account); User user2 = new User("Denis", "<PASSWORD>"); bank.addUser(user2); List<Account> list = bank.getUserAccounts("pass1"); assertThat(list.size(), is(1)); assertThat(list.get(0), is(account)); } @Test public void whenDeleteUserThenHasNoAccounts() { User user = new User("Denis", "<PASSWORD>"); bank.addUser(user); bank.addAccountToUser("pass1", new Account("requisites", 0)); bank.deleteUser(user); List<Account> list = bank.getUserAccounts("pass1"); assertThat(list.size(), is(0)); } @Test public void whenDeleteAccountThenHasNoSuchAccount() { bank.addUser(new User("Denis", "<PASSWORD>")); Account first = new Account("requisites1", 0); bank.addAccountToUser("pass1", first); bank.addAccountToUser("pass1", new Account("requisites2", 0)); assertThat(bank.getUserAccounts("pass1").size(), is(2)); bank.deleteAccountFromUser("pass1", first); List<Account> list = bank.getUserAccounts("pass1"); assertThat(list.size(), is(1)); assertThat(list.get(0).getRequisites(), is("requisites2")); } @Test(expected = AccountNotFoundException.class) public void whenDeleteNonExistingAccountThenException() { bank.addUser(new User("Denis", "<PASSWORD>")); bank.addAccountToUser("pass1", new Account("requisites1", 0)); Account nonExistingAccount = new Account("non-existing-requisites", 0.0); bank.deleteAccountFromUser("pass1", nonExistingAccount); } @Test public void whenTransferringToSameUserAccountThenSuccess() { bank.addUser(new User("Denis", "<PASSWORD>")); Account fromAccount = new Account("reqFrom", 100.0); Account toAccount = new Account("reqTo", 0); bank.addAccountToUser("pass1", fromAccount); bank.addAccountToUser("pass1", toAccount); assertThat(fromAccount.getValue(), closeTo(100.0, DELTA)); assertThat(toAccount.getValue(), closeTo(0.0, DELTA)); boolean result = bank.transferMoney("pass1", "reqFrom", "pass1", "reqTo", 90.0); assertThat(result, is(true)); assertThat(fromAccount.getValue(), closeTo(10.0, DELTA)); assertThat(toAccount.getValue(), closeTo(90.0, DELTA)); } @Test public void whenTransferringToOtherUserAccountThenSuccess() { bank.addUser(new User("Denis", "<PASSWORD>From")); bank.addUser(new User("Sasha", "<PASSWORD>To")); Account fromAccount = new Account("reqFrom", 100.0); Account toAccount = new Account("reqTo", 1000.0); bank.addAccountToUser("passFrom", fromAccount); bank.addAccountToUser("passTo", toAccount); assertThat(fromAccount.getValue(), closeTo(100.0, DELTA)); assertThat(toAccount.getValue(), closeTo(1000.0, DELTA)); boolean result = bank.transferMoney("passFrom", "reqFrom", "passTo", "reqTo", 80.0); assertThat(result, is(true)); assertThat(fromAccount.getValue(), closeTo(20.0, DELTA)); assertThat(toAccount.getValue(), closeTo(1080.0, DELTA)); } @Test public void whenTransferringFromNonExistingUserThenReturnFalse() { bank.addUser(new User("Sasha", "<PASSWORD>To")); Account toAccount = new Account("reqTo", 1000.0); bank.addAccountToUser("passTo", toAccount); boolean result = bank.transferMoney("passFrom", "reqFrom", "passTo", "reqTo", 80.0); assertThat(result, is(false)); assertThat(toAccount.getValue(), closeTo(1000.0, DELTA)); } @Test public void whenTransferringToNonExistingUserThenReturnFalse() { bank.addUser(new User("Sasha", "<PASSWORD>From")); Account fromAccount = new Account("reqFrom", 1000.0); bank.addAccountToUser("passFrom", fromAccount); boolean result = bank.transferMoney("passFrom", "reqFrom", "passTo", "reqTo", 80.0); assertThat(result, is(false)); assertThat(fromAccount.getValue(), closeTo(1000.0, DELTA)); } @Test public void whenTransferringFromNonExistingAccountThenReturnFalse() { bank.addUser(new User("Denis", "passFrom")); bank.addUser(new User("Sasha", "<PASSWORD>To")); Account fromAccount = new Account("reqFrom", 100.0); Account toAccount = new Account("reqTo", 1000.0); bank.addAccountToUser("passFrom", fromAccount); bank.addAccountToUser("passTo", toAccount); boolean result = bank.transferMoney("passFrom", "reqNonExisting", "passTo", "reqTo", 80.0); assertThat(result, is(false)); assertThat(toAccount.getValue(), closeTo(1000.0, DELTA)); } @Test public void whenTransferringToNonExistingAccountThenReturnFalse() { bank.addUser(new User("Denis", "<PASSWORD>From")); bank.addUser(new User("Sasha", "<PASSWORD>To")); Account fromAccount = new Account("reqFrom", 100.0); Account toAccount = new Account("reqTo", 1000.0); bank.addAccountToUser("passFrom", fromAccount); bank.addAccountToUser("passTo", toAccount); boolean result = bank.transferMoney("passFrom", "reqFrom", "passTo", "reqNonExisting", 80.0); assertThat(result, is(false)); assertThat(fromAccount.getValue(), closeTo(100.0, DELTA)); } @Test public void whenNotEnoughMoneyThenReturnFalse() { bank.addUser(new User("Denis", "<PASSWORD>From")); bank.addUser(new User("Sasha", "<PASSWORD>")); Account fromAccount = new Account("reqFrom", 100.0); Account toAccount = new Account("reqTo", 1000.0); bank.addAccountToUser("passFrom", fromAccount); bank.addAccountToUser("passTo", toAccount); boolean result = bank.transferMoney("passFrom", "reqFrom", "passTo", "reqTo", 101.0); assertThat(result, is(false)); assertThat(fromAccount.getValue(), closeTo(100.0, DELTA)); assertThat(toAccount.getValue(), closeTo(1000.0, DELTA)); } } <file_sep>package ru.job4j.array; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; public class ArrayCharTest { @Test public void whenStartsWithPrefixThenTrue() { ArrayChar word = new ArrayChar("Hello"); boolean result = word.startsWith("He"); assertThat(result, is(true)); } @Test public void whenDoesNotStartWithPrefixThenFalse() { ArrayChar word = new ArrayChar("Hello"); boolean result = word.startsWith("Hi"); assertThat(result, is(false)); } } <file_sep>package ru.job4j.io.netw.bot; import java.util.Map; /** * Implements an {@link Oracle} that uses a collection of possible responses. */ public class WiseOracle implements Oracle { /** Regular expression used to split a request to words. */ private static final String SPLIT_REGEX = "\\s|\\?"; /** Map where key represents a keyword, and value represents an answer. */ private final Map<String, String> answers; /** The default response to questions containing no keywords. */ private String defaultResponse = "I don't know"; /** * Constructs an oracle and initializes it with the answers. * @param answers collection of keyword-answer pairs */ public WiseOracle(Map<String, String> answers) { this.answers = answers; defaultResponse = answers.getOrDefault("default", defaultResponse); } /** * Provides a response to a request. * @param request a sentence representing request to the oracle * @return response of the oracle */ @Override public String reply(String request) { String[] words = request.split(SPLIT_REGEX); for (String key : words) { String answer = answers.get(key); if (answer != null) { return answer; } } return defaultResponse; } } <file_sep>package ru.job4j.vacparser; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.vacparser.util.AppSettings; /** * Application scheduler that starts processing according to the settings. */ public class AppScheduler { private static final Logger LOG = LoggerFactory.getLogger(AppScheduler.class); private static final String JOB_NAME = "vacparserJob"; private static final String TRIGGER_NAME = "vacparserTrigger"; private static final String GROUP = "vacparserGroup"; private final Class<? extends Job> jobClass; private final AppSettings appSettings; /** * Initializes scheduler with job and application settings. * @param jobClass class for the job that will be started * @param appSettings application settings used by the job */ public AppScheduler(Class<? extends Job> jobClass, AppSettings appSettings) { this.jobClass = jobClass; this.appSettings = appSettings; } /** * Starts processing. * @throws SchedulerException if error within the Quartz scheduler */ public void start() throws SchedulerException { SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler quartzScheduler = schedulerFactory.getScheduler(); quartzScheduler.start(); JobDataMap dataMap = new JobDataMap(); dataMap.put("appSettings", appSettings); JobDetail jobDetail = JobBuilder.newJob(jobClass) .withIdentity(JOB_NAME, GROUP) .usingJobData(dataMap) .build(); String cronExpression = appSettings.cronTime(); LOG.info("Using cron expression: {}", cronExpression); CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity(TRIGGER_NAME, GROUP) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) .forJob(JOB_NAME, GROUP) .build(); quartzScheduler.scheduleJob(jobDetail, trigger); } } <file_sep>package ru.job4j.ood.tictac; /** * Factory that can create a human or random computer player. */ public class HumanVsRandomPlayerFactory implements PlayerFactory { /** Creates player with the specified parameters. */ @Override public Player create(Mark mark, PlayerType type, Input input) { if (type == PlayerType.HUMAN) { return new HumanPlayer(mark, input); } else if (type == PlayerType.COMPUTER) { return new RandomComputerPlayer(mark); } throw new IllegalArgumentException("Invalid player type: " + type); } } <file_sep>package ru.job4j.io.netw.bot; /** * Represents an oracle that can reply to requests. */ public interface Oracle { /** * Provides a response to a request. * @param request a sentence representing request to the oracle * @return response of the oracle */ String reply(String request); } <file_sep>package ru.job4j.ood.tictac; /** * Game grid that stores marks in a two-dimensional array of cells. */ public class ArrayGrid implements GameGrid { private final Mark[][] cells; /** Constructs the grid using the specified grid size. */ public ArrayGrid(int size) { cells = new Mark[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cells[i][j] = Mark.EMPTY; } } } /** Returns mark at the specified position. */ @Override public Mark markAt(Position position) { return cells[position.getRow()][position.getCol()]; } /** Changes mark of the grid cell at the specified position. */ @Override public void changeCell(Position position, Mark mark) { if (!isFreeAt(position)) { throw new IllegalStateException("This cell is busy"); } cells[position.getRow()][position.getCol()] = mark; } /** * Tries to find a winner having the specified number of adjacent marks. * @param lineLength number of adjacent marks that should be on one line. * @return mark of the winner or null if there is no winner yet */ @Override public Mark findWinningMark(int lineLength) { Mark result = checkVerticalsAndHorizontals(lineLength); if (result != null) { return result; } return checkSlopes(lineLength); } /** Checks whether the cell the specified position is free or busy. */ @Override public boolean isFreeAt(Position position) { return cells[position.getRow()][position.getCol()] == Mark.EMPTY; } /** Returns true if all cells in the grid are busy, false otherwise. */ @Override public boolean isFull() { for (Mark[] row : cells) { for (Mark mark : row) { if (mark == Mark.EMPTY) { return false; } } } return true; } /** Returns size of the grid. */ @Override public int size() { return cells.length; } private Mark checkVerticalsAndHorizontals(int lineLength) { for (int i = 0; i < cells.length; i++) { Mark vMark = cells[0][i]; int vertCount = 1; Mark horMark = cells[i][0]; int horCount = 1; for (int j = 1; j < cells.length; j++) { if (cells[j][i] == vMark) { vertCount++; if (vertCount == lineLength && vMark != Mark.EMPTY) { return vMark; } } else { vMark = cells[j][i]; vertCount = 1; } if (cells[i][j] == horMark) { horCount++; if (horCount == lineLength && horMark != Mark.EMPTY) { return horMark; } } else { horMark = cells[i][j]; horCount = 1; } } } return null; } private Mark checkSlopes(int lineLength) { Mark m = checkAllLeftSlopes(lineLength); if (m != null) { return m; } return checkAllRightSlopes(lineLength); } private Mark checkAllLeftSlopes(int lineLength) { int stop = cells.length - lineLength; for (int r = 0; r <= stop; r++) { for (int c = 0; c <= stop; c++) { Mark m = checkOneLeftSlope(r, c, lineLength); if (m != null) { return m; } } } return null; } private Mark checkAllRightSlopes(int lineLength) { int stop = cells.length - lineLength; for (int r = 0; r <= stop; r++) { for (int c = lineLength - 1; c < cells.length; c++) { Mark m = checkOneRightSlope(r, c, lineLength); if (m != null) { return m; } } } return null; } private Mark checkOneRightSlope(int r, int c, int lineLength) { Mark m = cells[r][c]; int count = 1; for (int i = r + 1, j = c - 1; i < cells.length && j >= 0; i++, j--) { if (m != cells[i][j]) { m = cells[i][j]; count = 1; } else { count++; if (count == lineLength && m != Mark.EMPTY) { return m; } } } return null; } private Mark checkOneLeftSlope(int r, int c, int lineLength) { Mark m = cells[r][c]; int count = 1; for (int i = r + 1, j = c + 1; i < cells.length && j < cells.length; i++, j++) { if (m != cells[i][j]) { m = cells[i][j]; count = 1; } else { count++; if (count == lineLength && m != Mark.EMPTY) { return m; } } } return null; } } <file_sep>package ru.job4j.stream9; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Selects groups of students. */ public class SelectStudents { /** * Selects students with score greater than the specified bound. * @param students list of students, may contain null values * @param bound boundary value, the students with score less or equal * than this bound are not included in the result * @return list of selected students with score greater than the bound */ public List<Student> levelOf(List<Student> students, int bound) { return students.stream() .flatMap(Stream::ofNullable) .sorted(Comparator.reverseOrder()) .takeWhile(s -> s.getScore() > bound) .collect(Collectors.toList()); } } <file_sep>package ru.job4j.ood.store; import java.util.List; /** * Represents interface for a food store that can accept or reject food items. */ public interface Store { /** Adds the specified food to the store. * @param food added food instance */ void add(Food food); /** Checks if the store can accept the specified food * @param food checked food * @return true if the store can accept the food instance, false otherwise */ boolean accepts(Food food); /** * Takes and removes all foods from the store * @return list of taken food */ List<Food> takeAll(); /** * Checks if the store contains the specified food instance. * @param food food to check * @return true if the store contains the food, false otherwise */ boolean contains(Food food); /** * Checks if the store is empty. * @return true if the store is empty, false otherwise */ boolean isEmpty(); } <file_sep>package ru.job4j.ood.calculator; import ru.job4j.calculate.Calculate; import java.util.Map; import java.util.function.BiConsumer; /** Allows calculator to be used as {@link ArithmeticCalculator}. */ public class ArithmeticCalculatorAdapter implements ArithmeticCalculator { /** Used calculator. */ private final Calculate calculator; /** Map of arithmetic operations (in string format) to concrete methods. */ private Map<ArithmeticOperation, BiConsumer<Double, Double>> operationsMap; /** Initializes adapter with the specified calculator. */ public ArithmeticCalculatorAdapter(Calculate calculator) { this.calculator = calculator; initOperations(); } /** * Calculates result of arithmetic operation with two operands * @param op1 first operand * @param operation arithmetic operation * @param op2 second operand * @return result of calculation */ @Override public double calculate(double op1, ArithmeticOperation operation, double op2) { operationsMap.get(operation).accept(op1, op2); return calculator.getResult(); } private void initOperations() { operationsMap = Map.of( ArithmeticOperation.ADD, calculator::add, ArithmeticOperation.SUBTRACT, calculator::subtract, ArithmeticOperation.MULTIPLY, calculator::multiply, ArithmeticOperation.DIVIDE, calculator::div ); } } <file_sep>package ru.job4j.io.pack; import org.junit.Test; import java.util.List; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; public class ArgsTest { @Test public void whenAllCmdArgumentsSuppliedThenReturnsAllParameters() { Args args = new Args("-d c:\\project\\job4j\\ -e java xml -o project.zip".split(" ")); assertThat(args.directory(), is("c:\\project\\job4j\\")); assertThat(args.exclude(), is(List.of("java", "xml"))); assertThat(args.output(), is("project.zip")); } @Test public void whenAllCmdArgumentsShuffledThenReturnsAllParameters() { Args args = new Args("-o project.zip -d c:\\project\\job4j\\ -e java xml".split(" ")); assertThat(args.directory(), is("c:\\project\\job4j\\")); assertThat(args.exclude(), is(List.of("java", "xml"))); assertThat(args.output(), is("project.zip")); } @Test public void whenOutputNotSuppliedThenReturnDefaultOutput() { Args args = new Args("-d job4j -e doc class".split(" ")); assertThat(args.output(), is("job4j.zip")); assertThat(args.exclude(), is(List.of("doc", "class"))); } @Test public void whenExcludeNotSuppliedThenReturnEmptyList() { Args args = new Args("-d c:\\project\\job4j\\ -o c:\\tmp\\project.zip".split(" ")); assertThat(args.directory(), is("c:\\project\\job4j\\")); assertThat(args.exclude(), is(List.of())); assertThat(args.output(), is("c:\\tmp\\project.zip")); } @Test(expected = IllegalArgumentException.class) public void whenNoDirectoryThenThrowException() { new Args("-o c:\\tmp\\project.zip".split(" ")); } } <file_sep>package ru.job4j.io.pack; import java.util.ArrayList; import java.util.List; /** * Parser of command line arguments. */ public class Args { /** Path to the source directory. */ private String dir; /** List of file extensions that should be excluded. */ private List<String> extList; /** Path to the output file. */ private String out; /** Constructs instance using array of command line arguments. */ public Args(String[] args) { parse(args); } /** * Parses command line arguments. * @param args array of arguments */ private void parse(String[] args) { extList = new ArrayList<>(); for (int i = 0; i < args.length; i++) { String token = args[i]; if ("-d".equals(token)) { dir = args[++i]; } else if ("-e".equals(token)) { int j = i + 1; while (j < args.length) { token = args[j]; if (token.startsWith("-")) { break; } else { extList.add(token); j++; } } i = j - 1; } else if ("-o".equals(token)) { out = args[++i]; } } if (dir == null) { throw new IllegalArgumentException("args should contain '-d' 'directory' arguments"); } if (out == null) { out = dir + ".zip"; } } /** * @return path to the source directory */ public String directory() { return dir; } /** * @return list of file extensions that should be excluded */ public List<String> exclude() { return extList; } /** * @return path to the output file */ public String output() { return out; } } <file_sep>-- Создание таблиц: -- 1. Есть таблица встреч(id, name), есть таблица юзеров(id, name). CREATE TABLE meeting ( id serial PRIMARY KEY, "name" text ); CREATE TABLE "user" ( id serial PRIMARY KEY, "name" text ); -- Нужно доработать модель базы данных, так чтобы пользователи могли учавствовать во встречах. -- У каждого участника встречи может быть разный статус участия - например подтвердил участие, отклонил. CREATE TABLE user_meeting ( meeting_id int NOT NULL REFERENCES meeting(id), user_id int NOT NULL REFERENCES "user"(id), status text CHECK (status IN ('accept', 'cancel')), PRIMARY KEY (meeting_id, user_id) ); -- Наполнение таблиц INSERT INTO "user" ("name") VALUES ('<NAME>'), ('<NAME>'), ('<NAME>'); INSERT INTO meeting ("name") VALUES ('Search ships'), ('Destroy ships'), ('Build ships'); INSERT INTO user_meeting VALUES (1, 1, 'accept'), (1, 2, 'accept'), (1, 3, 'accept'); INSERT INTO user_meeting VALUES (2, 1, 'cancel'), (2, 2, 'accept'), (2, 3, 'accept'); -- 2. Нужно написать запрос, -- который получит список всех заявок и количество подтвердивших участников. SELECT meeting."name", count(user_meeting.user_id) FROM meeting JOIN user_meeting ON meeting.id = user_meeting.meeting_id WHERE user_meeting.status = 'accept' GROUP BY meeting."name"; -- 3. Нужно получить все совещания, где не было ни одной заявки на посещения SELECT meeting."name" FROM meeting LEFT JOIN user_meeting ON meeting.id = user_meeting.meeting_id WHERE user_meeting.user_id IS NULL; -- Вариант получения всех совещаний, где либо не было ни одной заявки, либо у заявки не было определенного статуса SELECT meeting.name FROM meeting LEFT JOIN user_meeting AS um1 ON meeting.id = um1.meeting_id GROUP BY meeting.name, um1.meeting_id HAVING ( SELECT count(*) FROM user_meeting AS um2 WHERE um2.meeting_id = um1.meeting_id AND um2.status IN ('accept', 'cancel') ) = 0; -- Упрощеннй, без группировки: SELECT DISTINCT meeting.name FROM meeting LEFT JOIN user_meeting AS um1 ON meeting.id = um1.meeting_id WHERE ( SELECT count(*) FROM user_meeting AS um2 WHERE um2.meeting_id = um1.meeting_id AND um2.status IN ('accept', 'cancel') ) = 0; --Более упрощенный вариант, который дает такой же результат: SELECT meeting.name FROM meeting WHERE ( SELECT count(*) FROM user_meeting WHERE meeting_id = meeting.id AND status IN ('accept', 'cancel') ) = 0; --Этот запрос возвращает те совещания, где совсем не было заявок, либо у заявок пустой статус (NULL) --Если нужно получить все совещания, где нет ни одной подвтержденной заявки, тогда --Вариант 1: SELECT meeting.name FROM meeting WHERE ( SELECT count(*) FROM user_meeting WHERE meeting_id = meeting.id AND status = 'accept' ) = 0; --Вариант 2: SELECT name FROM meeting EXCEPT SELECT DISTINCT meeting.name FROM meeting LEFT JOIN user_meeting ON meeting.id = user_meeting.meeting_id WHERE status = 'accept';<file_sep>create table if not exists item ( id serial primary key, name varchar(128), description varchar(128), created bigint ); <file_sep>package ru.job4j.collections.stats; import java.util.HashMap; import java.util.List; import java.util.Objects; /** * List change analyzer. */ public class Analyzer { /** * Calculates list change statistics. * @param previous list in the previous state * @param current list in the current state * @return change statistics */ public Info diff(List<User> previous, List<User> current) { Info info = new Info(); var idUsers = new HashMap<Integer, User>(); current.forEach(user -> idUsers.put(user.id, user)); previous.forEach(prev -> { User found = idUsers.get(prev.id); if (found == null) { info.deleted++; } else if (!Objects.equals(found.name, prev.name)) { info.changed++; } }); info.added = current.size() - (previous.size() - info.deleted); return info; } /** * Represents user that has id and name. */ public static class User { /** ID of the user. */ public final int id; /** Name of the user. */ public final String name; /** * Constructs user and initializes with the specified ID and name. * @param id ID of the user * @param name name of the user */ public User(int id, String name) { this.id = id; this.name = name; } } /** * Statistics info that contains numbers of added, changed and deleted elements. */ public static class Info { /** Number of changed elements. */ int changed; /** Number of deleted elements. */ int deleted; /** Number of added elements. */ int added; } } <file_sep>package ru.job4j.ood.warehouse.foods; import ru.job4j.ood.warehouse.Food; import java.math.BigDecimal; import java.time.LocalDate; /** Represents meat. */ public class Meat extends Food { public Meat(LocalDate createDate, LocalDate expireDate, BigDecimal price) { super("Meat", createDate, expireDate, price, null); } } <file_sep>package ru.job4j.array; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; public class MergeArraysTest { @Test public void whenFirstArrayEmptyThenReturnSecond() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {}; int[] array2 = {2}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {2}; assertThat(result, is(expected)); } @Test public void whenSecondArrayEmptyThenReturnFirst() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {1}; int[] array2 = {}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {1}; assertThat(result, is(expected)); } @Test public void whenBothEmptyThenReturnEmpty() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {}; int[] array2 = {}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {}; assertThat(result, is(expected)); } @Test public void whenMergingArraysLength1And1ThenResult2() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {1}; int[] array2 = {2}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {1, 2}; assertThat(result, is(expected)); } @Test public void whenFirstArrayLongerThenResultIsNonDecreasing() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {1, 3, 5, 7, 9}; int[] array2 = {2, 4, 6}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {1, 2, 3, 4, 5, 6, 7, 9}; assertThat(result, is(expected)); } @Test public void whenSecondArrayLongerThenResultIsNonDecreasing() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {1, 3, 5, 7, 9}; int[] array2 = {2, 4, 6, 8, 10, 12, 14}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14}; assertThat(result, is(expected)); } @Test public void whenEqualArraysThenResultIsNonDecreasing() { MergeArrays mergeArrays = new MergeArrays(); int[] array1 = {1, 3, 5, 7, 9}; int[] array2 = {1, 3, 5, 7, 9}; int[] result = mergeArrays.merge(array1, array2); int[] expected = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9}; assertThat(result, is(expected)); } }<file_sep>package ru.job4j.sqltoxml; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Stores and retrieves database records. * The instance of {@code StoreSQL} should be instantiated within try-with-resources block. */ @SuppressWarnings("SqlResolve") public class StoreSQL implements AutoCloseable { private Connection connection; /** Constructs the instance and opens connection according to the specified config. */ public StoreSQL(Config config) throws SQLException { connection = DriverManager.getConnection(config.get("url")); } /** * If the database contains any records then deletes all records. * Then generates the specified number of records. * @param size number of records */ @SuppressWarnings("SqlWithoutWhere") public void generate(int size) throws SQLException { try (Statement stmt = connection.createStatement()) { stmt.executeUpdate("create table if not exists entry (field integer)"); stmt.executeUpdate("delete from entry"); } try (PreparedStatement insert = connection.prepareStatement("insert into entry (field) values (?)")) { connection.setAutoCommit(false); for (int i = 1; i <= size; i++) { insert.setInt(1, i); insert.addBatch(); } insert.executeBatch(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } } /** * Retrieves all the records from the database. * @return list of records */ public List<Entry> load() throws SQLException { List<Entry> entries = new ArrayList<>(); try (Statement st = connection.createStatement()) { ResultSet rs = st.executeQuery("select field from entry"); while (rs.next()) { Entry entry = new Entry(rs.getInt("field")); entries.add(entry); } } return entries; } /** Closes the connection. */ @Override public void close() throws Exception { if (connection != null && !connection.isClosed()) { connection.close(); } } } <file_sep>package ru.job4j.loop; /** * Contains methods for counting. */ public class Counter { /** * Counts the sum of even numbers in the range. * @param start starting value of range * @param finish finishing value of range (inclusive) * @return sum of even numbers */ public int add(int start, int finish) { int sum = 0; for (int i = start; i <= finish; i++) { if (i % 2 == 0) { sum += i; } } return sum; } } <file_sep>package ru.job4j.pseudo; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class SquareTest { @Test public void whenCreateSquareWithLength3ThenReturnSquareShapeSize3Characters() { Shape square = new Square(3); @SuppressWarnings("StringBufferReplaceableByString") String expected = new StringBuilder() .append("***").append(Shape.NEW_LINE) .append("***").append(Shape.NEW_LINE) .append("***").append(Shape.NEW_LINE).toString(); assertThat(square.draw(), is(expected)); } } <file_sep>package ru.job4j.io.scripts; import java.util.*; /** * Задан список скриптов с указанием их зависимосей. * 1 - [2, 3], 2 - [4], 3 - [4, 5], 4 - [], 5 - [] * Необходим написать метод, который возвращает список всех скриптов, * которые нужны для загрузки входящего скрипта. * Например, чтобы выполнить скрипт 1. нужно выполнить скрипт (2, 3), * которые в свою очередь зависят от 4 и 5 скрипта. */ public class ScriptDependencies { /** * Возвращает список id всех скриптов, которые нужны для загрузки заданного скрипта * @param dependencies зависимости скриптов * @param scriptId id заданного скрипта * @return список id скриптов или пустой список если нет зависимосей */ List<Integer> load(Map<Integer, List<Integer>> dependencies, Integer scriptId) { List<Integer> idList = dependencies.get(scriptId); if (idList == null) { return List.of(); } LinkedHashSet<Integer> idSet = new LinkedHashSet<>(); Queue<List<Integer>> queue = new ArrayDeque<>(); queue.add(idList); while (!queue.isEmpty()) { for (Integer id : queue.remove()) { idSet.add(id); idList = dependencies.get(id); if (idList != null && !idList.isEmpty()) { queue.add(idList); } } } return new ArrayList<>(idSet); } } <file_sep>package ru.job4j.ood.warehouse.quality; import org.junit.Before; import org.junit.Test; import ru.job4j.ood.warehouse.Food; import ru.job4j.ood.warehouse.Shop; import ru.job4j.ood.warehouse.Trash; import ru.job4j.ood.warehouse.Warehouse; import ru.job4j.ood.warehouse.foods.Milk; import java.math.BigDecimal; import java.util.List; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static ru.job4j.ood.warehouse.quality.TestHelpers.stubDate; public class ControlQualityTest { private RuleBasedDestinationSorter<Food> strategy; private ControlQuality<Food> control; @Before public void setup() { strategy = new RuleBasedDestinationSorter<>( new SimpleStoreCycleCalculator(25, 75, stubDate(10))); control = new ControlQuality<>(strategy); } @Test public void whenShelfLifeLessThan25ThenMoveToWarehouse() { Warehouse warehouse = new Warehouse(); Milk milk = createMilk(8, 18); List<Food> foods = List.of(milk); strategy.setRule(StoreCycle.STORAGE, DestId.WAREHOUSE); control.addDestination(DestId.WAREHOUSE, warehouse); assertThat(warehouse.contains(milk), is(false)); control.sort(foods); assertThat(warehouse.contains(milk), is(true)); } @Test public void whenShelfLife25To75ThenMoveToShop() { Shop shop = new Shop(); Milk milk = createMilk(5, 15); List<Food> foods = List.of(milk); strategy.setRule(StoreCycle.FOR_SALE, DestId.SHOP); control.addDestination(DestId.SHOP, shop); assertThat(shop.contains(milk), is(false)); control.sort(foods); assertThat(shop.contains(milk), is(true)); } @Test public void whenShelfLifeGreaterThan75ThenDiscountAndMoveToShop() { Shop shop = new Shop(); Milk milk = createMilk(2, 12); List<Food> foods = List.of(milk); strategy.setRule(StoreCycle.DISCOUNT_SALE, DestId.SHOP, food -> food.setDiscount(BigDecimal.valueOf(0.3))); control.addDestination(DestId.SHOP, shop); BigDecimal expectedDiscount = BigDecimal.valueOf(0.3); assertThat(shop.contains(milk), is(false)); assertThat(milk.getDiscount(), is(not(expectedDiscount))); control.sort(foods); assertThat(shop.contains(milk), is(true)); assertThat(milk.getDiscount(), is(expectedDiscount)); } @Test public void whenShelfLifeExpiresThenMoveToTrash() { Trash trash = new Trash(); Milk milk = createMilk(1, 9); List<Food> foods = List.of(milk); strategy.setRule(StoreCycle.EXPIRED, DestId.TRASH); control.addDestination(DestId.TRASH, trash); assertThat(trash.contains(milk), is(false)); control.sort(foods); assertThat(trash.contains(milk), is(true)); } @Test public void whenChangeSortingStrategyThenChangesDistribution() { Shop shop = new Shop(); Milk milk = createMilk(1, 11); strategy.setRule(StoreCycle.DISCOUNT_SALE, DestId.SHOP, food -> food.setDiscount(BigDecimal.valueOf(0.2))); control.addDestination(DestId.SHOP, shop); BigDecimal expectedDiscount = BigDecimal.valueOf(0.2); assertThat(shop.contains(milk), is(false)); assertThat(milk.getDiscount(), is(not(expectedDiscount))); control.sort(List.of(milk)); assertThat(shop.contains(milk), is(true)); assertThat(milk.getDiscount(), is(expectedDiscount)); RuleBasedDestinationSorter<Food> savingStrategy = new RuleBasedDestinationSorter<>( new SimpleStoreCycleCalculator(25, 95, stubDate(10))); savingStrategy.setRule(StoreCycle.FOR_SALE, DestId.SHOP); control.setSortingStrategy(savingStrategy); Milk milk2 = createMilk(1, 11); assertThat(shop.contains(milk2), is(false)); control.sort(List.of(milk2)); assertThat(shop.contains(milk2), is(true)); assertNull(milk2.getDiscount()); } private Milk createMilk(int creationDay, int expirationDay) { return new Milk(stubDate(creationDay), stubDate(expirationDay), BigDecimal.valueOf(90)); } } <file_sep>package ru.job4j.collections.map; /** * Represents integer for testing purposes only. * Uses last digit of the integer as return value of method {@code hashCode}. * Uses whole integer value in method {@code equals}. */ public final class FakeInt { private final int value; private FakeInt(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof FakeInt) { return ((FakeInt) o).value == this.value; } return false; } @Override public int hashCode() { return value % 10; } @Override public String toString() { return "FakeInt{value=" + value + '}'; } static FakeInt of(int n) { return new FakeInt(n); } } <file_sep>package ru.job4j.tictactoe; import javafx.scene.shape.Rectangle; /** * Represents a cell in game board. * Contains methods for checking if cell contains X, O, or is empty. */ public class Figure3T extends Rectangle { private boolean markX = false; private boolean markO = false; public Figure3T() { } public Figure3T(boolean markX) { this.markX = markX; this.markO = !markX; } public void take(boolean markX) { this.markX = markX; this.markO = !markX; } public boolean hasMarkX() { return this.markX; } public boolean hasMarkO() { return this.markO; } }<file_sep>[![Build Status](https://travis-ci.org/dpopkov/job4j.svg?branch=master)](https://travis-ci.org/dpopkov/job4j) [![codecov](https://codecov.io/gh/dpopkov/job4j/branch/master/graph/badge.svg)](https://codecov.io/gh/dpopkov/job4j) # <NAME> Задания курса [Job4j](http://job4j.ru). ## Некоторые задания, реализованные за время обучения * [Задания по Memory Model, Garbage Collector и Profiling](chapter_009_gc/src/main/java/ru/job4j/jmm) * [Генератор шаблонов](chapter_008_ood/src/main/java/ru/job4j/ood/templates) * [Модель динамического распределения товаров](chapter_008_ood/src/main/java/ru/job4j/ood/store) * [Модель Парковки машин](chapter_008_ood/src/main/java/ru/job4j/ood/carparking) * [Модель Warehouse](chapter_008_ood/src/main/java/ru/job4j/ood/warehouse) * [Парсер вакансий с запуском по расписанию](vacparser/src/main/java/ru/job4j/vacparser) * [Реализация Proxy для JDBC connection](chapter_007_db/src/test/java/ru/job4j/tracker/ConnectionRollback.java) * [Задания на XML/XSLT](chapter_007_db/src/main/java/ru/job4j/sqltoxml) * [Консольный Tracker DB записей](chapter_007_db/src/main/java/ru/job4j/tracker) * [Утилита поиска файлов](find/src/main/java/ru/job4j/io/find) * [Симулятор сетевого бота](chapter_006_io/src/main/java/ru/job4j/io/netw/bot) * [Консольный чат](chapter_006_io/src/main/java/ru/job4j/io/chat) * [Консольный архиватор](pack/src/main/java/ru/job4j/io/pack) * [Сканирование файловой системы](chapter_006_io/src/main/java/ru/job4j/search) * [Задания на Input/Output](chapter_006_io/src/main/java/ru/job4j/io) * [GUI для приложения Puzzle](puzzle/src/main/java/ru/job4j/puzzle) * [Реализации Коллекций](chapter_005/src/main/java/ru/job4j/collections) * [Шахматная доска, каркас](chess/src/main/java/ru/job4j/chess) * [Консольный Tracker записей](chapter_002/src/main/java/ru/job4j/tracker) * [Крестики-нолики на JavaFX](chapter_001/src/main/java/ru/job4j/tictactoe) #### VM options для запуска проектов JavaFX на JDK 11 --module-path c:\path-to-javafx\javafx-sdk-11\lib --add-modules=javafx.controls,javafx.fxml <file_sep>package ru.job4j.sqltoxml; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; /** * Contains methods for transforming XML files using XSLT. */ public class ConvertXSLT { /** * Converts the source file using the specified XSLT document. * @param source source file * @param dest destination file * @param xslt XSLT document */ public void convert(Path source, Path dest, Path xslt) throws IOException, TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; try (Reader xsltInput = Files.newBufferedReader(xslt)) { transformer = factory.newTransformer(new StreamSource(xsltInput)); } try (Reader in = Files.newBufferedReader(source); Writer out = Files.newBufferedWriter(dest)) { transformer.transform(new StreamSource(in), new StreamResult(out)); } } } <file_sep>package ru.job4j.tracker; /** * Defines input system. */ public interface Input { /** * Outputs a question and retrieves a response. * @param question question * @return response */ String ask(String question); /** * Outputs a question and retrieves integer response within specified range. * @param question question * @param range allowable range of responses * @return response */ int ask(String question, int[] range); } <file_sep>package ru.job4j.ood.calculator; import org.hamcrest.Matchers; import org.junit.Test; import static org.junit.Assert.assertThat; public class TrigonometricFunctionCalculatorTest { public static final double DELTA = 1e-15; @Test public void canCalculateSinus() { FunctionCalculator calc = new TrigonometricFunctionCalculator(); double result = calc.calculate(FunctionName.SIN, 30); assertThat(result, Matchers.closeTo(0.5, DELTA)); } @Test public void canCalculateCosine() { FunctionCalculator calc = new TrigonometricFunctionCalculator(); double result = calc.calculate(FunctionName.COS, 60); assertThat(result, Matchers.closeTo(0.5, DELTA)); } @Test public void canCalculateTangent() { FunctionCalculator calc = new TrigonometricFunctionCalculator(); double result = calc.calculate(FunctionName.TAN, 45); assertThat(result, Matchers.closeTo(1.0, DELTA)); } } <file_sep>-- 1. Вывести список всех машин и все привязанные к ним детали. select c.name as Car, bt.name as BodyType, e.description as Engine, gb.description as Gearbox from car as c inner join body_type as bt on c.body_type_id = bt.body_type_id inner join engine as e on c.engine_id = e.engine_id inner join gearbox as gb on c.gearbox_id = gb.gearbox_id; -- 2. Вывести отдельно детали, которые не используются в машине, кузова, двигатели, коробки передач. -- Неиспользуемые кузова select bt.name from car as c right join body_type as bt on c.body_type_id = bt.body_type_id where c.car_id is null; -- Неиспользуемые двигатели select e.description from car as c right join engine as e on c.engine_id = e.engine_id where c.car_id is null; -- Неиспользуемые коробки передач select gb.description from car as c right join gearbox as gb on c.gearbox_id = gb.gearbox_id where c.car_id is null; <file_sep>package ru.job4j.departments; import java.util.*; /** * Contains methods sorting departments codes. */ public class CodeSorter { /** * Delimiter separating sub-departments in department codes. */ private static final String DELIMITER = "\\"; /** * Delimiter used in regular expression. */ private static final String REGEX_DELIMITER = "\\\\"; /** * Sorts department codes in ascending order. Original list remains unchanged. * Adds sub-divisions missing in the hierarchy. * @param codes list of department codes * @return list of sorted codes */ public List<String> sortAscending(List<String> codes) { return sort(codes, null); } /** * Sorts department codes in descending order. Original list remains unchanged. * Adds sub-divisions missing in the hierarchy. * @param codes list of department codes * @return list of sorted codes */ public List<String> sortDescending(List<String> codes) { return sort(codes, new DescendingComparator()); } /** * Sorts list of codes according to specified comparator. * If no comparator is supplied (argument is null) then sorts in natural order. * @param codes list of department codes * @param comparator department codes comparator * @return list of sorted codes (original list remains unchanged) */ private List<String> sort(List<String> codes, Comparator<String[]> comparator) { List<String> sortedList; if (comparator == null) { SortedSet<String> sortedSet = new TreeSet<>(codes); for (String code : codes) { ensureSuperCodes(sortedSet, code); } sortedList = new ArrayList<>(sortedSet); } else { SortedMap<String[], String> sortedMap = listToMapOfSplittedCodes(codes, comparator); for (String code : codes) { ensureSuperCodes(sortedMap, code); } sortedList = new ArrayList<>(sortedMap.values()); } return sortedList; } /** * Converts list of codes to sorted map where arrays of splitted sub-codes are associated to the original codes. * @param list list of original codes * @param comparator comparator that will compare splitted sub-codes * @return map of splitted sub-codes to codes */ private SortedMap<String[], String> listToMapOfSplittedCodes(List<String> list, Comparator<String[]> comparator) { SortedMap<String[], String> sorted = new TreeMap<>(comparator); for (String code : list) { String[] subCodes = code.split(REGEX_DELIMITER); sorted.put(subCodes, code); } return sorted; } /** * Implements comparator for descending order preserving hierarchy of sub-departments. */ private class DescendingComparator implements Comparator<String[]> { @Override public int compare(String[] subCodes1, String[] subCodes2) { int minLength = Math.min(subCodes1.length, subCodes2.length); for (int i = 0; i < minLength; i++) { int rst = subCodes2[i].compareTo(subCodes1[i]); if (rst != 0) { return rst; } } return Integer.compare(subCodes1.length, subCodes2.length); } } /** * Ensures that the specified sorted set contains super codes for the specified code. * @param set sorted set of codes * @param code checked code */ private void ensureSuperCodes(SortedSet<String> set, String code) { String superCode = getSuperCode(code); if (superCode != null) { if (!set.contains(superCode)) { set.add(superCode); ensureSuperCodes(set, superCode); } } } /** * Ensures that the specified sorted map contains super codes for the specified code. * @param map sorted map of splitted sub-codes arrays to original codes * @param code checked code */ private void ensureSuperCodes(SortedMap<String[], String> map, String code) { String superCode = getSuperCode(code); if (superCode != null && !map.containsValue(superCode)) { map.put(superCode.split(REGEX_DELIMITER), superCode); ensureSuperCodes(map, superCode); } } /** * Gets super code according to department hierarchy represented in the specified code. * @param code department code * @return super code */ private static String getSuperCode(String code) { int pos = code.lastIndexOf(DELIMITER); if (pos == -1) { return null; } return code.substring(0, pos); } } <file_sep>package ru.job4j.max; /** * Contains methods for finding the maximum value. */ public class Max { /** * Finds maximum value of two integer numbers. * @param first first number * @param second second number * @return maximum value */ @SuppressWarnings("ManualMinMaxCalculation") public int max(int first, int second) { return first > second ? first : second; } /** * Finds maximum value of three integer numbers. * @param first first number * @param second second number * @param third third number * @return maximum value */ public int max(int first, int second, int third) { return max(max(first, second), third); } } <file_sep>package ru.job4j.ood.carparking; import org.junit.Test; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class TruckTest { @Test public void whenGetIdAndSizeThenReturnsIdAndSize() { Vehicle truck = new Truck(new LicensePlateNumber("123"), 4); assertThat(truck.getId(), is("123")); assertThat(truck.size(), is(4)); } } <file_sep>package ru.job4j.ood.calculator; import ru.job4j.calculate.Calculate; import java.util.Scanner; import java.util.function.Supplier; /** * Main class that starts the calculator application.<br> * * Example of interaction:<br> * Enter expression: <kbd>3 + 2</kbd><br> * 5.0 <kbd>/ 2</kbd><br> * 2.5 <kbd>* 3</kbd><br> * 7.5 <kbd>- 0.5</kbd><br> * 7.0 <kbd>exit</kbd> */ public class InteractCalcMain { public static void main(String[] args) { InteractCalc calc = new InteractCalc( new SimpleExpressionEvaluator(new SimpleExpressionParser( new ArithmeticCalculatorAdapter(new Calculate()), new TrigonometricFunctionCalculator()) ), new Supplier<>() { private final Scanner in = new Scanner(System.in); @Override public String get() { return in.nextLine(); } }, System.out::print); calc.start(); } } <file_sep>url=jdbc:sqlite::memory:<file_sep>package ru.job4j.tracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * The repository for the list of items that allows to add, delete, replace and find items. * All data is stored in a database. */ @SuppressWarnings({"SqlResolve", "SqlWithoutWhere"}) public class TrackerSQL implements ITracker, AutoCloseable { static final String ADD_ITEM = "insert into item (name, description, created) values (?, ?, ?)"; static final String REPLACE_ITEM = "update item set name = ?, description = ?, created = ? WHERE id = ?"; static final String DELETE_ITEM = "delete from item where id = ?"; static final String FIND_ALL = "select id, name, description, created from item"; static final String FIND_BY_NAME = "select id, name, description, created from item where name = ?"; static final String FIND_BY_ID = "select id, name, description, created from item where id = ?"; static final String DELETE_ALL = "delete from item"; private static final Logger LOG = LoggerFactory.getLogger(TrackerSQL.class); /** A connection with a working database. */ private final Connection connection; /** * Constructs and initializes tracker with the specified open connection. * @param connection open connection */ public TrackerSQL(Connection connection) { this.connection = connection; } /** * Adds an item and sets unique id of the item. * @param item new item * @return item with initialized id */ @Override public Item add(Item item) { try (PreparedStatement ps = connection.prepareStatement(ADD_ITEM, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, item.getName()); ps.setString(2, item.getDesc()); ps.setLong(3, item.getCreated()); ps.executeUpdate(); ResultSet keys = ps.getGeneratedKeys(); if (keys.next()) { int id = keys.getInt(1); item.setId(Integer.toString(id)); return item; } else { throw new SQLException("Could not get generated key"); } } catch (SQLException e) { LOG.error(e.getMessage(), e); return null; } } /** * Replaces existing item with other item. * @param id id of existing item * @param item new item * @return true if replaced item, false otherwise */ @Override public boolean replace(String id, Item item) { try (PreparedStatement ps = connection.prepareStatement(REPLACE_ITEM)) { ps.setString(1, item.getName()); ps.setString(2, item.getDesc()); ps.setLong(3, item.getCreated()); ps.setInt(4, Integer.parseInt(id)); int numRows = ps.executeUpdate(); return numRows == 1; } catch (SQLException e) { LOG.error(e.getMessage(), e); return false; } } /** * Deletes item by id. * @param id id of existing item * @return true if item was deleted, false otherwise */ @Override public boolean delete(String id) { try (PreparedStatement ps = connection.prepareStatement(DELETE_ITEM)) { ps.setInt(1, Integer.parseInt(id)); ps.executeUpdate(); return true; } catch (SQLException e) { LOG.error(e.getMessage(), e); return false; } } /** * Gets all items in tracker. * @return all items */ @Override public List<Item> findAll() { try (PreparedStatement ps = connection.prepareStatement(FIND_ALL)) { return queryItems(ps); } catch (SQLException e) { LOG.error(e.getMessage(), e); return List.of(); } } /** * Finds by name. * @param name name of item * @return items with names that equal specified key */ @Override public List<Item> findByName(String name) { try (PreparedStatement ps = connection.prepareStatement(FIND_BY_NAME)) { ps.setString(1, name); return queryItems(ps); } catch (SQLException e) { LOG.error(e.getMessage(), e); return List.of(); } } /** * Finds item by specified id. * @param id id of item * @return found item or null if there is no item with specified id */ @Override public Item findById(String id) { try (PreparedStatement ps = connection.prepareStatement(FIND_BY_ID)) { ps.setInt(1, Integer.parseInt(id)); List<Item> items = queryItems(ps); if (items.size() == 1) { return items.get(0); } else { return null; } } catch (SQLException e) { LOG.error(e.getMessage(), e); return null; } } /** * Queries items using the specified prepared statement. * @param ps prepared statement with all the parameters set to the proper values * @return list of found items * @throws SQLException if a database access error occurs */ private List<Item> queryItems(PreparedStatement ps) throws SQLException { ArrayList<Item> items = new ArrayList<>(); ResultSet rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String nameValue = rs.getString("name"); String desc = rs.getString("description"); long created = rs.getLong("created"); Item item = new Item(nameValue, desc, created); item.setId(Integer.toString(id)); items.add(item); } return items; } /** * Deletes all items. * @throws SQLException if a database access error occurs */ public void deleteAll() throws SQLException { try (Statement stmt = connection.createStatement()) { stmt.executeUpdate(DELETE_ALL); } } /** * Closes this resource, relinquishing any underlying resources. * This method is invoked automatically on objects managed by the * {@code try}-with-resources statement. * @throws Exception if this resource cannot be closed */ @Override public void close() throws Exception { if (connection != null && !connection.isClosed()) { connection.close(); } } } <file_sep>package ru.job4j.ood.calculator; /** Represents a function expression that can be calculated. */ public class FunctionExpression implements Expression { /** Argument of the function. */ private final Expression argument; /** Name of the function. */ private final FunctionName functionName; /** Used calculator. */ private final FunctionCalculator calculator; /** Initializes function expression with the specified argument, name and calculator. * @param argument argument of the function * @param functionName name of the function * @param calculator used calculator */ public FunctionExpression(Expression argument, FunctionName functionName, FunctionCalculator calculator) { this.argument = argument; this.functionName = functionName; this.calculator = calculator; } /** Evaluates the expression and returns result. */ @Override public double evaluate() { return calculator.calculate(functionName, argument.evaluate()); } } <file_sep>package ru.job4j.tracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.List; import java.util.Properties; /** * Contains helper methods to create, delete, populate and open connection to a database. */ public class JdbcHelper { public static final String PROPERTIES_FILENAME = "db.properties"; public static final String PROPERTIES_TRAVIS_FILENAME = "db-on-travis.properties"; public static final String CHECK_DB_SQL = "SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower(?)"; private static final Logger LOG = LoggerFactory.getLogger(JdbcHelper.class); /** Properties that contain baseUrl, user and password. */ private final Properties properties; /** Url to the base part of db url not containing database name. */ private final String baseUrl; /** Url to the postgres database. */ private final String postgresUrl; /** * Constructs and initializes this helper with the specified properties. * @param properties properties containing these keys: baseUrl, user, password */ public JdbcHelper(Properties properties) { this.properties = properties; baseUrl = properties.getProperty("baseUrl"); postgresUrl = baseUrl + "postgres"; } /** * Checks if the specified database exists. * @param pgConnection connection to the postgres database * @param dbName name of the database * @return true if db exists, false otherwise * @throws SQLException if a database access error occurs */ public boolean dbExists(Connection pgConnection, String dbName) throws SQLException { try (PreparedStatement ps = pgConnection.prepareStatement(CHECK_DB_SQL)) { ps.setString(1, dbName); ResultSet result = ps.executeQuery(); return result.next(); } } /** * Creates database with the specified name. * @param pgConnection connection to the postgres database * @param dbName name of the database * @throws SQLException if a database access error occurs */ public void createDb(Connection pgConnection, String dbName) throws SQLException { String createDbSql = "create database " + dbName; try (Statement st = pgConnection.createStatement()) { st.execute(createDbSql); } } /** * Populates the specified database with data. * @param dbConnection connection to the database * @param sqlStatements sql statements to populate the database */ public void populateDb(Connection dbConnection, List<String> sqlStatements) throws SQLException { try (Statement st = dbConnection.createStatement()) { for (String sql : sqlStatements) { st.addBatch(sql); } st.executeBatch(); } } /** * Deletes the specified database. * @param pgConnection connection to the postgres database * @param dbName name of the database */ public void dropDb(Connection pgConnection, String dbName) throws SQLException { String sql = "drop database if exists " + dbName; try (Statement st = pgConnection.createStatement()) { st.execute(sql); } } /** * Ensures that the specified database exists, or creates and fills it with data. * @param dbName name of the database * @param scriptName name of the script containing sql statements to insert data to the database * @throws SQLException if a database access error occurs * @throws IOException if an I/O error occurs */ public void ensureDbExists(String dbName, String scriptName) throws SQLException, IOException { try (Connection pgConnection = DriverManager.getConnection(postgresUrl, properties)) { if (dbExists(pgConnection, dbName)) { return; } else { createDb(pgConnection, dbName); } } try (InputStream in = JdbcHelper.class.getClassLoader().getResourceAsStream(scriptName); Connection dbConnection = DriverManager.getConnection(baseUrl + dbName, properties)) { List<String> sqlList = new SqlReader().readSqlStatements(in); populateDb(dbConnection, sqlList); } } /** * Ensures that the specified database exists, or creates and fills it with data, * then opens the connection to the database. * @param dbName database name * @param scriptName name of the script containing sql statements to insert data to the database * @return connection to existing database * @throws SQLException if a database access error occurs * @throws IOException if an I/O error occurs */ public Connection connectToExistingDb(String dbName, String scriptName) throws SQLException, IOException { boolean populate = false; try (Connection pgConnection = DriverManager.getConnection(postgresUrl, properties)) { if (!dbExists(pgConnection, dbName)) { createDb(pgConnection, dbName); populate = true; } } Connection dbConnection = DriverManager.getConnection(baseUrl + dbName, properties); if (populate) { try (InputStream in = JdbcHelper.class.getClassLoader().getResourceAsStream(scriptName)) { List<String> sqlList = new SqlReader().readSqlStatements(in); populateDb(dbConnection, sqlList); } } return dbConnection; } /** * Reads properties file with the specified file name. * @param filename name of the properties file * @return properties object */ public static Properties readProperties(String filename) { Properties props = new Properties(); try { InputStream in = JdbcHelper.class.getClassLoader().getResourceAsStream(filename); if (in != null) { props.load(in); } else { LOG.error("Cannot load DB properties file: " + filename); System.exit(-1); } } catch (IOException e) { LOG.error(e.getMessage(), e); System.exit(-1); } return props; } /** * Gets helper initialized with the default properties file. * @return initialized instance */ public static JdbcHelper defaultHelper() { String dbProfile = System.getProperty("USED_DB_PROFILE"); String propertiesFile; if (dbProfile != null && dbProfile.equals("travis")) { propertiesFile = PROPERTIES_TRAVIS_FILENAME; } else { propertiesFile = PROPERTIES_FILENAME; } return new JdbcHelper(readProperties(propertiesFile)); } } <file_sep>package ru.job4j.ood.warehouse.foods; import ru.job4j.ood.warehouse.Food; import java.math.BigDecimal; import java.time.LocalDate; /** Represents cheese. */ public class Cheese extends Food { public Cheese(LocalDate createDate, LocalDate expireDate, BigDecimal price) { super("Cheese", createDate, expireDate, price, null); } } <file_sep>package ru.job4j.ood.tictac; /** * Represents symbols used by players in the game. */ public enum Mark { X("X"), O("O"), EMPTY(" "); private final String symbol; Mark(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } } <file_sep>package ru.job4j.jmm.prof; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.tracker.ITracker; import ru.job4j.tracker.Item; import ru.job4j.tracker.Tracker; import java.util.List; /** * Loads the {@link Tracker} for research purposes. */ public class TrackerLoader { private static final Logger LOG = LoggerFactory.getLogger(TrackerLoader.class); private final ITracker tracker; private final int initialNumItems; private final int numReplacements; private final long delayInMs; public TrackerLoader(ITracker tracker, int initialNumItems, int numReplacements, long delayInMs) { this.tracker = tracker; this.initialNumItems = initialNumItems; this.numReplacements = numReplacements; this.delayInMs = delayInMs; } /** Adds fixed amount of items. */ public void addItems() { LOG.info("Starting adding {} items", initialNumItems); for (int i = 0; i < initialNumItems; i++) { Item item = new Item("name-" + i, "description-" + i, System.currentTimeMillis()); tracker.add(item); } LOG.info("Number of items added to Tracker: {}", initialNumItems); } /** Replaces fixed amount of items. */ public void replaceItems() throws InterruptedException { LOG.info("Starting replacing {} items", numReplacements); for (int i = 0; i < numReplacements; i++) { List<Item> found = tracker.findByName("name-" + i); if (found.size() > 0) { Item item = found.get(0); Item newItem = new Item("new-name-" + i, "description-" + i, System.currentTimeMillis()); tracker.replace(item.getId(), newItem); if (delayInMs > 0) { Thread.sleep(delayInMs); } } } LOG.info("Number of replaced items: {}", numReplacements); } public static void main(String[] args) { int numInitial = 1000; long delay = 0L; if (args.length > 0) { numInitial = Integer.parseInt(args[0]); } int numReplacements = numInitial; if (args.length > 1) { numReplacements = Integer.parseInt(args[1]); if (numReplacements > numInitial) { throw new IllegalArgumentException( "Number of replacements greater than number of items"); } } if (args.length > 2) { delay = Long.parseLong(args[1]); } ITracker tracker = new Tracker(); TrackerLoader loader = new TrackerLoader(tracker, numInitial, numReplacements, delay); loader.addItems(); try { loader.replaceItems(); } catch (InterruptedException e) { e.printStackTrace(); } } } <file_sep>package ru.job4j.io.find; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class FindTest { @Test public void whenMainWithInvalidArgumentsThenPrintUsage() { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(buffer)); Find.main(new String[] {"--non-existing"}); String expected = String.join(System.lineSeparator(), "Usage: java -jar find.jar [-d directory] -n name [-m | -f | -r] [-o output]", "", "-d directory directory where the search starts", "-n name name of the file or pattern for other types of search", "-m search by mask", "-f search by full name", "-r search by regular expression", "-o output name of the result file", "", "default starting directory is the current directory", "default search is by full name", "default result file is 'log.txt'", ""); assertThat(buffer.toString(), is(expected)); } @Test public void whenMainCalledWithProperArgumentsThenFilesAreFoundAndResultSaved() throws IOException { TestDirWrapper testDirWrapper = new TestDirWrapper(true); Path testDir = testDirWrapper.getPath(); Path dir1 = Files.createTempDirectory(testDir, "dir1"); Path dir2 = Files.createTempDirectory(testDir, "dir2"); Path file1 = Files.createFile(dir1.resolve("test1.xml")); Path file2 = Files.createFile(dir2.resolve("test2.txt")); Path log = testDir.resolve("log.txt"); String[] args = { "-d", testDir.toAbsolutePath().toString(), "-r", "-n", "test\\d\\.(xml|txt)", "-o", log.toAbsolutePath().toString() }; Find.main(args); assertThat(Files.exists(log), is(true)); List<String> result = Files.readAllLines(log); assertThat(result.size(), is(2)); assertThat(result, hasItems(file1.toString(), file2.toString())); testDirWrapper.clean(); } } <file_sep>package ru.job4j.chess.figures.black; import ru.job4j.chess.behaviors.NoMove; import ru.job4j.chess.figures.Cell; import ru.job4j.chess.figures.Figure; public class KnightBlack extends Figure { /** * Constructs KnightBlack with specified position. * @param position position on board */ public KnightBlack(Cell position) { super(position, new NoMove()); } } <file_sep>package ru.job4j.io.pack; import ru.job4j.search.FileExtensionFilter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Contains methods for compressing folders. */ public class FolderArchiver { /** * Compresses the specified directory. * @param directory path to directory * @param output path to output file * @param excludeExt list of extensions to exclude from compressing * or null to compress all files * @return path to output file * @throws IOException if an I/O error occurs */ public Path compress(String directory, String output, List<String> excludeExt) throws IOException { return compress(Paths.get(directory), Paths.get(output), excludeExt); } /** * Compresses the specified directory. * @param directory path to directory * @param output path to output file * @param excludeExt list of extensions to exclude from compressing * or null to compress all files * @return path to output file * @throws IOException if an I/O error occurs when accessing files in the directory or opening output stream * @throws WrappedIOException if an I/O error occurs when writing entries to zip file */ public Path compress(Path directory, Path output, List<String> excludeExt) throws IOException { FileExtensionFilter exclude = new FileExtensionFilter(excludeExt); try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(output))) { Files.walk(directory) .filter(entry -> Files.isRegularFile(entry) && (excludeExt == null || exclude.reject(entry))) .forEach(entry -> writeEntryToZip(out, directory, entry)); } return output; } /** * Writes the specified entry to zip output stream. The output stream remains open. * @param out open output stream to zip * @param baseDir base directory, all files of which are archived * @param entry path to every file that should be zipped * @throws WrappedIOException if an I/O error has occurred then this exception wraps the cause exception. */ public void writeEntryToZip(ZipOutputStream out, Path baseDir, Path entry) { try { out.putNextEntry(new ZipEntry(baseDir.relativize(entry).toString())); out.write(Files.readAllBytes(entry)); out.closeEntry(); } catch (IOException e) { throw new WrappedIOException(e); } } /** * Runtime exception wrapper for {@code IOException}. */ public static class WrappedIOException extends RuntimeException { public WrappedIOException(IOException cause) { super(cause); } } } <file_sep>#!/bin/bash # This script supplies input for adding the specified number of items # to the tracker started with command line UI after redirection symbol. # Arguments: # $1 - number of items # Example of usage: # ./../../../chapter_009_gc/sh/add-items.sh 1000 | java ru.job4j.tracker.StartUI x=1 while [ $x -le $1 ] do # Send 'Add new Item' command to tracker echo 0 echo "name-$x" echo "description-$x" x=$(( $x + 1 )) done # Send 'Exit Program' command to tracker echo 6 <file_sep>package ru.job4j.io.chat; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; /** * Main class that starts the console chat. */ public class ConsoleChatApp { public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: java ConsoleChatApp inputFile logFile"); return; } Path input = Paths.get(args[0]); Path log = Paths.get(args[1]); ConsoleChat chat = new ConsoleChat(input, log); try { chat.start(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package ru.job4j.ood.warehouse; /** Represents warehouse. */ public class Warehouse extends FoodCollection { public Warehouse() { super("Warehouse"); } } <file_sep>package ru.job4j.io.find; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * Main class that starts the application using command line arguments. */ public class Find { /** * @param args used arguments: [-d directory] -n name [-m | -f | -r] [-o output] * * -d directory directory where the search starts * -n name name of the file or pattern for other types of search * -m search by mask * -f search by full name * -r search by regular expression * -o output name of the result file * * default starting directory is the current directory * default search is by full name * default result file is 'log.txt' */ public static void main(String[] args) { Args arguments; try { arguments = new Args(args); } catch (IllegalArgumentException e) { displayUsage(); return; } try { List<String> result = findFiles(arguments.getDirectory(), arguments.getName(), arguments.getSearchBy()); writeResult(result, arguments.getOutput()); } catch (IOException e) { e.printStackTrace(); } } /** * Finds files in the specified directory. * @param dir starting directory * @param name name of the file or pattern for other types of search * @param type type of search * @return list of found files * @throws IOException if an I/O error occurs */ private static List<String> findFiles(Path dir, String name, SearchBy type) throws IOException { Finder finder = new Finder(dir, Integer.MAX_VALUE); List<Path> paths = finder.find(name, type); List<String> lines = new ArrayList<>(); paths.forEach(p -> lines.add(p.toString())); return lines; } /** * Writes result to the specified file. * @param lines list of lines * @param output path to the output file * @throws IOException if an I/O error occurs */ private static void writeResult(List<String> lines, String output) throws IOException { ListWriter writer = new ListWriter(Paths.get(output)); writer.write(lines); } /** * Prints usage instructions to the console. */ private static void displayUsage() { final String usage = String.join(System.lineSeparator(), "Usage: java -jar find.jar [-d directory] -n name [-m | -f | -r] [-o output]", "", "-d directory directory where the search starts", "-n name name of the file or pattern for other types of search", "-m search by mask", "-f search by full name", "-r search by regular expression", "-o output name of the result file", "", "default starting directory is the current directory", "default search is by full name", "default result file is 'log.txt'"); System.out.println(usage); } } <file_sep>package ru.job4j.loop; /** * Represents a chess board. */ public class Board { private static final String LINE_SEPARATOR = System.lineSeparator(); /** * Creates a string representation of a bord with specified dimensions. * @param width width of the board (number of columns) * @param height height of the board (number of rows) * @return board as string of characters */ public String paint(int width, int height) { StringBuilder screen = new StringBuilder(); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { if ((row + col) % 2 == 0) { screen.append("X"); } else { screen.append(" "); } } screen.append(LINE_SEPARATOR); } return screen.toString(); } } <file_sep>package ru.job4j.bank; import java.util.Objects; /** * Represents a user who has a name and passport. */ public class User { /** * Name of the user. */ private final String name; /** * Passport of the user. */ private final String passport; /** * Constructs user using specified name and passport. * @param name name of the user * @param passport passport of the user */ public User(String name, String passport) { this.name = name; this.passport = passport; } /** * @return name of the user */ public String getName() { return name; } /** * @return passport of the user */ public String getPassport() { return passport; } /** * Indicates whether some object is equal to this user. * @param obj other object * @return true if equal, false otherwise */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } User other = (User) obj; return Objects.equals(this.name, other.name) && Objects.equals(this.passport, other.passport); } /** * @return a hash code value for the user */ @Override public int hashCode() { return Objects.hash(this.name, this.passport); } } <file_sep>package ru.job4j.pseudo; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.StringJoiner; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; @SuppressWarnings("StringBufferReplaceableByString") public class PaintTest { private final PrintStream stdOut = System.out; private final ByteArrayOutputStream out = new ByteArrayOutputStream(); @Before public void setStandardOutput() { System.setOut(new PrintStream(this.out)); } @After public void restoreStandardOutput() { System.setOut(this.stdOut); } @Test public void whenDrawSquare() { new Paint().draw(new Square(2)); String expected = new StringJoiner(Shape.NEW_LINE, "", Shape.NEW_LINE) .add("**") .add("**").toString(); assertThat(this.out.toString(), is(expected)); } @Test public void whenDrawTriangle() { new Paint().draw(new Triangle(3)); String expected = new StringJoiner(Shape.NEW_LINE, "", Shape.NEW_LINE) .add(" * ") .add(" *** ") .add("*****").toString(); assertThat(this.out.toString(), is(expected)); } } <file_sep>package ru.job4j.tools; import java.util.Scanner; public class CmdInput { private final Scanner scanner = new Scanner(System.in); private CmdInput() { } public Scanner getScanner() { return scanner; } private static final CmdInput INSTANCE = new CmdInput(); public static long nextLong(String prompt) { System.out.print(prompt); return INSTANCE.getScanner().nextLong(); } public static int nextInt(String prompt) { System.out.print(prompt); return INSTANCE.getScanner().nextInt(); } public static String next(String prompt) { System.out.print(prompt); return INSTANCE.getScanner().next(); } public static String nextLine(String prompt) { System.out.print(prompt); return INSTANCE.getScanner().nextLine(); } } <file_sep>package ru.job4j.collections.tree; import java.util.Optional; /** * Interface of a simple iterable tree. * @param <E> type of element */ public interface SimpleTree<E> extends Iterable<E> { /** * Adds child value to the parent node with the specified value. * @param parent value of the parent node * @param child value to add * @return true if child node was added, otherwise false */ boolean add(E parent, E child); /** * Finds a node that contains the specified value. * @param value value to find * @return container which may or may not contain the found node */ Optional<Node<E>> findBy(E value); } <file_sep>package ru.job4j.tracker; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; @Ignore("Do not run unless it is necessary to test integration with PostgreSQL") public class JdbcHelperIntegrationTest { public static final String DB_NAME = "test_item_tracker"; public static final String SCRIPT_NAME = "sql/createItemTracker.sql"; @SuppressWarnings("TryFinallyCanBeTryWithResources") @Test public void whenNotExistingDbThenCreatesDbAndOpensConnection() throws IOException, SQLException { Properties props = JdbcHelper.readProperties(JdbcHelper.PROPERTIES_FILENAME); JdbcHelper helper = new JdbcHelper(props); try (Connection postgresConnection = DriverManager.getConnection(props.getProperty("baseUrl") + "postgres", props)) { Connection dbConnection = null; try { dbConnection = helper.connectToExistingDb(DB_NAME, SCRIPT_NAME); assertNotNull("This connection should not be null", dbConnection); } finally { if (dbConnection != null) { dbConnection.close(); } } assertThat(helper.dbExists(postgresConnection, DB_NAME), is(true)); helper.dropDb(postgresConnection, DB_NAME); assertThat(helper.dbExists(postgresConnection, DB_NAME), is(false)); } } } <file_sep>-- create database car_storage; -- Кузов create table body_type ( body_type_id serial primary key, name varchar(30) ); -- Двигатель create table engine ( engine_id serial primary key, description varchar(80) ); -- Коробка передач create table gearbox ( gearbox_id serial primary key, description varchar(30) ); -- Машина create table car ( car_id serial primary key, name varchar(30), body_type_id int references body_type (body_type_id), engine_id int references engine (engine_id), gearbox_id int references gearbox (gearbox_id) ); insert into body_type (name) values ('Седан'), ('Лифтбек'), ('Внедорожник 5 дв.'), ('Хэтчбек 5 дв.'); insert into engine (description) values ('2.4 л / 152 л.с. / Бензин'), ('2.0 л / 220 л.с. / Бензин'), ('2.0 л / 184 л.с. / Бензин'), ('1.4 л / 107 л.с. / Бензин'), ('2.0 л / 147 л.с. / Бензин'), ('1.6 л / 105 л.с. / Бензин'); insert into gearbox (description) values ('Автоматическая'), ('Роботизированная'), ('Механическая'), ('Бесступенчатая'); insert into car (name, body_type_id, engine_id, gearbox_id) values ('Toyota Camry V (XV30)', 1, 1, 1), ('Skoda Octavia RS III', 2, 2, 2), ('BMW X4 I (F26) 20i', 3, 3, 1), ('Kia Rio III', 4, 4, 1), ('Mazda 6 II (GH)', 1, 5, 3); <file_sep>package ru.job4j.pseudo; /** * Declares method for drawing shapes. */ public interface Shape { /** * Line separator constant for new line. */ String NEW_LINE = System.lineSeparator(); /** * Returns a pseudo-graphic representation of a shape. * @return pseudo-graphic shape */ String draw(); } <file_sep>package ru.job4j.ood.tictac; /** * Formatter of grid that uses pseudo-symbols for displaying grid lines. */ public class PseudoTextGridFormatter implements GridFormatter { private final static String NEW_LINE = System.lineSeparator(); private final static String HOR_LINE = "\u2500\u2500\u2500"; private final static char VERT_LINE = '\u2502'; private final static char TOP_LEFT_CORNER = '\u250C'; private final static char TOP_RIGHT_CORNER = '\u2510'; private final static char BOTTOM_LEFT_CORNER = '\u2514'; private final static char BOTTOM_RIGHT_CORNER = '\u2518'; private final static char LEFT_TEE = '\u251C'; private final static char RIGHT_TEE = '\u2524'; private final static char TOP_TEE = '\u252C'; private final static char BOTTOM_TEE = '\u2534'; private final static char CROSS = '\u253C'; /** Formats the specified grid into String. */ @Override public String format(GridView grid) { StringBuilder buffer = new StringBuilder(); int size = grid.size(); makeTop(buffer, size); for (int r = 0; r < size; r++) { makeMarkRow(buffer, r, grid); if (r < size - 1) { makeHorizontal(buffer, size); } } makeBottom(buffer, size); return buffer.toString(); } private void makeMarkRow(StringBuilder buffer, int row, GridView grid) { int size = grid.size(); buffer.append(VERT_LINE); for (int c = 0; c < size; c++) { buffer.append(" "); buffer.append(grid.markAt(new Position(row, c))); buffer.append(" "); buffer.append(VERT_LINE); } buffer.append(NEW_LINE); } private void makeHorizontal(StringBuilder buffer, int size) { makeGraphRow(buffer, size, LEFT_TEE, CROSS, RIGHT_TEE); } private void makeBottom(StringBuilder buffer, int size) { makeGraphRow(buffer, size, BOTTOM_LEFT_CORNER, BOTTOM_TEE, BOTTOM_RIGHT_CORNER); } private void makeTop(StringBuilder buffer, int size) { makeGraphRow(buffer, size, TOP_LEFT_CORNER, TOP_TEE, TOP_RIGHT_CORNER); } private void makeGraphRow(StringBuilder buffer, int size, char start, char middle, char end) { buffer.append(start); for (int i = 0; i < size; i++) { buffer.append(HOR_LINE); if (i < size - 1) { buffer.append(middle); } } buffer.append(end); buffer.append(NEW_LINE); } } <file_sep>package ru.job4j.jmm.cache; import org.junit.Test; import java.util.function.Function; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class CacheTest { @Test public void whenDoesNotHaveCachedValueThenReceivesValueFromProvider() { Function<String, Long> provider = Long::valueOf; Cache<String, Long> cache = new Cache<>(provider); Long result = cache.get("123"); assertThat(result, is(123L)); cache.setProvider((s) -> Long.parseLong(s) * 2); result = cache.get("321"); assertThat(result, is(642L)); } @Test public void whenHasCachedValueThenReturnsCachedInstance() { Function<String, Dummy> provider = (s) -> new Dummy(); Cache<String, Dummy> cache = new Cache<>(provider); Dummy first = cache.get("key"); Dummy second = cache.get("key"); assertThat(first, sameInstance(second)); } private static class Dummy { } } <file_sep>package ru.job4j.io.netw.bot; import org.junit.Before; import org.junit.Test; import java.util.Map; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class WiseOracleTest { private WiseOracle oracle; @Before public void setup() { Map<String, String> data = Map.of("Java", "Java is used for web and mobile applications."); oracle = new WiseOracle(data); } @Test public void whenRequestContainsKeyWordThenResponseContainsKeyWord() { String question = "What is Java commonly used for?"; String answer = oracle.reply(question); assertThat(answer, containsString("Java")); } @Test public void whenRequestContainsNoKeyWordsThenResponseIsIDontKnow() { String question = "When was Python invented?"; String answer = oracle.reply(question); assertThat(answer, is("I don't know")); } } <file_sep>package ru.job4j.collections.iterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * Implements iterator for two-dimensional array of Integers. */ public class IntMatrixIterator implements Iterator<Integer> { /** Values over which iterator runs. */ private final int[][] values; /** Current row. */ private int row; /** Current column. */ private int col; /** * Constructs iterator and initializes it with specified array of values. * @param values array of iterated values */ public IntMatrixIterator(int[][] values) { this.values = values; } /** * @return true if the iterator has more elements */ @Override public boolean hasNext() { return row < values.length && col < values[row].length; } /** * @return next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ @Override public Integer next() throws NoSuchElementException { if (!hasNext()) { throw new NoSuchElementException(); } int value = values[row][col++]; if (col == values[row].length) { row++; col = 0; } return value; } } <file_sep>### Контрольные вопросы #### 1.4 FP, Lambda, Stream API 1. Что такое функциональное программирование? 2. Какие нововведения появились в Java 8 связанные с ФП? 3. Как отсортировать список строк с помощью лямбда-выражений? 4. Какова структура лямбда-выражения? 5. К каким переменным есть доступ у лямбда-выражений? 6. Что такое ссылки на метод? 7. Какие виды ссылок на методы вы знаете? 8. Объясните выражение System.out::println? 9. Что такое функциональные интерфейсы? 10. Для чего нужен интерфейс Consumer<T>? 11. Для чего нужен интерфейс Function<T, R> 12. Для чего нужен интерфейс Predicate<T>? 13. Для чего нужен интерфейс Supplier<T>? 14. Что такое потоки (Stream) в Java 8? 15. Для чего нужен метод collect в Java 8? 16. В чем разница между коллекцией (Collection) и потоком (Stream)? 17. Для чего предназначен метод forEach в потоках? 18. Как вывести на экран 10 случайных чисел, используя forEach? 19. Для чего предназначен метод map в потоках? 20. Как можно вывести на экран уникальные квадраты чисел использую метод map? 21. Какова цель метода filter в потоках? 22. Как вывести на экран количество пустых строк с помощью метода filter? 23. Для чего предназначен метод limit в потоках? 24. Для чего предназначен метод sorted в потоках? 25. Как вывести на экран 10 случайных чисел в отсортированном порядке в Java 8? 26. Для чего предназначен метод flatMap в потоках? 27. Для чего предназначен метод reduce в потоках? 28. Как сделать параллельную обработку потока? 29. Как найти максимальное число в списке Java 8? 30. Как найти минимальное число в списке Java 8? 31. Как получить сумму всех чисел в списке Java 8? 32. Как получить среднее значение всех чисел в списке? 33. Что такое Optional? <file_sep>package ru.job4j.ood.carparking; /** * Represents truck. */ public class Truck implements Vehicle { private final LicensePlateNumber licensePlate; private final int size; public Truck(LicensePlateNumber licensePlate, int size) { this.licensePlate = licensePlate; this.size = size; } @Override public String getId() { return licensePlate.getNumber(); } @Override public int size() { return size; } @Override public String toString() { return "Truck{licensePlate=" + licensePlate + ", size=" + size + '}'; } } <file_sep>package ru.job4j.array; /** * Contains method for reversing arrays. */ public class Turn { /** * Reverses array in place. * @param array array * @return reversed array */ public int[] turn(int[] array) { for (int i = 0, j = array.length - 1, tmp; i < j; i++, j--) { tmp = array[i]; array[i] = array[j]; array[j] = tmp; } return array; } } <file_sep>package ru.job4j.ood.tictac; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.InputStream; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class ConsoleInputTest { private final Output output = mock(Output.class); @Test public void whenRequestPositionThenOutputsPrompt() { InputStream inputStream = new ByteArrayInputStream("1 2".getBytes()); Input input = new ConsoleInput(output, inputStream); input.requestPosition("Prompt"); verify(output).print("Prompt"); } @Test public void whenRequestPositionThenCanReturnPosition() { InputStream inputStream = new ByteArrayInputStream("1 2".getBytes()); Input input = new ConsoleInput(output, inputStream); Position pos = input.requestPosition(""); assertThat(pos.getRow(), is(1)); assertThat(pos.getCol(), is(2)); } @Test public void whenRequestPositionGivenIncorrectInputThenPrintsMessageAndRetries() { InputStream inputStream = new ByteArrayInputStream("12\nthree four\n5 6".getBytes()); Input input = new ConsoleInput(output, inputStream); Position pos = input.requestPosition(""); verify(output, times(2)).print("Incorrect position. Try again"); assertThat(pos.getRow(), is(5)); assertThat(pos.getCol(), is(6)); } } <file_sep>package ru.job4j.vacparser.parsers; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import ru.job4j.vacparser.model.ForumPage; import ru.job4j.vacparser.model.Vacancy; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; /** * Parser of forum page documents. */ public class ForumPageParser { private final DateTimeParser dateTimeParser = new DateTimeParser(); /** * Parses the specified forum page document and returns as a result a list of vacancies and next page link. * Returned vacancies contain only name, link and creation time. * Other vacancy info should be received from vacancy pages. * @param document document that represents forum page * @param skipRows number of rows on the page that should be skipped because they don't contain vacancy info * @return forum page object */ public ForumPage parse(Document document, int skipRows) { ForumPage forumPage = new ForumPage(); List<Vacancy> vacancies = parseVacancies(document, skipRows); String nextPage = parseNextPageUrl(document); forumPage.setVacancies(vacancies); forumPage.setNextPage(nextPage); return forumPage; } /** Skips specified number of rows and then parses vacancies in the specified document. */ private List<Vacancy> parseVacancies(Document document, int skipRows) { LinkedHashMap<String, Vacancy> map = new LinkedHashMap<>(); Element table = document.selectFirst("#content-wrapper-forum > table.forumTable > tbody"); Elements rows = table.select("tr"); for (int i = skipRows; i < rows.size(); i++) { Element row = rows.get(i); Element a = row.selectFirst("td.postslisttopic > a:first-child"); String name = a.text(); if (!map.containsKey(name)) { String href = a.attr("href"); String dateStr = row.selectFirst("td:nth-child(6)").text(); LocalDateTime modified = dateTimeParser.parse(dateStr); Vacancy vacancy = new Vacancy(name, href, modified); map.put(name, vacancy); } } return new ArrayList<>(map.values()); } /** Parses the URL of the next forum page. */ private String parseNextPageUrl(Document document) { Element pages = document.selectFirst("#content-wrapper-forum > table:nth-child(6) > tbody > tr > td:nth-child(1)"); Element currentPage = pages.selectFirst("b"); Element nextLink = currentPage.nextElementSibling(); if (nextLink != null) { Element a = nextLink.selectFirst("a"); if (a != null) { return a.attr("href"); } } return null; } } <file_sep>package ru.job4j.map; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * Contains methods for converting collections of {@link User} elements. */ public class UserConvert { /** * Converts list of {@link User} instances to a map in which keys * contain IDs of the users. * @param list list of users * @return map of users */ public HashMap<Integer, User> process(List<User> list) { return list.stream().collect(Collectors.toMap( User::getId, user -> user, (oldUser, newUser) -> newUser, HashMap::new) ); } } <file_sep>package ru.job4j.io.find; import org.junit.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class FinderTest { private TestDirWrapper testDirWrapper; private Path testDir; private Finder finder; @Before public void setup() throws IOException { testDirWrapper = new TestDirWrapper(); testDir = testDirWrapper.getPath(); finder = new Finder(testDir, 5); } @Test public void whenFindByFullNameThenFindsTheFile() throws IOException { Files.createTempFile(testDir, "test1", ".tmp"); Path file2 = Files.createTempFile(testDir, "test2", ".tmp"); List<Path> result = finder.find(file2.getFileName().toString(), SearchBy.FULL); assertThat(result, is(List.of(file2))); } @Test public void whenFindByMaskThenFindsCorrectGroupOfFiles() throws IOException { Path file1 = Files.createTempFile(testDir, "test11", ".xml"); Files.createTempFile(testDir, "test22", ".tmp"); Path file3 = Files.createTempFile(testDir, "test33", ".xml"); List<Path> result = finder.find("*.xml", SearchBy.MASK); assertThat(result.size(), is(2)); assertThat(result, hasItems(file1, file3)); } @Test public void whenFindByRegexThenFindsCorrectGroupOfFiles() throws IOException { Path file1 = Files.createTempFile(testDir, "reg1ex", null); Files.createTempFile(testDir, "reg2ex", ".tmp"); Path file3 = Files.createTempFile(testDir, "reg3ex", null); List<Path> result = finder.find("^reg[13]ex.+", SearchBy.REGEX); assertThat(result.size(), is(2)); assertThat(result, hasItems(file1, file3)); } @Test public void whenFindInNestedFoldersThenFindsCorrectGroupOfFiles() throws IOException { Path dir1 = Files.createTempDirectory(testDir, "dir1"); Path file1 = Files.createTempFile(dir1, "nested", ".txt"); Path dir12 = Files.createTempDirectory(dir1, "dir12"); Files.createTempFile(dir12, "irrelevant", ".txt"); Path file3 = Files.createTempFile(dir12, "nested", ".txt"); List<Path> result = finder.find("nested*.txt", SearchBy.MASK); assertThat(result.size(), is(2)); assertThat(result, hasItems(file1, file3)); } @Test public void whenFindInNestedFoldersByFullNameThenFindsCorrectGroupOfFiles() throws IOException { final String fileName = "test42.txt"; Path file0 = Files.createFile(testDir.resolve(fileName)); Files.createFile(testDir.resolve("irrelevant")); Path dir1 = Files.createTempDirectory(testDir, "dir1"); Path file1 = Files.createFile(dir1.resolve(fileName)); Path dir12 = Files.createTempDirectory(dir1, "dir12"); Path file3 = Files.createFile(dir12.resolve(fileName)); List<Path> result = finder.find(fileName, SearchBy.FULL); assertThat(result.size(), is(3)); assertThat(result, hasItems(file0, file1, file3)); } @After public void cleanTestDir() throws IOException { testDirWrapper.clean(); } } <file_sep>package ru.job4j.ood.tictac; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; public class ArrayGridTest { private GameGrid grid = new ArrayGrid(3); @Test public void whenInitializedThenCellsAreFree() { assertTrue(grid.isFreeAt(new Position(0, 2))); assertTrue(grid.isFreeAt(new Position(2, 0))); } @Test(expected = IllegalStateException.class) public void whenSettingBusyCellThenException() { setMark(2, 2, Mark.X); assertThat(grid.markAt(new Position(2, 2)), is(Mark.X)); setMark(2, 2, Mark.O); } @Test public void whenNoWinnerThenReturnsNull() { assertNull(grid.findWinningMark(3)); setMark(0, 0, Mark.X); setMark(1, 1, Mark.O); setMark(2, 2, Mark.X); assertNull(grid.findWinningMark(3)); } @Test public void whenVerticalWinnerThenReturnsMark() { setMark(0, 0, Mark.X); setMark(1, 0, Mark.X); setMark(2, 0, Mark.X); assertThat(grid.findWinningMark(3), is(Mark.X)); } @Test public void whenHorizontalWinnerThenReturnsMark() { setMark(1, 0, Mark.O); setMark(1, 1, Mark.O); setMark(1, 2, Mark.O); assertThat(grid.findWinningMark(3), is(Mark.O)); } @Test public void whenLeftDiagonalWinnerThenReturnsMark() { setMark(0, 0, Mark.O); setMark(1, 1, Mark.O); setMark(2, 2, Mark.O); assertThat(grid.findWinningMark(3), is(Mark.O)); } @Test public void whenRightDiagonalWinnerLessThanGridThenReturnsMark() { grid = new ArrayGrid(5); setMark(1, 3, Mark.O); setMark(2, 2, Mark.O); setMark(3, 1, Mark.O); assertThat(grid.findWinningMark(3), is(Mark.O)); } @Test public void whenLeftSlopeWinnerThenReturnsMark() { grid = new ArrayGrid(4); setMark(1, 0, Mark.X); setMark(2, 1, Mark.X); setMark(3, 2, Mark.X); assertThat(grid.findWinningMark(3), is(Mark.X)); } @Test public void whenRightSlopeWinnerThenReturnsMark() { grid = new ArrayGrid(4); setMark(0, 2, Mark.O); setMark(1, 1, Mark.O); setMark(2, 0, Mark.O); assertThat(grid.findWinningMark(3), is(Mark.O)); } @Test public void whenAllCellsAreBusyThenGridIsFull() { grid = new ArrayGrid(2); assertFalse(grid.isFull()); setMark(0, 0, Mark.O); assertFalse(grid.isFull()); setMark(0, 1, Mark.X); setMark(1, 0, Mark.O); assertFalse(grid.isFull()); setMark(1, 1, Mark.X); assertTrue(grid.isFull()); } private void setMark(int r, int c, Mark m) { grid.changeCell(new Position(r, c), m); } } <file_sep>package ru.job4j.ood.calculator; import java.util.function.Consumer; import java.util.function.Supplier; /** * Interactive text input driven calculator. * It can solve a simple arithmetic expression, e.g 3 + 2. * or an expression using the previous result, e.g. Result + 42 * Uses empty input (press Enter) to start interaction loop from the beginning. * Uses command 'exit' to quit. */ public class InteractCalc { /** String expression evaluator. */ private final ExpressionEvaluator evaluator; /** Sources of string input. */ private Supplier<String> input; /** Destination of output. */ private final Consumer<String> output; /** Flags the first expression in a sequence of user inputs. */ private boolean firstExpression = true; /** Current result of calculation. */ private double result; /** Constructs the calculator using the specified evaluator and output consumer. * The source of input should be initialized by {@link #setInput(Supplier)} method. * @param evaluator string expression evaluator * @param output destination of output */ public InteractCalc(ExpressionEvaluator evaluator, Consumer<String> output) { this.evaluator = evaluator; this.output = output; } /** * Constructs the calculator using the specified evaluator, input producer, and output consumer * @param evaluator string expression evaluator * @param input source of input * @param output destination of output */ public InteractCalc(ExpressionEvaluator evaluator, Supplier<String> input, Consumer<String> output) { this.evaluator = evaluator; this.input = input; this.output = output; } /** Sets the source of string input. */ public void setInput(Supplier<String> input) { this.input = input; } /** * Starts the loop of interaction. */ public void start() { if (input == null) { throw new IllegalStateException("Input is not initialized yet."); } prompt(); while (true) { String expression = input.get(); if (expression.isEmpty()) { restartInteraction(); continue; } else if ("exit".equals(expression)) { break; } else if (firstExpression) { result = evaluator.evaluate(expression); firstExpression = false; } else { result = evaluator.evaluate(result, expression); } output.accept(result + " "); } } private void prompt() { output.accept("Enter expression: "); } private void restartInteraction() { firstExpression = true; prompt(); } } <file_sep>package ru.job4j.ood.menu; import java.util.ArrayList; import java.util.List; /** * Represents menu that can contain any number of nested levels. */ public class Menu implements NestedItem { /** Items of the menu on the 1-st level relative to the level of the menu. */ private final List<NestedItem> items = new ArrayList<>(); /** Name of the menu. */ private final String name; /** Rendered used for rendering of all menu items. */ private Renderer renderer; /** Nesting level of the menu. */ private int nestingLevel; /** Constructs the menu using the specified name. */ public Menu(String name) { this.name = name; } /** Constructs the menu using the specified name and renderer. */ public Menu(String name, Renderer renderer) { this.name = name; this.renderer = renderer; } /** Sets the specified renderer. */ @Override public void setRenderer(Renderer renderer) { this.renderer = renderer; } /** Displays the menu and all its items. */ @Override public void display() { renderer.render(this); for (NestedItem item : items) { item.display(); } } /** Returns the name of the menu. */ @Override public String name() { return name; } /** Returns the nesting level of the menu. */ @Override public int getLevel() { return nestingLevel; } /** Sets the nesting level of the menu. */ @Override public void setLevel(int level) { nestingLevel = level; } /** Adds nested items to the menu. */ public void addItem(NestedItem item) { item.setLevel(this.getLevel() + 1); item.setRenderer(this.renderer); items.add(item); } } <file_sep>package ru.job4j.professions; public class Engineer extends Profession { public Engineer(String name) { super(name, "Engineer"); } public void build(House house) { } }
22a4d49f9bbfe9cd09f3c8bdcb55e5715a65e3a3
[ "SQL", "Markdown", "INI", "Java", "Shell" ]
179
Java
dpopkov/job4j
b96f49f7b9ccd0469bf059663d81b3bde739363c
47b0511818a0a2539dc9e977036a6cc0bf0ed973
refs/heads/master
<repo_name>sazuna/game<file_sep>/Dockerfile FROM node:custom ENV SERVER_PORT 8888 WORKDIR /app<file_sep>/server/index.js import express from 'express'; import { graphqlExpress, graphiqlExpress, } from 'graphql-server-express'; import bodyParser from 'body-parser'; import { schema } from '../schema'; const app = express() app.use('/graphql', bodyParser.json(), graphqlExpress({ schema })); app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' })); app.get('/', function (req, res) { res.send('Hello World!') }) app.listen(process.env.SERVER_PORT, '0.0.0.0', function () { console.log(`Example app listening on port ${process.env.SERVER_PORT}!`) })
34524a2fa6e1eb910d3557d7f7adc9c3ad988b42
[ "JavaScript", "Dockerfile" ]
2
Dockerfile
sazuna/game
b7b5932af0178eaff6cb328bf34d8a49a1c11fc3
affcb689eda29e5ffea7d5b28b4e01aad53b072d
refs/heads/master
<file_sep>var React = require('react'); var PropTypes = React.PropTypes; function way(obj){ return <pre>{JSON.stringify(obj, null, ' ')}</pre> } function Results(props){ return <div>{way(props)}</div> } Results.propTypes = { isLoading: PropTypes.bool.isRequired, playersInfo: PropTypes.array.isRequired, scores: PropTypes.array.isRequired } module.exports = Results;
b6375d76ec22eda98173daa06fe09e997eb52f20
[ "JavaScript" ]
1
JavaScript
ion99/github-battle
9006f0944f3cada6fd18b1c90f1011a4c4a78233
1da00c515a94ee104eba26d5cac190989ec8404a
refs/heads/main
<file_sep>import React from 'react' import {Navbar} from 'react-bootstrap'; const Navigation = () => { return ( <div> <Navbar variant='dark' className='py-3' style={{backgroundColor: '#163a62'}}> <Navbar.Brand href='/'><h2>Secret Stash</h2></Navbar.Brand> </Navbar> </div> ) } export default Navigation <file_sep>import React, {useState} from 'react' import {Card, Button, Form, Divider, Segment, Icon, Input, Loader, Popup} from 'semantic-ui-react'; import {Container, Row, Col, Alert} from 'react-bootstrap'; import Api from '../util/Api'; const Home = () => { const [userPassword, setUserPassword] = useState({ password: '', salt: '' }); const [newPassword, setNewPassword] = useState({ password: '' }) const [password, setPassword] = useState(''); const [click, setClick] = useState(false); const [clickPw, setClickPw] = useState(false); const [error, setError] = useState(false); const [loading, setLoading] = useState(true); const [copyRandom, setCopyRandom] = useState(false); const [copySecure, setCopySecure] = useState(false); const handleOpen = () => { setCopyRandom(true) setTimeout(() => { setCopyRandom(false) }, 2500) } const copiedSecureOpen = () => { setCopySecure(true) setTimeout(() => { setCopySecure(false) }, 2500) } const copiedSecureClose = () => { setCopySecure(false) clearTimeout() } const handleClose = () => { setCopyRandom(false) clearTimeout() } const generatePW = async () => { try { const res = await Api.get('random') setPassword(res.data.password) setError(false) setLoading(false) } catch (err) { console.error(err) setError(true) setLoading(false) } } const hashCustomPW = async (pw) => { const config = { headers: { 'Content-Type': 'application/json' } } try { const res = await Api.post('custom', pw , config) setNewPassword({ password: <PASSWORD>, }) setUserPassword({ password: <PASSWORD>, salt: res.data.salt }) if(newPassword !== null) { setUserPassword({ password: '', salt: '' }) } setLoading(false) setError(false) } catch (err) { console.error(err) setError(true) setLoading(false) } } const errorMessage = () => { return ( <Alert variant='danger'> <p className='mb-0 mt-0 text-center'>There was a problem generating your password</p> </Alert> ) } const load = () => { return ( <div> <Row className='align-items-center mt-auto'> <Col > <Loader active size='small'>Loading</Loader> </Col> </Row> </div> ) } const onChange = (e) => { setUserPassword({ ...userPassword, [e.target.name] : e.target.value }) } const onSubmit = (e) => { e.preventDefault(); if(userPassword.password !== '') { hashCustomPW(userPassword) } } return ( <Container className='py-5'> <Card > <Card.Content style={{margin: '2rem 0', paddingBottom:'0'}}> <Row className='d-flex'> <Col xs className='mx-auto'> <Card.Header> {error && errorMessage()} <h1 style={{textAlign: 'center', color: '#163a62'}}>Generate a secure password</h1> </Card.Header> </Col> </Row> <Row className='d-flex '> <Col xs className='d-flex justify-content-center'> <Card.Description style={{color: '#163a62'}}> <h2 className='mt-3'> Use our tool to create the world's strongest password with just a click </h2> <Segment raised size='huge' className='seg mx-auto'> <Row > <Col xs={10} lg={11} className='flex-column m-auto'> {loading && click ? load() : <strong>{password}</strong>} </Col> <Col xs={2} md={1} className='flex-column mx-auto'> <Popup trigger={ <Icon size='large' link='/' name='copy outline' onClick={() => navigator.clipboard.writeText(password)} /> } content={'Copied!'} on='click' open={copyRandom} onClose={handleClose} onOpen={handleOpen} position='bottom right' size='tiny' /> </Col> </Row> </Segment> <Button color='violet' onClick={() => generatePW() && setClick(true)}>Generate Password</Button> <h3 className='mt-5'>Secure your existing password</h3> <Divider /> <Form style={{marginTop: '2rem'}} onSubmit={onSubmit}> <Form.Field required> <label for='password'>Password</label> <Input name="password" type='password' id='password' placeholder='Enter Password' value={userPassword.password} onChange={onChange} /> </Form.Field> <Row className='d-flex mb-3'> <Col xs={10} lg={11} className='pr-0'> <Form.Field> <label for='salt'>Salt</label> <Input name="salt" id='salt' type='text' placeholder='Enter Salt' value={userPassword.salt} onChange={onChange} /> </Form.Field> </Col> <Col xs={2} md={1} className='mt-4 pl-0'> <Popup trigger={ <Icon style={{float: 'right'}} name='question circle outline' size='large' /> } content="Salt extends the password's hash and transforms it into a unique password by adding another layer of security on top of what you have already entered." /> </Col> </Row> <Button color='violet' type='submit' onClick={() => { return setClickPw(true)}}>Secure password</Button> </Form> <div className='my-5'> <h3>New Password</h3> <Segment raised size='huge' className='seg mx-auto'> <Row > <Col xs={10} lg={11} className='flex-column m-auto'> {loading && clickPw && newPassword.password !== null ? load() : <strong>{newPassword.password}</strong>} </Col> <Col xs={2} md={1} className='flex-column mx-auto'> <Popup trigger={ <Icon size='large' link='/' name='copy outline' onClick={() => navigator.clipboard.writeText(newPassword.password)} /> } content={'Copied!'} on='click' open={copySecure} onClose={copiedSecureClose} onOpen={copiedSecureOpen} position='bottom right' size='tiny' /> </Col> </Row> </Segment> </div> </Card.Description> </Col> </Row> </Card.Content> </Card> </Container> ) } export default Home <file_sep>import React from 'react' import { Row, Col, Nav, NavItem } from 'react-bootstrap'; const Footer = () => { return ( <footer style={{overflow: 'hidden'}}> <Row className='d-flex justify-content-center align-items-center' style={{backgroundColor: '#163A62', height: '3.5rem'}}> <Nav justified> <Col> <NavItem > <p className=' text-center mb-0 text-white'>By <span className='text-white pl-1'> <a href='https://dnadevelopers.net'> DNA Developers </a> </span> </p> </NavItem> </Col> </Nav> </Row> </footer> ) } export default Footer <file_sep># Secret Stash Secret Stash is a random password generator using an encryption algorithm to hash your password. Secret Stash is a Progressive Web Application, allowing you to install it directly onto your device after you visit the site giving you the capability of always have access to it even while offline. You have the ability to generate a secure password with a click of a button or you can input your current password add salt to it and generate a new secured one. <br/> ## Technologies used HTML5<br/> CSS<br/> Javascript<br/> React.js<br/> Semantic Ui<br/> RESTful API<br/> ### www.secretstash.tech
efc6e33a2ea5d7c0148ab4db915f1157c7465f9c
[ "JavaScript", "Markdown" ]
4
JavaScript
Dallen9/Secret-Stash
fd6e8205b4ff2e45588301f391ec77c70bf40a9a
0ede632d4595e164e2de9300044621312835d15c
refs/heads/master
<repo_name>mondolmislam/backend-todoapp-spring-boot<file_sep>/README.md # backend todo app spring-boot # To Do App It is a sample project for spring boot developer. Here I try to implement JPA,ORM concept, PostgreSQL, Jackson, RestTemplete, REST API concept # How Can I run the project? - Create database in you PgAdmin or Postgre command line. - The database name will be **todo_app**, **Username** will be **maidul**, **password** will be **<PASSWORD>** # How Can I run the project using own database,username,password? Yes, You can use your own database,password,username. - Please find the **application.properties** file under **java/resources** folder - Change properties file according to your database properties # How can I found frontend app? - Please visit this link. - https://github.com/mondolmislam/FrontEnd-Spring-boot-vaadin # Feature of the project - Spring boot REST api Concept - CRUD operation - User spring Security - Entity base programming # REST API testing URL - GET ALL, by http get request http://localhost:8080/api/todo - GET Perticular data, by http get request http://localhost:8080/api/todo?id=1 - SAVE data, by http POST request http://localhost:8080/api/todo - UPDATE data, by http PUT request http://localhost:8080/api/todo?id=1 <file_sep>/src/main/java/com/proit/todoapp/domains/ToDoItemResponse.java package com.proit.todoapp.domains; import java.util.List; public class ToDoItemResponse { private List<ToDoItem> ToDoItems; public ToDoItemResponse() { super(); } public ToDoItemResponse(List<ToDoItem> toDoItems) { super(); ToDoItems = toDoItems; } public List<ToDoItem> getToDoItems() { return ToDoItems; } public void setToDoItems(List<ToDoItem> toDoItems) { ToDoItems = toDoItems; } } <file_sep>/src/main/java/com/proit/todoapp/repositories/ToDoItemRepository.java package com.proit.todoapp.repositories; import org.springframework.data.repository.CrudRepository; import com.proit.todoapp.domains.ToDoItem; public interface ToDoItemRepository extends CrudRepository<ToDoItem, Long>{ }
345e535214145867a74e3eb8d846691cd89c9328
[ "Markdown", "Java" ]
3
Markdown
mondolmislam/backend-todoapp-spring-boot
f873c21e084dbfb99d16b5b5c9b99298aebcf276
04f04791bc3f423905a3d91b0288015ba59c2be6
refs/heads/main
<repo_name>Asir-Saadat/Hand-Recognizer-<file_sep>/main.py import cv2 import time import mediapipe as mp mpHand = mp.solutions.hands hand = mpHand.Hands() mpDraw = mp.solutions.drawing_utils cap_video=cv2.VideoCapture(0) cTime=0 pTime=0 while True: success,img = cap_video.read() # Default, it stays in BGR mode, so we need to convert it to RGB imgRGB=cv2.cvtColor(img,cv2.COLOR_BGRA2RGB) result = hand.process(imgRGB) #print(result.multi_hand_landmarks) Gets the landmarks of the hands. if result.multi_hand_landmarks: for landmarks in result.multi_hand_landmarks: for id,lm in enumerate(landmarks.landmark): #print(id) #print(lm.x,lm.y,lm.z) imw,imh,imc=img.shape cx,cy =int((lm.x*lm.y)), int(lm.y*imh) print(id,cx,cy) if id == 1: cv2.circle(img,(cx,cy),15,(255,0,0),cv2.FILLED) #print(landmarks) mpDraw.draw_landmarks(img, landmarks, mpHand.HAND_CONNECTIONS) cTime=time.time() fps=1/(cTime-pTime) pTime=cTime # This means that, we can get the frame per second cv2.putText(img,str(int(fps)), (10,70),cv2.FONT_ITALIC,3,(255,0,250),3) cv2.imshow("Image",img) key = cv2.waitKey(1) & 0xFF if key == ord('q'): #If I press q, this means the vidoe fill stop. break
c850988e42886879e6142b299c6bbca7910942c0
[ "Python" ]
1
Python
Asir-Saadat/Hand-Recognizer-
01e79aaad898086564b909540ca2ee6e47e9afc2
8997749c9253a8943395426c6db4823acb264888
refs/heads/main
<file_sep># WinningPath You and your friend decide to play a game. From a pile of stones, each player places 1-2 stones forming a tower. If there are no remaining stones on a turn, that player loses. This program prompts user for the amount of stones in the pile, then outputs all guaranteed winning paths (no matter what the enemy plays). ## What I Learned - Binary tree data structure using nodes - Developing algorithms through recursion <file_sep>/* Name: <NAME> Description: Program prompts for a starting amount of stones and outputs guaranteed win paths for rock game Input: number of stones Output: Properly formatted guaranteed win paths */ #include <iostream> //create tree node structure template <typename Type> struct binTreeNode{ binTreeNode<Type> *left, *right; Type data; }; /* function_identifier: builds left and right subtrees recursively parameters: binTreeNode<Type> *r (points to root), int rockAmount(num of rocks) return value: N/A */ template <typename Type> void buildTree(binTreeNode<Type> * r, int rockAmount){ if(rockAmount == 0) return; //create temp pointer binTreeNode<int> * t; //create left node r -> left = new binTreeNode<int>; t = r -> left; t -> data = rockAmount - 1; t -> left = t -> right = NULL; buildTree( t, rockAmount -1 ); //create right node if( rockAmount > 1 ){ r -> right = new binTreeNode<int>; t = r -> right; t -> data = rockAmount - 2; t -> left = t -> right = NULL; buildTree( t, rockAmount - 2 ); } } /* function_identifier: deallocates the decision tree parameters: binTreeNode<Type> *r (points to root) return value: N/A */ template <typename Type> void destroyTree(binTreeNode<Type> *r){ if(!r) return; destroyTree(r -> left); delete r -> left; destroyTree(r -> right); delete r -> right; delete r; } /* function_identifier: determines if a win can be guaranteed parameters: binTreeNode<Type> *r, bool turn (turn variable) return value: true/false if a win can be guaranteed */ template <typename Type> bool determineWinningPath(binTreeNode<Type> *r, bool turn){ if( r -> data == 0 && turn == false ) return true; else if( r -> data == 0 && turn == true) return false; //flip turn if( turn == false ) turn = true; else turn = false; binTreeNode<int> * t, * t1; t = r -> right; t1 = r -> left; // if the right node is not null if( t != NULL ){ //if both left and right are true if( determineWinningPath( t, turn ) == true && determineWinningPath(t1, turn) == true) return true; //if either left or right are true else if (determineWinningPath(t, turn) == true || determineWinningPath(t1, turn) == true){ //if my turn, i can pick the right choice //turn was switched earlier for next value if(turn == false) return true; else return false; } //if neither left or right are true else return false; } // go down the left node to get to 0 else{ t = r -> left; if( determineWinningPath(t, turn) == true) return true; else return false; } } /* function_identifier: prints out the path to victory, calls determineWinningPath parameters: binTreeNode<Type> *r, bool turn, int level return value: */ template <typename Type> void printWinningPath(binTreeNode<Type> *r, bool turn, int level){ //flip turn if( turn == false ) turn = true; else turn = false; binTreeNode<int> * t; t = r -> right; //check if right node is NULL if( t != NULL){ //if right path has a guarantee win if( determineWinningPath( t, turn ) == true ){ //handle indents for(int i = 0; i < level; i++) std::cout << " "; //printing format std::cout << r -> data << ": "; if(turn == false) std::cout << "You selected 2 stones \n"; else std::cout << "Opponent selected 2 stones \n"; printWinningPath( t, turn, level + 1 ); } } t = r -> left; if(t == NULL) return; //if left path has a guaranteed win if( determineWinningPath( t, turn ) == true ){ //Printing format for(int i = 0; i < level; i++) std::cout << " "; std::cout << r -> data << ": "; if(turn == false) std::cout << "You selected 1 stone \n"; else std::cout << "Opponent selected 1 stone \n"; printWinningPath( t, turn, level + 1); } else return; } /* function_identifier: main function prompts for an integer to denote starting num of rocks parameters: N/A return value: N/A */ int main() { //create root binTreeNode<int> * root; root = new binTreeNode<int>; root -> left = NULL; root -> right = NULL; root -> data = 0; int rockAmount; std::cout << "Enter the amount of stones to start the game: "; std::cin >> rockAmount; //check for valid input while(std::cin.fail() || rockAmount <= 0) { std::cout << "Please enter a valid amount: " << std::endl; std::cin.clear(); std::cin.ignore(256,'\n'); std::cin >> rockAmount; } std::cout << std::endl; //There are no guaranteed path for amounts divisible by 3 if(rockAmount % 3 == 0){ std::cout << "There is no guaranteed path :c \n\n"; return 0; } //build tree root -> data = rockAmount; buildTree(root, rockAmount); printWinningPath(root, true, 0); std::cout << std::endl; return 0; }
debb7c4f151ee2b1bed177abef441caeaf03da07
[ "Markdown", "C++" ]
2
Markdown
telanis/WinningPath
030c12835df8c60319c3610f5b0c2da53367a097
c169d5c11295574753241965f8a602dd3ffbca8c
refs/heads/master
<file_sep>-- recipes, sulfur and plastic bar alternates data:extend( { { type = "recipe", name = "sulfurification-vulcanization", icon = "__Sulfurification__/graphics/icons/vulcanization.png", icon_size = 32, category = "chemistry", subgroup = "raw-material", normal = { enabled = "false", energy_required = 5, ingredients = { {type = "item", name = "sulfur", amount = 3}, {type = "fluid", name = "steam", amount = 30}, {type = "item", name = "plastic-bar", amount = 1}, }, result = "plastic-bar", result_count = 2, }, expensive = { enabled = "false", energy_required = 5, ingredients = { {type = "item", name = "sulfur", amount = 5}, {type = "fluid", name = "steam", amount = 30}, {type = "item", name = "plastic-bar", amount = 1}, }, result = "plastic-bar", result_count = 2, } }, { type = "recipe", name = "sulfurification-coalwashing", icon = "__Sulfurification__/graphics/icons/coalwashing.png", icon_size = 32, subgroup = "raw-material", category = "chemistry", normal = { enabled = "false", energy_required = 3, ingredients = { {type = "item", name = "coal", amount = 5}, {type = "fluid", name = "water", amount = 50}, }, results = { {type = "item", name = "coal", amount = 3}, {type = "item", name = "sulfur", amount = 1}, } }, expensive = { enabled = "false", energy_required = 3, ingredients = { {type = "item", name = "coal", amount = 5}, {type = "fluid", name = "water", amount = 50}, }, results = { {type = "item", name = "coal", amount = 2}, {type = "item", name = "sulfur", amount = 1}, } } }, }) <file_sep># factorio-sulfurification a mod for factorio - sulfurification adds two new recipes to game with sulfur. first is to create sulfur from coal : http://www.coaleducation.org/lessons/sec/Illinois/cleanil.htm second is creating plastic bar with sulfur: https://www.nature.com/articles/s41467-019-08430-8 they are not efficient compared to regular recipes but provides alternates. <file_sep>--require("prototypes.category") --require("prototypes.items") --require("prototypes.entities") require("prototypes.recipes") --require("prototypes.technology") -- data.raw.recipe["sulfuric-acid"].energy_required = 3 data.raw.recipe["sulfurification-coalwashing"].order = "g[sulfurification-coalwashing]" data.raw.recipe["sulfurification-vulcanization"].order = "f[sulfurification-vulcanization]" table.insert(data.raw["technology"]["sulfur-processing"].effects, { type = "unlock-recipe", recipe = "sulfurification-vulcanization" } ) table.insert(data.raw["technology"]["sulfur-processing"].effects, { type = "unlock-recipe", recipe = "sulfurification-coalwashing" } ) for k, v in pairs(data.raw.module) do if v.name:find("productivity%-module") and v.limitation then table.insert(v.limitation, "sulfurification-vulcanization") table.insert(v.limitation, "sulfurification-coalwashing") end end
3b48d2525e1587c8f876c0cdb30b07a6c13f4cb7
[ "Markdown", "Lua" ]
3
Lua
gungorenu/factorio-sulfurification
f69f217e7dba86674da3bf8e1f11e0dd620eeaa2
24ce436a1e3c0c56cf7506d35eb80384456bcc75
refs/heads/master
<repo_name>cperez58/chem160module14<file_sep>/graph.R d<-read.table("data.txt") png("plot1.png") plot(d$V2~d$V1,main="Chem 160 graph") x<-dev.off() png("plot2.png") plot(d$V2~d$V1,pch=3,ylab="Temp",xlab="Time") #chang plot symbol x<-dev.off() png("plot3.png") plot(d$V2~d$V1,type="l") #Line plot (lower case l) x<-dev.off png("plot4.png") plot(d$V2~d$V1,type="l",lty=2,col=3,lwd=2) x<-dev.off
92857fa28127f093508e4d51d64e223a89c77b59
[ "R" ]
1
R
cperez58/chem160module14
6ad7df5d7ca62b4eec09a8235e5615be4f4e4b9d
c898a45e93569bd4bdf723bd052bc95ff2d645be
refs/heads/master
<repo_name>lincis/ProgrammingAssignment2<file_sep>/cachematrix.R ## ## Set of functions for caching inverses of matrices ## # Function converts input to square matrix and tests for singularity makeSquareMatrix <- function(Mx = matrix()) { # Convert input data to matrix Mx <- as.matrix(Mx) # Read matrix dimensions dims <- dim(Mx) if( dims[1] != dims[2] ) { # Convert non-square matrix to square matrix by expanding dimSq <- ceiling(sqrt(dims[1] * dims[2])) Mx <- matrix(Mx, dimSq, dimSq) d1 <- dims[1] d2 <- dims[2] message(paste("Non square matrix (", d1, "x", d2, ") converted to square matrix (", \ dimSq, "x", dimSq, ")")) } # Test if matrix is singular and return NULL if true if( det(Mx) == 0 ) { message("Sorry the matrix is singular, NULL object returned") return(NULL) } # Return a non-singular matrix Mx } # Function to make matrix with cached inverse matrix makeCacheMatrix <- function(Mi = matrix()) { Mx <- makeSquareMatrix(Mi) # Variable i will store inverse of Mx, initialize to NULL i <- NULL # Function to set matrix to new value set <- function(My) { Mx <<- makeSquareMatrix(My) # New matrix requires resetting inverse matrix as well i <<- NULL } # Function to return "original" matrix get <- function() Mx # Function to set inverse matrix setinv <- function(inv) i <<- inv # Function to return the inverse matrix getinv <- function() i # Return statement: a list of all defined functions list(set = set, get = get, setinv = setinv, getinv = getinv) } # Function to return inverse matrix (either cahced or freshly calculated) cacheSolve <- function(Mx, ...) { # Let's get current inverse matrix i <- Mx$getinv() # If it is not NULL return the stored value if(!is.null(i)) { message("getting cached data") return(i) } # Otherwise calculate the inverse matrix i <- solve(Mx$get(), ...) # And cache the calculated matrix Mx$setinv(i) # And return it i }
fd0417506ff40a41406112b5d99de47eba621e98
[ "R" ]
1
R
lincis/ProgrammingAssignment2
210f03529f7ace91a5f4ea969578a28fb727eb5f
88743b33908d3a1ae34a71dcd38b8665a0442b2e
refs/heads/master
<repo_name>Pea-Shooter/JenkinsTest<file_sep>/README.md Jenkins test demo. <file_sep>/test.py str = "hello" print str
8b4eda9dbd1732de9b66e963c0e9fd1db697571e
[ "Markdown", "Python" ]
2
Markdown
Pea-Shooter/JenkinsTest
27d4da5af583ad335360188c3eeef79752a13e66
21f5fa0ada986aeba6d17100829e9f61f3b509c9
refs/heads/master
<repo_name>Alan951/MaquinaTuringFx<file_sep>/src/maquinaturing/MT/MaquinaTuring.java package maquinaturing.MT; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MaquinaTuring { private List<Cinta> cintas; private List<Estado> estados; private int estadoActual; private int estadoInicial; private int estadoFinal; private Estado estadoActualObj; public boolean termino = false; private List<CellAffected> cellAffecteds; private List<Cinta> cintasMoved; private String inputUser; public int PHASE_SEARCH = 1; public int PHASE_REPLACE = 2; public int PHASE_MOVE = 3; private int status; public MaquinaTuring(int numCintas, int estadoInicial, int estadoFinal, String cadena){ cintas = new ArrayList<>(); cellAffecteds = new ArrayList<>(); cintasMoved = new ArrayList<>(); inputUser = cadena; this.estados = new ArrayList<Estado>(); this.estadoActual = estadoInicial; this.estadoInicial = estadoInicial; this.estadoFinal = estadoFinal; for(int x = 0 ; x < numCintas ; x++){ cintas.add(new Cinta()); } cintas.get(0).createCinta(cadena); } public Estado futureState(){ System.out.println("futureState invoked"); List<Estado> estados = searchEstadosByNumber(estadoActual); boolean eval = false; for(Estado estado : estados){ for(int mIt = 0 ; mIt < cintas.size() ; mIt++){ if(estado.getInParm().get(mIt).equals(cintas.get(mIt).getChar())){ //estadoActual = estado.getNextEstado(); eval = true; return estado; }else{ eval = false; break; } } if(!eval){ continue; } break; } return null; } public boolean nextStep(int phase){ System.out.println("nextStep invoked"); cellAffecteds.clear(); cintasMoved.clear(); List<Estado> estados = searchEstadosByNumber(estadoActual); //Obtengo el obj estado actual boolean eval = false; Estado estadoChecked = checkInputParms(estados.stream().toArray(Estado[]::new)); if(estadoChecked != null){ //Estado valido //Actualizar valor en las cintas for(int x = 0 ; x < cintas.size() ; x++){ cintas.get(x).updateChar(estadoChecked.getOutParm().get(x)); cellAffecteds.add(new CellAffected(cintas.get(x), cintas.get(x).getCursorValue())); } //Mover cinta for(int x = 0 ; x < cintas.size() ; x++){ if(estadoChecked.getCursorDirection().get(x) != Cinta.NO_MOVE) cintasMoved.add(cintas.get(x)); cintas.get(x).next(estadoChecked.getCursorDirection().get(x)); } estadoActual = estadoChecked.getNextEstado(); estadoActualObj = estadoChecked; eval = true; }else{ //No encontro estado } if(estadoActual == estadoFinal){ System.out.println("Llego al estado de aceptación"); termino = true; } return eval; } /* Esta función busca el candidato al estado cuyos parametros de entrada coincidan con los simbolos que hay en las cintas |a|b|c|a|b|c| (q1, (a)) = (q2, (b), (S)) ^ inParm Recibe por parametro una lista de estados que coinciden con el estado actual. Regresa un objeto de tipo Estado en caso de que haya estado valido y un null en caso de que no lo haya, por lo tanto se entiende que la maquina de turing y a no puede seguir. */ public Estado checkInputParms(Estado... estados){ boolean valid = false; for(Estado estado : estados){ for(int x = 0 ; x < cintas.size() ; x++){ //El numero de estados a validar es exactamente el mismo a la cantidad de cintas que hay en la maquina de turing. //Compruebo que la entrada de caracteres sea el mismo que el valor que hay en la cinta. if(estado.getInParm().get(x).equals(cintas.get(x).getChar())){ valid = true; }else{ valid = false; //En cuanto una parametro de entrada sea diferente al // simbolo // que hay en la cinta, el estado se descarta y se busca // el siguiente estado, por lo tanto, el for se estara // ciclando hasta que encuentre un estado valido y ya no haya mas estados que verificar. break; } } if(valid){//regresa el estado valido return estado; } } return null; } public List<CellAffected> getCellAffecteds(){ return cellAffecteds; } public void reset(){ termino = false; estadoActual = estadoInicial; cellAffecteds.clear(); cintas.get(0).createCinta(inputUser); for(int x = 1 ; x < cintas.size() ; x++){ cintas.get(x).reset(); } } public void setInputUser(String cadena){ this.inputUser = cadena; } public List<Estado> searchEstadosByNumber(int number){ List<Estado> estados = new ArrayList<Estado>(); for(Estado estado : this.estados){ if(estado.getEstado() == number){ estados.add(estado); } } return estados; } public List<Cinta> getCintas() { return cintas; } public List<Cinta> getCintasMoved(){ return cintasMoved; } public List<Estado> getEstados() { return estados; } public void setEstados(List<Estado> estados){ this.estados = estados; } public Estado getEstadoActualObj(){ return estadoActualObj; } public int getEstadoActual() { return estadoActual; } public int getEstadoFinal() { return estadoFinal; } public int getStatus(){ return status; } @Override public String toString() { return "MaquinaTuring{" + "cintas=" + cintas + ", estados=" + estados + ", estadoActual=" + estadoActual + ", estadoFinal=" + estadoFinal + ", termino=" + termino + '}'; } } <file_sep>/src/maquinaturing/MT/Cinta.java package maquinaturing.MT; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.application.Platform; import maquinaturing.view.CintaViewController; class CellHistory{ private List<Character> lista; public CellHistory(Character first){ lista = new ArrayList<>(); lista.add(first); } public List<Character> getLastTree(){ List<Character> lista = new ArrayList<>(); for(int x = lista.size() ; x > 0 ; x--){ lista.add(this.lista.get(x)); } return lista; } public void add(Character c){ lista.add(c); } public Character getLast(){ return lista.get(lista.size()-1); } public Character getPenultimo(){ if(lista.size() == 1) return getLast(); else return lista.get(lista.size()-2); } } public class Cinta { private List<Character> cinta; private Map<Integer, CellHistory> historial; private int cursor; public final static int RIGHT = 1; public final static int LEFT = -1; public final static int NO_MOVE = 0; public final static Character WHITE_SPACE = (char)254; private final static int CINTA_LIMITE = 102; private CintaViewController controller; public Cinta(){ cinta = new ArrayList<>(); historial = new HashMap<>(); reset(); cursor = CINTA_LIMITE / 2; } public void reset(){ cinta.clear(); historial.clear(); if(controller != null) controller.clearLabels(); for(int x = 0 ; x < CINTA_LIMITE ; x++){ cinta.add(WHITE_SPACE); if(controller != null) controller.addLabel(cinta.get(x)); historial.put(x, new CellHistory(WHITE_SPACE)); } cursor = CINTA_LIMITE / 2; if(controller != null){ controller.setCursorLabelPos(Integer.toString(cursor)); //Actualiza el label que muestra la posición del cursor controller.toggleCursor(cursor); //Actualiza el label de la celda cursor } } public void setController(CintaViewController controller){ this.controller = controller; for(int x = 0 ; x < CINTA_LIMITE ; x++){ controller.addLabel(cinta.get(x)); } controller.toggleCursor(cursor); } public Cinta createCinta(String chars){ cinta.clear(); historial.clear(); if(controller != null) controller.clearLabels(); for(int x = 0 ; x < CINTA_LIMITE ; x ++){ cinta.add(WHITE_SPACE); if(controller != null) controller.addLabel(WHITE_SPACE); historial.put(x, new CellHistory(WHITE_SPACE)); } cursor = (int)((CINTA_LIMITE / 2) - (chars.length() / 2)); if(controller != null) controller.setCursorLabelPos(Integer.toString(cursor)); int tempCursor = cursor; for(int x = 0 ; x < chars.length() ; x++){ cinta.set(tempCursor, chars.charAt(x)); if(controller != null) controller.updateLabel(tempCursor, chars.charAt(x)); historial.get(tempCursor).add(chars.charAt(x)); tempCursor++; } if(controller != null){ controller.toggleCursor(cursor); } return this; } public Character nextRight(){ Character charObj = null; if(cursor + 1 <= cinta.size()){ charObj = cinta.get(++cursor); if(controller != null) controller.toggleCursor(cursor); } return cinta.get(cursor); } public Character nextLeft(){ Character charObj = null; if(cursor - 1 > 0){ charObj = cinta.get(--cursor); if(controller != null) controller.toggleCursor(cursor); } return charObj; } public Character next(int direction){ if(direction == RIGHT){ return nextRight(); }else if(direction == LEFT){ return nextLeft(); }else if(direction == NO_MOVE){ return getChar(); } return null; } public Character getChar(){ return cinta.get(cursor); } public void updateChar(Character charObj){ cinta.set(cursor, charObj); if(controller != null) controller.updateLabel(cursor, charObj); historial.get(cursor).add(charObj); } public List<Character> getCinta(){ List<Character> lista = new ArrayList<>(); int topCursor = CINTA_LIMITE - 1; int botCursor = 0; while(true){ if(cinta.get(topCursor) != WHITE_SPACE && cinta.get(botCursor) != WHITE_SPACE){ break; } if(cinta.get(topCursor) == WHITE_SPACE){ topCursor--; } if(cinta.get(botCursor) == WHITE_SPACE){ botCursor++; } if(topCursor == 0 || botCursor == CINTA_LIMITE - 1){ break; } } topCursor = (topCursor == CINTA_LIMITE - 1) ? CINTA_LIMITE - 1 : topCursor + 1; botCursor = (botCursor == 0) ? 0 : botCursor - 1; for(int x = botCursor ; x <= topCursor ; x++){ lista.add(cinta.get(x)); } return lista; } public int getCursorValue(){ return cursor; } public CellHistory getHistoryOf(int pos){ if(pos < 0 || pos > CINTA_LIMITE){ return null; }else{ return historial.get(pos); } } public List<Character> getFullCinta(){ return cinta; } @Override public String toString() { String c = "["; int topCursor = CINTA_LIMITE - 1; int botCursor = 0; while(true){ if(cinta.get(topCursor) != WHITE_SPACE && cinta.get(botCursor) != WHITE_SPACE){ break; } if(cinta.get(topCursor) == WHITE_SPACE){ topCursor--; } if(cinta.get(botCursor) == WHITE_SPACE){ botCursor++; } if(topCursor == 0 || botCursor == CINTA_LIMITE - 1){ c+="]"; break; } } topCursor = (topCursor == CINTA_LIMITE - 1) ? CINTA_LIMITE - 1 : topCursor + 1; botCursor = (botCursor == 0) ? 0 : botCursor - 1; for(int x = botCursor ; x <= topCursor ; x++){ if(x >= topCursor){ c += cinta.get(x)+"]"; }else{ c += cinta.get(x)+ ", "; } } return "Cinta{" + "cinta=" + c + ", cursor=" + cursor + '}'; } } <file_sep>/src/maquinaturing/MT/Estado.java package maquinaturing.MT; import java.util.List; public class Estado { private int nextEstado; private int estado; private int numParm; private List<Character> inParm; private List<Character> outParm; private List<Integer> cursorDirection; public Estado(int estado, int nextEstado, List<Character> inParm, List<Character> outParm, List<Integer> cursorDirection) { this.nextEstado = nextEstado; this.estado = estado; this.inParm = inParm; this.outParm = outParm; this.cursorDirection = cursorDirection; } public boolean validate(){ return cursorDirection.size() != outParm.size() && outParm.size() != inParm.size(); } public int getNextEstado() { return nextEstado; } public void setNextEstado(int nextEstado) { this.nextEstado = nextEstado; } public int getEstado() { return estado; } public void setEstado(int estado) { this.estado = estado; } public int getNumParm() { return numParm; } public void setNumParm(int numParm) { this.numParm = numParm; } public List<Character> getInParm() { return inParm; } public void setInParm(List<Character> inParm) { this.inParm = inParm; } public List<Character> getOutParm() { return outParm; } public void setOutParm(List<Character> outParm) { this.outParm = outParm; } public List<Integer> getCursorDirection() { return cursorDirection; } public void setCursorDirection(List<Integer> cursorDirection) { this.cursorDirection = cursorDirection; } @Override public String toString() { //(q1, (þ, þ)) = (q5, (þ, þ), (S, S)) String fString = null; fString = "(q"+this.estado+", "; fString += "("; for(int x = 0 ; x < this.inParm.size() ; x++){ if(x < this.inParm.size() - 1){ fString += inParm.get(x) + ", "; }else{ fString += inParm.get(x) + ")"; } } fString += ") = (q"+this.nextEstado+", ("; for(int x = 0 ; x < this.outParm.size() ; x++){ if(x < this.outParm.size() -1 ){ fString += outParm.get(x) + ", "; }else{ fString += outParm.get(x) +")"; } } fString +=", ("; for(int x = 0 ; x < this.cursorDirection.size() ; x++){ if(this.cursorDirection.get(x) == Cinta.LEFT){ fString += "L"; }else if(this.cursorDirection.get(x) == Cinta.RIGHT){ fString += "R"; }else if(this.cursorDirection.get(x) == Cinta.NO_MOVE){ fString += "S"; } if(x < this.cursorDirection.size() -1){ fString += ", "; }else{ fString += ")"; } } fString += ")"; return fString; } } <file_sep>/src/maquinaturing/animtests/AnimTestController.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package maquinaturing.animtests; import javafx.animation.Animation; import javafx.animation.FadeTransition; import javafx.animation.Interpolator; import javafx.animation.Transition; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.paint.Color; import javafx.util.Duration; /** * * @author Ck */ public class AnimTestController { @FXML private Label lblHello; @FXML private Button btnHello; @FXML private AnchorPane container; @FXML private Button btnInterpole; private FadeTransition ft; public AnimTestController(){} @FXML public void initialize(){} public void init(){ ft = new FadeTransition(Duration.millis(200), lblHello); ft.setFromValue(1.0); ft.setToValue(0.0); } @FXML public void onAction(){ System.out.println("onAction invoked!"); ft.play(); } @FXML public void onInterpole(){ final Animation animation = new Transition() { { setCycleDuration(Duration.millis(1000)); setInterpolator(Interpolator.EASE_OUT); } @Override protected void interpolate(double frac) { System.out.println("frac: "+ frac); //Color vColor = new Color(0.5, 0, 0, 1 - frac); Color vColor = Color.rgb(18, 183,32, 1 - frac); lblHello.setBackground(new Background(new BackgroundFill(vColor, CornerRadii.EMPTY, Insets.EMPTY))); } }; animation.play(); } } <file_sep>/src/maquinaturing/MT/Step.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package maquinaturing.MT; import java.util.Map; /** * * @author Ck */ public class Step { private int currentStep; private int totalSteps; private Map<Integer, String> stepName; public Step(){ } public int getCurrentStep() { return currentStep; } public void setCurrentStep(int currentStep) { this.currentStep = currentStep; } public int getTotalSteps() { return totalSteps; } public void setTotalSteps(int totalSteps) { this.totalSteps = totalSteps; } public String getStepName(int step) { return stepName.get(step); } public Map<Integer, String> getMapStepNames(){ return stepName; } public void setMapStepNames(Map<Integer, String> map){ this.stepName = map; } @Override public String toString() { return "Step{" + "currentStep=" + currentStep + ", totalSteps=" + totalSteps + ", stepName=" + stepName + '}'; } }
f52fb0bde5299c5029faea05ceea82d4e58e5e3d
[ "Java" ]
5
Java
Alan951/MaquinaTuringFx
e4c9507a804d8563d759c878707393d9ef823cc5
5e8b1eb001c5c939bd4310ea8e78f7734f167cb0
refs/heads/master
<file_sep>package com.example.daggerdemo.ui; import com.example.daggerdemo.data.local.DatabaseService; import com.example.daggerdemo.data.remote.NetworkService; public class MainViewModel { private DatabaseService databaseService; private NetworkService networkService; public MainViewModel(DatabaseService databaseService, NetworkService networkService) { this.databaseService = databaseService; this.networkService = networkService; } public String getSomeData() { return databaseService.getDummyData() + " : " + networkService.getDummyData(); } } <file_sep>package com.example.daggerdemo.di.module; import com.example.daggerdemo.MyApplication; import com.example.daggerdemo.data.local.DatabaseService; import com.example.daggerdemo.data.remote.NetworkService; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module public class ApplicationModule { private MyApplication myApplication; public ApplicationModule(MyApplication myApplication) { this.myApplication = myApplication; } @Singleton @Provides NetworkService provideNetworkService(){ return new NetworkService(myApplication, "xyz"); } @Singleton @Provides DatabaseService provideDatabaseService(){ return new DatabaseService(myApplication, "abc", 1); } }
025789fbd226065c9745c356ce9651841982b3eb
[ "Java" ]
2
Java
VinayDelhi/DaggerDemo_Stage_3
a77b8e1ea41d2af93174b449008e4cd0fff41d8c
f43135fe163dd1d603037f5a35542a463c7fa615
refs/heads/master
<file_sep>'use strict' /* DOM Document Object Model Todos los scripts de DOM deben ir al final del body para que los pueda cargar correctamente y lea todo. */ //SELECCION DE ELEMENTOS POR ID CONCRETO function cambiacolor(color) { caja1.style.color = color; } function cambiafondo(color) { caja1.style.background = color; } //Tomando el elemento para javascript forma 1 var caja1 = document.getElementById('caja1'); //Tomando el elemento por id caja1 console.log(caja1); caja1.innerHTML = "Texto diferente"; // Cambiar el html de el elemento caja1.style.background = "green"; //color caja1.style.padding = "20px"; caja1.style.color = "white"; //Tomando el elemento para javascript forma 2 var caja2 = document.querySelector("#caja2"); caja2.innerHTML = "CAJA 2 MODIFICADO CON JAVASCRIPT"; caja2.style.background = "red"; //color caja2.style.padding = "20px"; caja2.style.color = "white"; //SELECCIONAR CLASES Y DIVS CON JAVASCRIPT //Seleccionar elementos por su etiqueta var todoslosdivs = document.getElementsByTagName('div'); console.log(todoslosdivs); var contenido = todoslosdivs[2].textContent; console.log(contenido); var seccion = document.querySelector("#miseccion"); var linea = document.createElement("hr"); var valor; for (valor in todoslosdivs) { if (typeof todoslosdivs[valor].textContent == 'string') { var parrafo = document.createElement("p"); var texto = document.createTextNode(todoslosdivs[valor].textContent); parrafo.append(texto) seccion.append(parrafo); } } seccion.append(linea);<file_sep>'use strict' //Operadores console.log("\nOPERADORES\n\n"); var num1 = 10; var num2 = 35; var suma = num1+num2; var resta = num1-num2; var multi = num1*num2; var divi = num1/num2; var modulo = num1%num2; console.log("La suma de los numero es: ",suma); console.log("La resta de los numero es: ",resta); console.log("La multiplicacion de los numero es: ",multi); console.log("La division de los numero es: ",divi); console.log("El modulo de los numero es: ",modulo); //Tipo de Datos var entero = 44; var flotante = 3.567; var texto = "Hola 'que' tal"; var texto2 = 'Hola que "tal"'; var booleano = true; //Conversiones console.log("\nCONVERSIONES\n\n"); var entero_text = "22"; var entero_float = "2.57"; console.log(Number(entero_text)+5); //Number convierte string a numero; console.log(parseInt(entero_text)+2); //parseInt convierte string a entero; console.log(parseFloat(entero_float)+2); //parseFloat convierte string a flotante; console.log(String(entero_text)+6); //parseInt convierte numeros a string; //Que tipo de variable es console.log("\nSABER QUE TIPO DE VARIABLE es\n\n"); console.log(typeof entero); console.log(typeof flotante); console.log(typeof texto); console.log(typeof booleano); <file_sep>"use strict" //Constantes son variables que no puede varias //Se coloca la palabra reservada const var pagina ="https://facebook.com" const ip = "192.168.100.1" console.log(pagina,ip); <file_sep>'use strict' //Funciones var num1 = parseInt(prompt("Numero uno: ")); var num2 = parseInt(prompt("Numero dos: ")); //Parametros opcionales son parametros que ya vienen inicializados function consola(num1, num2){ console.log("Suma: "+(num1+num2)); console.log("Resta: "+(num1-num2)); console.log("Multiplicación: "+(num1*num2)); console.log("División: "+(num1/num2)); } function pantalla(num1,num2){ document.write("Suma: "+(num1+num2)+"<br>"); document.write("Resta: "+(num1-num2)+"<br>"); document.write("Multiplicación: "+(num1*num2)+"<br>"); document.write("División: "+(num1/num2)+"<br>"); } function calculadora(num1, num2, mostrar=true){ if (mostrar==false) { consola(num1,num2); }else{ pantalla(num1,num2); } return "Hola soy la calculadora"; } console.log(calculadora(num1, num2)); <file_sep>'use strict' //Alerta //alert(mensaje) alert("Esta es una Alerta"); //Confirmacion //confirm(mensaje) var confirmacion = confirm("¿Estas seguro que quieres continuar?"); console.log(confirmacion); //Ingreso de Datos //prompt(mesaje,dafault) var edad = prompt("¿Qué edad tienes?",18); console.log(edad); console.log(typeof edad); <file_sep>'use strict' /* Mostrar todos los numero impares quehay entre 2 numeros */ var num1 = parseInt(prompt("Ingrese el número 1: ",0)); var num2 = parseInt(prompt("Ingrese el número 2: ",0)); for (var i = num1+1; i < num2; i++) { if (i%2!=0) { console.log(i); } } <file_sep>'use strict' var divsRojos = document.getElementsByClassName("rojo"); var divAmarillo = document.getElementsByClassName("amarillo"); for (const indice in divsRojos) { divsRojos[indice].style.padding = "2rem"; divsRojos[indice].style.background = "red"; }<file_sep>'use strict' //Plantillas de texto JavaScript var nombre = prompt("Ingresa un nombre: "); var apellidos = prompt("Ingresa los apellidos: "); /* Para concatenar un texto con una platilla de manera multinilinea se puede realizar de la siguiente manera*/ var texto =` <h1>Hola que tal</h1> <h3>Mi nombre es: ${nombre}</h3> <h3>Mis apellidos son: ${apellidos}</h3> `; document.write(texto);<file_sep>'use strict' var num=100 for (var i = 0; i < 100; i++) { console.log(i+1); //debugger; } //Con debuger podemos mirar el paso a paso del programa<file_sep># Course_Javascript-Frameworks Repository for the course of Javascript and Frameworks <file_sep>//'use strict' para el modo estricto y evitar declarar variables sin poner var, para evitar errores posteriormente 'use strict' // Variables en Javascript //Se definen las varaibles con la palabra reservada var o let (se usa más en typescrpt) var pais = "España"; var continente = "Europa"; var ano = 2020; //Concatenando variables string var PaisYContinente = pais+' '+continente; let prueba = "Hola"; alert(prueba); console.log(pais,continente,ano); alert(PaisYContinente); //Modo Estricto <file_sep>'use strict' //Transformacion de textos var num = 223; var texto1 = "Bienvenido al curso de JavaScript, el mejor curso del mundo."; var texto2 = " es el mejor"; var dato = num.toString();//Convirtiendo numero a String dato = texto1.toUpperCase();//Convertir a mayusculas dato = texto1.toLowerCase();//Convertir a minusculas console.log(dato); //Calcular longitud var nombre =""; console.log(nombre.length);//Contar cantidad de letras de un texto var array = ["hola",123]; console.log(array.length);//Contar elementos del array //Concatenar textos //Forma 1 var textoTotal = texto1+texto2; console.log(textoTotal); //Forma 2 textoTotal = ""; textoTotal = texto1.concat(texto2); console.log(textoTotal); //METODOS DE BUSQUEDA //Si fallan regresan -1 var busqueda = texto1.indexOf("curso");// marca a partir de que caracter esta la palabra var busqueda2 = texto1.lastIndexOf("curso");//Busca la ultima palabra en todo el texto var busqueda3 = texto1.match("curso");//Regresa un array con toda la info de la palabra encontrada var busqueda4 = texto1.match(/curso/g);//Regresa un array con toda la info de la palabra encontrada console.log(busqueda); console.log(busqueda2); console.log(busqueda3); console.log(busqueda4); //Substraer texto de un texto var sub = texto1.substr(14, 5); // desde el caracter 14 solo 5 letras console.log(sub); var sub2 = texto1.charAt(5); // Solo una letra console.log(sub2); var encontrado = texto1.startsWith("Bienvenido"); // Busca al inicio del string , si la encuentra en el texto regresa true console.log(encontrado); var encontrado2 = texto1.endsWith("Bienvenido"); // Busca al final del string , si la encuentra en el texto regresa true console.log(encontrado2); var encontrado3 = texto1.includes("Bienvenido"); // Busca la palabra dentro del string , si la encuentra en el texto regresa true console.log(encontrado3); //Funciones de reemplazo de texto var reemplazo = texto1.replace("Bienvenido","Hola, sea usted bienvenido"); //Remplaza lo buscado por el parametro console.log(reemplazo); var cortar = texto1.slice(11); //Separa el string a partir del caracter mencionado console.log(cortar); var separar = texto1.split(" "); //Mete todo el string en un array y si lo quiero separar por espacios coloco el parametro y me arroja un array separado por espacios console.log(separar); var sobrante = texto1.trim(); //Quita los espacios por delante y por detras del string console.log(sobrante); // <file_sep>'use strict' /* Programa que nos diga si un numero es par o impar, debe tener prompt, comprobar si un numero o es valido vuelva a pedir numero y mostrar par o impar. */ var num1 = parseInt(prompt("Ingrese el numero: ",0)); while(isNaN(num1)){ num1 = parseInt(prompt("Ingrese el numero: ",0)); } if(num1%2==0){ alert("Es un numero par"); }else{ alert("Es un número impar"); }<file_sep>'use strict' /* Utilizando un bucle mostrar la suma y la media de los numeros introducidos asta introducir un numero negativo y ahi mostrar el resultado. */ var num; var suma=0; var contador=0; do{ num = parseInt(prompt("Ingrese un numero: ",0)); if(isNaN(num)){ num=0; }else if(num>=0){ suma += num; contador++; } }while(num>=0); alert("La suma de los numero ingresados es: "+suma); alert("La media es: "+(suma/contador));<file_sep>'use strict' //Parametos REST y SPREAD /* Parametro REST sirve cuando no sabes cuantos vas a recibir y colocas trs puntos y colocas el nombre de la varibale y lo guarda en un array, asi mismo lo muestra. */ function listadoFrutas(fruta1, fruta2,...todasLasFrutas){ console.log("Fruta 1: "+fruta1); console.log("Fruta 2: "+fruta2); console.log("Resto de frutas: "+todasLasFrutas); } listadoFrutas("Naranja", "Manzana","Pera","Sandía","Melon"); /* Hacer un SPREAD de parametros Haces un array de los parametros y luego lo ingresas con ... para que lo tome como parametros independientes */ var arregloFrutas =["Kiwi","Durazno"]; listadoFrutas(...arregloFrutas,"Naranja", "Manzana","Pera","Sandía","Melon");<file_sep>'use strict' //Arreglos o Matrices basicas en JavaScript var nombre = "<NAME>"; var nombres = ["<NAME>",24,true,"hombre"]; var lenguajes = new Array("PHP","JAVASCRIPT","GO","JAVA"); console.log(nombres[0]); console.log(lenguajes); //Longitud de un array console.log(nombres.length); //Recorrer arrays con ciclo For ******************************************** document.write("<h1>Lenguajes de programación For</h1>") document.write("<ul>"); for (var i = 0; i < lenguajes.length; i++) { document.write("<li>"+lenguajes[i]+"</li>"); } document.write("</ul>"); //Recorrer arrays con ciclo ForEach **************************************** /* SINTAXIS arr.forEach(function callback(currentValue, index, array) { // tu iterador }[, thisArg]); callback: Función a ejecutar por cada elemento, que recibe tres argumentos: currentValue: El elemento actual siendo procesado en el array. index (opcional): El índice del elemento actual siendo procesado en el array. array (opcional): El vector en el que forEach() esta siendo aplicado. thisArg (opcional): Valor que se usará como this cuando se ejecute el callback. */ document.write("<h1>Lenguajes de programación ForEach</h1>") document.write("<ul>"); lenguajes.forEach((elemento,index,array)=>{ document.write("<li>"+index+" - "+elemento+"</li>"); }); document.write("</ul>"); //Recorrer arrays con ciclo For in ******************************************** document.write("<h1>Lenguajes de programación For In </h1>") document.write("<ul>"); for (let indice in lenguajes) { document.write("<li>"+indice+".- "+lenguajes[indice]+"</li>"); } document.write("</ul>"); //BUSQUEDAS EN UN ARRAY //Forma 1, regresa lo buscado var busqueda = lenguajes.find(function(lenguaje){ return lenguaje == "PHP"; }); console.log(busqueda); //Forma 2, regresa lo buscado var busqueda = lenguajes.find(lenguaje => lenguaje == "PHP"); console.log(busqueda); //Forma 3, regresa el indice de lo buscado var busqueda = lenguajes.findIndex(lenguaje => lenguaje == "PHP"); console.log(busqueda); var precios = [10,20,30,50]; busqueda = precios.some(precio => precio > 20);//Si existe algo mayo a lo indicado console.log(busqueda); <file_sep>'use strict' /* Es una funcion que no tiene nombre y se puede guardar en una variable, y se utiliza para hacer callbacks. */ var pelicula = function (nombre){ return "La pelicula es "+nombre; } //Callback function sumame(num1, num2,SumaYMuestra,SumaPorDos){ var sumar = num1+num2; SumaYMuestra(sumar); SumaPorDos(sumar); return sumar; } sumame(5,7,function(dato){ console.log("La suma es: "+dato); },function(dato){ console.log("La suma por dos es: "+(dato*2)); }); //Funciones de flecha es lo mismo que callback pero en vez de la palabra function en el parametro se pone una flecha function sumame2(num1, num2,SumaYMuestra,SumaPorDos){ var sumar = num1+num2; SumaYMuestra(sumar); SumaPorDos(sumar); return sumar; } sumame2(5,7,dato=>{ console.log("La suma es: "+dato); },dato=>{ console.log("La suma por dos es: "+(dato*2)); });<file_sep>'use strict' var edad = 16; var nombre = "<NAME>"; /* Mayor que > Menor que < Mayor o igual >= Menor o igual <= Igual == Diferente != Y && O || */ //Condicional con IF if (edad >= 18) { console.log(nombre+" es mayor de edad"); }else{ console.log(nombre+" es menor de edad"); } <file_sep>'use strict' //Puedo acceder a las variables globales desde cualquier funcion, pero si hay una variable creada dentro de //una función no se puede acceder de otro lado que no sea la funcion. function holaMundo(texto){ var hola_mundo = "Hola, soy una variable dentro de una función"; console.log(texto); console.log(num); console.log(num.toString());//Convirtiendo a string console.log(hola_mundo); } var num = 50; var texto = "Hola Mundo, soy una variable String"; holaMundo(texto);
986549129227a65f4a9a31c0dac7a9e801e09ce9
[ "JavaScript", "Markdown" ]
19
JavaScript
abdieloflores/Course_Javascript-Frameworks
b17d75da12e15d2984742b5ef81118256533e8f3
f479fbb41981a9d8c17e7702b9ff7c3fbf8477d9
refs/heads/master
<file_sep>package com.shopnum1.distributionportal; //我的收藏 import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.nostra13.universalimageloader.core.ImageLoader; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; public class MemberCollect extends Activity { private HttpConn httpget = new HttpConn(); private ListAdapter adapter; private int requestTime = 1; private Dialog pBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.member_collect); initLayout(); addList(); } //初始化 public void initLayout() { //返回 ((LinearLayout)findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); } public void addList(){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); ListView listview = (ListView)findViewById(R.id.listview); adapter = new ListAdapter(this); listview.setAdapter(adapter); registerForContextMenu(listview); //商品详情 listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) { try { Intent intent = new Intent(getApplicationContext(), ProductDetails.class); intent.putExtra("guid", adapter.getInfo(i).getString("ProductGuid")); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); listview.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { return false; } }); listview.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(final AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { // 判断是否滚动到底部 if (view.getLastVisiblePosition() == view.getCount() - 1) adapter.upData("/api/collectlist/?pageIndex=" + requestTime + "?pageCount=5&MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign, false); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(v==((ListView)findViewById(R.id.listview))){ menu.setHeaderTitle("确定删除吗?"); menu.add(0, 0, 0, "确定"); menu.add(0, 1, 0, "取消"); } } @Override public boolean onContextItemSelected(MenuItem item) { int selectedPosition=((AdapterContextMenuInfo)item.getMenuInfo()).position; if(item.getItemId()==0){ try { delCollection(adapter.getInfo(selectedPosition).getString("Guid")); } catch (JSONException e) { e.printStackTrace(); } } return super.onContextItemSelected(item); } public void delCollection(final String guid){ new Thread(){ @Override public void run(){ httpget.getArray("/api/collectdelete?CollectId=" + guid + "&MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); Message message = Message.obtain(); message.what = 4; handler.sendMessage(message); } }.start(); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: if(!adapter.isdown){ adapter.isdown = true; adapter.notifyDataSetChanged(); adapter.isdown = false; } break; case 2: if(msg.obj.equals("202")) Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show(); finish(); startActivity(new Intent(getApplicationContext(), MemberCollect.class)); break; case 3: ((TextView)findViewById(R.id.nocontent)).setVisibility(View.VISIBLE); break; case 4: addList(); break; default: break; } super.handleMessage(msg); } }; class ListAdapter extends BaseAdapter{ private ArrayList<Bitmap> bm = new ArrayList<Bitmap>(); private JSONArray collectList = new JSONArray(); private boolean isend = false; //已发送 private boolean isdown = false; //在下拉 int count = 0; public JSONObject getInfo(int position) { JSONObject result = null; try { result = collectList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return result; } //翻页 public void upData(final String port, final boolean isRebuilt) { if (isRebuilt) isend = false; if (!isend) { if (!isdown) { isdown = true; new Thread() { @Override public void run() { StringBuffer temp = httpget.getArray(port); if (temp.length() == 0) { isend = true; if (requestTime == 1) { collectList = new JSONArray(); bm.clear(); isdown = false; Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } else isdown = false; } else { requestTime++; try { StringBuffer data = new StringBuffer(); if (isRebuilt) { bm.clear(); data.append(temp); } else { data.append(collectList.toString()); data.setCharAt(data.length() - 1, ','); data.append(new JSONObject(temp.toString()).getJSONArray("Data").toString().substring(1)); } collectList = new JSONArray(data.toString()); int start = bm.size(); int end = collectList.length(); if(end <= count) { for (int i = start; i < end; i++) bm.add(null); } isdown = false; Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); isdown = false; isend = true; } } } }.start(); } } } public ListAdapter(Context c) { isdown = true; new Thread() { @Override public void run() { try { StringBuffer result = httpget.getArray("/api/collectlist/?pageIndex=1&pageCount=50&MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); pBar.dismiss(); collectList = new JSONObject(result.toString()).getJSONArray("Data"); count = Integer.parseInt(new JSONObject(result.toString()).get("Count").toString()); if(count == 0){ Message message = Message.obtain(); message.what = 3; handler.sendMessage(message); } else { requestTime++; } for (int i = 0; i < collectList.length(); i++) bm.add(null); isdown = false; Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } catch (JSONException e) { isdown = false; isend = true; e.printStackTrace(); } } }.start(); } @Override public int getCount() { return bm.size(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.product_item, parent, false); holder.ProductName = (TextView)convertView.findViewById(R.id.textView1); holder.ShopPrice = (TextView)convertView.findViewById(R.id.textView2); holder.MarketPrice = (TextView)convertView.findViewById(R.id.textView3); holder.ProductImage = (ImageView)convertView.findViewById(R.id.imageView1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { holder.ProductName.setText(collectList.getJSONObject(position).getString("Name")); holder.ShopPrice.setText("¥" + collectList.getJSONObject(position).getString("ShopPrice")); holder.MarketPrice.setHint("¥" + collectList.getJSONObject(position).getString("MarketPrice")); if(HttpConn.showImage) ImageLoader.getInstance().displayImage(collectList.getJSONObject(position).getString("OriginalImge"), holder.ProductImage, MyApplication.options); } catch (JSONException e) { e.printStackTrace(); } return convertView; } } class ViewHolder { ImageView ProductImage; TextView ProductName; TextView ShopPrice; TextView MarketPrice; } public void delMessage(final String msgid) { new Thread(){ @Override public void run(){ try { StringBuffer result = httpget.getArray("/api/membermessage/delete/?msgId=" + msgid + "&MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); Message msg = Message.obtain(); msg.obj = new JSONObject(result.toString()).getString("return"); msg.what = 2; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } }<file_sep>package com.shopnum1.distributionportal; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.alipay.sdk.pay.PayUtil; import com.shopnum1.distributionportal.util.HttpConn; /** * 我要充值的Activity */ public class RechargeActivity extends Activity { private HttpConn httpget = new HttpConn(); private Dialog pBar; //加载进度 //充值金额编辑 private EditText et1; //用户填写的充值金额 private String et1Val; //提交按钮 private TextView commitTv; //支付类型的jsonArray private JSONArray paymentArray; //支付类型的名字 private String typeName; //支付类型的guid private String typeGuid; //获得返回的订单号 private String orderNum; private TextView payName; private ArrayList<Map<String, String>> PaymentList; private String paynametype=""; public static RechargeActivity rechargeActivity = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recharge); rechargeActivity = RechargeActivity.this; currentPayment = getIntent().getDoubleExtra("AdvancePayment",0.00); //充值金额编辑 et1 = (EditText) findViewById(R.id.et1); et1.addTextChangedListener(mEtWatcher); //提交按钮 commitTv = (TextView) findViewById(R.id.commitTv); //初始化界面 initLayout(); } TextWatcher mEtWatcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().contains(".")) { if (s.length() - 1 - s.toString().indexOf(".") > 2) { s = s.toString().subSequence(0, s.toString().indexOf(".") + 3); et1.setText(s); et1.setSelection(s.length()); } } if (s.toString().trim().substring(0).equals(".")) { s = "0" + s; et1.setText(s); et1.setSelection(2); } if (s.toString().startsWith("0") && s.toString().trim().length() > 1) { if (!s.toString().substring(1, 2).equals(".")) { et1.setText(s.subSequence(0, 1)); et1.setSelection(1); return; } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }; //初始化界面 public void initLayout(){ getTypeGuid(); //返回 ((ImageView)findViewById(R.id.iv_back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); ((RelativeLayout)findViewById(R.id.rl_payment)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Dialog dialog = new Dialog(RechargeActivity.this, R.style.MyDialog2); View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.dialog2, null); ListView listview = (ListView) view.findViewById(R.id.listview); SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), PaymentList, R.layout.city_item, new String[] {"guid", "name"}, new int[] {R.id.guid, R.id.name}); listview.setAdapter(adapter); dialog.setContentView(view); dialog.show(); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { payName = (TextView) view.findViewById(R.id.name); paynametype=payName.getText().toString(); tv_paymode.setText(paynametype); dialog.dismiss(); } }); } }); //提交按钮 commitTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //设置不可点击 commitTv.setClickable(false); //获得用户填写的金额 et1Val = et1.getText().toString().trim(); if (et1Val == null || "".equals(et1Val)) { //提示用户输入充值金额 Toast.makeText(getApplicationContext(), "请输入充值金额", Toast.LENGTH_SHORT).show(); //设置可点击 commitTv.setClickable(true); } else if ("0".equals(et1Val) || "0.0".equals(et1Val) || "0.00".equals(et1Val)) { //提示用户输入充值金额 Toast.makeText(getApplicationContext(), "充值金额不能为0", Toast.LENGTH_SHORT).show(); //设置可点击 commitTv.setClickable(true); } else { //获取支付方式guid //getTypeGuid(); if(typeGuid == null || "".equals(typeGuid) || "null".equals(typeGuid)){ //提示用户获取数据失败 Toast.makeText(getApplicationContext(), "生成充值订单失败", Toast.LENGTH_SHORT).show(); //设置可点击 commitTv.setClickable(true); if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } }else{ //插入充值记录,得到订单号 insertValue(); } } } }); } //获取支付方式guid public void getTypeGuid(){ if(pBar == null){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); } if(pBar != null && !pBar.isShowing()){ pBar.show(); } new Thread() { @Override public void run() { Message message = Message.obtain(); //获取支付类型guid try { StringBuffer result = httpget.getArray("/api/payment/?AppSign=" + HttpConn.AppSign); JSONObject paymentTypeObj = new JSONObject(result.toString()); paymentArray = paymentTypeObj.getJSONArray("data"); PaymentList = new ArrayList<Map<String, String>>(); for (int i = 0; i < paymentArray.length(); i++) { HashMap<String, String> map = new HashMap<String, String>(); map.put("guid", paymentArray.getJSONObject(i).getString("Guid")); map.put("name", paymentArray.getJSONObject(i).getString("NAME")); if(!(paymentArray.getJSONObject(i).getString("NAME")).startsWith("预存款")){ PaymentList.add(map); } if (paymentArray.getJSONObject(i).getString("NAME").startsWith("支付宝支付")) { if (paymentArray.getJSONObject(i).getString("Public_Key") != null && !"".equals(paymentArray.getJSONObject(i) .getString("Public_Key"))) { PayUtil.RSA_PUBLIC = paymentArray.getJSONObject(i) .getString("Public_Key"); } if (paymentArray.getJSONObject(i).getString("Private_Key") != null && !"".equals(paymentArray.getJSONObject(i) .getString("Private_Key"))) { PayUtil.RSA_PRIVATE = paymentArray.getJSONObject(i) .getString("Private_Key"); } if (paymentArray.getJSONObject(i).getString("MerchantCode") != null && !"".equals(paymentArray.getJSONObject(i) .getString("Partner"))) { PayUtil.PARTNER = paymentArray.getJSONObject(i) .getString("MerchantCode"); } if (paymentArray.getJSONObject(i).getString("Email") != null && !"".equals(paymentArray.getJSONObject(i) .getString("Email"))) { PayUtil.SELLER = paymentArray.getJSONObject(i) .getString("Email"); } } } if(PaymentList.size()>0){ paynametype=PaymentList.get(0).get("name"); } message.what = 1; } catch (JSONException e) { message.what = 0; e.printStackTrace(); } handler.sendMessage(message); } }.start(); } //插入充值记录,返回订单号 public void insertValue(){ if(pBar == null){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); } if(pBar != null && !pBar.isShowing()){ pBar.show(); } new Thread() { @Override public void run() { Message message = Message.obtain(); //获取预存款列表集合 try { StringBuffer result = null; try { result = httpget.getArray("/api/insertAdvancePaymentApplyLog?MemLoginID=" + HttpConn.username + "&CurrentAdvancePayment="+currentPayment+ "&OperateMoney="+ et1Val + "&PaymentGuid=" + typeGuid + "&PaymentName=" + URLEncoder.encode(typeName,"utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } JSONObject resultObj = new JSONObject(result.toString()); String IsSuccessVal = resultObj.getString("return"); if("202".equals(IsSuccessVal)){ String OrderNumber = resultObj.getString("OrderNumber"); message.obj = OrderNumber; message.what = 3; }else{ message.what = 2; } } catch (JSONException e) { message.what = 2; e.printStackTrace(); } handler.sendMessage(message); } }.start(); } @SuppressLint("HandlerLeak") Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: //提示用户获取数据失败 Toast.makeText(getApplicationContext(), "获取支付数据失败", Toast.LENGTH_SHORT).show(); //设置可点击 commitTv.setClickable(true); if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } break; case 1: if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } //得到支付宝支付的guid tv_paymode = (TextView) findViewById(R.id.tv_paymode); tv_paymode.setText(PaymentList.get(0).get("name")); try { for (int i = 0; i < paymentArray.length(); i++) { JSONObject payObj = paymentArray.getJSONObject(i); String payname = payObj.getString("NAME"); String PaymentType = payObj.getString("PaymentType"); if("Alipay.aspx".equals(PaymentType)){ typeName = payname; typeGuid = payObj.getString("Guid"); }else if("Tenpay.aspx".equals(PaymentType)){ typeName = payname; typeGuid = payObj.getString("Guid"); }else if ("Weixin.aspx".equals(PaymentType)) { typeName = payname; typeGuid = payObj.getString("Guid"); } else if ("AlipaySDK.aspx".equals(PaymentType)) { typeName = payname; typeGuid = payObj.getString("Guid"); } } } catch (JSONException e) { typeGuid = ""; e.printStackTrace(); } break; case 2: //提交失败 Toast.makeText(getApplicationContext(), "提交失败", Toast.LENGTH_SHORT).show(); //设置可点击 commitTv.setClickable(true); if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } break; case 3: //设置可点击 pBar.dismiss(); commitTv.setClickable(true); orderNum = (String) msg.obj; if(paynametype.startsWith("微信")){ Toast.makeText(RechargeActivity.this, "请绑定商户ID", 0).show(); }else if(paynametype.startsWith("财付通")){ Intent intent = new Intent(new Intent(getApplicationContext(),TenpayActivity.class)); intent.putExtra("order_no", orderNum); intent.putExtra("source", "RechargeActivity"); intent.putExtra("order_price",et1Val ); startActivity(intent); finish(); }else if(paynametype.startsWith("支付宝手机网站")){ Intent intent = new Intent(new Intent(getApplicationContext(),AlipayActivity.class)); intent.putExtra("order", orderNum); intent.putExtra("total",et1Val ); startActivity(intent); finish(); }else if(paynametype.startsWith("支付宝SDK支付")){ PayUtil PayUtil = new PayUtil( RechargeActivity.this, "分销门户", orderNum, et1Val, new PayUtil.CallbackListener() { @Override public void updateOrderState() { updateState(orderNum); } }); PayUtil.pay(); }else if(paynametype.startsWith("京东支付")){ Intent intent = new Intent(new Intent(getApplicationContext(),JingDongActivity.class)); intent.putExtra("order", orderNum); intent.putExtra("total",et1Val ); intent.putExtra("source","RechargeActivity" ); startActivity(intent); finish(); } break; case 4: if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } Intent intent = new Intent(RechargeActivity.this, MemberActivity.class); startActivity(intent); finish(); if (msg.obj.equals("true")) { Toast.makeText(getApplicationContext(), "充值成功",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "充值失败",Toast.LENGTH_SHORT).show(); } break; default: break; } super.handleMessage(msg); } }; private Double currentPayment; private TextView tv_paymode; /** * 充值结果 * @param orderNumber */ public void updateState(final String orderNumber) { new Thread() { public void run() { JSONObject object = new JSONObject(); try { object.put("OrderNumber", orderNumber); StringBuffer stateList= httpget.postJSON("/api/UpdateAdvancePayMentLog/", object.toString()); Message msg = Message.obtain(); msg.obj = new JSONObject(stateList.toString()).getString("Data"); msg.what = 4; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } } <file_sep>package com.shopnum1.distributionportal.util; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; import android.widget.Gallery; @SuppressWarnings("deprecation") public class MyGallery extends Gallery { public MyGallery(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { int keyCode; if (e2.getX() > e1.getX()) keyCode = KeyEvent.KEYCODE_DPAD_LEFT; else keyCode = KeyEvent.KEYCODE_DPAD_RIGHT; onKeyDown(keyCode, null); return true; } } <file_sep>package com.shopnum1.distributionportal; //积分明细 import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; public class MemberScoreDetail extends Activity { private HttpConn httpget = new HttpConn(); private int Score; private JSONArray ScoreList; private ListAdapter adapter; //商品适配器 private Dialog pBar; //加载进度 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.member_score_detail); initLayout(); } //初始化 public void initLayout() { //返回 ((ImageView) findViewById(R.id.iv_back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); // //快捷方式 // ((LinearLayout)findViewById(R.id.more)).setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View arg0) { // httpget.showMenu(MemberScoreDetail.this, findViewById(R.id.member_score_detail)); // } // }); //获取数据 getData(); getList(); } //获取用户信息 public void getData(){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); new Thread(){ public void run(){ try { StringBuffer result = httpget.getArray("/api/accountget/?MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); Score = new JSONObject(result.toString()).getJSONObject("AccoutInfo").getInt("Score"); Message msg = Message.obtain(); msg.what = 1; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: pBar.dismiss(); break; case 1: ((TextView)findViewById(R.id.score)).setText("" + Score); break; case 2: ListView listview = (ListView)findViewById(R.id.listview); adapter = new ListAdapter(); listview.setAdapter(adapter); pBar.dismiss(); break; default: break; }; super.handleMessage(msg); } }; //获取积分明细 public void getList(){ new Thread(){ public void run(){ Message msg = Message.obtain(); try { Log.i("fly", HttpConn.urlName + "/api/getscoremodifylog/?MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); StringBuffer result = httpget.getArray("/api/getscoremodifylog/?MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); ScoreList = new JSONObject(result.toString()).getJSONArray("Data"); msg.what = 2; } catch (JSONException e) { msg.what = 0; e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } //适配器 public class ListAdapter extends BaseAdapter { @Override public int getCount() { return ScoreList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg1) { return arg1; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_score, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(R.id.text1); holder.text2 = (TextView) convertView.findViewById(R.id.text2); holder.text3 = (TextView) convertView.findViewById(R.id.text3); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { String Date = ScoreList.getJSONObject(position).getString("Date"); String Memo = ScoreList.getJSONObject(position).getString("Memo"); int OperateType = ScoreList.getJSONObject(position).getInt("OperateType"); holder.text1.setText(Date.replace("/", "-")); if(Memo.equals("")){ if(OperateType == 0){ holder.text2.setText("后台提取"); } else { holder.text2.setText("后台充值"); } } else { holder.text2.setText(Memo); } if(OperateType == 0) { holder.text3.setText("-" + ScoreList.getJSONObject(position).getString("OperateScore")); } else { holder.text3.setText("+" + ScoreList.getJSONObject(position).getString("OperateScore")); } } catch (JSONException e) { e.printStackTrace(); } return convertView; } } static class ViewHolder { TextView text1, text2, text3; } }<file_sep>package com.shopnum1.distributionportal; //商品评价 import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; import com.shopnum1.distributionportal.util.ViewPagerAdapter; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.TranslateAnimation; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; public class ProductComment extends Activity { private View view1, view2; //评价和晒单页面 private TextView textview1, textview2; //评价和晒单按钮 private int cursor_width= 0; //游标宽度 private ImageView cursor = null; //游标图片 private ViewPager viewPager = null; //滑动视图 private int currentIndex = 0; //滑动视图位置 private HttpConn httpget = new HttpConn(); private JSONArray commentList1, commentList2; private Dialog pBar; //加载进度 private GridAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.product_comment); initLayout(); initViewpager(); getData(); } //初始化 public void initLayout() { //返回 ((LinearLayout) findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } //初始化ViewPager public void initViewpager() { cursor = (ImageView) this.findViewById(R.id.cursor); DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); cursor_width = metric.widthPixels / 2; LayoutParams params = (LayoutParams)cursor.getLayoutParams(); params.width = cursor_width; cursor.setLayoutParams(params); LayoutInflater inflater = getLayoutInflater(); List<View> pager = new ArrayList<View>(); view1 = inflater.inflate(R.layout.comment_pager, null); view2 = inflater.inflate(R.layout.comment_pager, null); pager.add(view1); pager.add(view2); viewPager = (ViewPager) this.findViewById(R.id.viewPager); viewPager.setAdapter(new ViewPagerAdapter(pager)); viewPager.setCurrentItem(0); viewPager.setOnPageChangeListener(new MyOnClickPagerChange()); textview1 = (TextView)findViewById(R.id.textview1); textview2 = (TextView)findViewById(R.id.textview2); textview1.setOnClickListener(new Myclick(0)); textview2.setOnClickListener(new Myclick(1)); } //按钮切换 class Myclick implements View.OnClickListener { int mark; public Myclick(int dex) { mark = dex; } @Override public void onClick(View arg0) { viewPager.setCurrentItem(mark); } } //滑动页面切换 class MyOnClickPagerChange implements android.support.v4.view.ViewPager.OnPageChangeListener { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int arg0) { TranslateAnimation animation = null; switch (arg0) { case 0: textview1.setTextColor(Color.RED); textview2.setTextColor(Color.BLACK); if (currentIndex == 1) { animation = new TranslateAnimation(cursor_width, 0, 0, 0); } break; case 1: textview1.setTextColor(Color.BLACK); textview2.setTextColor(Color.RED); if (currentIndex == 0) { animation = new TranslateAnimation(0, cursor_width, 0, 0); } break; } currentIndex = arg0; animation.setFillAfter(true); animation.setDuration(300); cursor.startAnimation(animation); } } public void getData(){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); new Thread(){ public void run(){ StringBuffer result = httpget.getArray("/api/getProductCommentByProductGuid/?productGuid="+getIntent().getStringExtra("guid") +"&AppSign="+HttpConn.AppSign+"&memLoginId="+HttpConn.username); StringBuffer result2 = httpget.getArray("/api/getBaskOrderLogByProductGuid/?memLoginId="+HttpConn.username+"&productGuid=" + getIntent().getStringExtra("guid")+"&AppSign="+HttpConn.AppSign); Log.i("fly", result.toString()); Message msg = Message.obtain(); try { if(new JSONObject(result.toString()).getString("Data") == "null"){ commentList1 = new JSONArray(); }else{ commentList1 = new JSONObject(result.toString()).getJSONArray("Data"); } if(new JSONObject(result2.toString()).getString("Data") == "null"){ commentList2 = new JSONArray(); }else{ commentList2 = new JSONObject(result2.toString()).getJSONArray("Data"); } msg.what = 1; } catch (JSONException e) { msg.what = 0; e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } public void addList(){ ListView listview1 = (ListView)view1.findViewById(R.id.listview); listview1.setSelector(new ColorDrawable(Color.TRANSPARENT));; listview1.setAdapter(new MyAdapter(commentList1, 1)); ListView listview2 = (ListView)view2.findViewById(R.id.listview); listview2.setSelector(new ColorDrawable(Color.TRANSPARENT));; listview2.setAdapter(new MyAdapter(commentList2, 2)); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: pBar.dismiss(); break; case 1: addList(); pBar.dismiss(); break; case 2: adapter.notifyDataSetChanged(); break; default: break; } super.handleMessage(msg); } }; //适配器 class MyAdapter extends BaseAdapter{ JSONArray commentList; int id; public MyAdapter(JSONArray commentList, int id){ this.commentList = commentList; this.id = id; } @Override public int getCount() { return commentList.length(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_comment, parent, false); holder.userid = (TextView)convertView.findViewById(R.id.userid); holder.content = (TextView)convertView.findViewById(R.id.comment); holder.title = (TextView)convertView.findViewById(R.id.title); holder.time = (TextView)convertView.findViewById(R.id.time); holder.gridview = (GridView)convertView.findViewById(R.id.gridview); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { holder.userid.setText(commentList.getJSONObject(position).getString("MemLoginID")); holder.content.setText(commentList.getJSONObject(position).getString("Content")); if(id == 1){ holder.time.setText(commentList.getJSONObject(position).getString("SendTime")); } else { holder.title.setVisibility(View.VISIBLE); holder.title.setText(commentList.getJSONObject(position).getString("Title")); holder.time.setText(commentList.getJSONObject(position).getString("CreateTime")); String Image = commentList.getJSONObject(position).getString("Image").replace("|", ","); if(!Image.equals("")){ holder.gridview.setVisibility(View.VISIBLE); adapter = new GridAdapter(Image.split(",")); holder.gridview.setAdapter(adapter); } else { holder.gridview.setVisibility(View.GONE); } } } catch (JSONException e) { e.printStackTrace(); } return convertView; } class ViewHolder { TextView userid; TextView title; TextView content; TextView time; GridView gridview; } } class GridAdapter extends BaseAdapter{ String[] url; public GridAdapter(final String[] url){ this.url = url; } @Override public int getCount() { return url.length; } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View convertView, ViewGroup arg2) { if(convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_show, null); } ImageView imageview = (ImageView)convertView.findViewById(R.id.img); ImageLoader.getInstance().displayImage(HttpConn.urlName + url[arg0], imageview, MyApplication.options); return convertView; } } }<file_sep>package com.shopnum1.distributionportal.util; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "imgcache.db"; public DbHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table comimage(_id integer primary key autoincrement, lastdate integer not null, imgpath text not null, photo blob)"); db.execSQL("create table proimage(_id integer primary key autoincrement, lastdate integer not null, imgpath text not null, photo blob)"); db.execSQL("create table picimage(_id integer primary key autoincrement, lastdate integer not null, imgpath text not null, photo blob)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table comimage if exists"); db.execSQL("drop table proimage if exists"); db.execSQL("drop table picimage if exists"); onCreate(db); } }<file_sep>package com.shopnum1.distributionportal; //搜索 import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import com.zxing.activity.CaptureActivity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.shopnum1.distributionportal.R; public class SearchMain extends Activity { private AutoCompleteTextView edittext; //搜索框 private Boolean showHistory = false; //是否显示搜索历史 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); ((LinearLayout) findViewById(R.id.mainview)).setVisibility(View.GONE); ((LinearLayout) findViewById(R.id.qrcode)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(getBaseContext(), CaptureActivity.class), 0); } }); search(); initAutoComplete(); } //点击搜索 public void search(){ edittext = (AutoCompleteTextView) findViewById(R.id.search_edit); ((Button) findViewById(R.id.search_btn)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(((Button) findViewById(R.id.search_btn)).getWindowToken(), 0); String text = edittext.getText().toString(); if(TextUtils.isEmpty(text)){ Toast.makeText(getApplicationContext(), "请输入搜索的关键字", 0).show(); }else{ SharedPreferences sp = getSharedPreferences("search_name", 0); String longhistory = sp.getString("product_history", ""); if (!longhistory.contains(text + ",")) { StringBuilder builder = new StringBuilder(longhistory); builder.insert(0, text + ","); sp.edit().putString("product_history", builder.toString()).commit(); } edittext.setText(""); Intent intent = new Intent(getApplicationContext(), SearchResult.class); intent.putExtra("title", "搜索结果"); intent.putExtra("type", "search"); intent.putExtra("typeid", "0"); intent.putExtra("searchstr", text.trim()); startActivity(intent); } } }); } //初始化历史记录 private void initAutoComplete() { SharedPreferences sp = getSharedPreferences("search_name", 0); String longhistory = sp.getString("product_history", ""); final String[] histories = longhistory.split(","); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.search_history, histories); for (int i = 0; i < histories.length; i++) { if(histories[i] != "") showHistory = true; } // 只保留最近的10条的记录 if (histories.length > 10) { String[] newHistories = new String[5]; System.arraycopy(histories, 0, newHistories, 0, 5); adapter = new ArrayAdapter<String>(this, R.layout.search_history, newHistories); } edittext.setAdapter(adapter); edittext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AutoCompleteTextView view = (AutoCompleteTextView) v; if (showHistory) { view.showDropDown(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == 1){ String mresult = data.getExtras().getString("mresult"); Log.i("fly", mresult); if(mresult.contains("html")){ Intent intent = new Intent(getApplicationContext(), ProductDetails.class); intent.putExtra("guid", mresult.split("html")[1].substring(1)); startActivity(intent); }else{ Toast.makeText(getApplicationContext(), "没有找到该商品", Toast.LENGTH_SHORT).show(); } } super.onActivityResult(requestCode, resultCode, data); } }<file_sep>package com.zxing.bean; import java.io.Serializable; public class Announcement implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String Guid; private String Title; private String Remark; private String CreateUser; private String CreateTime; private String ModifyUser; private String ModifyTime; private int IsDeleted; private String AgentID; public String getGuid() { return Guid; } public void setGuid(String guid) { Guid = guid; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getRemark() { return Remark; } public void setRemark(String remark) { Remark = remark; } public String getCreateUser() { return CreateUser; } public void setCreateUser(String createUser) { CreateUser = createUser; } public String getCreateTime() { return CreateTime; } public void setCreateTime(String createTime) { CreateTime = createTime; } public String getModifyUser() { return ModifyUser; } public void setModifyUser(String modifyUser) { ModifyUser = modifyUser; } public String getModifyTime() { return ModifyTime; } public void setModifyTime(String modifyTime) { ModifyTime = modifyTime; } public int getIsDeleted() { return IsDeleted; } public void setIsDeleted(int isDeleted) { IsDeleted = isDeleted; } public String getAgentID() { return AgentID; } public void setAgentID(String agentID) { AgentID = agentID; } } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.R.integer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.SparseBooleanArray; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.TextView.OnEditorActionListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; public class EntityshopActivity extends Activity { private DisplayImageOptions options; static EntityshopActivity instance; private float SCREEN_WIDTH = 0;//屏幕的宽度 private LinearLayout group; private ListView adresslistView; private ListView StorelistView; private MyShopadapter shopadapter; private MyCityadapter adressadapter; private List<Map<String, String>> leftdata=new ArrayList<Map<String,String>>(); private List<Map<String, String>> rightdata=new ArrayList<Map<String,String>>(); private HttpConn httpget = new HttpConn(); private Boolean isfirst=true; private EditText rl_search; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_entityshopactivity); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); SCREEN_WIDTH = dm.widthPixels; instance = this; initLayout(); } @Override protected void onResume() { if (HttpConn.isNetwork) { if (HttpConn.isLogin) if (HttpConn.cartNum > 0) { ((TextView) findViewById(R.id.num)).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.num)).setText(HttpConn.cartNum + ""); } else { ((TextView) findViewById(R.id.num)).setVisibility(View.GONE); } } else { httpget.setNetwork(this); // 设置网络 } super.onResume(); } //初始化 public void initLayout(){ rl_search=(EditText) findViewById(R.id.rl_search); rl_search.setImeOptions(EditorInfo.IME_ACTION_SEARCH); rl_search.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) { // TODO Auto-generated method stub if (arg1==EditorInfo.IME_ACTION_SEARCH ||(arg2!=null&&arg2.getKeyCode()== KeyEvent.KEYCODE_ENTER)) { // 先隐藏键盘 ((InputMethodManager) rl_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(EntityshopActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS); Intent intent = new Intent(getApplicationContext(), SearchResult.class); intent.putExtra("title", "搜索结果"); intent.putExtra("type", "search"); intent.putExtra("typeid", "0"); intent.putExtra("searchstr", rl_search.getText().toString().trim()); startActivity(intent); return true; } return false; } }); // 主界面 ((RelativeLayout) findViewById(R.id.imageButton1)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getBaseContext(),MainActivity.class)); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); if (!HttpConn.isNetwork) finish(); } }); // ((RelativeLayout) findViewById(R.id.sousuo)) // .setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { // startActivity(new Intent(getBaseContext(), // SearchMain.class)); // overridePendingTransition(android.R.anim.fade_in, // android.R.anim.fade_out); // if (!HttpConn.isNetwork) // finish(); // } // // }); // 购物车 ((RelativeLayout) findViewById(R.id.imageButton3)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (HttpConn.isLogin) { startActivity(new Intent(getBaseContext(),CartActivity.class)); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); } else { Intent intent = new Intent(getApplicationContext(),UserLogin.class); intent.putExtra("cart", ""); startActivity(intent); } if (!HttpConn.isNetwork) finish(); } }); // 个人中心 ((RelativeLayout) findViewById(R.id.imageButton4)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (HttpConn.isLogin) { startActivity(new Intent(getBaseContext(), MemberActivity.class)); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } else { Intent intent = new Intent(getApplicationContext(),UserLogin.class); intent.putExtra("person", ""); startActivity(intent); } if (!HttpConn.isNetwork) finish(); } }); getdata(); adresslistView=(ListView)findViewById(R.id.adresslistView); group=(LinearLayout) findViewById(R.id.viewGroup); adresslistView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); adressadapter=new MyCityadapter(leftdata); adresslistView.setAdapter(adressadapter); adresslistView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub adresslistView.setItemChecked(arg2, true); isfirst=false; adresslistView.setBackgroundColor(Color.parseColor("#f6f6f6")); StorelistView.setVisibility(View.VISIBLE); getdata1(leftdata.get(arg2).get("ID")); } }); StorelistView=(ListView)findViewById(R.id.storelistView); shopadapter=new MyShopadapter(rightdata); StorelistView.setAdapter(shopadapter); StorelistView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) { // TODO Auto-generated method stub Intent intent = new Intent(getApplicationContext(), SearchResult.class); intent.putExtra("title", rightdata.get(arg2).get("Name")); intent.putExtra("type", "list"); intent.putExtra("typeid", Integer.parseInt( rightdata.get(arg2).get("ID"))); intent.putExtra("searchstr", ""); startActivity(intent); } }); //参数配置 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).threadPoolSize(3) .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().build(); ImageLoader.getInstance().init(config); options = new DisplayImageOptions.Builder() .imageScaleType(ImageScaleType.EXACTLY).showImageOnLoading(R.drawable.pic1).showImageForEmptyUri(R.drawable.pic1) .showImageOnFail(R.drawable.pic1).cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build(); } private void getdata() { HttpUtils hu = new HttpUtils(); String productCatagoryUrl = HttpConn.hostName+ "/api/productcatagory/?id=0&AppSign="+HttpConn.AppSign+"&AgentID="+MyApplication.agentId +"&sbool=true"; hu.send(HttpMethod.GET,productCatagoryUrl , new RequestCallBack<String>() { @Override public void onFailure(HttpException arg0, String arg1) { } @Override public void onSuccess(ResponseInfo<String> data) { if(!"".equals(data.result.toString())){ try { JSONObject object=new JSONObject(data.result.toString()); leftdata.clear(); JSONArray array=object.optJSONArray("Data"); for(int i=0;i<array.length();i++){ Map<String, String> map=new HashMap<String, String>(); JSONObject mObject=array.optJSONObject(i); map.put("Name", mObject.optString("Name")); map.put("ID", mObject.optString("ID")); leftdata.add(map); } adressadapter.notifyDataSetChanged(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } private void getdata1(String id) { // TODO Auto-generated method stub HttpUtils hu = new HttpUtils(); String productCatagoryUrl = HttpConn.hostName+ "/api/productcatagory/?id="+id+"&AppSign="+HttpConn.AppSign +"&AgentID="+MyApplication.agentId +"&sbool=true"; hu.send(HttpMethod.GET, productCatagoryUrl, new RequestCallBack<String>() { @Override public void onFailure(HttpException arg0, String arg1) { } @Override public void onSuccess(ResponseInfo<String> data) { if(!"".equals(data.result.toString())){ try { JSONObject object=new JSONObject(data.result.toString()); rightdata.clear(); JSONArray array=object.optJSONArray("Data"); for(int i=0;i<array.length();i++){ Map<String, String> map=new HashMap<String, String>(); JSONObject mObject=array.optJSONObject(i); map.put("Name", mObject.optString("Name")); map.put("ID", mObject.optString("ID")); map.put("type", "0");//第一层 rightdata.add(map); JSONArray array2= mObject.optJSONArray("Description"); for (int j = 0; j < array2.length(); j++) { Map<String, String> map2=new HashMap<String, String>(); JSONObject mObject2=array2.optJSONObject(j); map2.put("Name", mObject2.optString("Name")); map2.put("ID", mObject2.optString("ID")); map2.put("type", "1");//第二层 rightdata.add(map2); } } List<Map<String, String>> temp = rightdata; shopadapter.notifyDataSetChanged(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); } public class MyShopadapter extends BaseAdapter { private List<Map<String, String>> data; private LayoutInflater inflate; Context context; private final int FISRT_TYPE = 0 ; private final int SENCOND_TYPE = 1 ; public MyShopadapter( List<Map<String, String>> data) { this.data = data; inflate = LayoutInflater.from(EntityshopActivity.this); } @Override public int getItemViewType(int position) { int type = Integer.valueOf(data.get(position).get("type")); return type; } @Override public int getViewTypeCount() { // TODO Auto-generated method stub return 2; } public int getCount() { if(data==null) return 0; return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = inflate.inflate(R.layout.entryshopitem, null); holder.name = (TextView) convertView.findViewById(R.id.shopname); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.name.setText(data.get(position).get("Name")); int type = getItemViewType(position); switch (type) { case FISRT_TYPE: holder.name.setBackgroundResource(R.drawable.round_gray_line); holder.name.setGravity(Gravity.CENTER_HORIZONTAL); break; case SENCOND_TYPE: break; default: break; } return convertView; } } public class MyCityadapter extends BaseAdapter { private List<Map<String, String>> data; private LayoutInflater inflate; Context context; public MyCityadapter(List<Map<String, String>> data) { this.data = data; inflate = LayoutInflater.from(EntityshopActivity.this); } public int getCount() { if(data==null) return 0; return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = inflate.inflate(R.layout.entryshopitem1, null); holder.city = (TextView) convertView.findViewById(R.id.city); // holder.view_left=(View)convertView.findViewById(R.id.view_left); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } SparseBooleanArray booleanArray = adresslistView.getCheckedItemPositions(); if (booleanArray != null && booleanArray.size() > 0) { boolean isChecked = booleanArray.get(position); // holder.view_left.setBackgroundColor(Color.parseColor(isChecked ? "#eb0028" : "#BFBFBF")); if(isfirst){ convertView.findViewById(R.id.rl_item).setBackgroundColor(Color.parseColor("#ffffff")); }else{ if (isChecked){ convertView.findViewById(R.id.rl_item).setBackgroundColor(Color.parseColor("#ffffff")); holder.city.setTextColor(Color.parseColor("#e9544d"));} else{ holder.city.setTextColor(Color.parseColor("#888888")); convertView.findViewById(R.id.rl_item).setBackgroundResource(R.drawable.round_gray_line); } } } holder.city.setText(data.get(position).get("Name")); return convertView; } } private class ViewHolder { TextView name,distance,city; View view_left,view_right; } } <file_sep>include ':library' include ':quanqiugogou' <file_sep>package com.shopnum1.distributionportal; import java.net.URLEncoder; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; public class TenpayActivity extends Activity { private WebView webview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); webview = (WebView) findViewById(R.id.webview); webview.addJavascriptInterface(new MyObject(this), "MyObject"); webview.getSettings().setJavaScriptEnabled(true); webview.setWebViewClient(new WebViewClient() { ProgressDialog pBar = ProgressDialog.show(TenpayActivity.this, null, "正在加载..."); @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { pBar.show(); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { pBar.dismiss(); super.onPageFinished(view, url); } }); String order = getIntent().getStringExtra("order_no"); String total = getIntent().getStringExtra("order_price"); if(total.indexOf("元")!=-1){ total=total.substring(0, total.indexOf("元")); } if(getIntent().getStringExtra("source")!=null){ if(getIntent().getStringExtra("source").equals("RechargeActivity")){//代表是从商品的那里下单来的 webview.loadUrl(HttpConn.hostName + "/PayReturn/CZPay/tenpay/CZ_payRequest.aspx?order_no="+ order + "&order_price=" + total+"&product_name=1"+"&remarkexplain=1"); } }else{ webview.loadUrl(HttpConn.hostName + "/PayReturn/ZFPay/tenpay/payRequest.aspx?order_no="+ order + "&order_price=" + total+"&product_name=1"+"&remarkexplain=1"); } } public class MyObject { private Context mContext; public MyObject(Context mContext) { this.mContext = mContext; } @JavascriptInterface public void startMainActivity() { Intent mIntent = new Intent(TenpayActivity.this, MainActivity.class); mContext.startActivity(mIntent); } } @Override public void onBackPressed() { Intent intent = new Intent(new Intent(getApplicationContext(), OrderActivity.class)); intent.putExtra("type", 0); intent.putExtra("title", "全部订单"); startActivity(intent); finish(); super.onBackPressed(); } } <file_sep>package com.shopnum1.distributionportal; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; public class MemberMessage extends Activity { private HttpConn httpget = new HttpConn(); private ListAdapter adapter; private int requestTime = 1; private Dialog pBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.member_message); initLayout(); addList(); } //初始化 public void initLayout() { //返回 ((LinearLayout)findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); } public void addList(){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); ListView listview = (ListView)findViewById(R.id.listview); adapter = new ListAdapter(this); listview.setAdapter(adapter); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, final int arg2, long arg3) { Intent intent = new Intent(getBaseContext(), MyMessageDetail.class); intent.putExtra("title", ((TextView)v.findViewById(R.id.title)).getText().toString()); intent.putExtra("time", ((TextView)v.findViewById(R.id.time)).getText().toString()); intent.putExtra("content", ((TextView)v.findViewById(R.id.content)).getText().toString()); startActivityForResult(intent, 0); new Thread(){ public void run(){ try { String guid = adapter.getInfo(arg2).getString("Guid"); httpget.getArray("/api/membermessageisread/?id=" + guid + "&memLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } }); listview.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(final AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { // 判断是否滚动到底部 if (view.getLastVisiblePosition() == view.getCount() - 1) adapter.upData("/api/membermessagelist/?pageIndex=" + requestTime + "&pageCount=5&receiveMemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign, false); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: if(!adapter.isdown){ adapter.isdown = true; adapter.notifyDataSetChanged(); adapter.isdown = false; } break; case 2: if(msg.obj.equals("202")) Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show(); finish(); startActivity(new Intent(getApplicationContext(), MemberMessage.class)); break; case 3: ((TextView)findViewById(R.id.nocontent)).setVisibility(View.VISIBLE); break; case 12: if(msg.obj.equals("202")) Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show(); finish(); startActivity(new Intent(getApplicationContext(), MemberMessage.class)); break; default: break; } super.handleMessage(msg); } }; class ListAdapter extends BaseAdapter{ private ArrayList<Bitmap> bm = new ArrayList<Bitmap>(); private JSONArray msgList = new JSONArray(); private boolean isend = false; //已发送 private boolean isdown = false; //在下拉 int count = 0; public JSONObject getInfo(int position) { JSONObject result = null; try { result = msgList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return result; } //翻页 public void upData(final String port, final boolean isRebuilt) { if (isRebuilt) isend = false; if (!isend) { if (!isdown) { isdown = true; new Thread() { @Override public void run() { StringBuffer temp = httpget.getArray(port); if (temp.length() == 0) { isend = true; if (requestTime == 1) { msgList = new JSONArray(); bm.clear(); isdown = false; Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } else isdown = false; } else { requestTime++; try { StringBuffer data = new StringBuffer(); if (isRebuilt) { bm.clear(); data.append(temp); } else { data.append(msgList.toString()); data.setCharAt(data.length() - 1, ','); data.append(new JSONObject(temp.toString()).getJSONArray("Data").toString().substring(1)); } msgList = new JSONArray(data.toString()); int start = bm.size(); int end = msgList.length(); if(end <= count) { for (int i = start; i < end; i++) bm.add(null); } isdown = false; Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); isdown = false; isend = true; } } } }.start(); } } } public ListAdapter(Context c) { isdown = true; new Thread() { @Override public void run() { try { StringBuffer result = httpget.getArray("/api/membermessagelist/?pageIndex=1&pageCount=50&receiveMemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); pBar.dismiss(); msgList = new JSONObject(result.toString()).getJSONArray("Data"); count = Integer.parseInt(new JSONObject(result.toString()).get("Count").toString()); if(count == 0){ Message message = Message.obtain(); message.what = 3; handler.sendMessage(message); } else { requestTime++; } for (int i = 0; i < msgList.length(); i++) bm.add(null); isdown = false; Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); isdown = false; isend = true; } } }.start(); } @Override public int getCount() { return bm.size(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_message, null); holder.title = (TextView)convertView.findViewById(R.id.title); holder.content = (TextView)convertView.findViewById(R.id.content); holder.time = (TextView)convertView.findViewById(R.id.time); holder.point = (ImageView)convertView.findViewById(R.id.point); holder.del = (Button)convertView.findViewById(R.id.del); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { holder.title.setText(msgList.getJSONObject(position).getString("Title")); holder.content.setText(msgList.getJSONObject(position).getString("Content")); holder.time.setText(msgList.getJSONObject(position).getString("CreateTime").replace("/", "-")); if(msgList.getJSONObject(position).getInt("IsRead") == 0){ holder.point.setVisibility(View.VISIBLE); } else { holder.point.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } holder.del.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { final Dialog dialog = new Dialog(MemberMessage.this, R.style.MyDialog); View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.dialog, null); ((TextView)view.findViewById(R.id.dialog_text)).setText("是否删除消息"); dialog.setContentView(view); dialog.show(); ((Button)view.findViewById(R.id.no)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { dialog.dismiss(); } }); ((Button)view.findViewById(R.id.yes)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { delMessage(msgList.getJSONObject(position).getString("Guid")); } catch (JSONException e) { e.printStackTrace(); } } }); } }); return convertView; } class ViewHolder { TextView title; TextView content; TextView time; ImageView point; Button del; } } public void delMessage(final String msgid) { new Thread(){ @Override public void run(){ try { StringBuffer result = httpget.getArray("/api/membermessagedelete/?msgId=" + msgid + "&MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); Message msg = Message.obtain(); msg.obj = new JSONObject(result.toString()).getString("return"); msg.what = 12; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } //返回结果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == 1) addList(); super.onActivityResult(requestCode, resultCode, data); } }<file_sep>package com.shopnum1.distributionportal; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.onekeyshare.OnekeyShare; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; public class RecommendActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recommend); initLayout(); } private void initLayout() { findViewById(R.id.back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); findViewById(R.id.tv_share).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showShare(); } }); ImageView iv = (ImageView) findViewById(R.id.iv); Bitmap bitmap; try { bitmap = Create2DCode(HttpConn.shareURL+"/Register.aspx?CommendPeople="+HttpConn.username+"&AgentID="+MyApplication.agentId); iv.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } } private void showShare() { ShareSDK.initSDK(this); OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法 //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name)); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用 oks.setTitle(getString(R.string.share)); // titleUrl是标题的网络链接,仅在人人网和QQ空间使用 oks.setTitleUrl(HttpConn.shareURL+"/Register.aspx?CommendPeople="+HttpConn.username+"&AgentID="+MyApplication.agentId); // text是分享文本,所有平台都需要这个字段 // oks.setDialogMode(); oks.setText(HttpConn.shareURL+"/Register.aspx?CommendPeople="+HttpConn.username+"&AgentID="+MyApplication.agentId); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 // oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 // url仅在微信(包括好友和朋友圈)中使用 // oks.setUrl("http://sharesdk.cn"); // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment("我是测试评论文本"); // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)); // siteUrl是分享此内容的网站地址,仅在QQ空间使用 oks.setSiteUrl("http://sharesdk.cn"); // 启动分享GUI oks.show(this); } /** * 用字符串生成二维码 * @param str * @author <EMAIL> * @return * @throws WriterException */ public Bitmap Create2DCode(String str) throws WriterException { //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败 BitMatrix matrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, 400, 400); int width = matrix.getWidth(); int height = matrix.getHeight(); //二维矩阵转为一维像素数组,也就是一直横着排了 int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if(matrix.get(x, y)){ pixels[y * width + x] = 0xff000000; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); //通过像素数组生成bitmap,具体参考api bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; import com.shopnum1.distributionportal.util.ViewPagerAdapter; //商品评价 import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; public class BrandCenter extends Activity { private View view1, view2; private TextView textview1, textview2; private int cursor_width = 0; // 游标宽度 private ImageView cursor = null; // 游标图片 private ViewPager viewPager = null; // 滑动视图 private int currentIndex = 0; // 滑动视图位置 private HttpConn httpget = new HttpConn(); private JSONArray AllList, BigList; private GridViewAdapter adapter1, adapter2; private Dialog pBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.brand_center); initLayout(); initViewpager(); getBrandAll(); getBrandBig(); } // 初始化 public void initLayout() { // 返回 ((LinearLayout) findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } // 初始化ViewPager public void initViewpager() { cursor = (ImageView) this.findViewById(R.id.cursor); DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); cursor_width = metric.widthPixels / 2; LayoutParams params = (LayoutParams) cursor.getLayoutParams(); params.width = cursor_width; cursor.setLayoutParams(params); LayoutInflater inflater = getLayoutInflater(); List<View> pager = new ArrayList<View>(); view1 = inflater.inflate(R.layout.gridview, null); view2 = inflater.inflate(R.layout.gridview, null); pager.add(view1); pager.add(view2); viewPager = (ViewPager) this.findViewById(R.id.viewPager); viewPager.setAdapter(new ViewPagerAdapter(pager)); viewPager.setCurrentItem(0); viewPager.setOnPageChangeListener(new MyOnClickPagerChange()); textview1 = (TextView) findViewById(R.id.textview1); textview2 = (TextView) findViewById(R.id.textview2); textview1.setOnClickListener(new Myclick(0)); textview2.setOnClickListener(new Myclick(1)); } // 按钮切换 class Myclick implements View.OnClickListener { int mark; public Myclick(int dex) { mark = dex; } @Override public void onClick(View arg0) { viewPager.setCurrentItem(mark); } } // 滑动页面切换 class MyOnClickPagerChange implements android.support.v4.view.ViewPager.OnPageChangeListener { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int arg0) { TranslateAnimation animation = null; switch (arg0) { case 0: textview1.setTextColor(Color.RED); textview2.setTextColor(Color.BLACK); if (currentIndex == 1) { animation = new TranslateAnimation(cursor_width, 0, 0, 0); } break; case 1: textview1.setTextColor(Color.BLACK); textview2.setTextColor(Color.RED); if (currentIndex == 0) { animation = new TranslateAnimation(0, cursor_width, 0, 0); } break; } currentIndex = arg0; animation.setFillAfter(true); animation.setDuration(300); cursor.startAnimation(animation); } } public void getBrandAll() { pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); new Thread(){ public void run(){ StringBuffer result = httpget.getArray("/api/productbrandlistisrecommend/?IsRecommend=1&AppSign=" + HttpConn.AppSign); Message msg = Message.obtain(); try { AllList = new JSONObject(result.toString()).getJSONArray("data"); msg.what = 1; } catch (JSONException e) { msg.what = 0; e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } public void getBrandBig() { new Thread(){ public void run(){ StringBuffer result = httpget.getArray("/api/productbrandlist/?AppSign=" + HttpConn.AppSign); Message msg = Message.obtain(); try { BigList = new JSONObject(result.toString()).getJSONArray("Data"); msg.what = 2; } catch (JSONException e) { msg.what = 0; e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: pBar.dismiss(); break; case 1: GridView gridview1 = ((GridView) view1.findViewById(R.id.gridview)); gridview1.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter1 = new GridViewAdapter(AllList); gridview1.setAdapter(adapter1); pBar.dismiss(); gridview1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) { TextView text1 = (TextView) v.findViewById(R.id.text1); TextView text2 = (TextView) v.findViewById(R.id.text2); Intent intent = new Intent(getBaseContext(), BrandDetail.class); intent.putExtra("Name", text1.getText().toString()); intent.putExtra("Guid", text2.getText().toString()); startActivity(intent); } }); break; case 2: GridView gridview2 = ((GridView) view2.findViewById(R.id.gridview)); gridview2.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter2 = new GridViewAdapter(BigList); gridview2.setAdapter(adapter2); gridview2.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) { TextView text1 = (TextView) v.findViewById(R.id.text1); TextView text2 = (TextView) v.findViewById(R.id.text2); TextView text3 = (TextView) v.findViewById(R.id.text3); Intent intent = new Intent(getBaseContext(), BrandDetail.class); intent.putExtra("Name", text1.getText().toString()); intent.putExtra("Guid", text2.getText().toString()); intent.putExtra("Logo", text3.getText().toString()); startActivity(intent); } }); break; } super.handleMessage(msg); } }; class GridViewAdapter extends BaseAdapter { JSONArray dataList; public GridViewAdapter(JSONArray dataList){ this.dataList = dataList; } @Override public int getCount() { return dataList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg1) { return arg1; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_brand, parent, false); } try { TextView text1 = (TextView) convertView.findViewById(R.id.text1); TextView text2 = (TextView) convertView.findViewById(R.id.text2); TextView text3 = (TextView) convertView.findViewById(R.id.text3); text1.setTextColor(Color.BLACK); text2.setVisibility(View.GONE); text1.setText(dataList.getJSONObject(position).getString("Name")); text2.setText(dataList.getJSONObject(position).getString("Guid")); String imgurl = dataList.getJSONObject(position).getString("Logo"); text3.setText(imgurl); Log.i("fly", imgurl); ImageView imageview = (ImageView) convertView.findViewById(R.id.img); if (HttpConn.showImage) ImageLoader.getInstance().displayImage(imgurl, imageview, MyApplication.options); } catch (JSONException e) { e.printStackTrace(); } return convertView; } } }<file_sep>package com.shopnum1.distributionportal.adater; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import android.content.Context; import android.graphics.Bitmap; import android.os.Handler; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { private ArrayList<JSONObject> list_data; private Context context; private DisplayImageOptions options; public ImageAdapter(ArrayList<JSONObject> list_data, Context context) { this.list_data = list_data; this.context = context; options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.notype) // 设置图片下载期间显示的图片 .showImageForEmptyUri(R.drawable.notype) // 设置图片Uri为空或是错误的时候显示的图片 .showImageOnFail(R.drawable.notype) // 设置图片加载或解码过程中发生错误显示的图片 .cacheInMemory(true) // default 设置下载的图片是否缓存在内存中 .cacheOnDisc(true) // default 设置下载的图片是否缓存在SD卡中 .considerExifParams(false) // default .imageScaleType(ImageScaleType.EXACTLY) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default 设置图片的解码类型 .handler(new Handler()) // default .build(); } @Override public int getCount() { return list_data.size(); } @Override public Object getItem(int position) { return list_data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView == null) { vh = new ViewHolder(); convertView = View.inflate(context, R.layout.type_item, null); vh.type_image = (ImageView) convertView .findViewById(R.id.type_image); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } try { if (HttpConn.showImage) { ImageLoader.getInstance().displayImage( list_data.get(position).getString("BackgroundImage") .replace("..", ""), vh.type_image, options); } } catch (JSONException e) { e.printStackTrace(); } return convertView; } static class ViewHolder { ImageView type_image; } } <file_sep>package com.shopnum1.distributionportal; import java.math.BigDecimal; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.PullToRefreshView; import com.shopnum1.distributionportal.util.PullToRefreshView.OnFooterRefreshListener; import com.shopnum1.distributionportal.util.PullToRefreshView.OnHeaderRefreshListener; /** * 预存款明细 */ public class PaymentDetail extends Activity implements OnHeaderRefreshListener,OnFooterRefreshListener { private HttpConn httpget = new HttpConn(); private Dialog pBar; //加载进度 //明细列表 private ListView listview; private List<HashMap<String, String>> mListItems = new LinkedList<HashMap<String,String>>(); private PaymentDetailAdapter mAdapter; private PullToRefreshView mPullToRefreshView; /** 分页页码*/ private int page = 1; private int pageSize = 10; private int totalCount = 0; //预存款的obj private JSONObject paymentObj; //用户当前的预存款 private String currentPayment; //预存款明细的JSONArray private JSONArray paymentArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.payment_detail); advancePayment = getIntent().getDoubleExtra("AdvancePayment", 0.00); //((TextView)findViewById(R.id.paymentValue)).setText(advancePayment+""); //通知adapter刷新 if(null != mListItems || mListItems.size()>0){ mListItems.clear(); } if(null != mAdapter){ mAdapter.notifyDataSetChanged(); } //明细列表 listview = (ListView) findViewById(R.id.listview); //初始化布局 initLayout(); } @Override protected void onResume() { super.onResume(); //获得预存款详细 getPaymentDetail(); } //初始化布局 public void initLayout(){ //返回 ((LinearLayout)findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); //我要充值 ((LinearLayout)findViewById(R.id.more)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //跳到我要充值界面 Intent intent = new Intent(getApplicationContext(), RechargeActivity.class); intent.putExtra("currentPayment", currentPayment); startActivity(intent); } }); mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view); mPullToRefreshView.setOnHeaderRefreshListener(this); mPullToRefreshView.setOnFooterRefreshListener(this); } //获得预存款详细 public void getPaymentDetail(){ if(pBar == null){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); } if(pBar != null && !pBar.isShowing()){ pBar.show(); } new Thread() { @Override public void run() { Message message = Message.obtain(); //获取预存款列表集合 try { StringBuffer result = httpget.getArray("/api/getAdvancePaymentModifyLog?MemLoginId="+HttpConn.username+"&AppSign="+HttpConn.AppSign); paymentObj = new JSONObject(result.toString()); //当前用户预存款 paymentArray = paymentObj.getJSONArray("data"); BigDecimal b = new BigDecimal(paymentArray.getJSONObject(0).getDouble("LastOperateMoney")); currentPayment =String.format("%.2f", b);; if(true){ if (paymentArray != null && paymentArray.length() == 0){ message.what = 0; }else{ if (paymentArray != null && paymentArray.length() > 0) { message.what = 1; }else{ message.what = 0; } } }else{ message.what = 0; } } catch (JSONException e) { currentPayment = "0.00"; message.what = 0; e.printStackTrace(); } handler.sendMessage(message); } }.start(); } @SuppressLint("HandlerLeak") Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: if (totalCount == 0) { ((TextView)findViewById(R.id.nocontent)).setVisibility(View.VISIBLE); ((ListView) findViewById(R.id.listview)).setVisibility(View.GONE); } ((TextView)findViewById(R.id.paymentValue)).setText(currentPayment+""); if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } break; case 1: ((TextView)findViewById(R.id.nocontent)).setVisibility(View.GONE); ((ListView) findViewById(R.id.listview)).setVisibility(View.VISIBLE); ((TextView)findViewById(R.id.paymentValue)).setText(currentPayment+""); try { for (int i = 0; i < paymentArray.length(); i++) { JSONObject payObj = paymentArray.getJSONObject(i); HashMap<String, String> map = new HashMap<String, String>(); map.put("Guid", payObj.getString("Guid")); map.put("OperateType", payObj.getString("OperateType")); map.put("CurrentAdvancePayment", new BigDecimal(payObj.getString("CurrentAdvancePayment")).toPlainString()); map.put("OperateMoney",new BigDecimal(payObj.getString("OperateMoney")).toPlainString()); map.put("LastOperateMoney", new BigDecimal(payObj.getString("LastOperateMoney")).toPlainString()); map.put("Date", payObj.getString("Date")); mListItems.add(map); } } catch (JSONException e) { e.printStackTrace(); } if (totalCount == 0) { totalCount = mListItems.size(); mAdapter = new PaymentDetailAdapter(mListItems); listview.setAdapter(mAdapter); } else if (totalCount > 0 && totalCount < mListItems.size()) { mAdapter.notifyDataSetChanged(); } if(pBar != null && pBar.isShowing()){ pBar.dismiss(); } break; default: break; } super.handleMessage(msg); } }; private Double advancePayment; //预存款列表适配器 class PaymentDetailAdapter extends BaseAdapter { private List<HashMap<String,String>> payListItems = new LinkedList<HashMap<String,String>>(); public PaymentDetailAdapter(List<HashMap<String,String>> payListItems){ this.payListItems = payListItems; } @Override public int getCount() { return payListItems.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @SuppressLint("InflateParams") @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.payment_detail_item, null); holder.timeTv = (TextView)convertView.findViewById(R.id.timeTv); holder.opertypeTv = (TextView)convertView.findViewById(R.id.opertypeTv); holder.opervalueTv = (TextView)convertView.findViewById(R.id.opervalueTv); holder.currentValue = (TextView)convertView.findViewById(R.id.currentValue); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } HashMap<String, String> map = payListItems.get(position); //时间 String DateVal = map.get("Date"); if(null == DateVal || "null".equals(DateVal) || "".equals(DateVal)){ holder.timeTv.setText(""); }else{ if(DateVal.contains("/Date(")){ DateVal = DateVal.replace("/Date(", "").replace(")/", ""); DateVal = DateVal.substring(0,13); Date date = new Date(Long.valueOf(DateVal)); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String showTimeVal = formatter.format(date); holder.timeTv.setText(showTimeVal); }else{ holder.timeTv.setText(DateVal); } } //描述信息(0提现,1充值,2转账,3 提成,4扣款,5回款,预存款抵扣00) String OperateTypeVal = map.get("OperateType"); if(null == OperateTypeVal || "null".equals(OperateTypeVal) || "".equals(OperateTypeVal)){ holder.opertypeTv.setText(""); }else{ if("0".equals(OperateTypeVal)){ holder.opertypeTv.setText("提现"); }else if("1".equals(OperateTypeVal)){ holder.opertypeTv.setText("充值"); }else if("2".equals(OperateTypeVal)){ holder.opertypeTv.setText("转账"); }else if("3".equals(OperateTypeVal)){ holder.opertypeTv.setText("提成"); }else if("4".equals(OperateTypeVal)){ holder.opertypeTv.setText("扣款"); }else if("5".equals(OperateTypeVal)){ holder.opertypeTv.setText("回款"); }else{ holder.opertypeTv.setText(""); } } //改变的金额 String opervalueTvVal = map.get("OperateMoney"); if(null == opervalueTvVal || "null".equals(opervalueTvVal) || "".equals(opervalueTvVal)){ holder.opervalueTv.setText(""); }else{ if("0".equals(OperateTypeVal)){ holder.opervalueTv.setText("-"+opervalueTvVal); holder.opervalueTv.setTextColor(getResources().getColor(R.color.green)); }else if("1".equals(OperateTypeVal)){ holder.opervalueTv.setText("+"+opervalueTvVal); holder.opervalueTv.setTextColor(getResources().getColor(R.color.red)); }else if("2".equals(OperateTypeVal)){ holder.opervalueTv.setText("-"+opervalueTvVal); holder.opervalueTv.setTextColor(getResources().getColor(R.color.green)); }else if("3".equals(OperateTypeVal)){ holder.opervalueTv.setText("+"+opervalueTvVal); holder.opervalueTv.setTextColor(getResources().getColor(R.color.red)); }else if("4".equals(OperateTypeVal)){ holder.opervalueTv.setText("-"+opervalueTvVal); holder.opervalueTv.setTextColor(getResources().getColor(R.color.green)); }else if("5".equals(OperateTypeVal)){ holder.opervalueTv.setText("+"+opervalueTvVal); holder.opervalueTv.setTextColor(getResources().getColor(R.color.red)); }else{ holder.opervalueTv.setText(""); } } //当前的预存款余额 String LastOperateMoneyVal = map.get("LastOperateMoney"); if(null == LastOperateMoneyVal || "null".equals(LastOperateMoneyVal) || "".equals(LastOperateMoneyVal)){ holder.currentValue.setText(""); }else{ holder.currentValue.setText(LastOperateMoneyVal); } return convertView; } private class ViewHolder { TextView timeTv, opertypeTv, opervalueTv, currentValue; } } @Override protected void onDestroy() { super.onDestroy(); page = 1; totalCount = 0; mListItems.clear(); //通知adapter刷新 if(null != mAdapter){ mAdapter.notifyDataSetChanged(); } } @Override protected void onRestart() { super.onRestart(); page = 1; totalCount = 0; mListItems.clear(); //通知adapter刷新 if(null != mAdapter){ mAdapter.notifyDataSetChanged(); } } @Override public void onFooterRefresh(PullToRefreshView view) { page++; getPaymentDetail(); mPullToRefreshView.postDelayed(new Runnable() { @Override public void run() { mPullToRefreshView.onFooterRefreshComplete(); } }, 1000); } @Override public void onHeaderRefresh(PullToRefreshView view) { page = 1; totalCount = 0; mListItems.clear(); //通知adapter刷新 if(null != mAdapter){ mAdapter.notifyDataSetChanged(); } getPaymentDetail(); mPullToRefreshView.postDelayed(new Runnable() { @Override public void run() { // 设置更新时间 mPullToRefreshView.onHeaderRefreshComplete(); } }, 1000); } } <file_sep>package com.shopnum1.distributionportal.util; public class FileBean { // (type= String.class) @TreeNodeId private int id; @TreeNodePid private int pId; @TreeNodeType private int type; @TreeNodeLabel private String label; @TreeNodeTypeAorB private int type2; @TreeNodeCode private String code;//这个的意思就是学院那里点了分类之后需传分类code,因此新增此字段 public int getType2() { return type2; } public void setType2(int type2) { this.type2 = type2; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } private String desc; public FileBean(int id, int pId, String label,int type,int type2,String code) { this.id = id; this.pId = pId; this.label = label;//名称 this.type=type;//item的类型 this.type2=type2;//标示是A类还是B类 this.code=code; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getpId() { return pId; } public void setpId(int pId) { this.pId = pId; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } // ... } <file_sep>package com.shopnum1.distributionportal; //订单详情 import java.text.DecimalFormat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import com.nostra13.universalimageloader.core.ImageLoader; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; public class OrderList extends Activity { private HttpConn httpget = new HttpConn(); private JSONArray ProductList; private ListAdapter adapter; private Dialog pBar; // 加载进度 private int times; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.order_list); initLayout(); getData(); } // 初始化 public void initLayout() { // 返回 ((LinearLayout) findViewById(R.id.back)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void getData() { pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); new Thread() { public void run() { String orderListUrl = "/api/order/member/OrderList/?pageIndex=1&pageCount=100&memLoginID=" + HttpConn.username + "&t=0&AppSign=" + HttpConn.AppSign+"&agentID="+MyApplication.agentId; StringBuffer result = httpget .getArray(orderListUrl); Message msg = Message.obtain(); try { JSONArray OrderList = new JSONObject(result.toString()) .getJSONArray("Data"); ProductList = new JSONArray(); for (int i = 0; i < OrderList.length(); i++) { JSONObject object = OrderList.getJSONObject(i); if ((object.getInt("ShipmentStatus") != 4 && object .getInt("OderStatus") == 5) || object.getInt("ShipmentStatus") == 2) { JSONArray array = object .getJSONArray("ProductList"); for (int j = 0; j < array.length(); j++) { JSONObject object2 = array.getJSONObject(j); StringBuffer result2 = httpget .getArray("/api/getbaskorderlogs/?pageIndex=1&pageSize=1&ProductGuid=" + array.getJSONObject(j) .getString( "ProductGuid") + "&OrderNumber=" + object.getString("OrderNumber") + "&AppSign=" + HttpConn.AppSign); if (new JSONObject(result2.toString()) .getInt("count") == 0) object2.put("isShown", false); else object2.put("isShown", true); object2.put("OrderNumber", object.getString("OrderNumber")); ProductList.put(object2); times++; } } } msg.what = 1; } catch (JSONException e) { e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: pBar.dismiss(); break; case 1: addList(); pBar.dismiss(); if (times == 0) ((TextView) findViewById(R.id.nocontent)) .setVisibility(View.VISIBLE); break; default: break; } super.handleMessage(msg); } }; public void addList() { ListView listview = (ListView) findViewById(R.id.listview); listview.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter = new ListAdapter(); listview.setAdapter(adapter); // 商品详情 listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) { try { Intent intent = new Intent(getApplicationContext(), ProductDetails.class); intent.putExtra("guid", ProductList.getJSONObject(i) .getString("ProductGuid")); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); } class ListAdapter extends BaseAdapter { @Override public int getCount() { return ProductList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(final int position, View convertView, ViewGroup arg2) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.order_item3, null); } try { ((TextView) convertView.findViewById(R.id.text1)) .setText(ProductList.getJSONObject(position).getString( "NAME")); Log.i("test", ProductList.getJSONObject(position) + ""); ((TextView) convertView.findViewById(R.id.text2)) .setText(ProductList.getJSONObject(position).getString( "Attributes")); ((TextView) convertView.findViewById(R.id.text3)) .setText("¥" + new DecimalFormat("0.00").format(ProductList .getJSONObject(position).getDouble( "BuyPrice"))); Boolean isShown = ProductList.getJSONObject(position) .getBoolean("isShown"); Button btn = (Button) convertView.findViewById(R.id.text4); btn.setVisibility(View.VISIBLE); if (isShown) { btn.setText("已晒单"); btn.setOnClickListener(null); } else { btn.setText("去晒单"); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { Intent intent = new Intent(getBaseContext(), OrderShow.class); intent.putExtra("ProductList", ProductList .getJSONObject(position).toString()); startActivityForResult(intent, 0); } catch (JSONException e) { e.printStackTrace(); } } }); } ImageView imageview = (ImageView) convertView .findViewById(R.id.imageView1); if (HttpConn.showImage) ImageLoader.getInstance().displayImage( ProductList.getJSONObject(position).getString( "OriginalImge"), imageview, MyApplication.options); } catch (JSONException e) { e.printStackTrace(); } return convertView; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == 1) { finish(); } super.onActivityResult(requestCode, resultCode, data); } }<file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; //商品搜索结果 import java.text.DecimalFormat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; public class ProductList extends Activity { String TAG = "ProductList"; private HttpConn httpget = new HttpConn(); private int type; private static ImageAdapter adapter1; // 商品适配器 private static ImageAdapter adapter2; // 商品适配器 private Dialog pBar; // 加载进度 int width; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.product_list); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); type = getIntent().getIntExtra("type", 0); width = dm.widthPixels;// 宽度 ((LinearLayout) findViewById(R.id.back)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); // 加载列表 addList(); } // 加载列表 public void addList() { pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); // 显示列表 final ListView listview = (ListView) findViewById(R.id.listview); adapter1 = new ImageAdapter(1); listview.setAdapter(adapter1); // 商品详情 listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) { try { Intent intent = new Intent(getApplicationContext(), ProductDetails.class); intent.putExtra("guid", adapter1.getInfo(i).getString("Guid")); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); // 显示大图 final GridView gridview = (GridView) findViewById(R.id.gridview); adapter2 = new ImageAdapter(2); gridview.setAdapter(adapter2); // 商品详情 gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) { try { Intent intent = new Intent(getApplicationContext(), ProductDetails.class); intent.putExtra("guid", adapter2.getInfo(i).getString("Guid")); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); // 切换显示 ((LinearLayout) findViewById(R.id.more)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (listview.isShown()) { listview.setVisibility(View.INVISIBLE); gridview.setVisibility(View.VISIBLE); ((ImageView) findViewById(R.id.switch_btn)) .setBackgroundResource(R.drawable.switch_list); } else { gridview.setVisibility(View.INVISIBLE); listview.setVisibility(View.VISIBLE); ((ImageView) findViewById(R.id.switch_btn)) .setBackgroundResource(R.drawable.switch_big); } } }); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { adapter1.notifyDataSetChanged(); adapter2.notifyDataSetChanged(); } if (msg.what == 2) { // 搜索为空 pBar.dismiss(); ((LinearLayout) findViewById(R.id.nocontent)) .setVisibility(View.VISIBLE); } super.handleMessage(msg); } }; // 商品适配器 public class ImageAdapter extends BaseAdapter { private JSONArray companyList = new JSONArray(); private int count, id; public JSONObject getInfo(int position) { JSONObject result = null; try { result = companyList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return result; } public ImageAdapter(int id) { this.id = id; new Thread() { @Override public void run() { try { StringBuffer result = null; if (type == 8) { result = httpget .getArray("/api/panicbuyinglist/?pageIndex=1&pageSize=100" + "&AppSign=" + HttpConn.AppSign); } else { String product2Url ="/api/product2/type/?type=" + type + "&sorts=ModifyTime&isASC=false&pageIndex=1&pageCount=100" + "&AppSign=" + HttpConn.AppSign + "&AgentID="+MyApplication.agentId +"&Sbool=true"; result = httpget .getArray(product2Url); Log.i(TAG,"product2Url = "+product2Url); Log.i(TAG,"product2Url result = "+result); } count = Integer.parseInt(new JSONObject(result .toString()).get("Count").toString()); if (result.toString().length() == 4 || count == 0) { Message message = Message.obtain(); message.what = 2; handler.sendMessage(message); } companyList = new JSONObject(result.toString()) .getJSONArray("Data"); Message message = Message.obtain(); message.what = 1; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } @Override public int getCount() { return companyList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg1) { return arg1; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (pBar.isShowing()) pBar.dismiss(); if (convertView == null) { if (id == 1) convertView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.product_item, null); else convertView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.product_item2, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView .findViewById(R.id.textView1); holder.text2 = (TextView) convertView .findViewById(R.id.textView2); holder.text3 = (TextView) convertView .findViewById(R.id.textView3); holder.imageview = (ImageView) convertView .findViewById(R.id.imageView1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { holder.text1.setText(companyList.getJSONObject(position) .getString("Name")); if (type == 8) { holder.text2.setText("¥" + new DecimalFormat("0.00").format(companyList .getJSONObject(position).getDouble( "PanicBuyingPrice"))); } else { holder.text2.setText("¥" + new DecimalFormat("0.00").format(companyList .getJSONObject(position).getDouble( "ShopPrice"))); holder.text3.setText("¥" + new DecimalFormat("0.00").format(companyList .getJSONObject(position).getDouble( "MarketPrice"))); } if (id==2) { LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) holder.imageview .getLayoutParams(); linearParams.height = (width - dip2px(ProductList.this, 15)) / 2; holder.imageview.setLayoutParams(linearParams); } if (HttpConn.showImage) ImageLoader.getInstance().displayImage( companyList.getJSONObject(position).getString( "OriginalImge"), holder.imageview, MyApplication.options); } catch (JSONException e) { e.printStackTrace(); } return convertView; } } static class ViewHolder { ImageView imageview; TextView text1, text2, text3; } public int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }<file_sep>package com.shopnum1.distributionportal.adater; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import com.shopnum1.distributionportal.BannerWeb; import com.shopnum1.distributionportal.MainActivity; public class GGPagerAdapter extends PagerAdapter { private ArrayList<View> viewList; JSONArray gg_list; private Context context; public GGPagerAdapter(ArrayList<View> viewList, JSONArray gg_list, Context context) { this.viewList = viewList; this.gg_list = gg_list; this.context = context; } @Override public int getCount() { if (viewList.size() > 3) { return Integer.MAX_VALUE; } return viewList.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public Object instantiateItem(ViewGroup container, final int position) { if (viewList.size() > 3) { container.addView(viewList.get(position % viewList.size())); return viewList.get(position % viewList.size()); } container.addView(viewList.get(position)); viewList.get(position % viewList.size()).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, BannerWeb.class); try { intent.putExtra( "Url", (gg_list).getJSONObject( position % viewList.size()) .getString("Url")); } catch (JSONException e) { e.printStackTrace(); } context.startActivity(intent); } }); return viewList.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (viewList.size() > 3) { container.removeView(viewList.get(position % viewList.size())); } else { container.removeView(viewList.get(position)); } } }<file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.ImplementDao; import com.shopnum1.distributionportal.util.MyApplication; import com.shopnum1.distributionportal.util.ShareUtils; //启动 import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; public class InitActivity extends Activity { private HttpConn httpget = new HttpConn(); private ImplementDao database = new ImplementDao(this); private Boolean exit = false; // 是否退出 private ImageView[] tips, imgViews; // 引导页图片 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_init); getSign(); } public void getSign() { new Thread() { public void run() { Message msg = Message.obtain(); StringBuffer result = httpget.getArray("/api/SignSet/?isSet=1"); try { HttpConn.AppSign = new JSONObject(result.toString()) .getString("AppSign"); } catch (JSONException e) { e.printStackTrace(); } handler.sendEmptyMessage(0); } }.start(); } public void getNumber() { SharedPreferences mPerferences = PreferenceManager .getDefaultSharedPreferences(this); // 是否登录 boolean islogin = mPerferences.getBoolean("islogin", false); String username = mPerferences.getString("name", ""); if (islogin) { HttpConn.isLogin = true; HttpConn.username = toUTF8(username); HttpConn.UserName = username; new Thread() { public void run() { String shoppingcartgetUrl = "/api/shoppingcartget/?loginId=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign + "&agentID="+MyApplication.agentId; StringBuffer result = httpget .getArray(shoppingcartgetUrl); try { HttpConn.cartNum = new JSONObject(result.toString()) .getJSONArray("Data").length(); Log.i("fly", HttpConn.AppSign); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } // 是否显示导航 boolean showImage = mPerferences.getBoolean("showImage", true); if (showImage) { initLayout(); Editor mEditor = mPerferences.edit(); mEditor.putBoolean("showImage", false); mEditor.commit(); } else { ((ImageView) findViewById(R.id.img)) .setBackgroundResource(R.drawable.guid); // ((ImageView)findViewById(R.id.img)).setBackgroundResource(R.drawable.startview); new Handler().postDelayed(new Runnable() { @Override public void run() { if (exit){ finish(); } else{ SelectAgent(); } finish(); } }, 1000); } } private void SelectAgent() { // TODO Auto-generated method stub // String agentId = ShareUtils.getString(getApplicationContext(), HttpConn.AGENT_ID_KEY, ""); String agentId = MyApplication.agentId; if(agentId==null || "".equals(agentId)){ //还没有选择分销商,前去选择分销商 startActivity(new Intent(getApplicationContext(),SelectAgentActivity.class)); }else{ startActivity(new Intent(getApplicationContext(), MainActivity.class)); // 进入主页 } } public String toUTF8(String name) { String username = ""; try { username = URLEncoder.encode(name, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return username; } // 显示引导图 public void initLayout() { ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup); ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager); // int[] img = new int[]{R.drawable.startview1, R.drawable.startview2, // R.drawable.startview3}; int[] img = new int[] { R.drawable.guid1, R.drawable.guid2, R.drawable.guid3 }; tips = new ImageView[img.length]; for (int i = 0; i < tips.length; i++) { ImageView imageView = new ImageView(this); imageView.setLayoutParams(new LayoutParams(10, 10)); tips[i] = imageView; if (i == 0) { tips[i].setBackgroundResource(R.drawable.point_white1); } else { tips[i].setBackgroundResource(R.drawable.point_white); } LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); layoutParams.leftMargin = 5; layoutParams.rightMargin = 5; layoutParams.topMargin = 5; layoutParams.bottomMargin = 10; group.addView(imageView, layoutParams); } imgViews = new ImageView[img.length]; for (int i = 0; i < imgViews.length; i++) { ImageView imageView = new ImageView(this); imgViews[i] = imageView; imageView.setBackgroundResource(img[i]); } viewPager.setAdapter(new MyAdapter()); viewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { for (int i = 0; i < tips.length; i++) { if (i == arg0) { tips[i].setBackgroundResource(R.drawable.point_white1); if (i == (imgViews.length - 1)) { imgViews[i] .setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // startActivity(new Intent( // getApplicationContext(), // MainActivity.class)); SelectAgent(); finish(); } }); } } else { tips[i].setBackgroundResource(R.drawable.point_white); } } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } // 引导图适配器 class MyAdapter extends PagerAdapter { @Override public int getCount() { return imgViews.length; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void destroyItem(View container, int position, Object object) { ((ViewPager) container).removeView(imgViews[position]); } @Override public Object instantiateItem(View container, int position) { ((ViewPager) container).addView(imgViews[position], 0); return imgViews[position]; } } public void login() { new Thread() { public void run() { String name = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()).getString("name", ""); String pwd = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()).getString("pwd", ""); try { StringBuffer result = httpget .getArray("/api/accountlogin/?MemLoginID=" + URLEncoder.encode(name, "utf-8") + "&Pwd=" + pwd + "&AppSign=" + HttpConn.AppSign); if (!new JSONObject(result.toString()).getString("return") .equals("202")) { HttpConn.isLogin = false; Editor editor = PreferenceManager .getDefaultSharedPreferences( getApplicationContext()).edit(); editor.putBoolean("islogin", false); editor.commit(); } } catch (JSONException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }.start(); } // 获取背景图片 public void getBitmap() { new Thread() { @Override @SuppressWarnings("deprecation") public void run() { StringBuffer ImageList = httpget.getArray("/api/welcome/?" + "AppSign=" + HttpConn.AppSign); String path = ""; try { path = new JSONObject(ImageList.toString()) .getJSONArray("ImageList").getJSONObject(0) .getString("Value"); } catch (JSONException e) { e.printStackTrace(); } Bitmap photo = database.imgQuery("picimage", path); if (photo != null) { Message msg = new Message(); msg.obj = photo; handler.sendMessage(msg); } else { Bitmap temp = httpget.getImage(path); if (temp != null) { float width = temp.getWidth(); float height = temp.getHeight(); float scaleX = getWindowManager().getDefaultDisplay() .getWidth() / width; float scaleY = getWindowManager().getDefaultDisplay() .getHeight() / height; Matrix matrix = new Matrix(); matrix.postScale(scaleX, scaleY); Bitmap bitmap = Bitmap.createBitmap(temp, 0, 0, (int) width, (int) height, matrix, true); database.imgInsert("picimage", path, bitmap); Message msg = new Message(); msg.obj = bitmap; handler.sendMessage(msg); if (!temp.isRecycled()) { temp.recycle(); temp = null; System.gc(); } } } } }.start(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { ((ImageView) findViewById(R.id.img)) .setImageBitmap((Bitmap) msg.obj); // 设置背景图片 super.handleMessage(msg); switch (0) { case 0: getNumber(); break; default: break; } } }; // 退出程序 @Override public void onBackPressed() { exit = true; super.onBackPressed(); } }<file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class KuaidiActivity extends Activity { private WebView webview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); webview = (WebView)findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.setWebViewClient(new WebViewClient(){ ProgressDialog pBar = ProgressDialog.show(KuaidiActivity.this, null, "正在加载..."); @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { pBar.show(); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { pBar.dismiss(); super.onPageFinished(view, url); } }); String code = getIntent().getStringExtra("code"); String id = getIntent().getStringExtra("id"); webview.loadUrl("http://m.kuaidi100.com/index_all.html?type=" + code + "&postid=" + id); } }<file_sep>package com.shopnum1.distributionportal.util; public class OrgBean { @TreeNodeId private int _id; @TreeNodePid private int parentId; @TreeNodeLabel private String name; @TreeNodeCode private String code; @TreeNodeType private int type; @TreeNodeTypeAorB private int type2; public OrgBean(int _id, int parentId, String name,int type,int type2,String code) { this._id = _id; this.parentId = parentId; this.name = name; this.type=type; this.type2=type2; this.code=code; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int getType2() { return type2; } public void setType2(int type2) { this.type2 = type2; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; public class BannerWeb extends Activity { private WebView webview; private ProgressBar progressbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.banner_web); progressbar = (ProgressBar) findViewById(R.id.progress); findViewById(R.id.back).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BannerWeb.this.finish(); } }); webview = (WebView) findViewById(R.id.banner_web); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl(getIntent().getStringExtra("Url")); webview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } }); webview.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { // TODO Auto-generated method stub if (newProgress == 100) { progressbar.setVisibility(View.GONE); } else { if (progressbar.getVisibility() == View.GONE) progressbar.setVisibility(View.VISIBLE); progressbar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (webview.canGoBack()) { webview.goBack(); return true; } else { this.finish(); } break; } return super.onKeyDown(keyCode, event); } } <file_sep>package com.shopnum1.distributionportal.adater; import java.util.ArrayList; import com.shopnum1.distributionportal.R; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.View.OnCreateContextMenuListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class OnlyImageAdapter extends BaseAdapter { private ArrayList<String> list_data; private Context context; public OnlyImageAdapter(ArrayList<String> list_data, Context context) { // TODO Auto-generated constructor stub this.list_data = list_data; this.context = context; } @Override public int getCount() { return 8; } @Override public Object getItem(int position) { return list_data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView == null) { vh = new ViewHolder(); convertView = View.inflate(context, R.layout.type_item, null); vh.type_image = (ImageView) convertView .findViewById(R.id.type_image); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } return convertView; } static class ViewHolder { ImageView type_image; } } <file_sep>package com.shopnum1.distributionportal.adater; import java.util.List; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.Node; import com.shopnum1.distributionportal.util.TreeHelper; import com.shopnum1.distributionportal.util.TreeListViewAdapter; public class SimpleTreeListViewAdapter<T> extends TreeListViewAdapter<T> { private String[] tag; public EditText ed_min; public EditText ed_max; private long Min = 0; private long Max = Long.MAX_VALUE; private ImageView iv; private ImageView IV2; public void setMin(long Min) { this.Min = Min; } public void setMax(long Max) { this.Max = Max; } public long getMin() { if (ed_min != null && !ed_min.getText().toString().equals("")) { return Long.parseLong(ed_min.getText().toString()); } return 0; } public long getMax() { if (ed_max != null && !ed_max.getText().toString().equals("")) { return Long.parseLong(ed_max.getText().toString()); } return Long.MAX_VALUE; } public SimpleTreeListViewAdapter(ListView tree, Context context, List<T> datas, int defaultExpandLevel) throws IllegalArgumentException, IllegalAccessException { super(tree, context, datas, defaultExpandLevel, false); } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } @Override public int getViewTypeCount() { return 3; } public void setTag(String[] tag) { this.tag = tag; } @Override public View getConvertView(Node node, int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); if (node.getType() == 0) { convertView = mInflater.inflate(R.layout.item1, parent, false); holder.mText = (TextView) convertView .findViewById(R.id.id_item_text); } else if (node.getType() == 1) { convertView = mInflater.inflate(R.layout.item2, parent, false); holder.mText = (TextView) convertView .findViewById(R.id.id_item_text1); holder.iv = (ImageView) convertView.findViewById(R.id.gougou); } else if (node.getType() == 2) { convertView = mInflater.inflate(R.layout.item3, parent, false); ed_min = (EditText) convertView.findViewById(R.id.button1); ed_max = (EditText) convertView.findViewById(R.id.button2); iv = (ImageView) convertView.findViewById(R.id.gougou); } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (node.getType() == 0) { holder.mText.setText(node.getName()); } if (node.getType() == 1) { holder.mText.setText(node.getName()); if (Min == 0 && Max == Long.MAX_VALUE && node.getName().equals("全部价格")) { holder.iv.setVisibility(View.VISIBLE); if(node.getpId() == 1){ IV2=holder.iv; } } else if ((Min + "-" + Max).equals(node.getName())&&(ed_min.getText().toString().equals("")&&ed_max.getText().toString().equals(""))) { holder.iv.setVisibility(View.VISIBLE); if(node.getpId() == 1){ IV2=holder.iv; } } else if (tag[0].equals(node.getName())) { holder.iv.setVisibility(View.VISIBLE); if(node.getpId() == 1){ IV2=holder.iv; } } else if (tag[1].equals(node.getName())) { holder.iv.setVisibility(View.VISIBLE); if(node.getpId() == 1){ IV2=holder.iv; } } else { holder.iv.setVisibility(View.GONE); } } if (node.getType() == 2) { ed_min.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(count>0){ iv.setVisibility(View.VISIBLE); if(IV2!=null){ IV2.setVisibility(View.GONE); } }else{ iv.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (!ed_min.getText().toString().equals("")) { if (Long.parseLong((ed_min.getText().toString())) >= Long.MAX_VALUE) { ed_min.setText(Long.MAX_VALUE + ""); } } } @Override public void afterTextChanged(Editable s) { } }); ed_max.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(count>0){ iv.setVisibility(View.VISIBLE); if(IV2!=null){ IV2.setVisibility(View.GONE); } }else{ iv.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (!ed_max.getText().toString().equals("")) { if (Long.parseLong((ed_max.getText().toString())) >= Long.MAX_VALUE) { ed_max.setText(Long.MAX_VALUE + ""); } } } @Override public void afterTextChanged(Editable s) { } }); } return convertView; } private class ViewHolder { TextView mText; TextView nText; ImageView iv; } /** * 动态插入节点 * * @param position * @param string */ public void addExtraNode(int position, String string, int type, int type2, String code) { Node node = mVisibleNodes.get(position); int indexOf = mAllNodes.indexOf(node); // Node Node extraNode = new Node(-1, node.getId(), string, type, type2, code); extraNode.setParent(node); node.getChildren().add(extraNode); mAllNodes.add(indexOf + 1, extraNode); mVisibleNodes = TreeHelper.filterVisibleNodes(mAllNodes); notifyDataSetChanged(); } } <file_sep>package com.shopnum1.distributionportal; //分类浏览 import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; public class CityList extends Activity { private HttpConn httpget = new HttpConn(); private List<Map<String, String>> list; private Dialog pBar; private int index = 0; private String OrderID = "0"; private String cityName = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city_list); initLayout(); addData(); } public void initLayout(){ //返回 ((LinearLayout)findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); } //加载数据 public void addData(){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); new Thread() { @Override public void run(){ StringBuffer result = httpget.getArray("/api/region/?parentId=" + OrderID + "&AppSign=" + HttpConn.AppSign); try { JSONArray sortList = new JSONObject(result.toString()).getJSONArray("Data"); list = new ArrayList<Map<String, String>>(); for (int i = 0; i < sortList.length(); i++) { Map<String, String> map = new HashMap<String, String>(); map.put("name", sortList.getJSONObject(i).getString("Name")); map.put("id", sortList.getJSONObject(i).getString("OrderID")); map.put("code", sortList.getJSONObject(i).getString("Code")); list.add(map); } Message msg = new Message(); handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } public void addList(){ ListView listview = (ListView)findViewById(R.id.listview); SimpleAdapter gridadapter = new SimpleAdapter(getApplicationContext(), list, R.layout.city_item, new String[]{"name"}, new int[]{R.id.name}); listview.setAdapter(gridadapter); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) { String code = list.get(i).get("code"); cityName += list.get(i).get("name"); if(index < 2) { OrderID = list.get(i).get("id"); addData(); index++; } else { HttpConn.cityName = cityName; Intent intent = getIntent(); intent.putExtra("code", code); setResult(1, intent); finish(); } } }); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { pBar.dismiss(); addList(); super.handleMessage(msg); } }; }<file_sep>package com.shopnum1.distributionportal.util; import java.io.IOException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; public class CommonUtility { /** * 读取图片属性:旋转的角度 * @param path 图片绝对路径 * @return degree 旋转的角度 */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 旋转图片,使图片保持正确的方向。 * @param bitmap 原始图片 * @param degrees 原始图片的角度 * @return Bitmap 旋转后的图片 */ public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) { if (degrees == 0 || null == bitmap) { return bitmap; } Matrix matrix = new Matrix(); matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2); Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); if (null != bitmap) { bitmap.recycle(); } return bmp; } /** 计算图片缩放比例*/ public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio; } return inSampleSize; } } <file_sep>package com.shopnum1.distributionportal.adater; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import com.nostra13.universalimageloader.core.ImageLoader; import com.shopnum1.distributionportal.PhotoshowActivity; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.NoScrollGridView; import com.shopnum1.distributionportal.util.RoundImageView; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.RatingBar; import android.widget.TextView; public class CommentAdapter extends BaseAdapter { private ArrayList<JSONObject> list_data; private Context context; private ArrayList<BaseAdapter> adapter; public CommentAdapter(ArrayList<JSONObject> list_data, Context context, ArrayList<BaseAdapter> adapter) { this.list_data = list_data; this.context = context; this.adapter = adapter; } @Override public int getCount() { return list_data.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder vh; if (convertView == null) { vh = new ViewHolder(); convertView = View.inflate(context, R.layout.comment_item, null); vh.user_name = (TextView) convertView.findViewById(R.id.user_name); vh.user_comment = (TextView) convertView.findViewById(R.id.user_comment); vh.user_head = (RoundImageView) convertView.findViewById(R.id.user_head); vh.user_time = (TextView) convertView.findViewById(R.id.user_time); vh.user_params = (TextView) convertView.findViewById(R.id.user_params); vh.user_rating = (RatingBar) convertView.findViewById(R.id.user_rating); vh.image_grid = (NoScrollGridView) convertView.findViewById(R.id.image_grid); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } try { vh.user_rating.setRating(list_data.get(position).getInt("rank")); vh.image_grid.setAdapter(adapter.get(position)); vh.image_grid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) { Intent x=new Intent(context, PhotoshowActivity.class); BaseImageAdapter madapter=(BaseImageAdapter) adapter.get(position); x.putExtra("icon", madapter.getImagePath()); x.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); x.putExtra("selection", 0); context.startActivity(x); // (()context).overridePendingTransition(R.anim.wave_scale,R.anim.my_alpha_action); } }); ImageLoader.getInstance().displayImage(HttpConn.hostName+ list_data.get(position).getString("memphoto"),vh.user_head); vh.user_comment.setText(list_data.get(position).getString("content")); vh.user_params.setText(list_data.get(position).getString("attributes")); vh.user_name.setText(list_data.get(position).getString("memname")); vh.user_time.setText(list_data.get(position).getString("sendtime")); } catch (JSONException e) { e.printStackTrace(); } return convertView; } static class ViewHolder { private TextView user_name; private TextView user_comment; private TextView user_params; private TextView user_time; private RatingBar user_rating; private RoundImageView user_head; private NoScrollGridView image_grid; } } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.CustomDigitalClock; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.nostra13.universalimageloader.core.ImageLoader; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class LimitProductActivity extends Activity { private HttpConn httpget = new HttpConn(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_limit_product_list); initLayout(); } @Override protected void onResume() { ListView lv = (ListView) findViewById(R.id.listview); adapter2 = new GridViewAdapter2(); lv.setAdapter(adapter2); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { Intent intent = new Intent(getApplicationContext(), ProductDetails.class); intent.putExtra("guid", adapter2.getInfo(position).getString("ProductGuid")); intent.putExtra("EndTime", adapter2.getInfo(position).getString("EndTime")); intent.putExtra("RestrictCount", adapter2.getInfo(position).getInt("RestrictCount")); intent.putExtra("ShopPrice", adapter2.getInfo(position).getDouble("PanicBuyingPrice")); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } }); super.onResume(); } private void initLayout() { findViewById(R.id.back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 10: adapter2.notifyDataSetChanged(); break; default: break; } }; }; private GridViewAdapter2 adapter2; //商品适配器 class GridViewAdapter2 extends BaseAdapter { private JSONArray companyList = new JSONArray(); public JSONObject getInfo(int position) { JSONObject result = null; try { result = companyList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return result; } public GridViewAdapter2() { new Thread() { @Override public void run() { StringBuffer result = httpget.getArray("/api/panicbuyinglist/?pageIndex=1&pageSize=100" + "&AppSign=" + HttpConn.AppSign); Log.i("TAG", result.toString()); try { companyList = new JSONObject(result.toString()).getJSONArray("Data"); Message message = Message.obtain(); message.what = 10; handler.sendMessage(message); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } @Override public int getCount() { return companyList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg1) { return arg1; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.limit_product_item, parent, false); } try { TextView text1 = (TextView) convertView.findViewById(R.id.text1); TextView text2 = (TextView) convertView.findViewById(R.id.text2); CustomDigitalClock text3 = (CustomDigitalClock) convertView.findViewById(R.id.text3); text1.setText(companyList.getJSONObject(position).getString("Name")); text2.setText("¥" + new DecimalFormat("0.00").format(companyList.getJSONObject(position).getDouble("PanicBuyingPrice"))); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date d2 = sdf.parse(companyList.getJSONObject(position).getString("EndTime")); text3.setEndTime(d2.getTime()); ImageView imageview = (ImageView) convertView.findViewById(R.id.img); if(HttpConn.showImage) ImageLoader.getInstance().displayImage(companyList.getJSONObject(position).getString("OriginalImge"), imageview, MyApplication.options); } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return convertView; } } }<file_sep>package com.shopnum1.distributionportal; //我的消息 import com.shopnum1.distributionportal.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; public class MemberAddress extends Activity { private HttpConn httpget = new HttpConn(); private ListAdapter adapter; private Dialog pBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.member_address); initLayout(); addList(); } //初始化 public void initLayout() { //返回 ((LinearLayout)findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { setResult(2, getIntent()); finish(); } }); //新增 ((LinearLayout)findViewById(R.id.add)).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { startActivityForResult(new Intent(getBaseContext(), MemberAddressEdit.class), 0); } }); } public void addList(){ pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); ListView listview = (ListView)findViewById(R.id.listview); listview.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter = new ListAdapter(this); listview.setAdapter(adapter); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) { String name = ((TextView)v.findViewById(R.id.textView1)).getText().toString(); String mobile = ((TextView)v.findViewById(R.id.textView2)).getText().toString(); String address = ((TextView)v.findViewById(R.id.textView3)).getText().toString(); String code = ((TextView)v.findViewById(R.id.textView4)).getText().toString(); String guid = ((TextView)v.findViewById(R.id.textView5)).getText().toString(); Intent intent = getIntent(); intent.putExtra("name", name); intent.putExtra("mobile", mobile); intent.putExtra("address", address); intent.putExtra("code", code); intent.putExtra("guid", guid); setResult(1, intent); finish(); } }); } Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: ((TextView)findViewById(R.id.nocontent)).setVisibility(View.VISIBLE); break; case 1: ((TextView)findViewById(R.id.nocontent)).setVisibility(View.GONE); adapter.notifyDataSetChanged(); break; default: break; } super.handleMessage(msg); } }; class ListAdapter extends BaseAdapter{ private JSONArray addressList = new JSONArray(); int count = 0; public JSONObject getInfo(int position) { JSONObject result = null; try { result = addressList.getJSONObject(position); } catch (JSONException e) { e.printStackTrace(); } return result; } public ListAdapter(Context c) { new Thread() { @Override public void run() { Message message = Message.obtain(); try { StringBuffer result = httpget.getArray("/api/address/?MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); addressList = new JSONObject(result.toString()).getJSONArray("Data"); if(addressList.length() == 0) message.what = 0; else message.what = 1; } catch (JSONException e) { message.what = 0; e.printStackTrace(); } handler.sendMessage(message); pBar.dismiss(); } }.start(); } @Override public int getCount() { return addressList.length(); } @Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null){ holder = new ViewHolder(); convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_address, parent, false); holder.name = (TextView)convertView.findViewById(R.id.textView1); holder.mobile = (TextView)convertView.findViewById(R.id.textView2); holder.address = (TextView)convertView.findViewById(R.id.textView3); holder.code = (TextView)convertView.findViewById(R.id.textView4); holder.guid = (TextView)convertView.findViewById(R.id.textView5); holder.edit = (ImageView)convertView.findViewById(R.id.edit); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { holder.name.setText(addressList.getJSONObject(position).getString("NAME")); holder.mobile.setText(addressList.getJSONObject(position).getString("Mobile")); holder.address.setText(addressList.getJSONObject(position).getString("Address")); holder.code.setText(addressList.getJSONObject(position).getString("Code")); holder.guid.setText(addressList.getJSONObject(position).getString("Guid")); } catch (JSONException e) { e.printStackTrace(); } holder.edit.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { Intent intent = new Intent(getBaseContext(), MemberAddressEdit.class); intent.putExtra("addressList", addressList.getJSONObject(position).toString()); startActivityForResult(intent, 0); } catch (JSONException e) { e.printStackTrace(); } } }); return convertView; } } class ViewHolder { TextView name; TextView mobile; TextView address; TextView code; TextView guid; ImageView edit; } @Override public void onBackPressed() { setResult(2, getIntent()); finish(); super.onBackPressed(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == 1){ addList(); } super.onActivityResult(requestCode, resultCode, data); } }<file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 19 buildToolsVersion "27.0.2" defaultConfig { applicationId "com.shopnum1.distributionportal" minSdkVersion 14 targetSdkVersion 19 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile project(':library') compile files('libs/MobLogCollector.jar') compile files('libs/MobTools.jar') compile files('libs/ShareSDK-Core-2.6.3.jar') compile files('libs/ShareSDK-QQ-2.6.3.jar') compile files('libs/ShareSDK-QZone-2.6.3.jar') compile files('libs/ShareSDK-SinaWeibo-2.6.3.jar') compile files('libs/ShareSDK-Wechat-2.6.3.jar') compile files('libs/ShareSDK-Wechat-Core-2.6.3.jar') compile files('libs/ShareSDK-Wechat-Moments-2.6.3.jar') compile files('libs/alipaySDK-20150818.jar') compile files('libs/android-support-v13.jar') compile files('libs/libammsdk.jar') compile files('libs/locSDK_4.1.jar') compile files('libs/pushservice-4.5.3.48.jar') compile files('libs/universal-image-loader-1.9.2-SNAPSHOT-with-sources.jar') compile files('libs/volley.jar') compile files('libs/xUtils-2.6.14.jar') compile files('libs/zxing.jar') } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; import com.shopnum1.distributionportal.util.ShareUtils; import com.zxing.bean.Agent; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Message; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; public class RegistActivity2 extends Activity { private EditText et_pass; private EditText et_pass_again; private EditText et_user; private Button btn_ok; private String Phone; // final List<Agent> agenLists = new ArrayList<Agent>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.regist_activity2); initLayout(); } @Override protected void onResume() { // TODO Auto-generated method stub // getAgentList(); // Log.i("test", "list length="+list.size()); super.onResume(); } // private void getAgentList() { // HttpUtils hu = new HttpUtils(); // // String urlStr = HttpConn.hostName // + "/api/GetAgentList?AppSign=" + HttpConn.AppSign ; // hu.send(HttpMethod.GET, urlStr // , new RequestCallBack<String>() { // @Override // public void onFailure(HttpException arg0,String arg1) { // Toast.makeText(getApplicationContext(), // "服务异常,注册失败", 1000).show(); // } // @Override // public void onSuccess(ResponseInfo<String> data) { // try { // Log.i("test", "data:"+data.result); // String jsonStr = data.result; // JSONTokener jsonParser = new JSONTokener(jsonStr); // JSONObject dataJson = (JSONObject) jsonParser.nextValue(); // JSONArray dataArray = dataJson.getJSONArray("Data"); // Agent agent = new Agent(); // for (int i = 0;i<dataArray.length();i++){ // JSONObject agentObj= (JSONObject) dataArray.get(i); // String memLoginID = agentObj.getString("MemLoginID"); // String email = agentObj.getString("Email"); // agent.setMemLoginID(memLoginID); // agent.setEmail(email); // agenLists.add(agent); // } // List<Agent> agenLists2 =agenLists; //删 // Log.i("test", "agenLists2:"+agenLists2.size());//删 // // } catch (JSONException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // // }); // // } private void initLayout() { Phone = getIntent().getStringExtra("phoneNum"); btn_ok = (Button) this.findViewById(R.id.register); et_pass = (EditText) this.findViewById(R.id.pass); et_pass_again = (EditText) this.findViewById(R.id.pwd_again); et_user = (EditText) this.findViewById(R.id.user_name); btn_ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // //判断是否是分销商 // HttpUtils httpUtils = new HttpUtils(); // String checkUrl = HttpConn.hostName // + "/api/CheckIsAgent?AppSign=" + HttpConn.AppSign + "&AgentID="+et_user.getText().toString(); // httpUtils.send(HttpMethod.GET, HttpConn.hostName // + "/api/CheckIsAgent?AppSign=" + HttpConn.AppSign + "&MemLoginID="+et_user.getText().toString() // // , new RequestCallBack<String>() { // @Override // public void onFailure(HttpException arg0,String arg1) { // Toast.makeText(getApplicationContext(), // "服务异常,注册失败", 1000).show(); // } // @Override // public void onSuccess(ResponseInfo<String> data) { // try { // String result = data.result; // //判断是否是分销商 // gotoRegist(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // }); // gotoRegist(); } }); // et_user.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View arg0) { // // TODO Auto-generated method stub // Intent intent = new Intent(); // // intent.setClass(RegistActivity2.this, SelectAgentActivity.class); // startActivityForResult(intent, 100); // startActivity(intent); // } // }); } private void gotoRegist() { if (ispass(et_pass.getText().toString())) { if (!TextUtils.isEmpty(et_pass.getText().toString())&& (!TextUtils.isEmpty(et_pass_again.getText().toString()))) { if (et_pass.getText().toString().equals(et_pass_again.getText().toString())) { // String agentId = ShareUtils.getString(getApplicationContext(), HttpConn.AGENT_ID_KEY, ""); String agentId =MyApplication.agentId; String etTxt = et_user.getText().toString(); if(etTxt!=null&&!"".equals(etTxt)){ agentId=etTxt; } // String urlStr = HttpConn.hostName // + "/api/accountregist?MemLoginID=" + Phone // + "&Pwd=" + et_<PASSWORD>.getText().toString() // + "&CommendPeople=" // + "&Email=0&Mobile="+ Phone + "&AppSign=" + HttpConn.AppSign // + "&AgentID="+agentId; String urlStr = HttpConn.hostName + "/api/accountregist?MemLoginID=" + Phone + "&Pwd=" + et_pass.getText().toString() + "&Email=0&Mobile="+ Phone + "&AppSign=" + HttpConn.AppSign + "&AgentID="+agentId; if (et_pass.getText().toString().length()>=6) { HttpUtils hu = new HttpUtils(); hu.send(HttpMethod.GET, urlStr , new RequestCallBack<String>() { @Override public void onFailure(HttpException arg0,String arg1) { Toast.makeText(getApplicationContext(), "服务异常,注册失败", 1000).show(); } @Override public void onSuccess(ResponseInfo<String> data) { try { JSONObject object=new JSONObject(data.result); if(object.optString("return").equals("202")){ HttpConn.isLogin = true; HttpConn.username = Phone; HttpConn.UserName = Phone; Toast.makeText(RegistActivity2.this, "注册成功", Toast.LENGTH_SHORT).show(); Editor editor = PreferenceManager .getDefaultSharedPreferences( getApplicationContext()) .edit(); editor.putString("name", Phone); editor.putString("pwd", et_pass.getText() .toString()); editor.putBoolean("islogin", true); editor.commit(); Intent i = new Intent(RegistActivity2.this, MainActivity.class); setResult(1, getIntent()); startActivity(i); RegistActivity2.this.finish(); }else{ Toast.makeText(getApplicationContext(), "注册失败", 1000).show(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); }else { Toast.makeText(getApplicationContext(), "密码至少6位", 2000).show(); } } else { Toast.makeText(getApplicationContext(), "两次密码不一致", 2000).show(); } } else { Toast.makeText(getApplicationContext(), "密码和确认密码不能为空", 2000).show(); } } else { Toast.makeText(getApplicationContext(), "密码格式为 字母 数字和_", 2000) .show(); } } // 电话号码 public static boolean ispass(String str) { Pattern p = Pattern.compile("[A-Za-z0-9_]+"); Matcher m = p.matcher(str); if (m.find()) { return true; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TO DO Auto-generated method stub if(resultCode == 20){ String agent = data.getExtras().getString("agent"); et_user.setText(agent); Toast.makeText(getApplicationContext(), "agent:"+agent, 1).show(); } super.onActivityResult(requestCode, resultCode, data); } } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import java.util.List; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import com.baidu.android.pushservice.PushMessageReceiver; public class PushTestReceiver extends PushMessageReceiver{ @Override public void onBind(Context arg0, int arg1, String arg2, String arg3, String arg4, String arg5) { } @Override public void onDelTags(Context arg0, int arg1, List<String> arg2, List<String> arg3, String arg4) { } @Override public void onListTags(Context arg0, int arg1, List<String> arg2, String arg3) { } @Override public void onMessage(Context arg0, String arg1, String arg2) { } @Override public void onNotificationArrived(Context arg0, String arg1, String arg2, String arg3) { } @Override public void onNotificationClicked(Context context, String arg1, String arg2, String arg3) { Log.i(TAG, "arg1="+arg1+"arg2="+arg2+"arg3="+arg3); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.app_logo, "您有新消息", System.currentTimeMillis()); Intent i = new Intent(); i.setAction(Intent.ACTION_VIEW); i.setData(Uri.parse("http://fxv811.groupfly.cn/MobileAndroid.aspx")); PendingIntent contentIntent = PendingIntent.getActivity(context, 100, i, 0); notification.setLatestEventInfo(context, arg1, arg2, contentIntent); notification.flags = Notification.FLAG_AUTO_CANCEL; nm.notify(100, notification); } @Override public void onSetTags(Context arg0, int arg1, List<String> arg2, List<String> arg3, String arg4) { } @Override public void onUnbind(Context arg0, int arg1, String arg2) { } } <file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import com.shopnum1.distributionportal.util.HttpConn; import com.shopnum1.distributionportal.util.MyApplication; import java.io.IOException; import java.text.DecimalFormat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.graphics.Color; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.ColorDrawable; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.ImageLoader; public class FindActivity extends Activity { private HttpConn httpget = new HttpConn(); private int Score, Score2; private String Photo; // 用户头像地址 private ImageView userImg; private MediaPlayer mediaPlayer; private JSONArray ProductList; private ListAdapter adapter; //商品适配器 private Dialog pBar; //加载进度 private int IsNowDay = -1; // 当天是否已签到 0未签到,1已签到 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.member_score); } @Override protected void onResume() { if (HttpConn.isNetwork) { if (HttpConn.isLogin) if (HttpConn.cartNum > 0) { ((TextView) findViewById(R.id.num)) .setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.num)) .setText(HttpConn.cartNum + ""); } else { ((TextView) findViewById(R.id.num)) .setVisibility(View.GONE); } } else { httpget.setNetwork(this); // 设置网络 } initLayout(); super.onResume(); } //初始化 public void initLayout() { //首页 findViewById(R.id.imageButton1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(FindActivity.this, MainActivity.class)); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } }); //类目 findViewById(R.id.imageButton2).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (HttpConn.isLogin) { startActivity(new Intent(getBaseContext(),EntityshopActivity.class)); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); } else { Intent intent = new Intent(getApplicationContext(),UserLogin.class); intent.putExtra("cart", ""); startActivity(intent); } if (!HttpConn.isNetwork) finish(); } }); // 购物车 ((RelativeLayout) findViewById(R.id.imageButton3)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (HttpConn.isLogin) { startActivity(new Intent(getBaseContext(), CartActivity.class)); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } else { Intent intent = new Intent(getApplicationContext(), UserLogin.class); intent.putExtra("cart", ""); startActivity(intent); } if (!HttpConn.isNetwork) finish(); } }); // 个人中心 ((RelativeLayout) findViewById(R.id.imageButton4)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (HttpConn.isLogin) { startActivity(new Intent(getBaseContext(), MemberActivity.class)); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); } else { Intent intent = new Intent(getApplicationContext(),UserLogin.class); intent.putExtra("person", ""); startActivity(intent); } if (!HttpConn.isNetwork) finish(); } }); //返回 ((ImageView) findViewById(R.id.scroe_back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); // 用户头像 userImg = (ImageView) findViewById(R.id.user_head); if(HttpConn.getScore){ ((Button) findViewById(R.id.sign)).setBackgroundResource(R.drawable.sign1); } else { ((Button) findViewById(R.id.sign)).setBackgroundResource(R.drawable.sign); } //获取数据 getData(); getList(); // 判断用户今日是否已签到 getMemSign(); } //获取用户信息 public void getData(){ ((TextView)findViewById(R.id.username)).setText(HttpConn.UserName); pBar = new Dialog(this, R.style.dialog); pBar.setContentView(R.layout.progress); pBar.show(); new Thread(){ public void run(){ Message msg = Message.obtain(); msg.what = 1; try { StringBuffer result = httpget.getArray("/api/accountget/?MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); Photo = new JSONObject(result.toString()).getJSONObject("AccoutInfo").getString("Photo"); Score = new JSONObject(result.toString()).getJSONObject("AccoutInfo").getInt("Score"); msg.obj = "1"; } catch (JSONException e) { msg.obj = "0"; e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } //获取用户信息 public void getMemSign(){ new Thread(){ public void run(){ Message msg = Message.obtain(); msg.what = 0; try { StringBuffer result = httpget.getArray1("/Api/AppAPI/AppPublic.ashx?Method=SearchMemSign&MemLoginID=" + HttpConn.username); if (result != null && !("").equals(result) && !("null").equals(result)) { boolean IsSuccess = new JSONObject(result.toString()).getBoolean("IsSuccess"); if (IsSuccess) { IsNowDay = new JSONObject(result.toString()).getJSONArray("Data").getJSONObject(0).getInt("IsNowDay"); if (IsNowDay != -1 && IsNowDay == 1) { msg.obj = "1"; } else { msg.obj = "0"; } } else { msg.obj = "0"; } } else { msg.obj = "0"; } } catch (JSONException e) { msg.obj = "0"; e.printStackTrace(); } handler.sendMessage(msg); } }.start(); } //签到 public void scoreSign(){ ((Button) findViewById(R.id.sign)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(!HttpConn.getScore){ new Thread(){ public void run(){ try { httpget.getArray("/api/memberscoreupdate/?Score=10&MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); StringBuffer result = httpget.getArray("/api/accountget/?MemLoginID=" + HttpConn.username + "&AppSign=" + HttpConn.AppSign); Score2 = new JSONObject(result.toString()).getJSONObject("AccoutInfo").getInt("Score"); Message msg = Message.obtain(); msg.what = 2; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } } }); } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: String strObj = (String) msg.obj; if (strObj != null && !("").equals(strObj)) { if (strObj.equals("0")) { HttpConn.getScore = false; ((Button) findViewById(R.id.sign)).setBackgroundResource(R.drawable.sign); } else if (strObj.equals("1")) { HttpConn.getScore = true; ((Button) findViewById(R.id.sign)).setBackgroundResource(R.drawable.sign1); } } else { HttpConn.getScore = false; ((Button) findViewById(R.id.sign)).setBackgroundResource(R.drawable.sign); } pBar.dismiss(); break; case 1: String str = (String) msg.obj; if (str != null && !("").equals(str) && !("null").equals(str)) { ((TextView)findViewById(R.id.score)).setText("积分" + Score); // 设置用户头像 if (Photo == null || Photo.equals("") || Photo.equals("null")) { userImg.setImageResource(R.drawable.user_head); } else { if (HttpConn.showImage) { String userImgUrl; if (Photo.startsWith("~")) { userImgUrl = HttpConn.urlName + Photo.substring(1); ImageLoader.getInstance().displayImage(userImgUrl, userImg, MyApplication.options); } else { ImageLoader.getInstance().displayImage(HttpConn.urlName + Photo, userImg, MyApplication.options); } } else { userImg.setImageResource(R.drawable.user_head); } } } else { Toast.makeText(getApplicationContext(), "获取用户信息失败!", Toast.LENGTH_SHORT).show(); } scoreSign(); break; case 2: if(Score2 > Score){ HttpConn.getScore = true; ((TextView)findViewById(R.id.score)).setText("积分" + Score2); ((Button) findViewById(R.id.sign)).setBackgroundResource(R.drawable.sign1); startAnim(); } else { Toast.makeText(FindActivity.this, "今天已签到,明天再来吧!", Toast.LENGTH_SHORT).show(); HttpConn.getScore = true; } break; case 3: GridView gridview = (GridView)findViewById(R.id.gridview); gridview.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter = new ListAdapter(); gridview.setAdapter(adapter); pBar.dismiss(); gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { try { Intent intent = new Intent(getBaseContext(), ProductDetails.class); intent.putExtra("guid", ProductList.getJSONObject(arg2).getString("Guid")); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); break; default: break; }; super.handleMessage(msg); } }; private void startAnim(){ final ImageView imgv = (ImageView)findViewById(R.id.imgv); final AnimationDrawable draw = (AnimationDrawable) imgv.getBackground(); initBeepSound(); mediaPlayer.start(); draw.start(); int duration = 0; for(int i = 0; i < draw.getNumberOfFrames(); i++){ duration += draw.getDuration(i); } new Handler().postDelayed(new Runnable() { public void run() { draw.stop(); imgv.setVisibility(View.GONE); } }, duration); } private void initBeepSound() { if (mediaPlayer == null) { setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(beepListener); AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(0.10f, 0.10f); mediaPlayer.prepare(); } catch (IOException e) { mediaPlayer = null; } } } private final OnCompletionListener beepListener = new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.seekTo(0); } }; //获取积分商品 public void getList(){ new Thread(){ public void run(){ try { StringBuffer result = httpget.getArray("/api/GetScoreProductList?AppSign=" + HttpConn.AppSign); ProductList = new JSONObject(result.toString()).getJSONArray("Data"); Message msg = Message.obtain(); msg.what = 3; handler.sendMessage(msg); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } //商品适配器 public class ListAdapter extends BaseAdapter { @Override public int getCount() { return ProductList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg1) { return arg1; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.product_item2, null); holder = new ViewHolder(); holder.text1 = (TextView) convertView.findViewById(R.id.textView1); holder.text2 = (TextView) convertView.findViewById(R.id.textView2); holder.text3 = (TextView) convertView.findViewById(R.id.textView3); holder.text4 = (TextView) convertView.findViewById(R.id.textView4); holder.imageview = (ImageView) convertView.findViewById(R.id.imageView1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { holder.text1.setText(ProductList.getJSONObject(position).getString("Name")); holder.text2.setText("¥" + new DecimalFormat("0.00").format(ProductList.getJSONObject(position).getDouble("ShopPrice"))); holder.text3.setText("¥" + new DecimalFormat("0.00").format(ProductList.getJSONObject(position).getDouble("MarketPrice"))); holder.text4.setVisibility(View.VISIBLE); holder.text4.setText("积分可抵" + new DecimalFormat("0.00").format(ProductList.getJSONObject(position).getDouble("SocrePrice")) + "元"); if(HttpConn.showImage) ImageLoader.getInstance().displayImage(ProductList.getJSONObject(position).getString("OriginalImge"), holder.imageview, MyApplication.options); } catch (JSONException e) { e.printStackTrace(); } return convertView; } } static class ViewHolder { ImageView imageview; TextView text1, text2, text3, text4; } }<file_sep>package com.shopnum1.distributionportal; import com.shopnum1.distributionportal.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class SearchActivity2 extends Activity { private JSONArray CatagoryList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city_list); ((TextView) findViewById(R.id.title)).setText(getIntent().getStringExtra("title")); ((LinearLayout) findViewById(R.id.back)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); try { CatagoryList = new JSONArray(getIntent().getStringExtra("CatagoryList3")); JSONObject object = new JSONObject(); object.put("Name", "其它商品"); object.put("ID", getIntent().getStringExtra("typeid")); CatagoryList.put(object); } catch (JSONException e) { e.printStackTrace(); } addList(); } //一级分类列表 public void addList(){ ListView listview = (ListView)findViewById(R.id.listview); listview.setSelector(new ColorDrawable(Color.TRANSPARENT)); listview.setAdapter(new CatagoryAdapter()); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) { try { String name = CatagoryList.getJSONObject(position).getString("Name"); String id = CatagoryList.getJSONObject(position).getString("ID"); Intent intent = new Intent(getApplicationContext(), SearchResult.class); intent.putExtra("title", name); intent.putExtra("type", "list"); intent.putExtra("typeid", Integer.parseInt(id)); intent.putExtra("searchstr", ""); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); } //列表适配器 class CatagoryAdapter extends BaseAdapter{ @Override public int getCount() { return CatagoryList.length(); } @Override public Object getItem(int arg0) { return arg0; } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.city_item, null); convertView.setBackgroundResource(R.drawable.searchbg2); } try { ((TextView)convertView.findViewById(R.id.name)).setText(CatagoryList.getJSONObject(position).getString("Name")); } catch (JSONException e) { e.printStackTrace(); } return convertView; } } }
112b0573558b0c7f646fcba52d45cb70c96a49c2
[ "Java", "Gradle" ]
36
Java
ls895977/Quanqiugogou
b66a491ba63c1157bd43bbb89f1ce30f296a7554
9b719f058d9f028e4934781d0b387cf99dc9d72e
refs/heads/master
<file_sep># Wine Classification-Scikit-Learn Python code to classify "wine quality" as good or bad- RandomForestClassifier, SVM Classifier, MLP Classifier The csv format of the provided dataset was downloaded from the link: https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/ This python code uses various libraries provided by python like pandas,seaborn,scikit-learn. Scikit-learn is probably the most useful library for machine learning in Python. It is on NumPy, SciPy and matplotlib, this library contains a lot of effiecient tools for machine learning and statistical modeling including classification, regression, clustering and dimensionality reduction. ** Various code in the comments (#comment) can also be executed by simply removing the "#" in front of them. ** Details of dataset Features---->fixed acidity;"volatile acidity";"citric acid";"residual sugar";"chlorides";"free sulfur dioxide";"total sulfur dioxide";"density";"pH";"sulphates";"alcohol" Response variable---->"quality" ** Steps involved 1) Import all the necessary libraries 2) Load the datset using pandas 2) Pre-processing the data 2.1) Using pandas.cut we segment and sort data values into bins, labels are set as 'bad' or 'good' 2.2) Using LabelEncoder we set the labels as 0-bad wine & 1-good wine 3) Now divide the dataset into response variable and feature variables 4) Scale the training data using StandardScaler 5) Use the RandomForestClassifier to develop a machine learning model which trains the data 6) Predict using the test data 7) To check the model performance use classification_repot, confusion_matrix & accuracy_score 8) Repeat steps 5-7 for different classifiers like SVMClassifier & MLPClassifier 9) Later given is an example of the model predicting a new data using the RandomForestClassifier <file_sep>import pandas as pd import seaborn as sns # for graphs and visualizations import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC from sklearn import svm from sklearn.neural_network import MLPClassifier from sklearn.metrics import confusion_matrix,classification_report,accuracy_score from sklearn.preprocessing import StandardScaler,LabelEncoder from sklearn.model_selection import train_test_split # % matplotlib inline -- to be used in jupyter notebook wine=pd.read_csv("winequality-red.csv",sep=';') #print(wine.head()) #print(wine.info()) #print(wine.isnull().sum()) ''' Pre-processing data''' bins=(2,6.5,8) group_names=['bad','good'] wine['quality']=pd.cut(wine['quality'],bins=bins,labels=group_names) #print(wine['quality'].unique) label_quality=LabelEncoder() wine['quality']=label_quality.fit_transform(wine['quality']) #print(wine.head()) #print(wine['quality'].value_counts()) #print(sns.countplot(wine['quality'])) ''' Separate dataset as response variable and feature variables''' X=wine.drop('quality',axis=1) # all variables except quality variable forms the feature variables y=wine['quality'] # Train,test and split data X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42) # Apply standard scaling to get optimized result sc=StandardScaler() X_train=sc.fit_transform(X_train) X_test=sc.transform(X_test) ''' RANDOM FOREST CLASSIFIER ''' rfc=RandomForestClassifier(n_estimators=200) rfc.fit(X_train,y_train) # fit the training data into the model pred_rfc=rfc.predict(X_test) # predict using the test data #print(pred_rfc[:10]) ''' checking the model performance ''' print("Classification Report:\n",classification_report(y_test,pred_rfc)) # y_test v/s pred_rfc print("Confusion Matrix is:\n", confusion_matrix(y_test,pred_rfc)) print("Accuracy Score is:\n",accuracy_score(y_test,pred_rfc)) ''' SVM Classifier ''' svmc=svm.SVC() svmc.fit(X_train,y_train) pred_svmc=svmc.predict(X_test) print("Classification Report:\n",classification_report(y_test,pred_svmc)) # y_test v/s pred_rfc print("Confusion Matrix is:\n", confusion_matrix(y_test,pred_svmc)) ''' MULTILAYER PERCEPTRON CLASSIFIER ''' mlpc=MLPClassifier(hidden_layer_sizes=(11,11,11),max_iter=500) mlpc.fit(X_train,y_train) pred_mlpc=mlpc.predict(X_test) print("Classification Report:\n",classification_report(y_test,pred_mlpc)) # y_test v/s pred_rfc print("Confusion Matrix is:\n", confusion_matrix(y_test,pred_mlpc)) ''' Prediction of a new dataset ''' Xnew=[[7.3,0.58,0.00,2.0,0.065,15.0,21.0,0.9946,3.36,0.47,10.0]] Xnew=sc.transform(Xnew) ynew=rfc.predict(Xnew) print("\n\nPredicted label:",ynew,"\n") #the output is 0, meaning its a bad wine
94fbc31163b1d9a974e592ff2e94ca96ee0ee4df
[ "Markdown", "Python" ]
2
Markdown
NakulLakhotia/Wine-Quality-Classification
36b6163f77664707ec431b78a2214ad8cbe84435
38c87739762aae9a6b30eedc555eafec26ffbc48
refs/heads/main
<file_sep>from bs4 import BeautifulSoup import requests import discord from discord.ext import commands import time import datetime from currency_converter import CurrencyConverter c = CurrencyConverter() # Bot Token TOKEN = 'YOUR TOKEN <PASSWORD>' client = commands.Bot(command_prefix ='.') # Boot Message @client.event async def on_ready(): print("Titan Notifier Monitors Online!") # Setting Command @client.command() async def displayembeds(ctx): if ctx.channel.name != 'supreme-monitors': return else: await ctx.message.delete() # Supreme New York Shop supremeUrl supremeUrl = 'https://www.supremenewyork.com/shop' r = requests.get(supremeUrl) supremeContent = r.content # Supreme Shop Soup supremeSoup = BeautifulSoup(supremeContent, 'html.parser') supremeScroller = supremeSoup.find('ul', id='shop-scroller') # All List Items In Scroller listItems = supremeScroller.find_all('li') for item in listItems: itemAnchor = item.find('a') itemLink = itemAnchor.get('href') # Product Link productLinkFinal = f"https://www.supremenewyork.com{itemLink}" productRequest = requests.get(productLinkFinal) productContent = productRequest.content # Product Link Soup productSoup = BeautifulSoup(productContent, 'html.parser') productHeadings = productSoup.find_all('h1') productIndex1 = productHeadings[1] # Product Title productTitle = productIndex1.get_text() findProductPrice = productSoup.find('p', class_='price') # Product Price productPrice = findProductPrice.text priceRemoveComma = productPrice.replace(',', '') priceRemoveYen = priceRemoveComma.replace('¥', '') productPriceUSD = c.convert(priceRemoveYen, 'JPY', 'USD') productPriceUSD = round(productPriceUSD, 2) productImages = productSoup.find_all('img') productImages1 = productImages[0] # Product Image Link images = productImages1.get('src') # Creating Embed embed = discord.Embed( title = productTitle, url=productLinkFinal, colour = discord.Colour.red() ) # Getting Current Date and Time now = datetime.datetime.utcnow() timeNow = now.strftime('%H:%M:%S UTC on %A, %B the %dth, %Y') # Editing Embed embed.set_thumbnail(url=f"https:{images}") embed.add_field(name='Price', value=f'{productPrice}, ${productPriceUSD}', inline=True) embed.set_footer(text=f'{timeNow}\n© github.com/1nsaNeDynamic', icon_url='') # Sending Embed await ctx.send(embed = embed) time.sleep(1) client.run(TOKEN) <file_sep>from bs4 import BeautifulSoup import requests import time import datetime from currency_converter import CurrencyConverter c = CurrencyConverter() # Supreme New York Shop supremeUrl supremeUrl = 'https://www.supremenewyork.com/shop' r = requests.get(supremeUrl) supremeContent = r.content # Supreme Shop Soup supremeSoup = BeautifulSoup(supremeContent, 'html.parser') supremeScroller = supremeSoup.find('ul', id='shop-scroller') # All List Items In Scroller listItems = supremeScroller.find_all('li') for item in listItems: itemAnchor = item.find('a') itemLink = itemAnchor.get('href') # Product Link productLinkFinal = f"https://www.supremenewyork.com{itemLink}" productRequest = requests.get(productLinkFinal) productContent = productRequest.content # Product Link Soup productSoup = BeautifulSoup(productContent, 'html.parser') productHeadings = productSoup.find_all('h1') productIndex1 = productHeadings[1] # Product Title productTitle = productIndex1.get_text() findProductPrice = productSoup.find('p', class_='price') # Product Price productPrice = findProductPrice.text priceRemoveComma = productPrice.replace(',', '') priceRemoveYen = priceRemoveComma.replace('¥', '') productPriceUSD = c.convert(priceRemoveYen, 'JPY', 'USD') productPriceUSD = round(productPriceUSD, 2) productImages = productSoup.find_all('img') productImages1 = productImages[0] # Product Image Link images = productImages1.get('src') # Getting Current Date and Time now = datetime.datetime.utcnow() timeNow = now.strftime('%H:%M:%S UTC on %A, %B the %dth, %Y') print(f""" ===================================== Supreme Monitors {productTitle} {productLinkFinal} Price: ${productPriceUSD}, {productPrice} Updated: {timeNow} © github.com/1nsaNeDynamic """) time.sleep(1)
617bba639e83503c23a74b6e4213c90b9271fc61
[ "Python" ]
2
Python
1nsaNeDynamic/supremeMonitors
7052ed6832e60d8c5c937723e917d164239ca291
098801060401e3fd86430226f73eb812afb1d818
refs/heads/master
<file_sep>package pages; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import driver.BaseDriver; import pageobjects.PostReferralRequestPO; import utilitymethods.UtilityMethods; public class PostOrderConfirmPage extends BaseDriver { public static FirefoxDriver driver ; static Properties allInputValue; @BeforeTest public static void Start() throws Exception { driver = launchApp(); allInputValue = UtilityMethods.getPostPropValues(); PageFactory.initElements(driver, PostReferralRequestPO.class); } private static FirefoxDriver launchApp() { // TODO Auto-generated method stub return null; } public static void validateOperatorLogo() { WebElement operatorLogo = driver.findElement(By.xpath("//img[@alt='post']")); UtilityMethods.DisplayEnableValidator(operatorLogo, "NotEqual","Post Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(operatorLogo,"src",allInputValue.getProperty("tele2Logo"),"Post Operator Logo"); } public static void validateCompanyLogo() { WebElement companyLogo = driver.findElement(By.xpath("//img[@alt='Cisco Jasper']")); UtilityMethods.DisplayEnableValidator(companyLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(companyLogo,"src",allInputValue.getProperty("tele2CompanyLogo"),"Cisco Jasper Company Logo"); } public static void SectionOneTextValidation() { UtilityMethods.StringValidation(driver.findElement(By.xpath("//h2")).getText(), "Order IoT Starter Kit", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@class='order-status iot-kit-info']//span[@class='bl-status']")).getText(), "Your Information", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@class='order-status iot-kit-ship']//span[@class='bl-status']")).getText(), "Shipping", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@class='order-status iot-kit-pay']//span[@class='bl-status']")).getText(), "Review & Confirm", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//h4")).getText(), "Order Summary", "equalsignorecase"); } public static void SectionTwoTextValidation() { UtilityMethods.StringValidation(driver.findElement(By.xpath("//p[contains(.,'IoT')]")).getText(), "IoT Starter Kit", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//li[contains(.,'Test')]")).getText(), "3 Test SIMs", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//li[contains(.,'30')]")).getText(), "30MB per SIM per month", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//li[contains(.,'50')]")).getText(), "50 SMS per SIM per month", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//li[contains(.,'Post')]")).getText(), "Full access to Post Control Centre", "equalsignorecase"); } public static void SectionThreeTextValidation() { UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@class='col-xs-8 clr-black']")).getText(), "Shipping", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//p[text()='Included']")).getText(), "Included", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@class='ship_wrap clearfix']//h5")).getText(), "Shipping", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@class='payment_wrap clearfix']//h5")).getText(), "Billing", "equalsignorecase"); } public static void shippingEditButton() { UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//div[@class='ship_wrap clearfix']//a")), "NotEqual", "Edit button in shipping"); } public static void billingEditButton() { UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//div[@class='payment_wrap clearfix']//a")), "NotEqual", "Edit button in Billing"); } } <file_sep>package pages; import java.io.IOException; import java.io.PrintWriter; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterClass; import java.util.List; import java.util.Random; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.testng.annotations.*; import static org.testng.Assert.*; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import pageobjects.BellHomePagePO; import utilitymethods.UtilityMethods; public class LinkValidation { static WebDriver driver; public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://chinaun9c0nd.devm2m.com/?clLocaleCode=en"); System.out.println(""+driver.getTitle()); String temp =driver.findElement(By.tagName("body")).getText(); try { PrintWriter writer = new PrintWriter("China_Unicom_English.doc", "UTF-8"); writer.println(temp); writer.close(); } catch (IOException e) {} System.out.println(""+temp); /* System.out.println(""+GenerateRandomNum(5)+""); System.out.println(""+GenerateRandomString(5)+""); System.out.println(""+GenerateRandomAlphaNumeric(10)+"");*/ /*System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver= new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://bell.devm2m.com/"); Thread.sleep(5000); PageFactory.initElements(driver, BellHomePagePO.class); LinkValidation.PageNavigationValidation(BellHomePagePO.M2MDotCom, BellHomePagePO.M2MDotComFindElement,"M2M Developer Kits from the World’s Leading Mobile Operators"); */ /*driver.navigate().refresh(); driver.findElement(By.xpath("//input[@id='login']")).sendKeys("<PASSWORD>"); driver.findElement(By.xpath("//input[@value='Check Inbox']")).click(); Thread.sleep(3500); //driver.findElement(By.xpath("//a[@id='lrefr']/span")).click(); //Thread.sleep(3500); driver.findElement(By.xpath(".//*[@id='m1']//a[@class='lm']")).click(); Thread.sleep(3500); driver.findElement(By.xpath(".//*[@id='mailmillieu']//a[@rel='nofollow']")).click(); Thread.sleep(3500); */ /* /* String parentHandle = driver.getWindowHandle(); Thread.sleep(1500); driver.findElement(By.xpath("//input[@id='login']")).sendKeys("<PASSWORD>"); driver.findElement(By.xpath("//input[@value='Check Inbox']")).click(); Thread.sleep(3500); driver.findElement(By.xpath(".//*[@id='m1']//span[contains(.,'Your referral code to order a Post IoT M2M Developer Kit')]")).click(); Thread.sleep(1500); driver.findElement(By.xpath(".//*[@id='mailmillieu']//a[@rel='nofollow']")).click(); /*PageFactory.initElements(driver, Tele2ReferralRequestpagePO.class); UtilityMethods.PageNavigationValidation(Tele2ReferralRequestpagePO.M2MDotCom,Tele2ReferralRequestpagePO.selectKit,""); */ } public static String GenerateRandomNum(int length) { String alphabet = new String("0123456789"); int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<length; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static String GenerateRandomString(int length) { String alphabet = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //9 int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<length; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static String GenerateRandomAlphaNumeric(int length){ String alphabet =new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //9 int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<length; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static void PageNavigationValidation(WebElement linkbutton,WebElement targetElement, String PageTitile) throws InterruptedException { System.out.println("The Link button xpath is :"+linkbutton+""); System.out.println("The Find button xpath is :"+targetElement+""); String parentHandle=""; linkbutton.click(); System.out.println("link button clicked"); Thread.sleep(3000); parentHandle = driver.getWindowHandle(); try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); System.out.println("" +driver.getTitle()); if (driver.getTitle().equals(PageTitile)) { if(!targetElement.isDisplayed()) { System.out.println("Page Rredirection Failed for"+linkbutton.getText()+""); //Assert.assertEquals(true, FindElement.isDisplayed()); } } /* else { System.out.println("" +driver.getTitle()); //Assert.assertEquals(driver.getTitle(), PageTitile); }*/ } // driver.navigate().back(); driver.switchTo().window(parentHandle); } catch(Exception e) { System.out.println("Condition fail"); } } } <file_sep>package test; import java.awt.AWTException; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import bell.BellBillingInfo; import bell.BellControlCenter; import bell.BellHomePage; import bell.BellOrderSummary; import bell.BellReferralRequestPage; import bell.BellReferralRequestThankYou; import bell.BellReviewConfirm; import bell.BellShippingInfo; import bell.BellTrackOrder; import bell.BellYourInfo; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import pages.AdminOperation; import pages.EmailIntegration; import utilitymethods.UtilityMethods; import driver.BaseDriver; public class BellEndToEndExtended extends BaseDriver { public static WebDriver driver; static Properties allInputValue; public static ExtentReports extent; public static ExtentTest testcase; @BeforeTest public static void DeletingPreviousEmail() { //EmailIntegration.DeleteAllEmail(); extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/Advanced.html", true ); } @AfterMethod public static void getResult(ITestResult result) { if(result.getStatus()==ITestResult.FAILURE) { testcase.log(LogStatus.FAIL, result.getName()); } if(result.getStatus()==ITestResult.SUCCESS) { testcase.log(LogStatus.PASS, result.getName()); } extent.endTest(testcase); } @Test(priority=1) public static void BrowserIntilation() throws Exception { testcase = extent.startTest("Intialise Browser", "opening Browser and loading Base Home Page URL"); testcase.log(LogStatus.INFO, "opening Browser and loading base Home Page URL"); driver = BellHomePage.start(); } @Test(priority=2) public static void HomePageBellLogo() { testcase = extent.startTest("Home Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellHomePage.validateOperatorLogo(); } @Test(priority=3) public static void HomePageCiscoLogo() { testcase = extent.startTest("Home Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellHomePage.validateCompanyLogo(); } @Test(priority=4) public static void HomePageSecOneTextValidation() { testcase = extent.startTest("Home Page Section 1 ", "Section One Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellHomePage.sectionOneIotStarterKitBellValidation(); } @Test(priority=5) public static void HomePageTrackOrderValidation() throws InterruptedException { testcase = extent.startTest("Home Page Track Order", "Validating track Order Button"); testcase.log(LogStatus.INFO, "Validating String,PlaceHolder,Enabled,Displayed"); BellHomePage.sectionOneIotStarterKitTrackOrderValidation(); } @Test(priority=6) public static void HomePageReferralCodeValidation() throws InterruptedException { testcase = extent.startTest("Home Page Referral Code", "Validating ReferralCode"); testcase.log(LogStatus.INFO, "Validating String,PlaceHolder,Enabled,Displayed"); BellHomePage.sectionOneIotStarterKitEnterReferralCodeValidation(); } @Test(priority=7) public static void HomePageTrackOrderErrorValidation() throws InterruptedException { testcase = extent.startTest("Home Page Track Order pop up Error message and Close Icon", "Validating Track Order Error Message and Close Icon"); testcase.log(LogStatus.INFO, "Validating Error Message For Trak Order CLose Icon"); BellHomePage.sectionOneIotStarterKitTrackOrderErrorValidation(); } @Test(priority=8) public static void HomePageEnterrefrralCodeErrorvalidation() throws InterruptedException { testcase = extent.startTest("Home Page Enter Referral Code Error Message and Close Icon", "Validating Enter Referral Code Error Message and Close Icon"); testcase.log(LogStatus.INFO, "Validating Error Message For Trak Order CLose Icon"); BellHomePage.sectionOneIotStarterKitReferralCodeErrorValidation(); } @Test(priority=9) public static void HomePageSecTwoContentValidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Sim Content ", "Section Two Content Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesContentvalidation(); } @Test(priority=10) public static void HomePageSecTwoWhatThekitIncludesToolsvalidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Tools Content ", "Section Two Tools Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesToolsvalidation(); } @Test(priority=11) public static void HomePageSecTwoWhatThekitIncludesCentervalidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Center Content ", "Section Two Center Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesCentervalidation(); } @Test(priority=12) public static void HomePagesectionTwoWhatThekitIncludesSuppportvalidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Support Content ", "Section Two Support Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesSuppportvalidation(); } @Test(priority=13) public static void HomePagesectionThreeHowItWorksValidation() { testcase = extent.startTest("Home Page Section 3 How It Works", "Section Three How It Works Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellHomePage.sectionThreeHowItWorksValidation(); } @Test(priority=14) public static void HomePagesectionFourWhatIsIotValidation() { testcase = extent.startTest("Home Page Section 4 IoT From Bell ", "Section Four IoT From Bell Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFourWhatIsIotValidation(); } @Test(priority=15) public static void HomePagesectionOneLinkvalidation() throws Exception { testcase = extent.startTest("Home Page Section 1 Scrolling Link Validation ", "Section One Scrolling Link Validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Scrolling"); BellHomePage.sectionOneLinkvalidation(); } @Test(priority=16) public static void HomePagesectionFiveWithBell() { testcase = extent.startTest("Home Page Section 5 With Bell", "Section Five With Bell Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellHomePage.sectionFiveWithBell(); } @Test(priority=17) public static void HomePagesectionFiveLTE() { testcase = extent.startTest("Home Page Section 5 With Bell LTE ", "Section Five With Bell 1 Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFiveLTE(); } @Test(priority=18) public static void HomePagesectionFivePartners() { testcase = extent.startTest("Home Page Section 5 With Bell Partners", "Section Five With Bell 2 Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFivePartners(); } @Test(priority=19) public static void HomePagesectionFiveEndToEnd() { testcase = extent.startTest("Home Page Section 5 With Bell EndToEnd", "Section Five With Bell 2 Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFiveEndToEnd(); } @Test(priority=20) public static void HomePageLearnMoreFromBell() throws InterruptedException { testcase = extent.startTest("Home Page Section Learn More Link", "Learn More Link validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Redirection"); BellHomePage.sectionFourLearnMoreFromBell(); } @Test(priority=21) public static void HomePageSecOneReferralRequesButton() throws InterruptedException { testcase = extent.startTest("Home Page section One Referral Request", "Referral Request Link validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Redirection"); BellHomePage.sectionOneReferralRequestvalidation(); } @Test(priority=22) public static void HomePageM2MDotComvalidation() throws InterruptedException, IOException { testcase = extent.startTest("Home Page Section M2M.com Link", "M2M.com Link validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Redirection"); BellHomePage.sectionTwoM2MDotCom(); } @Test(priority=23) public static void HomePageSectwoReferralRequestButton() throws InterruptedException, AWTException { Thread.sleep(2000); testcase = extent.startTest("Home Page section Two Referral Request", "Referral Request Link validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Redirection"); BellHomePage.sectionTwoReferralRequestvalidation(); } @Test(priority=24) public static void HomePageBellLogoValidation() throws InterruptedException { testcase = extent.startTest("Home Page Bell Logo Page Navigation", "Bell Logo Link validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Redirection"); BellHomePage.bellLogoValidation(); } @Test(priority=25) public static void sectionOneReferralRequestvalidation() throws Exception { UtilityMethods.sleep(4000); try {allInputValue=UtilityMethods.getBellPropValues();} catch (IOException e) {e.printStackTrace();} BrowserForUse=allInputValue.getProperty("Broswer"); if(BrowserForUse.equals("Chrome")||BrowserForUse.equals("IE")) { driver.navigate().forward(); UtilityMethods.sleep(4000); testcase = extent.startTest("Page Redirection To Referral Request Page", "Referral Request Page validation"); testcase.log(LogStatus.INFO, "Enabled,Displayed,Page Redirection"); BellHomePage.ReferralRequestButtonRedirection(); UtilityMethods.sleep(4000); } else { UtilityMethods.sleep(4000); testcase = extent.startTest("Page Redirection To Referral Request Page", "Referral Request Page validation"); testcase.log(LogStatus.INFO, "Enabled,Displayed,Page Redirection"); BellHomePage.ReferralRequestButtonRedirection(); UtilityMethods.sleep(4000); } } @Test(priority=26) public static void ReferralRequestBellLogo() throws Exception { BellReferralRequestPage.BrowserIntilation(); testcase = extent.startTest("Referral Request Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellReferralRequestPage.validateOperatorLogo(); } @Test(priority=27) public static void ReferralRequestCompanyLogo() { testcase = extent.startTest("Referral Request Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellReferralRequestPage.validateCompanyLogo(); } @Test(priority=28) public static void ReferralRequestTextValiadtion() { UtilityMethods.sleep(2000); testcase = extent.startTest("Referral Request Page ", "Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellReferralRequestPage.ReferralRequestTextValidation(); } @Test(priority=29) public static void ReferralrequestTextBoxDisplayedAndEnabled() { testcase = extent.startTest("Referral Request Page TextBox,DropDown Button,Radio Button", "Displayed and Enabled Validation"); testcase.log(LogStatus.INFO, "Validating All Text Box,Radio Button,Drop Down Button Displayed and Enabled"); BellReferralRequestPage.RequestReferralCodeTextBoxDisplayedAndEnabled(); } @Test(priority=30) public static void ReferralrequestLabelDisplayedAndEnabled() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } testcase = extent.startTest("Referral Request Page Label Text", "Displayed and Enabled,String Validation"); testcase.log(LogStatus.INFO, "String Validation, Displayed and Enabled "); BellReferralRequestPage.RequestReferralCodeLabelTextDisplayedAndEnabled(); } @Test(priority=31) public static void ReferralRequestPlaceHolderValidation() { testcase = extent.startTest("Referral Request Page TextBox,DropDown Button", "Place Holder Validation"); testcase.log(LogStatus.INFO, "PlaceHolder Validation"); BellReferralRequestPage.RequestReferralCodePlaceholderValidation(); } @Test(priority=32) public static void ReferralRequestValidInputValidation() { testcase = extent.startTest("Referral Request Page TextBox,DropDown Button", "Input Validation"); testcase.log(LogStatus.INFO, "Error Message Should not be displayed For Valid Input"); BellReferralRequestPage.ReferralRequestCodeValidInputValidation(); } @Test(priority=33) public static void ReferrakRequestRequiredFieldValidation() { testcase = extent.startTest("Referral Request Page TextBox,DropDown Button,Radio Button", "Required Filed Error Message Validation"); testcase.log(LogStatus.INFO, "Required Field Error Message Should be displayed FOr All TextBox,DropDown Button,Radio Button"); BellReferralRequestPage.ReferralRequestRequiredFieldValidation(); } @Test(priority=34) public static void ReferralrequestSpaceNotAllowedValiadation() { testcase = extent.startTest("Referral Request Page TextBox", "Space Not Allowed Error Message Validation"); testcase.log(LogStatus.INFO, "Space Not Allowed Error Message Should be displayed For TextBox"); BellReferralRequestPage.ReferralRequestSpaceNotAllowedValidation(); } @Test(priority=35) public static void ReferralRequestMaximumInputValidation() { BellReferralRequestPage.ReferralRequestMaximumInputValidation(); } @Test(priority=36) public static void ReferralRequestMinimumInputValidation() { BellReferralRequestPage.ReferralRequestMinimumInputValidation(); } @Test(priority=37) public static void ReferralRequestEmailValidation() { BellReferralRequestPage.ReferralRequestEmailValidation(); } @Test(priority=38) public static void ReferralRequestNumericFeild() { BellReferralRequestPage.ReferralRequestNumericFieldValidation(); } @Test(priority=39) public static void ReferralRequestBellLogoValidation() throws InterruptedException { BellReferralRequestPage.BellLogoValidation(); } @Test(priority=40) public static void ReferralRequestBellCaLinkvalidation() throws InterruptedException { BellReferralRequestPage.BellCALinkValidation(); } @Test(priority=41) public static void RferrralRequestcancelButton() throws InterruptedException { BellReferralRequestPage.ReferralrequestCancelButton(); } @Test(priority=42) public static void ReferralRequestButtonvalidation() throws InterruptedException { BellReferralRequestPage.RequestButtonValidation(); Thread.sleep(3000); } @Test(priority=43) public static void ThankYouBellLogo() throws Exception { try { Thread.sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } BellReferralRequestThankYou.BrowserIntilation(); testcase = extent.startTest("Referral Request Thank You Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellReferralRequestThankYou.validateOperatorLogo(); } @Test(priority=44) public static void ThankYouCiscoLogo() { testcase = extent.startTest("HReferral Request Thank You Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellReferralRequestThankYou.validateCompanyLogo(); } @Test(priority=45) public static void ThankYouTextvalidation() { BellReferralRequestThankYou.ThankYouTextValidation(); } @Test(priority=46) public static void ThankYouIOTvalidation() throws InterruptedException { BellReferralRequestThankYou.backToIOT(); } @Test(priority=47) public static void ThankYouBellPageRedirection() throws InterruptedException { BellReferralRequestThankYou.bellLogoValidation(); } @Test(priority=48) public static void ThankYouIOTPagevalidation() throws InterruptedException { BellReferralRequestThankYou.backToIOTPageValidation(); } @Test(priority=49) public static void CheckingReferralRequest() { EmailIntegration.CheckEmailReceived(); } @Test(priority=50) public static void DeletingPrevEmail() { EmailIntegration.DeleteAllEmail(); } @Test(priority=51) public static void ReferralRequestAdminApproval() throws InterruptedException { AdminOperation.AdminApproval(); } @Test(priority=52) public static void CheckingReferralCodeEmail() { EmailIntegration.CheckEmailReceived(); } @Test(priority=53) public static void VerifyingControlCenterURL() throws Exception { driver = BellControlCenter.start(); } @Test(priority=54) public static void CCDisplayedAndEnabledValidation() { BellControlCenter.CCDisplayedAndEnabledValidation(); } @Test(priority=55) public static void CCContentValidation() { BellControlCenter.CCContentValidation(); } @Test(priority=56) public static void CCPlaceHolderValidation() { BellControlCenter.CCPlaceHolderValidation(); } @Test(priority=57) public static void CCRequiredFieldValidation() { BellControlCenter.CCRequiredFieldValidation(); } @Test(priority=58) public static void CCUserNameMinMaxValidation() { BellControlCenter.CCUserNameMinMaxValidation(); } @Test(priority=59) public static void CCPasswordValidation() { BellControlCenter.CCPasswordValidation(); } @Test(priority=60) public static void InputValidation() { BellControlCenter.InputValidation(); } @Test(priority=61) public static void referralRequestDataValidation() { driver.navigate().refresh(); UtilityMethods.sleep(4000); try {BellYourInfo.intial();} catch (IOException e) {e.printStackTrace();} UtilityMethods.sleep(2000); BellYourInfo.referralRequestDataValidation(); } @Test(priority=62) public static void TermsOfServiceTextValidation() { BellYourInfo.TermsOfServiceTextValidation(); } @Test(priority=63) public static void TermsOfServicePopUpCloseIcon() { BellYourInfo.TermsOfServicePopUpCloseIcon(); } @Test(priority=64) public static void TermsOfServicePopUpCloseButton() { BellYourInfo.TermsOfServicePopUpCloseButton(); } @Test(priority=65) public static void TermsOfServicePDFDownload() throws AWTException { BellYourInfo.TermsOfServicePDFDownload(); } @Test(priority=66) public static void YourInfoBellLogo() { testcase = extent.startTest("Your Info Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellYourInfo.validateOperatorLogo(); } @Test(priority=67) public static void YourInfoCompanyLogo() { testcase = extent.startTest("Your Info Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellYourInfo.validateCompanyLogo(); } @Test(priority=68) public static void YourInfoTextValiadtion() { UtilityMethods.sleep(2000); BellYourInfo.ReferralRequestTextValidation(); } @Test(priority=69) public static void YourInfoTextBoxDisplayedAndEnabled() { BellYourInfo.RequestReferralCodeTextBoxDisplayedAndEnabled(); } @Test(priority=70) public static void YourInfoLabelDisplayedAndEnabled() { UtilityMethods.sleep(2000); BellYourInfo.RequestReferralCodeLabelTextDisplayedAndEnabled(); } @Test(priority=71) public static void YourInfoValidInputValidation() { BellYourInfo.ReferralRequestCodeValidInputValidation(); } @Test(priority=72) public static void YourInfoRequiredFieldValidation() { BellYourInfo.ReferralRequestRequiredFieldValidation(); } @Test(priority=73) public static void YourInfoSpaceNotAllowedValiadation() { BellYourInfo.ReferralRequestSpaceNotAllowedValidation(); } @Test(priority=74) public static void YourInfoMaximumInputValidation() { BellYourInfo.ReferralRequestMaximumInputValidation(); } @Test(priority=75) public static void YourInfoMinimumInputValidation() { BellYourInfo.ReferralRequestMinimumInputValidation(); } @Test(priority=76) public static void YourInfoEmailValidation() { BellYourInfo.ReferralRequestEmailValidation(); } @Test(priority=77) public static void YourInfoNumericFeild() { BellYourInfo.ReferralRequestNumericFieldValidation(); } @Test(priority=78) public static void YourInfoBellLogoValidation() throws InterruptedException { BellYourInfo.BellLogoValidation(); } @Test(priority=79) public static void YourInfoBellCaLinkvalidation() throws InterruptedException { BellYourInfo.BellCALinkValidation(); } @Test(priority=80) public static void YourInfocancelButton() throws InterruptedException { BellYourInfo.ReferralrequestCancelButton(); } @Test(priority=81) public static void YourInfocontinueButton() throws InterruptedException, IOException { BellYourInfo.RequestButtonValidation(); UtilityMethods.sleep(4000); } @Test(priority=82) public static void ShippingInfovalidateOperatorLogo() throws Exception { driver.navigate().refresh(); UtilityMethods.sleep(4000); try {BellShippingInfo.Start();} catch (IOException e) {e.printStackTrace();} //driver.navigate().refresh(); UtilityMethods.sleep(5000); testcase = extent.startTest("Shipping Info Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellShippingInfo.validateOperatorLogo(); } @Test(priority=83) public static void ShippingInfovalidateCompanyLogo() { testcase = extent.startTest("Shipping Info Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellShippingInfo.validateCompanyLogo(); } @Test(priority=84) public static void ShippingInfoTextvalidation() { BellShippingInfo.ShippingInfoTextvalidation(); } @Test(priority=85) public static void shippingInfoLabelText() { BellShippingInfo.shippingInfoLabelText(); } @Test(priority=86) public static void shippingInfoInputField() { BellShippingInfo.shippingInfoInputField(); } @Test(priority=87) public static void ShippingInfoLinkButton() { BellShippingInfo.ShippingInfoLinkButton(); } @Test(priority=88) public static void ShippingInfoRequiredFieldvalidatoin() { BellShippingInfo.ShippingInfoRequiredFieldvalidatoin(); } @Test(priority=89) public static void ShippingInfoSpaceNotAllowedvalidatoin() { BellShippingInfo.ShippingInfoSpaceNotAllowedvalidatoin(); } @Test(priority=90) public static void ShippingInfoMaximumInputValidation() { BellShippingInfo.ShippingInfoMaximumInputValidation(); } @Test(priority=91) public static void ShippingInfoMinimumInputValidation() { BellShippingInfo.ShippingInfoMinimumInputValidation(); } @Test(priority=92) public static void ShippingInfoBellLogoValidation() throws InterruptedException { BellShippingInfo.ShippingBellLogoValidation(); } @Test(priority=93) public static void ShippingInfoCancelButtonValidation() throws InterruptedException { BellShippingInfo.ShippingCancelButtonValidation(); } @Test(priority=94) public static void ShippingInfoBackButtonValidation() throws InterruptedException { BellShippingInfo.ShippingBackButtonValidation(); } @Test(priority=95) public static void ShippingInfoSendInputs() { BellShippingInfo.ShippingInfoSendInputs(); } @Test(priority=96) public static void BillingInfovalidateOperatorLogo() { UtilityMethods.sleep(4000); try {BellBillingInfo.Start();} catch (Exception e) {e.printStackTrace();} UtilityMethods.sleep(2000); testcase = extent.startTest("Billing Info Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellBillingInfo.validateOperatorLogo(); } @Test(priority=97) public static void BillingInfovalidateCompanyLogo() { testcase = extent.startTest("Billing Info Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellBillingInfo.validateCompanyLogo(); } @Test(priority=98) public static void BillingInfoTextvalidation() { BellBillingInfo.BillingInfoTextvalidation(); } @Test(priority=99) public static void BillingCardDetailsLabelText() { BellBillingInfo.BillingCardDetailsLabelText(); } @Test(priority=100) public static void BillingCardDetailsInputFieldValidation() { BellBillingInfo.BillingCardDetailsInputFieldValidation(); } @Test(priority=101) public static void BillingCheckBoxVaildation() { BellBillingInfo.BillingCheckBoxVaildation(); } @Test(priority=102) public static void BillingInfoLabelText() { BellBillingInfo.BillingInfoLabelText(); } @Test(priority=103) public static void BillingInfoInputField() { BellBillingInfo.BillingInfoInputField(); } @Test(priority=104) public static void BillingInfoRequiredFieldvalidatoin() { BellBillingInfo.BillingInfoRequiredFieldvalidatoin(); } @Test(priority=105) public static void BillingInfoSpaceNotAllowedvalidatoin() { BellBillingInfo.BillingInfoSpaceNotAllowedvalidatoin(); } @Test(priority=106) public static void BillingInfoMaximumInputValidation() { BellBillingInfo.BillingInfoMaximumInputValidation(); } @Test(priority=107) public static void BillingInfoMinimumInputValidation() { BellBillingInfo.BillingInfoMinimumInputValidation(); } @Test(priority=108) public static void BellLogoValidation() throws InterruptedException { BellBillingInfo.BellLogoValidation(); } @Test(priority=109) public static void CancelButtonValidation() throws InterruptedException { BellBillingInfo.CancelButtonValidation(); } @Test(priority=110) public static void BackButtonValidation() throws InterruptedException { BellBillingInfo.BackButtonValidation(); } @Test(priority=111) public static void BillingInfoSendInputs() { BellBillingInfo.BillingInfoSendInputs(); } @Test(priority=112) public static void ReviewConfirmOperatorLogo() { try { BellReviewConfirm.Start(); } catch (Exception e) { e.printStackTrace(); } UtilityMethods.sleep(4000); testcase = extent.startTest("Review and Confirm Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellReviewConfirm.validateOperatorLogo(); } @Test(priority=113) public static void ReviewConfirmCompanyLogo() { testcase = extent.startTest("Review and Confirm Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellReviewConfirm.validateCompanyLogo(); } @Test(priority=114) public static void ReviewConfirmHeadertextValidation() { BellReviewConfirm.HeadertextValidation(); } @Test(priority=115) public static void ReviewConfirmSectionOneTextValidation() { BellReviewConfirm.SectionOneTextValidation(); } @Test(priority=116) public static void ReviewConfirmShippingBillingAddressValidation() { BellReviewConfirm.ShippingBillingAddressValidation(); } @Test(priority=117) public static void ReviewConfirmEditButtons() { BellReviewConfirm.EditButtonsValidation(); } @Test(priority=118) public static void ReviewConfirmBellLogo() throws InterruptedException { BellReviewConfirm.BellLogoValidation(); } @Test(priority=119) public static void ReviewConfirmCancelButton() throws InterruptedException { BellReviewConfirm.CancelButtonValidation(); } @Test(priority=120) public static void ShippingEditButtonValidation() throws InterruptedException { BellReviewConfirm.ShippingEditButtonValidation(); } @Test(priority=121) public static void BillingEditButtonValidation() throws InterruptedException { BellReviewConfirm.BillingEditButtonValidation(); } @Test(priority=122) public static void ReviewConfirmButton() { BellReviewConfirm.ConfirmButtonClick(); } @Test(priority=123) public static void OrderSummaryBellLogo() { UtilityMethods.sleep(4000); try {BellOrderSummary.Start();} catch (Exception e) {e.printStackTrace();} UtilityMethods.sleep(4000); testcase = extent.startTest("Order Summary Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellOrderSummary.validateOperatorLogo(); } @Test(priority=124) public static void OrderSummaryCompanyLogo() { testcase = extent.startTest("Order Summary Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellOrderSummary.validateCompanyLogo(); } @Test(priority=125) public static void OrderSummaryHeadertextValidation() { BellOrderSummary.HeadertextValidation(); } @Test(priority=126) public static void orderSummaryShipBillAddressVAlidation() { BellOrderSummary.ShipBillAddressValidation(); } @Test(priority=127) public static void OrderSummarysectionTwoTextValidation() { BellOrderSummary.sectionTwoTextValidation(); } @Test(priority=128) public static void OrderSummarysectionThreeTextValidation() { BellOrderSummary.sectionThreeTextValidation(); } @Test(priority=129) public static void OrderSummaryBellLogoValidation() throws InterruptedException { BellOrderSummary.sectionOneBellLogoValidation(); } @Test(priority=130) public static void OrderSummaryBackToIOTValidation() throws InterruptedException { BellOrderSummary.sectionOneBackToIOTValidation(); } @Test(priority=131) public static void OrderSummaryTrackOrderValidation() throws InterruptedException { BellOrderSummary.sectionOneTrackOrderValidation(); } @Test(priority=132) public static void OrderSummaryhomePageLinkvalidation() throws InterruptedException { BellOrderSummary.homePageLinkvalidation(); } @Test(priority=133) public static void CheckingOrderSucessEmail() { EmailIntegration.CheckEmailReceived(); } @Test(priority=134) public static void AdminOrderFulFilling() throws InterruptedException { AdminOperation.AdminOrderFulfill(); } @Test(priority=135) public static void DeletingOrderSucessEmail() { EmailIntegration.DeleteAllEmail(); } @Test(priority=136) public static void TrackOrderPage() throws Exception { driver = BellTrackOrder.start(); } @Test(priority=137) public static void Trackorderpageredirection() throws InterruptedException { BellTrackOrder.TrackOrderValidPageRedirection(); } @Test(priority=138) public static void TrackOrderOperatorLogo() { testcase = extent.startTest("Track Order Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellTrackOrder.validateOperatorLogo(); } @Test(priority=139) public static void TrackOrderComapnyLogo() { testcase = extent.startTest("Track Order Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellTrackOrder.validateCompanyLogo(); } @Test(priority=140) public static void TrackOrderSectionOneText() { BellTrackOrder.SectionOneTextValidaion(); } @Test(priority=141) public static void TrackOrderSectionTwoText() { BellTrackOrder.SectionTwoTextvalidation(); } @Test(priority=142) public static void BackToIOT() { BellTrackOrder.BackToIOT(); } @Test(priority=143) public static void TrackOrderBellLogoHomePage() { BellTrackOrder.BellLogoHomePage(); } @Test(priority=144) public static void TrackOrderResendButton() { BellTrackOrder.ResendConfirmationButton(); } @Test(priority=145) public static void TrackOrderResendEmailVerification() { BellTrackOrder.CheckingOrderSuccessEmail(); } } <file_sep>package utilitymethods; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Properties; import java.util.List; import java.util.Random; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.openqa.selenium.NotFoundException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import driver.BaseDriver; public class UtilityMethods extends BaseDriver { public static String GenerateRandomNum(int length) { String alphabet = new String("0123456789"); int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<length; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static String GenerateRandomString(int length) { String alphabet = new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //9 int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<length; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static String GenerateRandomAlphaNumeric(int length){ String alphabet =new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); //9 int n = alphabet.length(); String result = new String(); Random r = new Random(); for (int i=0; i<length; i++) result = result + alphabet.charAt(r.nextInt(n)); return result; } public static void InputDataValidation(WebElement InputField,String Compare,String fieldType) { switch (fieldType.toLowerCase()) { case "textbox": String Base =InputField.getAttribute("value"); if(!Base.equals(Compare)) { System.out.println("The Value given in referral request form: "+Compare+" is not equal to"+Base+" in Your Info"); } break; case "dropdown": break; case "radiobutton": String BaseRB =InputField.getText(); if(!BaseRB.equals(Compare)) { System.out.println("The Value given in referral request form: "+Compare+" is not equal to"+BaseRB+" in Your Info"); } break; } } public static void waitForWebElement(WebElement element) { WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.elementToBeClickable(element)); } public static void waitForWebElementdriver(WebDriver driver,WebElement element) { WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.elementToBeClickable(element)); } public static void PageNavigationValidation(WebElement Linkbutton,WebElement FindElement, String PageTitile) throws InterruptedException { waitForWebElement(Linkbutton); //driver.navigate().refresh(); //System.out.println("The Link button xpath is :"+Linkbutton+""); //System.out.println("The Find button xpath is :"+FindElement+""); //System.out.println(""+ Linkbutton.getAttribute("href")); //System.out.println(" The Linkbutton is displayed :"+Linkbutton.isDisplayed()+""); //System.out.println(" The Linkbutton is enabled :"+Linkbutton.isEnabled()+""); //sleep(4000); Linkbutton.click(); //System.out.println("link button clicked"); sleep(5000); String parentHandle = driver.getWindowHandle(); try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); //System.out.println("" +driver.getTitle()); if (driver.getTitle().equals(PageTitile)) { waitForWebElement(FindElement); if(!FindElement.isDisplayed()) { System.out.println("Page Rredirection Failed for"+Linkbutton.getText()+""); } else { System.out.println("Page Redirection done"); driver.close(); } } } driver.switchTo().window(parentHandle); } catch(Exception e) { System.out.println("Condition fail :"+e+""); } } public static void ThankYouPageRedirection(WebElement Linkbutton,WebElement FindElement) { waitForWebElement(Linkbutton); Linkbutton.click(); waitForWebElement(FindElement); if(FindElement.isDisplayed()) { System.out.println("Page Redirection done"); driver.navigate().back(); } else if(!FindElement.isDisplayed()) { sleep(5000); System.out.println("Page Redirection done"); driver.navigate().back(); } else { System.out.println("Page Rredirection Failed for"+Linkbutton.getText()+""); driver.navigate().back(); } } public static void pageRedirection(WebElement Linkbutton,WebElement FindElement,String PageName) throws InterruptedException { driver.navigate().refresh(); waitForWebElement(Linkbutton); Linkbutton.click(); sleep(3000); driver.navigate().refresh(); sleep(3000); waitForWebElement(FindElement); if(FindElement.isDisplayed()) { driver.navigate().back(); System.out.println("Page Redirection done"); } else if(!FindElement.isDisplayed()) { sleep(5000); driver.navigate().back(); System.out.println("Page Redirection done"); } else { driver.navigate().back(); System.out.println("Page Rredirection Failed for"+Linkbutton.getText()+""); } } public static void howItWorksValidation(WebElement webObj,String str1,String str2,String str3) { String Temp = webObj.getText(); //System.out.println(""+Temp+""); String[] result = Temp.split("\n"); if((!result[0].equalsIgnoreCase(str1))) { System.out.println("Error in string validation "+result[0]); } else if(!result[1].equalsIgnoreCase(str2)) { System.out.println("Error in string validation "+result[1]); } else if (!result[2].equalsIgnoreCase(str3)) { System.out.println("Error in string validation "+result[2]); } } public static void sectionOneLinkvalidation(WebElement webObj) throws Exception { webObj.click(); sleep(1000); if(!webObj.getAttribute("class").equals("active")) { System.out.println("There is error in link validation "+webObj.getText()+""); } } public static void whatThekitIncludesTextValidation(WebElement webObj,String str1,String str2,String str3) { String Temp = webObj.getText(); String[] result = Temp.split("\n"); if((!result[0].equalsIgnoreCase(str1))) { System.out.println("Error in string validation "+result[0]); } else if(!result[1].equalsIgnoreCase(str2)) { System.out.println("Error in string validation "+result[1]); } else if (!result[2].equalsIgnoreCase(str3)) { System.out.println("Error in string validation "+result[2]); } } public static void whatTheKitIncludesImageAndTextValidation(WebElement imgObj,String imgsrc,WebElement TextObj,String Stringsrc) { //System.out.println(""+imgObj.getAttribute("src")); if (!imgObj.getAttribute("src").equals(imgsrc)) { //ScreenShot(driver, "Imagevalidation Source path "+imgsrc+""); System.out.println("The " + imgsrc +" is having wrong src Porperty"); } String Temp = TextObj.getText().replace("\n", " "); if((!Temp.equalsIgnoreCase(Stringsrc))) { System.out.println("Error in string validation "+Stringsrc); } } public static void InputValidation(WebElement Button1,WebElement InputElement,String Input,WebElement Button2) { for (String retval: Input.split(",")) { sleep(2500); System.out.println("The Valid Email Id Is"+retval); // driver.findElement(By.xpath("//div[@class='bl-val-chnge pb25']/a[text()='Track Order']")).click(); Button1.click(); sleep(2500); InputElement.clear(); InputElement.sendKeys(retval); Button2.click(); sleep(2500); //UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//div[@class='text-center']/a")), "NotEquals", "page navigation Error"); driver.navigate().back(); } } public static void SendInputValues(WebElement webObject,String Input,String type) { switch (type.toLowerCase()) { case "textbox": webObject.clear(); sleep(1000); webObject.sendKeys(Input); break; case "dropdown": sleep(1000); Select DropDown = new Select(webObject); DropDown.selectByVisibleText(Input); break; case "radiobutton": sleep(1000); webObject.click(); break; case "checkbox": sleep(1000); webObject.click(); break; } sleep(1000); } public static void sleep(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { e.printStackTrace(); } } public static void NumericFieldValidation(WebElement numericFieldObject,WebElement errorObject,String Input) { for (String retval: Input.split(",")) { numericFieldObject.clear(); numericFieldObject.sendKeys(retval); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter a valid number.")) { if(ErrorMessage.equals(" ")) { //ScreenShot(driver, ""+numericFieldObject.getAttribute("id")+" "+retval+""); System.out.println("Error Message is not displayed near Text box ID "+numericFieldObject.getAttribute("id")+"for input value : '"+retval+" '"); } else { //ScreenShot(driver, ""+numericFieldObject.getAttribute("id")+" "+retval+""); System.out.println("The Error Message displayed is "+ErrorMessage+" near Text Box ID "+numericFieldObject.getAttribute("id")+" for input value : '"+retval+" '"); } } } } public static void CCConfirmPasswordValidation(WebElement PasswordObj,WebElement ConfirmPasswordObj,WebElement errorObject,String input) { sleep(1000); for (String pwd: input.split(",")) { PasswordObj.clear(); ConfirmPasswordObj.clear(); PasswordObj.sendKeys(pwd); ConfirmPasswordObj.sendKeys(pwd); String ErrorMessage=errorObject.getText(); if(!ErrorMessage.equals("Please enter the same value again.")) { //ScreenShot(driver, ""+PasswordObj.getAttribute("id")+" "+pwd+""); System.out.println("Please enter the same value again. error message is not displayed for input "+pwd+""); } } } public static void CCPasswordAndConfirmPasswordValidation(WebElement PasswordObj,WebElement ConfirmPasswordObj,WebElement errorObject1,WebElement errorObject2,String Passwordinput) { sleep(1000); String ErrorMessage1 = null,ErrorMessage2 = null; for (String pwd: Passwordinput.split(",")) { PasswordObj.clear(); ConfirmPasswordObj.clear(); PasswordObj.sendKeys(pwd); ConfirmPasswordObj.sendKeys(pwd); ErrorMessage1=errorObject1.getText(); ErrorMessage2= errorObject2.getText(); if((!ErrorMessage1.equals(""))||(!ErrorMessage2.equals(""))) { //ScreenShot(driver, ""+PasswordObj.getAttribute("id")+" "+pwd+""); System.out.println("The Error Message displayed near password textbox is "+ErrorMessage1+"for input "+pwd+""); System.out.println("The Error Message displayed near Confirmpassword textbox is "+ErrorMessage2+"for input "+pwd+""); } } } public static void ControlCenterPasswordValidation(WebElement textBoxObject,WebElement errorObject,String input) { sleep(1000); for (String retval: input.split(",")) { textBoxObject.clear(); textBoxObject.sendKeys(retval); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter a valid password.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+retval+""); System.out.println("Please enter a valid password error message is not displayed for input "+retval+""); } } } public static void ControlCenterRequiredFieldValidation(WebElement textBoxObject,WebElement errorObject,String Type) { textBoxObject.clear(); sleep(2000); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter "+Type+"")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage+""); System.out.println("The Error Message displayed is "+ErrorMessage+" not equals to Please enter "+Type+""); } } public static void EnterReferralCodeValidation(WebElement textBoxObject,WebElement errorObject) { textBoxObject.clear(); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter Referral Code")) { System.out.println("Please enter Referral Code Error Message is Not Displayed"); } } public static void TrackOrderErrorValidation(WebElement textBoxObject,WebElement errorObject) { textBoxObject.clear(); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter Email Address")) { System.out.println("Please enter Email Address Error Message is Not Displayed"); } } public static void EmailIdInvalidvalidation(WebElement textBoxObject,WebElement errorObject,String Input) { for (String retval: Input.split(",")) { textBoxObject.clear(); textBoxObject.sendKeys(retval); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter a valid email address.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage+""); System.out.println("The Error Message displayed is "+ErrorMessage+" near Text Box ID "+textBoxObject.getAttribute("id")+" for input value : '"+retval+" '"); } } } public static void TrackEmailIdvalidation(WebElement textBoxObject,WebElement errorObject,String Input,WebElement linkButton) { for (String retval: Input.split(",")) { textBoxObject.clear(); textBoxObject.sendKeys(retval); linkButton.click(); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter a valid email address.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage+""); System.out.println("The Error Message displayed is "+ErrorMessage+" near Text Box ID "+textBoxObject.getAttribute("id")+" for input value : '"+retval+" '"); } } } public static void MaximumInputValidation(WebElement textBoxObject,WebElement errorObject,int Maximumvalue,String Input) { for (String retval: Input.split(",")) { sleep(1000); textBoxObject.clear(); textBoxObject.sendKeys(retval); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter no more than "+Maximumvalue+" characters.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+retval+""); System.out.println("The Error Message is "+ErrorMessage+" near Displayed Text Box ID "+textBoxObject.getAttribute("id")+" for input value : '"+retval+" '"); } } } public static void MinimumInputValidation(WebElement textBoxObject,WebElement errorObject,int Minimumvalue,String Input) { for (String retval: Input.split(",")) { sleep(1000); textBoxObject.clear(); textBoxObject.sendKeys(retval); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Please enter at least "+Minimumvalue+" characters.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+retval+""); System.out.println("The Error Message is "+ErrorMessage+" near Displayed Text Box ID "+textBoxObject.getAttribute("id")+" for input value : '"+retval+" '"); } } } public static void SpaceNotAllowedvalidation(WebElement textBoxObject,WebElement errorObject) { textBoxObject.clear(); textBoxObject.sendKeys(" "); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("Spaces not allowed before text")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage+""); System.out.println("The Error Message displayed is "+ErrorMessage+" not equals to 'Spaces not allowed before text'"); } } public static void RequiredFieldValidation(WebElement textBoxObject,WebElement errorObject,String type) { switch(type.toLowerCase()) { case "textbox": textBoxObject.clear(); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("This field is required.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage+""); System.out.println("The Error Message displayed is "+ErrorMessage+" not equals to 'This field is required.'"); } break; case "dropdown": Select DropDown = new Select(textBoxObject); DropDown.selectByVisibleText("Choose device type"); String ErrorMessage1= errorObject.getText(); if(!ErrorMessage1.equals("This field is required.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage1+""); System.out.println("The Error Message displayed is "+ErrorMessage1+" not equals to 'This field is required.'"); } break; case"radiobutton": String ErrorMessage2= errorObject.getText(); if(!ErrorMessage2.equals("This field is required.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage2+""); System.out.println("The Error Message displayed is "+ErrorMessage2+" not equals to 'This field is required.'"); } break; } } //ScreenShot Not Used public static void ValidateSimTypeRadioButton(int InputValue,WebElement errorObject) { List<WebElement> radios = driver.findElements(By.name("simTypeId")); if (InputValue > 0 && InputValue <= radios.size()) { radios.get(InputValue - 1).click(); } else { throw new NotFoundException("option " + InputValue + " not found"); } String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("")) { System.out.println("The Error Message is "+ErrorMessage+" near Displayed Radio Button "); } } public static void RequiredFieldShippingDropDown(WebElement textBoxObject,WebElement errorObject) { Select DropDown = new Select(textBoxObject); DropDown.selectByVisibleText("Select"); String ErrorMessage1= errorObject.getText(); if(!ErrorMessage1.equals("This field is required.")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+ErrorMessage1+""); System.out.println("The Error Message displayed is "+ErrorMessage1+" not equals to 'This field is required.'"); } } public static void ValidateDropDown(WebElement dropDownObject,String InputValue,WebElement errorObject) { Select DropDown = new Select(dropDownObject); DropDown.selectByVisibleText(InputValue); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("")) { //ScreenShot(driver, ""+dropDownObject.getAttribute("id")+" "+ErrorMessage+""); System.out.println("The Error Message is "+ErrorMessage+" near Displayed Drop Down ID "+dropDownObject.getAttribute("id")+" for input value : '"+InputValue+" '"); } } public static void ValidInputValidation(WebElement textBoxObject,String Input,WebElement errorObject) { for (String retval: Input.split(",")) { textBoxObject.clear(); textBoxObject.sendKeys(retval); String ErrorMessage= errorObject.getText(); if(!ErrorMessage.equals("")) { //ScreenShot(driver, ""+textBoxObject.getAttribute("id")+" "+retval+""); System.out.println("The Error Message is "+ErrorMessage+" near Displayed Text Box ID "+textBoxObject.getAttribute("id")+" for input value : '"+retval+" '"); } } } public static void PlaceholderValidation(WebElement textObject,String stringToCompare,String Result) { String stringBase=textObject.getAttribute("placeholder"); if(!stringBase.equalsIgnoreCase(stringToCompare)) { //ScreenShot(driver,"PlaceholderValidation " +textObject.getAttribute("id")+""); System.out.println("The Placeholder value in "+Result+" Input Field doesn't match."); } } public static void Imagevalidation(WebElement imgObject,String typeattribute,String value,String Result) { //System.out.println(""+imgObject.getAttribute(typeattribute)); //System.out.println(""+value+""); switch(typeattribute.toLowerCase()) { case "alt": if (!imgObject.getAttribute(typeattribute).equals(value)) { //ScreenShot(driver, "Imagevalidation Alternate Text "+Result+""); System.out.println("The " + Result +" is having wrong Alternate Text Porperty"); } break; case "src": if (!imgObject.getAttribute(typeattribute).equals(value)) { //ScreenShot(driver, "Imagevalidation Source path "+Result+""); System.out.println("The " + Result +" is having wrong src Porperty"); } break; } } public static void StringValidation(String stringBase, String stringToCompare,String value) { sleep(1000); boolean result = true; switch(value.toLowerCase()) { case "equal": result = stringBase.equals(stringToCompare); break; case "equalsignorecase": result = stringBase.equalsIgnoreCase(stringToCompare); break; case "doubleequals": result = stringBase==stringToCompare; break; } if (result == false) { System.out.println("Base String :"+stringBase+""); System.out.println("compare String :"+stringToCompare+""); //ScreenShot(driver, "StringValidation in "+stringBase+""); System.out.println("The String " + stringToCompare +" is not " + value +" to "+ stringBase +" "); } } public static void DisabledValidation(WebElement strObject,String Result) { if (strObject.isEnabled()) { System.out.println("The " + Result +" is Enabled"); } } public static void DisplayEnableValidator(WebElement strObject, String value, String Result) { sleep(1000); //System.out.println(" The "+Result+" is displayed :"+strObject.isDisplayed()+""); //System.out.println(" The "+Result+" is enabled :"+strObject.isEnabled()+""); //System.out.println(""+strObject); switch(value.toLowerCase()) { case "equal": if (strObject.isDisplayed() && strObject.isEnabled()) { //ScreenShot(driver,"DisplayEnableValidator "+ Result+""); //Assert.assertEquals(true, strObject.isDisplayed() && strObject.isEnabled()); System.out.println("The " + Result +" is Enabled"); } break; case "notequal": if (!strObject.isDisplayed() && !strObject.isEnabled()) { //ScreenShot(driver, Result); System.out.println("The " + Result +" is not Displayed or Enabled"); //Assert.assertEquals(false, strObject.isDisplayed() && strObject.isEnabled()); } break; } } public static void ScreenShot(WebDriver driver,String screenshotName) { try { sleep(1200); Calendar currentDate = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); String dateN = formatter.format(currentDate.getTime()).replace("/","_"); String dateNow = dateN.replace(":","_"); File source =((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(source, new File("./FailedScreenShot/"+screenshotName+" "+dateNow+".png")); System.out.println("Screenshot taken for failed testCase"); } catch (Exception e) { System.out.println("Exception while taking screenshot "+e.getMessage()); } } public static Properties getPropValues() throws IOException { Properties properties = new Properties(); String propertiesFile=System.getProperty("user.dir")+ "\\src\\testData.properties"; try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { System.out.println("Exception Occurred" + e.getMessage()); } return properties; } public static Properties getUnicomPropValues() throws IOException { Properties properties = new Properties(); String propertiesFile=System.getProperty("user.dir")+ "\\src\\UnicomTestData.properties"; try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { System.out.println("Exception Occurred" + e.getMessage()); } return properties; } public static Properties getBellPropValues() throws IOException { Properties properties = new Properties(); String propertiesFile=System.getProperty("user.dir")+ "\\src\\BellTestData.properties"; try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { System.out.println("Exception Occurred" + e.getMessage()); } return properties; } public static Properties getTele2PropValues() throws IOException { Properties properties = new Properties(); String propertiesFile=System.getProperty("user.dir")+ "\\src\\tele2TestData.properties"; try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { System.out.println("Exception Occurred" + e.getMessage()); } return properties; } public static Properties getPostPropValues() throws IOException { Properties properties = new Properties(); String propertiesFile=System.getProperty("user.dir")+ "\\src\\PostTestData.properties"; try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { System.out.println("Exception Occurred" + e.getMessage()); } return properties; } public static Properties getAdminPropValues() throws IOException { Properties properties = new Properties(); String propertiesFile=System.getProperty("user.dir")+ "\\src\\AdminTestData.properties"; try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { System.out.println("Exception Occurred" + e.getMessage()); } return properties; } } <file_sep>package pages; import java.io.IOException; import java.util.Properties; import pageobjects.Tele2ReferralRequestpagePO; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import utilitymethods.UtilityMethods; import driver.BaseDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class Tele2ReferralRequestpage extends BaseDriver { public static FirefoxDriver driver = launchApp(); static Properties allInputValue; @BeforeTest public static void Start() throws IOException { allInputValue = UtilityMethods.getTele2PropValues(); // headerValidation(); // //System.out.println("header Section Completed"); //sectionOneValidation(); //UtilityMethods.PageNavigationValidation(driver.findElement(By.xpath("//img[@alt='Tele2']")), driver.findElement(By.xpath("//img[@title='What is IoT']"))); //System.out.println("Section one Completed"); } private static FirefoxDriver launchApp() { // TODO Auto-generated method stub return null; } public static void headerValidation() { validateOperatorLogo(); validateCompanyLogo(); //UtilityMethods.PageNavigationValidation(driver.findElement(By.xpath("//img[@alt='Tele2']")), driver.findElement(By.xpath("//img[@title='What is IoT']"))); } @Test public static void validateOperatorLogo() { PageFactory.initElements(driver, Tele2ReferralRequestpagePO.class); UtilityMethods.DisplayEnableValidator(Tele2ReferralRequestpagePO.Tele2Logo, "NotEqual","Tele2 Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(Tele2ReferralRequestpagePO.Tele2Logo,"src",allInputValue.getProperty("tele2Logo"),"Tele2 Operator Logo"); } @Test(priority=1) public static void validateCompanyLogo() { WebElement companyLogo = driver.findElement(By.xpath("//img[@alt='Cisco Jasper']")); UtilityMethods.DisplayEnableValidator(companyLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(companyLogo,"src",allInputValue.getProperty("tele2CompanyLogo"),"Cisco Jasper Company Logo"); } public static void sectionOneValidation() { ReferralRequestTextValidation(); RequestReferralCodeTextBoxDisplayedAndEnabled(); RequestReferralCodeLabelTextDisplayedAndEnabled(); RequestReferralCodePlaceholderValidation(); ReferralRequestCodeValidInputValidation(); ReferralRequestRequiredFieldValidation(); ReferralRequestSpaceNotAllowedValidation(); ReferralRequestMaximumInputValidation(); ReferralRequestMinimumInputValidation(); ReferralRequestOtherValidation(); RequestButtonValidation(); } @Test(priority=2) public static void ReferralRequestTextValidation() { UtilityMethods.StringValidation(driver.findElement(By.xpath("//h2")).getText(), "Request a Referral Code", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//p")).getText(), allInputValue.getProperty("ReferralRequest.sectionOne"), "equalsignorecase"); UtilityMethods.StringValidation(driver.findElements(By.xpath("//h4")).get(0).getText(), "Contact Information", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElements(By.xpath("//h4")).get(1).getText(), "Device Information", "equalsignorecase"); } @Test(priority=3) public static void RequestReferralCodeTextBoxDisplayedAndEnabled() { UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='fname']")), "NotEqual", "First Name Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='lname']")), "NotEqual", "Last Name Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='company']")), "NotEqual", "Company Name Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='postion']")), "NotEqual", "Position/Role Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='phoneNumber']")), "NotEqual", "Phone Number Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='email']")), "NotEqual", "E-mail Address Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='device']")), "NotEqual", "Module Name Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//select[@id='industryId']")), "NotEqual", "Business Type Drop Down Menu"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='mini0']")), "NotEqual", "2FF Sim Type Radio Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='mini1']")), "NotEqual", "3FF Sim Type Radio Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='deviceVolume']")), "NotEqual", "Volume to deploy Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='with3mn00']")), "NotEqual", "Within 3 months Radio Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='with3mn01']")), "NotEqual", "3-6 months Radio Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='with3mn02']")), "NotEqual", "6-12 months Radio Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@id='with3mn03']")), "NotEqual", "More than 12 months/unknown Radio Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//textarea[@id='targetAudience']")), "NotEqual", "Description Input Field"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//a[@name='reset']")), "NotEqual", "Cancel Button"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//input[@value='Request']")), "NotEqual", "Request Button"); } @Test(priority=4) public static void RequestReferralCodeLabelTextDisplayedAndEnabled() { UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='First Name']")), "NotEqual", "First Name Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Last Name']")), "NotEqual", "Last Name Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Company Name']")), "NotEqual", "Company Name Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Position/Role']")), "NotEqual", "Position/Role Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Phone Number']")), "NotEqual", "Phone Number Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='E-mail Address']")), "NotEqual", "E-mail Address Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Module']")), "NotEqual", "Module Name Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Business Type']")), "NotEqual", "Business TypeLabel Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='SIM Type']")), "NotEqual", "Sim Type Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='2FF Mini']")), "NotEqual", "2FF Mini Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='3FF Micro']")), "NotEqual", "3FF Micro Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Volume to Deploy']")), "NotEqual", "Volume to deploy Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Launch Timeframe']")), "NotEqual", "Launch Timeframe Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Within 3 months']")), "NotEqual", "Within 3 months Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='3-6 months']")), "NotEqual", "3-6 months Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='6-12 months']")), "NotEqual", "6-12 months Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='More than 12 months/unknown']")), "NotEqual", "More than 12 months/unknown Label Text"); UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//label[text()='Description']")), "NotEqual", "Description Label Text"); } @Test(priority=5) public static void RequestReferralCodePlaceholderValidation() { UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='fname']")), "Enter your first name", "First Name"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='lname']")), "Enter your last name", "Last Name"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='company']")), "Enter your company name", "Company Name"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='postion']")), "Enter your position/role", "position/role"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='phoneNumber']")), "", "Phone Number"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='email']")), "Enter e-mail", "Email-ID"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='device']")), "Enter the module used in your device", "Module"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//input[@id='deviceVolume']")), "Enter first year quantity", "Volume to deploy"); UtilityMethods.PlaceholderValidation(driver.findElement(By.xpath("//textarea[@id='targetAudience']")), "Tell us a little about your device, target audience, and how we can help.", "Description"); } @Test(priority=6) public static void ReferralRequestCodeValidInputValidation() { driver.findElement(By.xpath("//input[@value='Request']")).click(); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='fname']")), allInputValue.getProperty("ValidFirstName"), driver.findElement(By.xpath("//div[@id='fname-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='lname']")), allInputValue.getProperty("ValidLastName"), driver.findElement(By.xpath("//div[@id='lname-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='company']")), allInputValue.getProperty("ValidCompanyName"), driver.findElement(By.xpath("//div[@id='company-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='postion']")), allInputValue.getProperty("ValidPosition"), driver.findElement(By.xpath("//div[@id='postion-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='phoneNumber']")),allInputValue.getProperty("ValidPhoneNumber"),driver.findElement(By.xpath("//div[@id='phoneNumber-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='email']")),allInputValue.getProperty("ValidEmailId") , driver.findElement(By.xpath("//div[@id='email-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='device']")), allInputValue.getProperty("ValidModule"), driver.findElement(By.xpath("//div[@id='device-error']"))); UtilityMethods.ValidateDropDown(driver.findElement(By.xpath("//select[@id='industryId']")), "Consumer electronics - personal navigation", driver.findElement(By.xpath("//div[@id='industryId-error']"))); //UtilityMethods.ValidateSimTypeRadioButton(2,driver.findElement(By.xpath("//div[@id='simTypeId-error']"))); //driver.findElement(By.xpath("//label[text()='2FF/Ruggedized']")).click(); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//input[@id='deviceVolume']")), allInputValue.getProperty("ValidVolumeToDeploy"), driver.findElement(By.xpath("//div[@id='deviceVolume-error']"))); UtilityMethods.ValidInputValidation(driver.findElement(By.xpath("//textarea[@id='targetAudience']")), allInputValue.getProperty("ValidDescription"), driver.findElement(By.xpath("//div[@id='targetAudience-error']"))); } @Test(priority=7) public static void ReferralRequestRequiredFieldValidation() { driver.findElement(By.xpath("//input[@value='Request']")).click(); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='fname']")), driver.findElement(By.xpath("//div[@id='fname-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='lname']")), driver.findElement(By.xpath("//div[@id='lname-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='company']")), driver.findElement(By.xpath("//div[@id='company-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='postion']")), driver.findElement(By.xpath("//div[@id='postion-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='phoneNumber']")), driver.findElement(By.xpath("//div[@id='phoneNumber-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='email']")), driver.findElement(By.xpath("//div[@id='email-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='device']")), driver.findElement(By.xpath("//div[@id='device-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//select[@id='industryId']")), driver.findElement(By.xpath("//div[@id='industryId-error']")),"DropDown"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//label[text()='SIM Type']")), driver.findElement(By.xpath("//div[@id='simTypeId-error']")),"RadioButton"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//input[@id='deviceVolume']")), driver.findElement(By.xpath("//div[@id='deviceVolume-error']")),"TextBox"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//label[text()='Launch Timeframe']")), driver.findElement(By.xpath("//div[@id='launchTimeFrameId-error']")),"RadioButton"); UtilityMethods.RequiredFieldValidation(driver.findElement(By.xpath("//textarea[@id='targetAudience']")), driver.findElement(By.xpath("//div[@id='targetAudience-error']")),"TextBox"); } @Test(priority=8) public static void ReferralRequestSpaceNotAllowedValidation() { driver.findElement(By.xpath("//input[@value='Request']")).click(); UtilityMethods.SpaceNotAllowedvalidation(driver.findElement(By.xpath("//input[@id='fname']")), driver.findElement(By.xpath("//div[@id='fname-error']"))); UtilityMethods.SpaceNotAllowedvalidation(driver.findElement(By.xpath("//input[@id='lname']")), driver.findElement(By.xpath("//div[@id='lname-error']"))); UtilityMethods.SpaceNotAllowedvalidation(driver.findElement(By.xpath("//input[@id='company']")), driver.findElement(By.xpath("//div[@id='company-error']"))); UtilityMethods.SpaceNotAllowedvalidation(driver.findElement(By.xpath("//input[@id='postion']")), driver.findElement(By.xpath("//div[@id='postion-error']"))); } @Test(priority=9) public static void ReferralRequestMaximumInputValidation() { driver.findElement(By.xpath("//input[@value='Request']")).click(); UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//input[@id='fname']")), driver.findElement(By.xpath("//div[@id='fname-error']")), 49, allInputValue.getProperty("InvalidInput")); UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//input[@id='lname']")), driver.findElement(By.xpath("//div[@id='lname-error']")), 49, allInputValue.getProperty("InvalidInput")); UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//input[@id='company']")), driver.findElement(By.xpath("//div[@id='company-error']")), 25, allInputValue.getProperty("InvalidCompanyName")); UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//input[@id='postion']")), driver.findElement(By.xpath("//div[@id='postion-error']")), 25, allInputValue.getProperty("InvalidCompanyName")); UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//input[@id='phoneNumber']")), driver.findElement(By.xpath("//div[@id='phoneNumber-error']")), 10, allInputValue.getProperty("Invalidphonenumber")); UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//textarea[@id='targetAudience']")), driver.findElement(By.xpath("//div[@id='targetAudience-error']")), 255, allInputValue.getProperty("InvalidDescription")); } @Test(priority=10) public static void ReferralRequestMinimumInputValidation() { driver.findElement(By.xpath("//input[@value='Request']")).click(); UtilityMethods.MinimumInputValidation(driver.findElement(By.xpath("//input[@id='company']")), driver.findElement(By.xpath("//div[@id='company-error']")), 3, allInputValue.getProperty("InvalidMinInput")); UtilityMethods.MinimumInputValidation(driver.findElement(By.xpath("//input[@id='phoneNumber']")), driver.findElement(By.xpath("//div[@id='phoneNumber-error']")), 10, allInputValue.getProperty("InvalidMinphonenumber")); } @Test(priority=11) public static void ReferralRequestOtherValidation() { driver.findElement(By.xpath("//input[@value='Request']")).click(); UtilityMethods.EmailIdInvalidvalidation(driver.findElement(By.xpath("//input[@id='email']")), driver.findElement(By.xpath("//div[@id='email-error']")), allInputValue.getProperty("InvalidEmailID")); UtilityMethods.NumericFieldValidation(driver.findElement(By.xpath("//input[@id='phoneNumber']")), driver.findElement(By.xpath("//div[@id='phoneNumber-error']")), allInputValue.getProperty("InvalidPhoneNumber")); UtilityMethods.NumericFieldValidation(driver.findElement(By.xpath("//input[@id='deviceVolume']")), driver.findElement(By.xpath("//div[@id='deviceVolume-error']")), allInputValue.getProperty("InvadildNumbericField")); } @Test(priority=12) public static void RequestButtonValidation() { UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='fname']")), "Testing1", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='lname']")), "Test1", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='company']")), "Testing Team 11", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='postion']")), "ELP 1", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='phoneNumber']")), "956874236951", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='email']")), "<EMAIL>", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='device']")), "M2M", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//select[@id='industryId']")), "Telematics - passenger vehicles, aftermarket", "DropDown"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//label[@for='mini0']")), "", "Radiobutton"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//input[@id='deviceVolume']")), "562", "TextBox"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//label[@for='with3mn02']")), "", "Radiobutton"); UtilityMethods.SendInputValues(driver.findElement(By.xpath("//textarea[@id='targetAudience']")), "Test Data", "TextBox"); //UtilityMethods.PageRedirection(driver.findElement(By.xpath("//input[@value='Request']")), driver.findElement(By.xpath("//a[text()='Back to IoT Starter Kit Page']"))); // UtilityMethods.PageNavigationValidation(driver.findElement(By.xpath("//input[@value='Request']")), driver.findElement(By.xpath("//a[text()='Back to IoT Starter Kit Page']"))); driver.findElement(By.xpath("//input[@value='Request']")).click(); driver.navigate().back(); /* driver.findElement(By.xpath("//input[@value='Request']")).click(); try{ Thread.sleep(2500);}catch (InterruptedException e) {e.printStackTrace();} // UtilityMethods.waitForElement(driver.findElement(By.xpath("//img[@title='What is IoT']"))); boolean Result = true; Result= driver.findElement(By.xpath("//a[text()='Back to IoT Starter Kit Page']")).isDisplayed(); System.out.println("The Result is "+Result); if(Result==false) { System.out.println("Page Navigation Error in "+driver.findElement(By.xpath("//img[@alt='Tele2']")).getText()); } */ } @AfterTest public static void Exit() { driver.close(); } } <file_sep>package pageobjects; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import driver.BaseDriver; public class BellBillingInfoPO extends BaseDriver { @FindBy(how=How.XPATH,using="//img[@alt='Bell']") public static WebElement BellLogo; @FindBy(how=How.XPATH,using="//img[@alt='Cisco Jasper']") public static WebElement CiscoLogo; @FindBy(how=How.XPATH,using="//h4") public static WebElement SectionOneHead4; @FindBy(how=How.XPATH,using="//p") public static WebElement ParagraphText; @FindBy(how=How.XPATH,using="//h2") public static WebElement OrderIotHeaderText; //input[@id='smebilling'] @FindBy(how=How.XPATH,using="//input[@id='smebilling']") public static WebElement SameBillAndShipcheckbox; @FindBy(how=How.XPATH,using="//label[@for='smebilling']") public static WebElement SameBillAndShipLabel; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-info']//span[@class='bl-status']") public static WebElement YourInfoText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-ship']//span[@class='bl-status']") public static WebElement ShppingText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-pay']//span[@class='bl-status']") public static WebElement PaymentText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-rc']//span[@class='bl-status']") public static WebElement ReviewConfirmText; @FindBy(how=How.XPATH,using="//label[@for='namecard']") public static WebElement NameOnCardLabel; @FindBy(how=How.XPATH,using="//label[@for='cardnum']") public static WebElement CardNumberLabel; @FindBy(how=How.XPATH,using="//label[text()='Expiry Date']") public static WebElement ExpiryDateLabel; @FindBy(how=How.XPATH,using="//label[@for='seccode']") public static WebElement CVVCodeLabel; @FindBy(how=How.XPATH,using="//input[@id='namecard']") public static WebElement NameOnCardInput; @FindBy(how=How.XPATH,using="//input[@id='cardnum']") public static WebElement CardNumberInput; @FindBy(how=How.XPATH,using="//input[@id='month']") public static WebElement ExpiryDate; @FindBy(how=How.XPATH,using="//input[@id='seccode']") public static WebElement CVVCodeInput; @FindBy(how=How.XPATH,using="//div[@class='bl-hid-pp']//label[text()='Address']") public static WebElement BillAddressLabel; @FindBy(how=How.XPATH,using="//div[@class='bl-hid-pp']//label[text()='Apt/Suite']") public static WebElement BillAptLabel; @FindBy(how=How.XPATH,using="//div[@class='bl-hid-pp']//label[text()='City']") public static WebElement BillCityLabel; @FindBy(how=How.XPATH,using="//div[@class='bl-hid-pp']//label[text()='State/Province']") public static WebElement BillProvinceLabel; @FindBy(how=How.XPATH,using="//div[@class='bl-hid-pp']//label[text()='Postal Code']") public static WebElement BillPostLabel; @FindBy(how=How.XPATH,using="//div[@class='bl-hid-pp']//label[text()='Country']") public static WebElement BillCountryLabel; @FindBy(how=How.XPATH,using="//input[@name='billAddress.addressLine1']") public static WebElement BillAddressInput; @FindBy(how=How.XPATH,using="//input[@name='billAddress.addressLine2']") public static WebElement BillAptInput; @FindBy(how=How.XPATH,using="//input[@name='billAddress.cityTown']") public static WebElement BillCityInput; @FindBy(how=How.XPATH,using="//select[@id='state']") public static WebElement BillProvinceInput; @FindBy(how=How.XPATH,using="//input[@name='billAddress.zipPostalCode']") public static WebElement BillPostInput; @FindBy(how=How.XPATH,using="//select[@id='bcountry']") public static WebElement BillCountryInput; @FindBy(how=How.XPATH,using="//div[@id='address1-error']") public static WebElement BillAddressError; @FindBy(how=How.XPATH,using="//div[@id='citytown-error']") public static WebElement BillCityError; @FindBy(how=How.XPATH,using="//div[@id='state-error']") public static WebElement BillProvinceError; @FindBy(how=How.XPATH,using="//div[@id='poscode-error']") public static WebElement BillPostError; @FindBy(how=How.XPATH,using="//div[@id='bcountry-error']") public static WebElement BillCountryError; @FindBy(how=How.XPATH,using="//input[@value='Review']") public static WebElement ReviewButton; @FindBy(how=How.XPATH,using="//a[@value='Cancel']") public static WebElement CancelButton; @FindBy(how=How.XPATH,using="//a[text()='Back']") public static WebElement BackButton; @FindBy(how=How.XPATH,using="//img[@title='What is IoT']") public static WebElement CancelButtonFindElement; @FindBy(how=How.XPATH,using="//input[@value='Continue']") public static WebElement BackFindElement; } <file_sep>package pages; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import pageobjects.PostHomePagePO; import utilitymethods.UtilityMethods; import driver.BaseDriver; public class PostHomePage extends BaseDriver { public static WebDriver driver =BaseDriver.driver; static Properties allInputValue; @BeforeTest public static WebDriver start() throws Exception { allInputValue = UtilityMethods.getPostPropValues(); return driver = launchApp(allInputValue.getProperty("BaseURl")); } @Test(priority=1) private static void validateOperatorLogo() { PageFactory.initElements(driver, PostHomePagePO.class); UtilityMethods.DisplayEnableValidator(PostHomePagePO.PostLogo, "NotEqual","Post Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(PostHomePagePO.PostLogo,"src",allInputValue.getProperty("postLogo"),"Post Operator Logo"); System.out.println(""+"TS001"); } @Test(priority=2) protected static void validateCompanyLogo() { PageFactory.initElements(driver, PostHomePagePO.class); UtilityMethods.DisplayEnableValidator(PostHomePagePO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(PostHomePagePO.CiscoLogo,"src",allInputValue.getProperty("ciscoLogo"),"Cisco Jasper Company Logo"); System.out.println(""+"TS002"); } @Test(priority=3) public static void sectionOneIotStarterKitPostValidation() { PageFactory.initElements(driver, PostHomePagePO.class); UtilityMethods.StringValidation(PostHomePagePO.TextBannerh1.getText(), allInputValue.getProperty("HomePage.Bannerh1"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextBannerh3.getText(), allInputValue.getProperty("HomePage.Bannerh3"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextBannerp1.getText().replace("\n", " "),allInputValue.getProperty("HomePage.Bannerp1"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextBannerp2.getText().replace("\n", " "), allInputValue.getProperty("HomePage.Bannerp2"), "equalsignorecase"); System.out.println(""+"TS003"); } @Test(priority=4) public static void sectionOneIotStarterKitTrackOrderValidation() throws InterruptedException { PageFactory.initElements(driver, PostHomePagePO.class); Thread.sleep(3000); UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneTrackOrderButton, "NotEqual","Track Order Button in IoT Starter Kit banner"); PostHomePagePO.SectionOneTrackOrderButton.click(); UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneTrackOrderPRButton, "NotEqual","Track Order on click Button in IoT Starter Kit Track Order"); UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneTrackOrderText, "NotEqual","Track Order on Click Text in IoT Starter Kit Track Order"); UtilityMethods.DisplayEnableValidator(PostHomePagePO.TrackOrderEmailID, "NotEqual","Enter Email ID Text Box in IoT Starter Kit Track Order"); UtilityMethods.PlaceholderValidation(PostHomePagePO.TrackOrderEmailID, "Enter Email Address", "Track Order Email ID"); UtilityMethods.DisplayEnableValidator(PostHomePagePO.TrackOrderCloseIcon, "NotEqual","Track Order Close Button in IoT Starter Kit"); PostHomePagePO.TrackOrderCloseIcon.click(); System.out.println(""+"TS004"); } @Test(priority=5) public static void sectionOneIotStarterKitEnterReferralCodeValidation() throws InterruptedException { Thread.sleep(3000); UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneEnterReferralCodeButton, "NotEqual","Enter Referral Code Button in IoT Starter Kit"); PostHomePagePO.SectionOneTrackOrderButton.click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace();} UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneOrderKitButton, "NotEqual","OrderKit Button in IoT Starter Kit "); UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneEnterReferralCodeText, "NotEqual","Enter Referral Code Text in IoT Starter Kit "); UtilityMethods.DisplayEnableValidator(PostHomePagePO.EnterReferralCode, "NotEqual","Enter Referral Code Text Box in IoT Starter Kit Track Order"); UtilityMethods.PlaceholderValidation(PostHomePagePO.EnterReferralCode, "Enter Referral Code", "Enter Referral Code"); UtilityMethods.DisplayEnableValidator(PostHomePagePO.EnterReferralCodeCloseIcon, "NotEqual","Enter Referral Code Close Button in IoT Starter Kit"); PostHomePagePO.EnterReferralCodeCloseIcon.click(); System.out.println(""+"TS005"); } @Test(priority=6) public static void sectionTwoWhatThekitIncludesContentvalidation() { UtilityMethods.Imagevalidation(PostHomePagePO.SimIcon, "src",allInputValue.getProperty("postSimIcon"), "Post Sim Icon"); UtilityMethods.StringValidation(PostHomePagePO.TextSimh1.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimh1"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextSimh2.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimh2"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextSimh3.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimh3"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextSimh4.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimh4"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextSimp1.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimp1"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextSimp2.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimp2"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.TextSimp3.getText(), allInputValue.getProperty("HomePage.WhatTheKitIncludesSimp3"), "equalsignorecase"); System.out.println(""+"TS006"); } @Test(priority=7) public static void sectionTwoWhatThekitIncludesToolsvalidation() { UtilityMethods.whatTheKitIncludesImageAndTextValidation(PostHomePagePO.ToolIcon, allInputValue.getProperty("postToolIcon"), PostHomePagePO.ToolText, "Real-Time Testing Tool"); UtilityMethods.whatThekitIncludesTextValidation(PostHomePagePO.ToolListText,"Test-as-you-build for fast, quality development","Visibility into device and network behavior","Diagnostics and troubleshooting help"); System.out.println(""+"TS007"); } @Test(priority=8) public static void sectionTwoWhatThekitIncludesCentervalidation() { UtilityMethods.whatTheKitIncludesImageAndTextValidation(PostHomePagePO.CenterIcon, allInputValue.getProperty("postCenterIcon"), PostHomePagePO.CenterText,"Full Access to Control Centre"); UtilityMethods.whatThekitIncludesTextValidation(PostHomePagePO.CenterListText, "Complete suite of developer tools", "User logins for everyone on your team","Same environment for testing and deployment"); System.out.println(""+"TS008"); } @Test(priority=9) public static void sectionTwoWhatThekitIncludesSuppportvalidation() { UtilityMethods.whatTheKitIncludesImageAndTextValidation(PostHomePagePO.SupportIcon, allInputValue.getProperty("postSupportIcon"), PostHomePagePO.SupportText,"Exceptional Developer Support"); UtilityMethods.whatThekitIncludesTextValidation(PostHomePagePO.SupportListText, "Developer guidelines and M2M.com forum", "Access to APIs","Accelerated device certification"); System.out.println(""+"TS009"); } @Test(priority=10) public static void sectionThreeHowItWorksValidation() { UtilityMethods.StringValidation(PostHomePagePO.HowItWorksText.getText(), "How it Works", "equalsignorecase"); UtilityMethods.howItWorksValidation(PostHomePagePO.HowItWorksOrder, "1", "Buy", allInputValue.getProperty("HomePage.HowItWorksText1")); UtilityMethods.howItWorksValidation(PostHomePagePO.HowItWorksActivate, "2", "Activate", allInputValue.getProperty("HomePage.HowItWorksText2")); UtilityMethods.howItWorksValidation(PostHomePagePO.HowItWorksExplore, "3", "Explore", allInputValue.getProperty("HomePage.HowItWorksText3")); UtilityMethods.howItWorksValidation(PostHomePagePO.HowItWorksMonetize, "4", "Launch", allInputValue.getProperty("HomePage.HowItWorksText4")); System.out.println(""+"TS0010"); } @Test(priority=11) public static void sectionFourWhatIsIotValidation() { UtilityMethods.Imagevalidation(PostHomePagePO.WhatIsIotImage, "src" , allInputValue.getProperty("whatIsIot"), "What is IoT?"); UtilityMethods.StringValidation(PostHomePagePO.WhatIsIotText.getText(), "What is IoT?", "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.WhatIsIotParaText1.getText(), allInputValue.getProperty("HomePage.WhatIsIoTP1"), "equalsignorecase"); UtilityMethods.StringValidation(PostHomePagePO.WhatIsIotParaText2.getText(), allInputValue.getProperty("HomePage.WhatIsIoTP2"), "equalsignorecase"); } @Test(priority=12) public static void sectionOneLinkvalidation() throws Exception { UtilityMethods.sectionOneLinkvalidation(PostHomePagePO.WhattheKitIncludeLink); UtilityMethods.sectionOneLinkvalidation(PostHomePagePO.HowItWorkslink); UtilityMethods.sectionOneLinkvalidation(PostHomePagePO.WhatIsIotLink); } @Test(priority=13) public static void SectionThreeLearnMore() throws InterruptedException { UtilityMethods.DisplayEnableValidator(PostHomePagePO.HowItWorksLearnMore, "NotEqual", "M2MDotCom Link Button"); UtilityMethods.PageNavigationValidation(PostHomePagePO.HowItWorksLearnMore,PostHomePagePO.M2MDotComFindElement,"Bell"); } @Test(priority=14) public static void TrackOrderValidPageRedirection() throws InterruptedException { PostHomePagePO.SectionOneTrackOrderButton.click(); PostHomePagePO.TrackOrderEmailID.sendKeys(allInputValue.getProperty("TrackOrder.validTrackOrderEmailID")); UtilityMethods.PageNavigationValidation(PostHomePagePO.SectionOneTrackOrderPRButton, PostHomePagePO.SectionOneTrackOrderFindElement, "Post"); } @Test(priority=15) public static void TrackOrderInValidPageRedirection() throws InterruptedException { PostHomePagePO.SectionOneTrackOrderButton.click(); PostHomePagePO.TrackOrderEmailID.sendKeys(allInputValue.getProperty("TrackOrder.InvalidTrackOrderEmailID")); UtilityMethods.PageNavigationValidation(PostHomePagePO.SectionOneTrackOrderPRButton, PostHomePagePO.WhatIsIotImage, "Post"); } @Test(priority=16) public static void SectionOTwoReferralRequestvalidation() throws InterruptedException { UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionTwoReferralRrequestButton, "NotEqual", "Section Two Referral Request Button"); UtilityMethods.PageNavigationValidation(PostHomePagePO.SectionTwoReferralRrequestButton,PostHomePagePO.ReferrralRequestFindElement,"Post"); } @Test(priority=17) public static void SectionOneReferralRequestvalidation() throws InterruptedException { UtilityMethods.DisplayEnableValidator(PostHomePagePO.SectionOneReferralRrequestButton, "NotEqual", "Section One Referral Request Button"); UtilityMethods.PageNavigationValidation(PostHomePagePO.SectionOneReferralRrequestButton,PostHomePagePO.ReferrralRequestFindElement,"Post"); } @Test(priority=18) public static void sectionTwoM2MDotCom() throws InterruptedException { UtilityMethods.DisplayEnableValidator(PostHomePagePO.M2mDotCom, "NotEqual", "M2MDotCom Link Button"); UtilityMethods.PageNavigationValidation(PostHomePagePO.M2mDotCom,PostHomePagePO.M2MDotComFindElement,"M2M Developer Kits from the World’s Leading Mobile Operators"); } @Test(priority=19) public static void sectionTwoM2MdotCo() { try { Thread.sleep(4500); } catch (InterruptedException e){ e.printStackTrace();} WebElement referralrequest= driver.findElement(By.xpath("//a[text()='M2M.com']")); UtilityMethods.DisplayEnableValidator(referralrequest, "NotEqual", "M2M.com Link Button"); referralrequest.click(); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace();} try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); WebElement FindElement= driver.findElement(By.xpath("//div[@id='footer_wrap']")); if (!FindElement.isDisplayed()) { System.out.println("The Page Redirection Error in Request Referral Code"); } } } catch(Exception e) { System.out.println("Condition fail for M2M.com link"); } driver.navigate().back(); } //Failed @Test(priority=20) public static void sectionFourJasperdotCom() throws InterruptedException { UtilityMethods.DisplayEnableValidator(PostHomePagePO.JasperDotCom, "NotEqual", "JasperDotCom Link Button"); UtilityMethods.PageNavigationValidation(PostHomePagePO.JasperDotCom, PostHomePagePO.JasperDotComFindElement, "IoT Connectivity Management Platform | Cisco Jasper"); } //failed @Test(priority=21) public static void sectionFourJasperdotCo() throws InterruptedException { Thread.sleep(2000); WebElement referralrequest= driver.findElement(By.xpath("//section[@id='what-iot']//a")); UtilityMethods.DisplayEnableValidator(referralrequest, "NotEqual", "Jasper.com Link Button"); referralrequest.click(); Thread.sleep(5000); try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); WebElement FindElement= driver.findElement(By.xpath("//footer")); if (!FindElement.isDisplayed()) { System.out.println("The Page Redirection Error in Request Referral Code"); } } } catch(Exception e) { System.out.println("Condition fail for jasper.com link"); } driver.navigate().back(); } @Test(priority=22) public static void sectionTwoReferralRequestButton() { try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace();} WebElement referralrequest= driver.findElement(By.xpath("//section[@id='kit-inc']//a[text()='Request Referral Code']")); UtilityMethods.DisplayEnableValidator(referralrequest, "NotEqual", "Referral Request Button"); referralrequest.click(); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace();} try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); WebElement FindElement= driver.findElement(By.xpath("//input[@value='Request']")); if (!FindElement.isDisplayed()) { System.out.println("The Page Redirection Error in Request Referral Code"); } } } catch(Exception e) { System.out.println("Condition fail for Referral request in section 2"); } driver.navigate().back(); } /* @AfterTest public static void Exit() { extent.endTest(testcase); extent.flush(); driver.close(); }*/ } <file_sep>package pages; import java.awt.AWTException; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import utilitymethods.UtilityMethods; import driver.BaseDriver; public class BellEndToEndFlowTwo extends BaseDriver { public static WebDriver driver; static Properties allInputValue; @BeforeTest public static void BrowserIntilation() throws Exception { driver = BellControlCenter.start(); } @Test(priority=1) public static void CCDisplayedAndEnabledValidation() { BellControlCenter.CCDisplayedAndEnabledValidation(); } @Test(priority=2) public static void CCContentValidation() { BellControlCenter.CCContentValidation(); } @Test(priority=3) public static void CCPlaceHolderValidation() { BellControlCenter.CCPlaceHolderValidation(); } @Test(priority=4) public static void CCRequiredFieldValidation() { BellControlCenter.CCRequiredFieldValidation(); } @Test(priority=5) public static void CCUserNameMinMaxValidation() { BellControlCenter.CCUserNameMinMaxValidation(); } @Test(priority=6) public static void CCPasswordValidation() { BellControlCenter.CCPasswordValidation(); } @Test(priority=7) public static void InputValidation() { BellControlCenter.InputValidation(); } @Test(priority=8) public static void referralRequestDataValidation() { driver.navigate().refresh(); UtilityMethods.sleep(4000); try {BellYourInfo.intial();} catch (IOException e) {e.printStackTrace();} UtilityMethods.sleep(2000); BellYourInfo.referralRequestDataValidation(); } @Test(priority=9) public static void TermsOfServiceTextValidation() { BellYourInfo.TermsOfServiceTextValidation(); } @Test(priority=10) public static void TermsOfServicePopUpCloseIcon() { BellYourInfo.TermsOfServicePopUpCloseIcon(); } @Test(priority=11) public static void TermsOfServicePopUpCloseButton() { BellYourInfo.TermsOfServicePopUpCloseButton(); } @Test(priority=12) public static void TermsOfServicePDFDownload() throws AWTException { BellYourInfo.TermsOfServicePDFDownload(); } @Test(priority=13) public static void YourInfoBellLogo() { BellYourInfo.validateOperatorLogo(); } @Test(priority=14) public static void YourInfoCompanyLogo() { BellYourInfo.validateCompanyLogo(); } @Test(priority=15) public static void YourInfoTextValiadtion() { UtilityMethods.sleep(2000); BellYourInfo.ReferralRequestTextValidation(); } @Test(priority=16) public static void YourInfoTextBoxDisplayedAndEnabled() { BellYourInfo.RequestReferralCodeTextBoxDisplayedAndEnabled(); } @Test(priority=17) public static void YourInfoLabelDisplayedAndEnabled() { UtilityMethods.sleep(2000); BellYourInfo.RequestReferralCodeLabelTextDisplayedAndEnabled(); } @Test(priority=18) public static void YourInfoValidInputValidation() { BellYourInfo.ReferralRequestCodeValidInputValidation(); } @Test(priority=19) public static void YourInfoRequiredFieldValidation() { BellYourInfo.ReferralRequestRequiredFieldValidation(); } @Test(priority=20) public static void YourInfoSpaceNotAllowedValiadation() { BellYourInfo.ReferralRequestSpaceNotAllowedValidation(); } @Test(priority=21) public static void YourInfoMaximumInputValidation() { BellYourInfo.ReferralRequestMaximumInputValidation(); } @Test(priority=22) public static void YourInfoMinimumInputValidation() { BellYourInfo.ReferralRequestMinimumInputValidation(); } @Test(priority=23) public static void YourInfoEmailValidation() { BellYourInfo.ReferralRequestEmailValidation(); } @Test(priority=25) public static void YourInfoNumericFeild() { BellYourInfo.ReferralRequestNumericFieldValidation(); } @Test(priority=26) public static void YourInfoBellLogoValidation() throws InterruptedException { BellYourInfo.BellLogoValidation(); } @Test(priority=27) public static void YourInfoBellCaLinkvalidation() throws InterruptedException { BellYourInfo.BellCALinkValidation(); } @Test(priority=28) public static void YourInfocancelButton() throws InterruptedException { BellYourInfo.ReferralrequestCancelButton(); } @Test(priority=29) public static void YourInfocontinueButton() throws InterruptedException, IOException { BellYourInfo.RequestButtonValidation(); UtilityMethods.sleep(4000); } @Test(priority=30) public static void ShippingInfovalidateOperatorLogo() throws Exception { driver.navigate().refresh(); UtilityMethods.sleep(4000); try {BellShippingInfo.Start();} catch (IOException e) {e.printStackTrace();} //driver.navigate().refresh(); UtilityMethods.sleep(5000); BellShippingInfo.validateOperatorLogo(); } @Test(priority=31) public static void ShippingInfovalidateCompanyLogo() { BellShippingInfo.validateCompanyLogo(); } @Test(priority=32) public static void ShippingInfoTextvalidation() { BellShippingInfo.ShippingInfoTextvalidation(); } @Test(priority=33) public static void shippingInfoLabelText() { BellShippingInfo.shippingInfoLabelText(); } @Test(priority=34) public static void shippingInfoInputField() { BellShippingInfo.shippingInfoInputField(); } @Test(priority=35) public static void ShippingInfoLinkButton() { BellShippingInfo.ShippingInfoLinkButton(); } @Test(priority=36) public static void ShippingInfoRequiredFieldvalidatoin() { BellShippingInfo.ShippingInfoRequiredFieldvalidatoin(); } @Test(priority=37) public static void ShippingInfoSpaceNotAllowedvalidatoin() { BellShippingInfo.ShippingInfoSpaceNotAllowedvalidatoin(); } @Test(priority=38) public static void ShippingInfoMaximumInputValidation() { BellShippingInfo.ShippingInfoMaximumInputValidation(); } @Test(priority=39) public static void ShippingInfoMinimumInputValidation() { BellShippingInfo.ShippingInfoMinimumInputValidation(); } @Test(priority=40) public static void ShippingInfoBellLogoValidation() throws InterruptedException { BellShippingInfo.ShippingBellLogoValidation(); } @Test(priority=41) public static void ShippingInfoCancelButtonValidation() throws InterruptedException { BellShippingInfo.ShippingCancelButtonValidation(); } @Test(priority=42) public static void ShippingInfoBackButtonValidation() throws InterruptedException { BellShippingInfo.ShippingBackButtonValidation(); } @Test(priority=43) public static void ShippingInfoSendInputs() { BellShippingInfo.ShippingInfoSendInputs(); } @Test(priority=44) public static void BillingInfovalidateOperatorLogo() { UtilityMethods.sleep(4000); try {BellBillingInfo.Start();} catch (Exception e) {e.printStackTrace();} UtilityMethods.sleep(2000); BellBillingInfo.validateOperatorLogo(); } @Test(priority=45) public static void BillingInfovalidateCompanyLogo() { BellBillingInfo.validateCompanyLogo(); } @Test(priority=46) public static void BillingInfoTextvalidation() { BellBillingInfo.BillingInfoTextvalidation(); } @Test(priority=47) public static void BillingCardDetailsLabelText() { BellBillingInfo.BillingCardDetailsLabelText(); } @Test(priority=48) public static void BillingCardDetailsInputFieldValidation() { BellBillingInfo.BillingCardDetailsInputFieldValidation(); } @Test(priority=49) public static void BillingCheckBoxVaildation() { BellBillingInfo.BillingCheckBoxVaildation(); } @Test(priority=50) public static void BillingInfoLabelText() { BellBillingInfo.BillingInfoLabelText(); } @Test(priority=51) public static void BillingInfoInputField() { BellBillingInfo.BillingInfoInputField(); } @Test(priority=52) public static void BillingInfoRequiredFieldvalidatoin() { BellBillingInfo.BillingInfoRequiredFieldvalidatoin(); } @Test(priority=53) public static void BillingInfoSpaceNotAllowedvalidatoin() { BellBillingInfo.BillingInfoSpaceNotAllowedvalidatoin(); } @Test(priority=54) public static void BillingInfoMaximumInputValidation() { BellBillingInfo.BillingInfoMaximumInputValidation(); } @Test(priority=55) public static void BillingInfoMinimumInputValidation() { BellBillingInfo.BillingInfoMinimumInputValidation(); } @Test(priority=56) public static void BellLogoValidation() throws InterruptedException { BellBillingInfo.BellLogoValidation(); } @Test(priority=57) public static void CancelButtonValidation() throws InterruptedException { BellBillingInfo.CancelButtonValidation(); } @Test(priority=58) public static void BackButtonValidation() throws InterruptedException { BellBillingInfo.BackButtonValidation(); } @Test(priority=59) public static void BillingInfoSendInputs() { BellBillingInfo.BillingInfoSendInputs(); } @Test(priority=60) public static void ReviewConfirmOperatorLogo() { try { BellReviewConfirm.Start(); } catch (Exception e) { e.printStackTrace(); } UtilityMethods.sleep(4000); BellReviewConfirm.validateOperatorLogo(); } @Test(priority=61) public static void ReviewConfirmCompanyLogo() { BellReviewConfirm.validateCompanyLogo(); } @Test(priority=62) public static void ReviewConfirmHeadertextValidation() { BellReviewConfirm.HeadertextValidation(); } @Test(priority=63) public static void ReviewConfirmSectionOneTextValidation() { BellReviewConfirm.SectionOneTextValidation(); } @Test(priority=64) public static void ReviewConfirmShippingBillingAddressValidation() { BellReviewConfirm.ShippingBillingAddressValidation(); } @Test(priority=65) public static void ReviewConfirmEditButtons() { BellReviewConfirm.EditButtonsValidation(); } @Test(priority=66) public static void ReviewConfirmBellLogo() throws InterruptedException { BellReviewConfirm.BellLogoValidation(); } @Test(priority=67) public static void ReviewConfirmCancelButton() throws InterruptedException { BellReviewConfirm.CancelButtonValidation(); } @Test(priority=68) public static void ShippingEditButtonValidation() throws InterruptedException { BellReviewConfirm.ShippingEditButtonValidation(); } //@Test(priority=69) public static void BillingEditButtonValidation() throws InterruptedException { BellReviewConfirm.BillingEditButtonValidation(); } @Test(priority=70) public static void ReviewConfirmButton() { BellReviewConfirm.ConfirmButtonClick(); } @Test(priority=71) public static void OrderSummaryBellLogo() { UtilityMethods.sleep(4000); try {BellOrderSummary.Start();} catch (Exception e) {e.printStackTrace();} UtilityMethods.sleep(4000); BellOrderSummary.validateOperatorLogo(); } @Test(priority=72) public static void OrderSummaryCompanyLogo() { BellOrderSummary.validateCompanyLogo(); } @Test(priority=73) public static void OrderSummaryHeadertextValidation() { BellOrderSummary.HeadertextValidation(); } @Test(priority=74) public static void orderSummaryShipBillAddressVAlidation() { BellOrderSummary.ShipBillAddressValidation(); } @Test(priority=75) public static void OrderSummarysectionTwoTextValidation() { BellOrderSummary.sectionTwoTextValidation(); } @Test(priority=76) public static void OrderSummarysectionThreeTextValidation() { BellOrderSummary.sectionThreeTextValidation(); } @Test(priority=77) public static void OrderSummaryBellLogoValidation() throws InterruptedException { BellOrderSummary.sectionOneBellLogoValidation(); } @Test(priority=78) public static void OrderSummaryBackToIOTValidation() throws InterruptedException { BellOrderSummary.sectionOneBackToIOTValidation(); } @Test(priority=79) public static void OrderSummaryTrackOrderValidation() throws InterruptedException { BellOrderSummary.sectionOneTrackOrderValidation(); } @Test(priority=80) public static void OrderSummaryhomePageLinkvalidation() throws InterruptedException { BellOrderSummary.homePageLinkvalidation(); } } <file_sep>package pages; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import utilitymethods.UtilityMethods; import driver.BaseDriver; import pageobjects.BellYourInfoPO; public class BellYourInfo extends BaseDriver { public static WebDriver driver; public static Properties allInputValue ; //@Test(priority=1) public static void intial() throws IOException { driver=BaseDriver.driver; allInputValue = UtilityMethods.getBellPropValues(); } //@Test(priority=2) public static void referralRequestDataValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(3000); UtilityMethods.InputDataValidation(BellYourInfoPO.FirstNameInput, allInputValue.getProperty("FirstName"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.LastNameInput, allInputValue.getProperty("LastName"),"textbox"); //UtilityMethods.InputDataValidation(BellYourInfoPO.CompanyNameInput, allInputValue.getProperty("CompanyName"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.PositionRoleInput, allInputValue.getProperty("Position"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.PhoneNumberInput, allInputValue.getProperty("PhoneNumber"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.EmailInput, allInputValue.getProperty("E-mailAddress"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.ModuleInput, allInputValue.getProperty("ModuleData"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.SimNanolabel, allInputValue.getProperty("SimType"),"radiobutton"); UtilityMethods.InputDataValidation(BellYourInfoPO.VolumetoDeployInput, allInputValue.getProperty("VolumeToDeploy"),"textbox"); UtilityMethods.InputDataValidation(BellYourInfoPO.IN12MonthLabel, allInputValue.getProperty("TimeFrame"),"radiobutton"); UtilityMethods.InputDataValidation(BellYourInfoPO.Description, allInputValue.getProperty("Description"),"textbox"); System.out.println("YI001"); UtilityMethods.sleep(2000); } //@Test(priority=3) public static void TermsOfServiceTextValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(5000); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.checkBoxTerms, "NotEqual","Terms Of Services"); UtilityMethods.StringValidation(BellYourInfoPO.checkBoxTerms.getText(), allInputValue.getProperty("TermsOfService"), "equalsignorecase"); UtilityMethods.sleep(5000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.checkBoxTerms, BellYourInfoPO.TermsOfServicesError,"radiobutton"); System.out.println("YI002"); UtilityMethods.sleep(5000); } //@Test(priority=4) public static void TermsOfServicePopUpCloseIcon() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(4000); BellYourInfoPO.TermsOfServicesLink.click(); UtilityMethods.sleep(4000); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CloseIcon, "NotEqual","Terms Of Services Icon"); BellYourInfoPO.CloseIcon.click(); System.out.println("YI003"); UtilityMethods.sleep(2000); } //@Test(priority=5) public static void TermsOfServicePopUpCloseButton() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.TermsOfServicesLink.click(); UtilityMethods.sleep(4000); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CloseButton, "NotEqual","Terms Of Services Button"); BellYourInfoPO.CloseButton.click(); UtilityMethods.sleep(2000); System.out.println("YI004"); UtilityMethods.sleep(2000); } //@Test(priority=6) public static void TermsOfServicePDFDownload() throws AWTException { PageFactory.initElements(driver, BellYourInfoPO.class); BellYourInfoPO.TermsOfServicesLink.click(); System.out.println("TS005.1"); UtilityMethods.sleep(2000); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.TermsOfServicesDownload, "NotEqual","Terms Of Services Download"); System.out.println("TS005.2"); if(allInputValue.getProperty("Broswer").equals("Firefox")) { BellYourInfoPO.TermsOfServicesDownload.click(); UtilityMethods.sleep(2000); System.out.println("File Downloaded"); Robot rb =new Robot(); rb.keyPress(KeyEvent.VK_ENTER); System.out.println("Pop up Closed"); UtilityMethods.sleep(1000); rb.keyRelease(KeyEvent.VK_ENTER); } else if(allInputValue.getProperty("Broswer").equals("IE")) { String PdfUrl = BellYourInfoPO.TermsOfServicesDownload.getAttribute("href"); System.out.println("The URL is: "+PdfUrl+""); System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+ "\\libs\\IEDriverServer.exe"); InternetExplorerDriver driver1 = new InternetExplorerDriver(); driver1.get(PdfUrl); UtilityMethods.sleep(5000); Robot rb =new Robot(); rb.keyPress(KeyEvent.VK_ALT); rb.keyPress(KeyEvent.VK_S); rb.keyRelease(KeyEvent.VK_ALT); rb.keyRelease(KeyEvent.VK_S); UtilityMethods.sleep(5000); System.out.println("File Downloaded"); driver1.close(); } else { BellYourInfoPO.TermsOfServicesDownload.click(); UtilityMethods.sleep(2000); System.out.println("File Downloaded"); System.out.println("Pop up Closed"); } BellYourInfoPO.CloseButton.click(); System.out.println("YI005"); UtilityMethods.sleep(2000); } //@Test(priority=7) public static void validateOperatorLogo() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.BellLogo, "NotEqual","Bell Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellYourInfoPO.BellLogo,"src",allInputValue.getProperty("bellLogo"),"Bell Operator Logo"); System.out.println("YI006"); UtilityMethods.sleep(2000); } //@Test(priority=8) public static void validateCompanyLogo() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellYourInfoPO.CiscoLogo,"src",allInputValue.getProperty("ciscoLogo"),"Cisco Jasper Company Logo"); System.out.println("YI007"); UtilityMethods.sleep(2000); } //@Test(priority=9) public static void ReferralRequestTextValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.StringValidation(BellYourInfoPO.ContactInfoText.getText(), "Contact Information", "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.DeviceInfoText.getText(), "Device Information", "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.checkBoxLabel.getText(), allInputValue.getProperty("referralrequestCheckBox"), "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.OrderIotHeaderText.getText(), "Order IoT Starter Kit", "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.YourInfoText.getText(), "Your Information", "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.ShppingText.getText(), "Shipping", "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.PaymentText.getText(), "Payment", "equalsignorecase"); UtilityMethods.StringValidation(BellYourInfoPO.ReviewConfirmText.getText(), "Review & Confirm", "equalsignorecase"); System.out.println("YI008"); UtilityMethods.sleep(2000); } //@Test(priority=10) public static void RequestReferralCodeTextBoxDisplayedAndEnabled() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.FirstNameInput, "NotEqual", "First Name Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.LastNameInput, "NotEqual", "Last Name Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CompanyNameInput, "NotEqual", "Company Name Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.PositionRoleInput, "NotEqual", "Position/Role Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.PhoneNumberInput, "NotEqual", "Phone Number Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.EmailInput, "NotEqual", "E-mail Address Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.ModuleInput, "NotEqual", "Module Name Input Field"); //UtilityMethods.DisplayEnableValidator(BellYourInfoPO.BusinessInput, "NotEqual", "Business Type Drop Down Menu"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Sim2FFInput, "NotEqual", "2FF Sim Type Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Sim3FFInput, "NotEqual", "3FF Sim Type Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.SimNanoInput, "NotEqual", "Nano Sim Type Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.VolumetoDeployInput, "NotEqual", "Volume to deploy Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.IN3MonthInput, "NotEqual", "Within 3 months Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.IN6MonthInput, "NotEqual", "3-6 months Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.IN12MonthInput, "NotEqual", "6-12 months Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Morethan12MonthInput, "NotEqual", "More than 12 months/unknown Radio Button"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Description, "NotEqual", "Description Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.checkBoxLabel, "NotEqual", "Check Box Input Field"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CancelButton, "NotEqual", "Cancel Button"); System.out.println("YI009"); UtilityMethods.sleep(2000); } //@Test(priority=11) public static void RequestReferralCodeLabelTextDisplayedAndEnabled() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.FirstNameLabel, "NotEqual", "First Name Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.LastNameLabel, "NotEqual", "Last Name Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CompanyNameLabel, "NotEqual", "Company Name Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.PositionRoleLabel, "NotEqual", "Position/Role Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.PhoneNumberLabel, "NotEqual", "Phone Number Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.EmailLabel, "NotEqual", "E-mail Address Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.ModuleLabel, "NotEqual", "Module Name Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.BusinessLabel, "NotEqual", "Business TypeLabel Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.SimLabel, "NotEqual", "Sim Type Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Sim2FFLabel, "NotEqual", "2FF Mini Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Sim3FFlabel, "NotEqual", "3FF Micro Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.SimNanolabel, "NotEqual", "3FF Micro Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.VolumetoDeployLabel, "NotEqual", "Volume to deploy Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.LastNameLabel, "NotEqual", "Launch Timeframe Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.IN3MonthLabel, "NotEqual", "Within 3 months Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.IN6Monthlabel, "NotEqual", "3-6 months Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.IN12MonthLabel, "NotEqual", "6-12 months Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.Morethan12Monthlabel, "NotEqual", "More than 12 months/unknown Label Text"); UtilityMethods.DisplayEnableValidator(BellYourInfoPO.DescriptionLabel, "NotEqual", "Description Label Text"); System.out.println("YI010"); UtilityMethods.sleep(2000); } //@Test(priority=12) public static void ReferralRequestCodeValidInputValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.ValidInputValidation(BellYourInfoPO.FirstNameInput, allInputValue.getProperty("ValidFirstName"), BellYourInfoPO.FirstNameError); UtilityMethods.ValidInputValidation(BellYourInfoPO.LastNameInput, allInputValue.getProperty("ValidLastName"),BellYourInfoPO.LastNameError ); UtilityMethods.ValidInputValidation(BellYourInfoPO.CompanyNameInput, allInputValue.getProperty("ValidCompanyName"), BellYourInfoPO.CompanyError); UtilityMethods.ValidInputValidation(BellYourInfoPO.PositionRoleInput, allInputValue.getProperty("ValidPosition"), BellYourInfoPO.PositionError); UtilityMethods.ValidInputValidation(BellYourInfoPO.PhoneNumberInput,allInputValue.getProperty("ValidPhoneNumber"),BellYourInfoPO.PhoneNumberError); UtilityMethods.ValidInputValidation(BellYourInfoPO.EmailInput,allInputValue.getProperty("ValidEmailId") , BellYourInfoPO.EmailError); UtilityMethods.ValidInputValidation(BellYourInfoPO.ModuleInput, allInputValue.getProperty("ValidModule"), BellYourInfoPO.ModuleError); //UtilityMethods.ValidateDropDown(BellYourInfoPO.BusinessInput, "Consumer electronics - personal navigation", BellYourInfoPO.BusinessTypeError); UtilityMethods.ValidInputValidation(BellYourInfoPO.VolumetoDeployInput, allInputValue.getProperty("ValidVolumeToDeploy"),BellYourInfoPO.VolumetoDeployError); UtilityMethods.ValidInputValidation(BellYourInfoPO.Description, allInputValue.getProperty("ValidDescription"), BellYourInfoPO.DescriptionError); //UtilityMethods.ValidateSimTypeRadioButton(2,driver.findElement(By.xpath("//div[@id='simTypeId-error']"))); //driver.findElement(By.xpath("//label[text()='2FF/Ruggedized']")).click(); System.out.println("YI011"); UtilityMethods.sleep(2000); } //@Test(priority=13) public static void ReferralRequestRequiredFieldValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.FirstNameInput, BellYourInfoPO.FirstNameError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.LastNameInput, BellYourInfoPO.LastNameError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.CompanyNameInput, BellYourInfoPO.CompanyError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.PositionRoleInput, BellYourInfoPO.PositionError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.PhoneNumberInput, BellYourInfoPO.PhoneNumberError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.EmailInput, BellYourInfoPO.EmailError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.ModuleInput, BellYourInfoPO.ModuleError,"TextBox"); //UtilityMethods.RequiredFieldValidation(BellYourInfoPO.BusinessInput, BellYourInfoPO.BusinessTypeError,"DropDown"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.VolumetoDeployInput, BellYourInfoPO.VolumetoDeployError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.LaunchTimeframeLabel, BellYourInfoPO.LastNameError,"RadioButton"); UtilityMethods.RequiredFieldValidation(BellYourInfoPO.Description, BellYourInfoPO.DescriptionError,"TextBox"); System.out.println("YI012"); UtilityMethods.sleep(2000); } //@Test(priority=14) public static void ReferralRequestSpaceNotAllowedValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.SpaceNotAllowedvalidation(BellYourInfoPO.FirstNameInput, BellYourInfoPO.FirstNameError); UtilityMethods.SpaceNotAllowedvalidation(BellYourInfoPO.LastNameInput, BellYourInfoPO.LastNameError); UtilityMethods.SpaceNotAllowedvalidation(BellYourInfoPO.CompanyNameInput, BellYourInfoPO.CompanyError); UtilityMethods.SpaceNotAllowedvalidation(BellYourInfoPO.PositionRoleInput, BellYourInfoPO.PositionError); System.out.println("YI013"); UtilityMethods.sleep(2000); } //@Test(priority=15) public static void ReferralRequestMaximumInputValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.MaximumInputValidation(BellYourInfoPO.FirstNameInput, BellYourInfoPO.FirstNameError, 49, allInputValue.getProperty("InvalidInput")); UtilityMethods.MaximumInputValidation(BellYourInfoPO.LastNameInput, BellYourInfoPO.LastNameError, 49, allInputValue.getProperty("InvalidInput")); UtilityMethods.MaximumInputValidation(BellYourInfoPO.CompanyNameInput, BellYourInfoPO.CompanyError, 25, allInputValue.getProperty("InvalidCompanyName")); UtilityMethods.MaximumInputValidation(BellYourInfoPO.PositionRoleInput, BellYourInfoPO.PositionError, 25, allInputValue.getProperty("InvalidCompanyName")); UtilityMethods.MaximumInputValidation(BellYourInfoPO.PhoneNumberInput, BellYourInfoPO.PhoneNumberError, 25, allInputValue.getProperty("Invalidphonenumber")); UtilityMethods.MaximumInputValidation(BellYourInfoPO.Description, BellYourInfoPO.DescriptionError, 255, allInputValue.getProperty("InvalidDescription")); System.out.println("YI014"); UtilityMethods.sleep(2000); } //@Test(priority=16) public static void ReferralRequestMinimumInputValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.MinimumInputValidation(BellYourInfoPO.CompanyNameInput, BellYourInfoPO.CompanyError, 3, allInputValue.getProperty("InvalidMinInput")); UtilityMethods.MinimumInputValidation(BellYourInfoPO.PhoneNumberInput, BellYourInfoPO.PhoneNumberError, 10, allInputValue.getProperty("InvalidMinphonenumber")); System.out.println("YI015"); UtilityMethods.sleep(2000); } //@Test(priority=17) public static void ReferralRequestEmailValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.EmailIdInvalidvalidation(BellYourInfoPO.EmailInput, BellYourInfoPO.EmailError, allInputValue.getProperty("InvalidEmailID")); System.out.println("YI016"); UtilityMethods.sleep(2000); } //@Test(priority=18) public static void ReferralRequestNumericFieldValidation() { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); UtilityMethods.sleep(5000); UtilityMethods.NumericFieldValidation(BellYourInfoPO.PhoneNumberInput, BellYourInfoPO.PhoneNumberError, allInputValue.getProperty("InvalidPhoneNumber")); UtilityMethods.NumericFieldValidation(BellYourInfoPO.VolumetoDeployInput, BellYourInfoPO.VolumetoDeployError, allInputValue.getProperty("InvadildNumbericField")); System.out.println("YI017"); UtilityMethods.sleep(2000); } //@Test(priority=19) public static void BellLogoValidation() throws InterruptedException { UtilityMethods.sleep(2000); UtilityMethods.pageRedirection(BellYourInfoPO.BellLogo, BellYourInfoPO.CancelButtonFindElement,"HomePage"); System.out.println("YI018"); UtilityMethods.sleep(2000); } //@Test(priority=20) public static void BellCALinkValidation() throws InterruptedException { UtilityMethods.DisplayEnableValidator(BellYourInfoPO.BellCaLink, "NotEqual","Bell Ca Link referral request page"); UtilityMethods.StringValidation(BellYourInfoPO.BellCaLink.getText(), "bell.ca/communicationpreferences", "equalsignorecase"); UtilityMethods.sleep(2000); UtilityMethods.PageNavigationValidation(BellYourInfoPO.BellCaLink, BellYourInfoPO.BellCaLinkFindElement, "Email updates from Bell Canada – manage your email preferences"); System.out.println("YI019"); UtilityMethods.sleep(2000); } //@Test(priority=21) public static void ReferralrequestCancelButton() throws InterruptedException { UtilityMethods.DisplayEnableValidator(BellYourInfoPO.CancelButton, "NotEqual","Your Info Cancel Button"); UtilityMethods.StringValidation(BellYourInfoPO.CancelButton.getText(), "Cancel", "equalsignorecase"); UtilityMethods.sleep(2000); UtilityMethods.pageRedirection(BellYourInfoPO.CancelButton, BellYourInfoPO.CancelButtonFindElement,"HomePage"); System.out.println("YI020"); UtilityMethods.sleep(2000); } //@Test(priority=22) public static void RequestButtonValidation() throws IOException { PageFactory.initElements(driver, BellYourInfoPO.class); UtilityMethods.sleep(2000); UtilityMethods.SendInputValues(BellYourInfoPO.FirstNameInput, allInputValue.getProperty("FirstName"), "TextBox"); UtilityMethods.SendInputValues(BellYourInfoPO.LastNameInput, allInputValue.getProperty("LastName"), "TextBox"); UtilityMethods.sleep(1000); UtilityMethods.SendInputValues(BellYourInfoPO.CompanyNameInput, allInputValue.getProperty("CompanyName")+UtilityMethods.GenerateRandomNum(5), "TextBox"); UtilityMethods.SendInputValues(BellYourInfoPO.PositionRoleInput, allInputValue.getProperty("Position"), "TextBox"); UtilityMethods.sleep(1000); UtilityMethods.SendInputValues(BellYourInfoPO.PhoneNumberInput, allInputValue.getProperty("PhoneNumber"), "TextBox"); UtilityMethods.SendInputValues(BellYourInfoPO.EmailInput, allInputValue.getProperty("E-mailAddress"), "TextBox"); UtilityMethods.sleep(1000); UtilityMethods.SendInputValues(BellYourInfoPO.ModuleInput, allInputValue.getProperty("ModuleData"), "TextBox"); //UtilityMethods.SendInputValues(BellYourInfoPO.BusinessInput, allInputValue.getProperty("BusinessType"), "DropDown"); UtilityMethods.sleep(1000); UtilityMethods.SendInputValues(BellYourInfoPO.SimNanolabel, "", "Radiobutton"); UtilityMethods.SendInputValues(BellYourInfoPO.VolumetoDeployInput, allInputValue.getProperty("VolumeToDeploy"), "TextBox"); UtilityMethods.sleep(1000); UtilityMethods.SendInputValues(BellYourInfoPO.IN12MonthLabel, "", "Radiobutton"); UtilityMethods.SendInputValues(BellYourInfoPO.Description, allInputValue.getProperty("Description"), "TextBox"); UtilityMethods.sleep(2000); BellYourInfoPO.checkBoxTerms.click(); UtilityMethods.sleep(2000); BellYourInfoPO.ContinueButton.click(); System.out.println("YI021"); UtilityMethods.sleep(2000); } } <file_sep>package pages; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import utilitymethods.*; public class AdminOperation { static Properties allInputValue; public static String BrowserForUse; public static WebDriver driver; //@Test(priority=1) public static void AdminApproval() throws InterruptedException { try {allInputValue=UtilityMethods.getPropValues();} catch (IOException e) {e.printStackTrace();} BrowserForUse=allInputValue.getProperty("Broswer"); if (BrowserForUse.equals("FireFox")) { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Mozilla FireFox browser launched"); } else if (BrowserForUse.equals("Chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\libs\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); System.out.println("Chrome browser launched"); } else if (BrowserForUse.equals("IE")) { System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+ "\\libs\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.manage().window().maximize(); System.out.println("Internet Explorer browser launched"); } else { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Default browser is Mozilla FireFox is launched"); } driver.get(allInputValue.getProperty("AdminURL")); Thread.sleep(4000); driver.findElement(By.xpath("//input[@id='userName']")).sendKeys(allInputValue.getProperty("AdminUserName")); driver.findElement(By.xpath("//input[@value='Login']")).click(); Thread.sleep(4000); driver.findElement(By.xpath("//div[@class='blpr-menu blpr-dsk-menu']//span[text()='Referrals']")).click(); Thread.sleep(4000); driver.findElement(By.xpath("//div[@id='approve0']")).click(); Thread.sleep(4000); driver.findElement(By.xpath("//div[@id='aprCode']//button[@type='submit']")).click(); driver.close(); System.out.println("Referral request Approved"); } //@BeforeTest public static void AdminOrderFulfill() throws InterruptedException { try {allInputValue=UtilityMethods.getPropValues();} catch (IOException e) {e.printStackTrace();} BrowserForUse=allInputValue.getProperty("Broswer"); if (BrowserForUse.equals("FireFox")) { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Mozilla FireFox browser launched"); } else if (BrowserForUse.equals("Chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\libs\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); System.out.println("Chrome browser launched"); } else if (BrowserForUse.equals("IE")) { System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+ "\\libs\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.manage().window().maximize(); System.out.println("Internet Explorer browser launched"); } else { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Default browser is Mozilla FireFox is launched"); } driver.get(allInputValue.getProperty("AdminURL")); Thread.sleep(4000); driver.findElement(By.xpath("//input[@id='userName']")).sendKeys(allInputValue.getProperty("AdminUserName")); driver.findElement(By.xpath("//input[@value='Login']")).click(); Thread.sleep(4000); driver.findElement(By.xpath("//div[@class='blpr-menu blpr-dsk-menu']//span[text()='Orders']")).click(); Thread.sleep(4000); driver.findElement(By.xpath("//div[@id='order0']")).click(); Thread.sleep(4000); driver.findElement(By.xpath("//input[@name='tracking_no']")).sendKeys(UtilityMethods.GenerateRandomAlphaNumeric(8)); driver.findElement(By.xpath("//input[@name='delivery_date']")).sendKeys("2017/10/10"); driver.findElement(By.xpath("//button[@id='create_fulfill']")).click(); driver.close(); System.out.println("Order Fulfilled"); } } <file_sep>package test; import java.awt.AWTException; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import bell.BellBillingInfo; import bell.BellControlCenter; import bell.BellHomePage; import bell.BellOrderSummary; import bell.BellReferralRequestPage; import bell.BellReferralRequestThankYou; import bell.BellReviewConfirm; import bell.BellShippingInfo; import bell.BellYourInfo; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import pages.AdminOperation; import pages.EmailIntegration; import utilitymethods.UtilityMethods; public class DummyTest { public static WebDriver driver; static Properties allInputValue; public static ExtentReports extent; public static ExtentTest testcase; @BeforeTest public static void DeletingPreviousEmail() { //EmailIntegration.DeleteAllEmail(); extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/Advanced.html", true ); } @AfterMethod public static void getResult(ITestResult result) { if(result.getStatus()==ITestResult.FAILURE) { testcase.log(LogStatus.FAIL, result.getName()); } if(result.getStatus()==ITestResult.SUCCESS) { testcase.log(LogStatus.PASS, result.getName()); } extent.endTest(testcase); } @Test(priority=1) public static void BrowserIntilation() throws Exception { testcase = extent.startTest("Intialise Browser", "opening Browser and loading Base Home Page URL"); testcase.log(LogStatus.INFO, "opening Browser and loading base Home Page URL"); driver = BellHomePage.start(); } @Test(priority=2) public static void HomePageBellLogo() { testcase = extent.startTest("Home Page Bell Logo", "Validating Bell logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellHomePage.validateOperatorLogo(); } @Test(priority=3) public static void HomePageCiscoLogo() { testcase = extent.startTest("Home Page Cisco Logo", "Validating Cisco logo"); testcase.log(LogStatus.INFO, "Validating Image URl,Displayed and Enabled"); BellHomePage.validateCompanyLogo(); } @Test(priority=4) public static void HomePageSecOneTextValidation() { testcase = extent.startTest("Home Page Section 1 ", "Section One Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellHomePage.sectionOneIotStarterKitBellValidation(); } @Test(priority=5) public static void HomePageTrackOrderValidation() throws InterruptedException { testcase = extent.startTest("Home Page Track Order", "Validating track Order Button"); testcase.log(LogStatus.INFO, "Validating String,PlaceHolder,Enabled,Displayed"); BellHomePage.sectionOneIotStarterKitTrackOrderValidation(); } @Test(priority=6) public static void HomePageReferralCodeValidation() throws InterruptedException { testcase = extent.startTest("Home Page Referral Code", "Validating ReferralCode"); testcase.log(LogStatus.INFO, "Validating String,PlaceHolder,Enabled,Displayed"); BellHomePage.sectionOneIotStarterKitEnterReferralCodeValidation(); } @Test(priority=7) public static void HomePageTrackOrderErrorValidation() throws InterruptedException { testcase = extent.startTest("Home Page Track Order pop up Error message and Close Icon", "Validating Track Order Error Message and Close Icon"); testcase.log(LogStatus.INFO, "Validating Error Message For Trak Order CLose Icon"); BellHomePage.sectionOneIotStarterKitTrackOrderErrorValidation(); } @Test(priority=8) public static void HomePageEnterrefrralCodeErrorvalidation() throws InterruptedException { testcase = extent.startTest("Home Page Enter Referral Code Error Message and Close Icon", "Validating Enter Referral Code Error Message and Close Icon"); testcase.log(LogStatus.INFO, "Validating Error Message For Trak Order CLose Icon"); BellHomePage.sectionOneIotStarterKitReferralCodeErrorValidation(); } @Test(priority=9) public static void HomePageSecTwoContentValidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Content ", "Section Two Content Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesContentvalidation(); } @Test(priority=10) public static void HomePageSecTwoWhatThekitIncludesToolsvalidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Content ", "Section Two Tools Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesToolsvalidation(); } @Test(priority=11) public static void HomePageSecTwoWhatThekitIncludesCentervalidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Content ", "Section Two Center Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesCentervalidation(); } @Test(priority=12) public static void HomePagesectionTwoWhatThekitIncludesSuppportvalidation() { testcase = extent.startTest("Home Page Section 2 What The kit includes Content ", "Section Two Support Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionTwoWhatThekitIncludesSuppportvalidation(); } @Test(priority=13) public static void HomePagesectionThreeHowItWorksValidation() { testcase = extent.startTest("Home Page Section 3 How It Works", "Section Three How It Works Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellHomePage.sectionThreeHowItWorksValidation(); } @Test(priority=14) public static void HomePagesectionFourWhatIsIotValidation() { testcase = extent.startTest("Home Page Section 4 IoT From Bell ", "Section Four IoT From Bell Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFourWhatIsIotValidation(); } @Test(priority=15) public static void HomePagesectionOneLinkvalidation() throws Exception { testcase = extent.startTest("Home Page Section 1 Scrolling Link Validation ", "Section One Scrolling Link Validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Page Scrolling"); BellHomePage.sectionOneLinkvalidation(); } @Test(priority=16) public static void HomePagesectionFiveWithBell() { testcase = extent.startTest("Home Page Section 5 With Bell", "Section Five With Bell Text validation"); testcase.log(LogStatus.INFO, "String Validation"); BellHomePage.sectionFiveWithBell(); } @Test(priority=17) public static void HomePagesectionFiveLTE() { testcase = extent.startTest("Home Page Section 5 With Bell ", "Section Five With Bell 1 Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFiveLTE(); } @Test(priority=18) public static void HomePagesectionFivePartners() { testcase = extent.startTest("Home Page Section 5 With Bell ", "Section Five With Bell 2 Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFivePartners(); } @Test(priority=19) public static void HomePagesectionFiveEndToEnd() { testcase = extent.startTest("Home Page Section 5 With Bell ", "Section Five With Bell 2 Text validation"); testcase.log(LogStatus.INFO, "String Validation,Enabled,Displayed,Image URl"); BellHomePage.sectionFiveEndToEnd(); } @AfterTest public static void Exit() { extent.endTest(testcase); extent.flush(); driver.close(); } } <file_sep>#Sat Apr 07 12:29:41 IST 2018 org.eclipse.core.runtime=2 org.eclipse.platform=4.4.2.v20150204-1700 <file_sep>package pages; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import pageobjects.BellTrackOrderPO; import driver.BaseDriver; import utilitymethods.UtilityMethods; public class BellTrackOrder extends BaseDriver { public static WebDriver driver; static Properties allInputValue; @BeforeTest public static WebDriver start() throws Exception { allInputValue = UtilityMethods.getBellPropValues(); driver = launchApp(allInputValue.getProperty("BaseURl")); return driver; } @Test(priority=1) public static void TrackOrderValidPageRedirection() throws InterruptedException { PageFactory.initElements(driver, BellTrackOrderPO.class); BellTrackOrderPO.SectionOneTrackOrderButton.click(); UtilityMethods.sleep(2000); BellTrackOrderPO.TrackOrderEmailID.sendKeys(allInputValue.getProperty("TrackOrder.validTrackOrderEmailID")); BellTrackOrderPO.SectionOneTrackOrderPRButton.click(); UtilityMethods.sleep(2000); System.out.println("TO001"); } @Test(priority=2) public static void validateOperatorLogo() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.DisplayEnableValidator(BellTrackOrderPO.BellLogo, "NotEqual","Bell Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellTrackOrderPO.BellLogo,"src",allInputValue.getProperty("bellLogo"),"Bell Operator Logo"); System.out.println("TO002"); } @Test(priority=3) public static void validateCompanyLogo() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.DisplayEnableValidator(BellTrackOrderPO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellTrackOrderPO.CiscoLogo,"src",allInputValue.getProperty("ciscoLogo"),"Cisco Jasper Company Logo"); System.out.println("TO003"); } @Test(priority=4) public static void SectionOneTextValidaion() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.StringValidation(BellTrackOrderPO.Headertext.getText(), "Track Your Order", "equalsignorecase"); UtilityMethods.StringValidation(BellTrackOrderPO.OrderdateText.getText(), "Order Date:", "equalsignorecase"); UtilityMethods.StringValidation(BellTrackOrderPO.Tracking_NOtext.getText(), "Tracking Number:", "equalsignorecase"); UtilityMethods.StringValidation(BellTrackOrderPO.EDDText.getText(), "Expected Delivery:", "equalsignorecase"); System.out.println("TO004"); } @Test(priority=5) public static void SectionTwoTextvalidation() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.StringValidation(BellTrackOrderPO.OrderReceivedtext.getText(), "Order Received", "equalsignorecase"); UtilityMethods.StringValidation(BellTrackOrderPO.ProcessingText.getText(), "Processing", "equalsignorecase"); UtilityMethods.StringValidation(BellTrackOrderPO.Shippedtext.getText(), "Shipped", "equalsignorecase"); System.out.println("TO005"); } @Test(priority=6) public static void BackToIOT() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.DisplayEnableValidator(BellTrackOrderPO.BackToIOT, "NotEqual","resend Confirmation Button"); UtilityMethods.ThankYouPageRedirection(BellTrackOrderPO.BackToIOT, BellTrackOrderPO.HomePageFindElement); System.out.println("TO006"); } @Test(priority=7) public static void BellLogoHomePage() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.DisplayEnableValidator(BellTrackOrderPO.BellLogo, "NotEqual","resend Confirmation Button"); UtilityMethods.ThankYouPageRedirection(BellTrackOrderPO.BellLogo, BellTrackOrderPO.HomePageFindElement); System.out.println("TO007"); } @Test(priority=8) public static void ResendConfirmationButton() { PageFactory.initElements(driver, BellTrackOrderPO.class); UtilityMethods.DisplayEnableValidator(BellTrackOrderPO.ResendConfirmation, "NotEqual","resend Confirmation Button"); BellTrackOrderPO.ResendConfirmation.click(); UtilityMethods.sleep(2000); String SuccessMessage= BellTrackOrderPO.ResendConfirmationSucessMessage.getText(); if(SuccessMessage.equals("Email sent successfully")) { System.out.println("Email Send Successfully"); } else if (SuccessMessage.equals("Sorry Email not sent successfully")) { System.out.println("Sorry Email not sent successfully"); } else { System.out.println("Message not displayed"); } System.out.println("TO008"); driver.close(); } @Test(priority=9) public static void CheckingOrderSuccessEmail() { EmailIntegration.CheckEmailReceived(); System.out.println("TO009"); } } <file_sep>package pageobjects; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; public class BellControlCenterPO { @FindBy(how=How.XPATH,using="//input[@id='uname']") public static WebElement UserNameInput; @FindBy(how=How.XPATH,using="//input[@id='psswrd']") public static WebElement PasswordInput; @FindBy(how=How.XPATH,using="//input[@id='cpsswrd']") public static WebElement ConfirmPasswordInput; @FindBy(how=How.XPATH,using="//input[@id='create_cc']") public static WebElement CreateButton; @FindBy(how=How.XPATH,using="//label[@for='uname']") public static WebElement UserNameLabel; @FindBy(how=How.XPATH,using="//label[@for='psswrd']") public static WebElement PasswordLabel; @FindBy(how=How.XPATH,using="//label[@for='cpsswrd']") public static WebElement ConfrimPasswordlabel; @FindBy(how=How.XPATH,using="//input[@value='Request']") public static WebElement CreateFindElement; @FindBy(how=How.XPATH,using="//div[@id='ctrlAcc']//h2") public static WebElement Header1; @FindBy(how=How.XPATH,using="//div[@class='text-center f16']//p") public static WebElement Para1; @FindBy(how=How.XPATH,using="//div[@class='uname form-group']//p") public static WebElement UserNamePara; @FindBy(how=How.XPATH,using="//div[@class='pword form-group']//p") public static WebElement PasswordPara; @FindBy(how=How.XPATH,using="//div[@id='psswrd-error']") public static WebElement PasswordError; @FindBy(how=How.XPATH,using="//div[@id='uname-error']") public static WebElement UserNameError; @FindBy(how=How.XPATH,using="//input[@id='cpsswrd-error']") public static WebElement ConfirmPasswordError; } <file_sep>package pages; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import driver.BaseDriver; import pageobjects.BellBillingInfoPO; import pageobjects.BellReviewConfirmPO; import utilitymethods.UtilityMethods; public class BellReviewConfirm extends BaseDriver { public static WebDriver driver =BaseDriver.driver; static Properties allInputValue; //@BeforeTest public static void Start() throws Exception { allInputValue = UtilityMethods.getBellPropValues(); PageFactory.initElements(driver, BellReviewConfirmPO.class); } public static void validateOperatorLogo() { UtilityMethods.DisplayEnableValidator(BellReviewConfirmPO.BellLogo, "NotEqual","Bell Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellReviewConfirmPO.BellLogo,"src",allInputValue.getProperty("bellLogo"),"Bell Operator Logo"); System.out.println("RC001"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } public static void validateCompanyLogo() { UtilityMethods.DisplayEnableValidator(BellReviewConfirmPO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellReviewConfirmPO.CiscoLogo,"src",allInputValue.getProperty("ciscoLogo"),"Cisco Jasper Company Logo"); System.out.println("RC002"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } public static void HeadertextValidation() { UtilityMethods.StringValidation(BellReviewConfirmPO.OrderIotHeaderText.getText(), "Order IoT Starter Kit", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.SectionOneHead4.getText(), "Order Summary", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.YourInfoText.getText(), "Your Information", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.ShppingText.getText(), "Shipping", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.PaymentText.getText(), "Payment", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.ReviewConfirmText.getText(), "Review & Confirm", "equalsignorecase"); System.out.println("RC003"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } public static void SectionOneTextValidation() { UtilityMethods.StringValidation(BellReviewConfirmPO.IOTText.getText(), "IoT Starter Kit", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.TestSimText.getText(), "3 Test SIMs", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.MBPerSimTextl.getText(), "30MB per SIM per month", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.SMSPerSimText.getText(), "50 SMS per SIM per month", "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.FullAcessText.getText(), "Full access to Bell Control Centre", "equalsignorecase"); System.out.println("RC004"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } public static void ShippingBillingAddressValidation() { if(allInputValue.getProperty("sameShippBillAddress").equals("Yes")) { UtilityMethods.StringValidation(BellReviewConfirmPO.ShippingAddress.getText().replace("\n", " "), allInputValue.getProperty("shippindAddress"), "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.BillingAddress.getText().replace("\n", " "), allInputValue.getProperty("shippindAddress"), "equalsignorecase"); System.out.println("RC005"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } else if (allInputValue.getProperty("sameShippBillAddress").equals("No")) { UtilityMethods.StringValidation(BellReviewConfirmPO.ShippingAddress.getText().replace("\n", " "), allInputValue.getProperty("shippindAddress"), "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.BillingAddress.getText().replace("\n", " "), allInputValue.getProperty("billingAddress"), "equalsignorecase"); System.out.println("RC005"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } else { UtilityMethods.StringValidation(BellReviewConfirmPO.ShippingAddress.getText().replace("\n", " "), allInputValue.getProperty("shippindAddress"), "equalsignorecase"); UtilityMethods.StringValidation(BellReviewConfirmPO.BillingAddress.getText().replace("\n", " "), allInputValue.getProperty("shippindAddress"), "equalsignorecase"); System.out.println("RC005"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } } public static void EditButtonsValidation() { UtilityMethods.DisplayEnableValidator(BellReviewConfirmPO.ShippingEdit, "NotEqual", "Edit button in shipping"); UtilityMethods.DisplayEnableValidator(BellReviewConfirmPO.BillingEdit, "NotEqual", "Edit button in Billing"); System.out.println("RC006"); try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} } public static void BellLogoValidation() throws InterruptedException { PageFactory.initElements(driver, BellReviewConfirmPO.class); UtilityMethods.pageRedirection(BellReviewConfirmPO.BellLogo, BellReviewConfirmPO.CancelButtonFindElement,"Others"); System.out.println("RC007"); try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();} } public static void CancelButtonValidation() throws InterruptedException { PageFactory.initElements(driver, BellReviewConfirmPO.class); UtilityMethods.pageRedirection(BellReviewConfirmPO.CancelButton, BellReviewConfirmPO.CancelButtonFindElement,"Others"); System.out.println("RC008"); try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();} } public static void ShippingEditButtonValidation() throws InterruptedException { PageFactory.initElements(driver, BellReviewConfirmPO.class); UtilityMethods.pageRedirection(BellReviewConfirmPO.ShippingEdit, BellReviewConfirmPO.ShipEditFindElement,"Others"); System.out.println("RC009"); try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();} } public static void BillingEditButtonValidation() throws InterruptedException { PageFactory.initElements(driver, BellReviewConfirmPO.class); UtilityMethods.pageRedirection(BellReviewConfirmPO.BillingEdit, BellReviewConfirmPO.BillEditFindElement,"Others"); System.out.println("RC010"); try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();} } public static void ConfirmButtonClick() { PageFactory.initElements(driver, BellReviewConfirmPO.class); UtilityMethods.DisplayEnableValidator(BellReviewConfirmPO.ConfirmButton, "NotEqual", "Edit button in Billing"); BellReviewConfirmPO.ConfirmButton.click(); System.out.println("RC011"); try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();} } } <file_sep>package pages; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import utilitymethods.UtilityMethods; import driver.BaseDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class Tele2ShippingInfo extends BaseDriver { public static FirefoxDriver driver = launchApp(); static Properties allInputValue; @BeforeTest public static void Start() throws IOException { allInputValue = UtilityMethods.getTele2PropValues(); } private static FirefoxDriver launchApp() { // TODO Auto-generated method stub return null; } @Test public static void validateOperatorLogo() { WebElement operatorLogo = driver.findElement(By.xpath("//img[@alt='Tele2']")); UtilityMethods.DisplayEnableValidator(operatorLogo, "NotEqual","Tele2 Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(operatorLogo,"src",allInputValue.getProperty("tele2Logo"),"Tele2 Operator Logo"); } @Test(priority=1) public static void validateCompanyLogo() { WebElement companyLogo = driver.findElement(By.xpath("//img[@alt='Cisco Jasper']")); UtilityMethods.DisplayEnableValidator(companyLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(companyLogo,"src",allInputValue.getProperty("tele2CompanyLogo"),"Cisco Jasper Company Logo"); } public static void HearTextvalidation() { UtilityMethods.StringValidation(driver.findElement(By.xpath("//section[@id='hero-wrp']//h2")).getText(), allInputValue.getProperty("HomePage.Bannerh2"), "equalsignorecase"); } } <file_sep>package pages; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import driver.BaseDriver; import pageobjects.BellBillingInfoPO; import pageobjects.BellShippingInfoPO; import pageobjects.BellYourInfoPO; import utilitymethods.UtilityMethods; public class BellBillingInfo extends BaseDriver { public static WebDriver driver =BaseDriver.driver ; static Properties allInputValue; public static void Start() throws Exception { allInputValue = UtilityMethods.getBellPropValues(); PageFactory.initElements(driver, BellBillingInfoPO.class); } public static void validateOperatorLogo() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BellLogo, "NotEqual","Bell Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellBillingInfoPO.BellLogo,"src",allInputValue.getProperty("bellLogo"),"Bell Operator Logo"); System.out.println("BI001"); UtilityMethods.sleep(2000); } public static void validateCompanyLogo() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellBillingInfoPO.CiscoLogo,"src",allInputValue.getProperty("ciscoLogo"),"Cisco Jasper Company Logo"); System.out.println("BI002"); UtilityMethods.sleep(2000); } public static void BillingInfoTextvalidation() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.StringValidation(BellBillingInfoPO.OrderIotHeaderText.getText(), "Order IoT Starter Kit", "equalsignorecase"); UtilityMethods.StringValidation(BellBillingInfoPO.SectionOneHead4.getText(), "Payment", "equalsignorecase"); UtilityMethods.StringValidation(BellBillingInfoPO.ParagraphText.getText(), allInputValue.getProperty("Billing.SectionOne"), "equalsignorecase"); UtilityMethods.StringValidation(BellBillingInfoPO.YourInfoText.getText(), "Your Information", "equalsignorecase"); UtilityMethods.StringValidation(BellBillingInfoPO.ShppingText.getText(), "Shipping", "equalsignorecase"); UtilityMethods.StringValidation(BellBillingInfoPO.PaymentText.getText(), "Payment", "equalsignorecase"); UtilityMethods.StringValidation(BellBillingInfoPO.ReviewConfirmText.getText(), "Review & Confirm", "equalsignorecase"); System.out.println("BI003"); UtilityMethods.sleep(2000); } public static void BillingCardDetailsLabelText() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.NameOnCardLabel, "NotEqual", "Name On Card Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.CardNumberLabel, "NotEqual", "Card Number Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.ExpiryDateLabel, "NotEqual", "Expiry Date Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.CVVCodeLabel, "NotEqual", "CVV Code Label Text"); System.out.println("BI004"); UtilityMethods.sleep(2000); } public static void BillingCardDetailsInputFieldValidation() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.sleep(2000); UtilityMethods.DisabledValidation(BellBillingInfoPO.NameOnCardInput,"Name On Card input Text"); UtilityMethods.DisabledValidation(BellBillingInfoPO.CardNumberInput, "Card Number input Text"); UtilityMethods.DisabledValidation(BellBillingInfoPO.ExpiryDate, "Expiry Date input Text"); UtilityMethods.DisabledValidation(BellBillingInfoPO.CVVCodeInput, "CVV Code input Text"); System.out.println("BI005"); } public static void BillingCheckBoxVaildation() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.sleep(2000); BellBillingInfoPO.SameBillAndShipLabel.click(); UtilityMethods.sleep(5000); System.out.println("BI006"); } public static void BillingInfoLabelText() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillAddressLabel, "NotEqual", "Address Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillAptLabel, "NotEqual", "Apt/Suite Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillCityLabel, "NotEqual", "City Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillProvinceLabel, "NotEqual", "Province Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillPostLabel, "NotEqual", "Postal Code Label Text"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillCountryLabel, "NotEqual", "Country Label Text"); System.out.println("BI007"); UtilityMethods.sleep(2000); } public static void BillingInfoInputField() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillAddressInput, "NotEqual", "Address Input Field"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillAptInput, "NotEqual", "Apt/Suite Input Field"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillCityInput, "NotEqual", "City Input Field"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillProvinceInput, "NotEqual", "Province Input Field"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillPostInput, "NotEqual", "Postal Code Input Field"); UtilityMethods.DisplayEnableValidator(BellBillingInfoPO.BillCountryInput, "NotEqual", "Country Drop Down"); System.out.println("BI008"); UtilityMethods.sleep(2000); } public static void BillingInfoRequiredFieldvalidatoin() { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.sleep(3000); BellBillingInfoPO.BillAddressInput.clear(); UtilityMethods.sleep(1000); BellBillingInfoPO.ReviewButton.click(); UtilityMethods.sleep(3000); UtilityMethods.RequiredFieldValidation(BellBillingInfoPO.BillAddressInput, BellBillingInfoPO.BillAddressError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellBillingInfoPO.BillCityInput, BellBillingInfoPO.BillCityError,"TextBox"); UtilityMethods.RequiredFieldValidation(BellBillingInfoPO.BillPostInput, BellBillingInfoPO.BillPostError,"TextBox"); UtilityMethods.RequiredFieldShippingDropDown(BellBillingInfoPO.BillProvinceInput, BellBillingInfoPO.BillProvinceError); UtilityMethods.RequiredFieldShippingDropDown(BellBillingInfoPO.BillCountryInput, BellBillingInfoPO.BillCountryError); System.out.println("BI009"); UtilityMethods.sleep(2000); } public static void BillingInfoSpaceNotAllowedvalidatoin() { PageFactory.initElements(driver, BellBillingInfoPO.class); BellBillingInfoPO.BillAddressInput.clear();UtilityMethods.sleep(1000); BellBillingInfoPO.ReviewButton.click(); UtilityMethods.SpaceNotAllowedvalidation(BellBillingInfoPO.BillAddressInput, BellBillingInfoPO.BillAddressError); UtilityMethods.SpaceNotAllowedvalidation(BellBillingInfoPO.BillCityInput, BellBillingInfoPO.BillCityError); System.out.println("BI010"); UtilityMethods.sleep(2000); } public static void BillingInfoMaximumInputValidation() { PageFactory.initElements(driver, BellBillingInfoPO.class); BellBillingInfoPO.BillAddressInput.clear();UtilityMethods.sleep(1000); BellBillingInfoPO.ReviewButton.click(); UtilityMethods.MaximumInputValidation(BellBillingInfoPO.BillAddressInput, BellBillingInfoPO.BillAddressError,100, allInputValue.getProperty("InvalidCity")); UtilityMethods.MaximumInputValidation(BellBillingInfoPO.BillCityInput, BellBillingInfoPO.BillCityError, 100, allInputValue.getProperty("InvalidCity")); //UtilityMethods.MaximumInputValidation(driver.findElement(By.xpath("//<EMAIL>='ship<EMAIL>']")), driver.findElement(By.xpath("//div[@id=''pscode-error']")), 6, allInputValue.getProperty("InvalidCompanyName")); //postal Code Maximum Input validation need to be verified System.out.println("BI011"); UtilityMethods.sleep(2000); } public static void BillingInfoMinimumInputValidation() { PageFactory.initElements(driver, BellBillingInfoPO.class); BellBillingInfoPO.BillAddressInput.clear();UtilityMethods.sleep(1000); BellBillingInfoPO.ReviewButton.click(); BellBillingInfoPO.ReviewButton.click(); UtilityMethods.MinimumInputValidation(BellBillingInfoPO.BillPostInput, BellBillingInfoPO.BillPostError, 3, allInputValue.getProperty("InvalidMinInput")); System.out.println("BI012"); UtilityMethods.sleep(2000); } public static void BellLogoValidation() throws InterruptedException { PageFactory.initElements(driver, BellBillingInfoPO.class); UtilityMethods.pageRedirection(BellBillingInfoPO.BellLogo, BellBillingInfoPO.CancelButtonFindElement,"Home"); System.out.println("BI013"); UtilityMethods.sleep(2000); } public static void CancelButtonValidation() throws InterruptedException { PageFactory.initElements(driver, BellBillingInfoPO.class); //UtilityMethods.sleep(5000); UtilityMethods.sleep(5000); UtilityMethods.pageRedirection(BellBillingInfoPO.CancelButton, BellBillingInfoPO.CancelButtonFindElement,"Others"); System.out.println("BI014"); UtilityMethods.sleep(5000); } public static void BackButtonValidation() throws InterruptedException { PageFactory.initElements(driver, BellBillingInfoPO.class); //UtilityMethods.sleep(5000); UtilityMethods.sleep(5000); UtilityMethods.pageRedirection(BellBillingInfoPO.BackButton, BellBillingInfoPO.BackFindElement,"Others"); System.out.println("BI015"); UtilityMethods.sleep(2000); } public static void BillingInfoSendInputs() { PageFactory.initElements(driver, BellBillingInfoPO.class); if(allInputValue.getProperty("sameShippBillAddress").equals("Yes")) { UtilityMethods.sleep(4000); BellBillingInfoPO.SameBillAndShipLabel.click(); UtilityMethods.sleep(3000); //System.out.println("The Xpath For Review button is :"+BellBillingInfoPO.ReviewButton+""); //System.out.println("The Xpath For Review button is Displayed:"+BellBillingInfoPO.ReviewButton.isDisplayed()+""); //System.out.println("The Xpath For Review button is Enabled:"+BellBillingInfoPO.ReviewButton.isEnabled()+""); driver.navigate().refresh(); UtilityMethods.sleep(5000); //System.out.println("The Xpath For Review button is :"+BellBillingInfoPO.ReviewButton+""); //System.out.println("The Xpath For Review button is Displayed:"+BellBillingInfoPO.ReviewButton.isDisplayed()+""); //System.out.println("The Xpath For Review button is Enabled:"+BellBillingInfoPO.ReviewButton.isEnabled()+""); BellBillingInfoPO.ReviewButton.click(); System.out.println("BI016"); UtilityMethods.sleep(2000); } else if(allInputValue.getProperty("sameShippBillAddress").equals("No")) { UtilityMethods.sleep(4000); BellBillingInfoPO.SameBillAndShipLabel.click(); UtilityMethods.sleep(4000); BellBillingInfoPO.SameBillAndShipLabel.click(); UtilityMethods.sleep(4000); UtilityMethods.SendInputValues(BellBillingInfoPO.BillAddressInput, allInputValue.getProperty("billingAddress1"), "TextBox"); UtilityMethods.SendInputValues(BellBillingInfoPO.BillAptInput, allInputValue.getProperty("billingAddress2"), "TextBox"); UtilityMethods.sleep(2000); UtilityMethods.SendInputValues(BellBillingInfoPO.BillCityInput, allInputValue.getProperty("billingCity"), "TextBox"); UtilityMethods.SendInputValues(BellBillingInfoPO.BillProvinceInput, allInputValue.getProperty("billingState"), "DropDown"); UtilityMethods.sleep(2000); UtilityMethods.SendInputValues(BellBillingInfoPO.BillPostInput, allInputValue.getProperty("billingPostalCode"), "TextBox"); UtilityMethods.SendInputValues(BellBillingInfoPO.BillCountryInput, allInputValue.getProperty("billingCountry"), "DropDown"); BellBillingInfoPO.ReviewButton.click(); System.out.println("BI016"); UtilityMethods.sleep(4000); } else { BellBillingInfoPO.SameBillAndShipLabel.click(); UtilityMethods.sleep(4000); BellBillingInfoPO.ReviewButton.click(); System.out.println("BI016"); UtilityMethods.sleep(4000); } } } <file_sep>package pages; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import driver.BaseDriver; import pageobjects.PostReferralRequestPO; import utilitymethods.UtilityMethods; public class PostReferralrequestThankYou extends BaseDriver { public static FirefoxDriver driver; static Properties allInputValue; @BeforeTest public static void Start() throws Exception { driver = launchApp(); allInputValue = UtilityMethods.getPostPropValues(); } private static FirefoxDriver launchApp() { // TODO Auto-generated method stub return null; } @Test(priority=1) public static void validateOperatorLogo() { PageFactory.initElements(driver, PostReferralRequestPO.class); UtilityMethods.DisplayEnableValidator(PostReferralRequestPO.PostLogo, "NotEqual","Post Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(PostReferralRequestPO.PostLogo,"src",allInputValue.getProperty("postLogo"),"Post Operator Logo"); } @Test(priority=2) public static void validateCompanyLogo() { PageFactory.initElements(driver, PostReferralRequestPO.class); UtilityMethods.DisplayEnableValidator(PostReferralRequestPO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(PostReferralRequestPO.CiscoLogo,"src",allInputValue.getProperty("CompanyLogo"),"Cisco Jasper Company Logo"); } @Test(priority=3) public static void sectionOneValidation() { UtilityMethods.StringValidation(driver.findElement(By.xpath("//h2")).getText(), "Thank you for your request!", "equalsignorecase"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//p")).getText(), "An e-mail has been sent to you to confirm your request has been received. You will receive a response within 3 business days.", "equalsignorecase"); } @Test(priority=4) public static void backToIotSatrterKit() { UtilityMethods.DisplayEnableValidator(driver.findElement(By.xpath("//div[@Class='text-center']//a")), "NotEqual","Post Operator Logo in IoT Starter Kit"); UtilityMethods.StringValidation(driver.findElement(By.xpath("//div[@Class='text-center']//a")).getText(), "Back to IoT Starter Kit Page", "equalsignorecase"); } @Test(priority=5) public static void backToIotSatrterKitRedirection() { } } <file_sep>Broswer=FireFox BaseURl=https://bell.devm2m.com/ bellLogo=http://bell.devm2m.com/img/bell/bell-logo.png ciscoLogo=http://bell.devm2m.com/img/bell/jasper-logo.png bellBanner=http://bell.devm2m.com/img/bell/bellbanner2.jpg bellSimIcon=http://bell.devm2m.com/img/bell/icons/sim.png bellToolIcon=http://bell.devm2m.com/img/bell/icons/tools.png bellCenterIcon=http://bell.devm2m.com/img/bell/icons/access.png bellSupportIcon=http://bell.devm2m.com/img/bell/icons/support.png whatIsIot=http://bell.devm2m.com/img/bell/whatisiot.png lTEIcon=http://bell.devm2m.com/img/bell/4gLTE.jpg partnerIcon=http://bell.devm2m.com/img/bell/hardwaresol.jpg endToEndIcon=http://bell.devm2m.com/img/bell/experts.jpg sectionOneH1=Discover Internet Of Things from Bell. sectionOneH3=IoT Starter Kit sectionOneP1=Growth opportunities are everywhere, and IoT technologies from Bell can help you uncover them. sectionOneP2=To order a kit that includes 3 test SIM cards (retail value: $199) you must have a referral code. whatTheKitIncludesSimh1=3 SIMS whatTheKitIncludesSimh2=30 MB/SIM whatTheKitIncludesSimh3=50 SMS whatTheKitIncludesSimh4=$199 whatTheKitIncludesSimp1=with Bell Connectivity whatTheKitIncludesSimp2=per month for 3 months whatTheKitIncludesSimp3=messages per SIM per month whatTheKitIncludesToolc1=Real-Time Testing Tool whatTheKitIncludesToolc2=Test-as-you-build for fast, quality development whatTheKitIncludesToolc3=Visibility into device and network behavior whatTheKitIncludesToolc4=Diagnostics and troubleshooting help whatTheKitIncludescenterc1=Full Access to Control Centre whatTheKitIncludescenterc2=Complete suite of developer tools whatTheKitIncludescenterc3=User logins for everyone on your team whatTheKitIncludescenterc4=Same environment for testing and deployment whatTheKitIncludesSupportc1=Exceptional Developer Support whatTheKitIncludesSupportc2=Developer guidelines and M2M.com forum whatTheKitIncludesSupportc3=Access to APIs whatTheKitIncludesSupportc4=Accelerated device certification pleaseNote=Please note: You must be using a Bell certified device or module to order the IoT starter kit. The IoT starter kit is currently not available outside of Canada. howItWorksText1=Place an order for your IoT Starter Kit (retail value: $199) using your referral code. howItWorksText2=Receive access credentials to the Bell Control Centre platform to manage device connectivity. howItWorksText3=Install your SIMs in your test devices and use Control Centre to connect them to Bell's network and your IoT applications. howItWorksText4=After completing your tests, you are now ready to launch your connected device services with Bell on Canada\u2019s fastest network. whatIsIoTP1=Internet of Things (IoT) enables machines and devices to talk to each other directly or through a cloud solution in order to deliver actionable data quickly. Achieve business success with IoT and transform your business. withBellH3=You get more with Bell withBellp1=With Canada's largest LTE network, your business is covered from coast to coast. We also work with a robust network of IoT partners and hardware providers to meet your unique business needs. withBellp2=With the largest support team in Canada, Bell has more than 3,000 certified professionals ready to help you design, implement and manage an IoT solution that best fits your needs, all backed by 24/7 bilingual support. lTEnetworkH3=1. Dependable coverage with Canada's largest LTE network lTEnetworkp1=With Canada's largest LTE network*, Bell covers over 32 million Canadians from coast to coast ensuring you can stay connected to your business, employees and customers wherever you are. partnersH3=2. A network of partners to address your needs partnersP1=We work closely with a robust network of partners to provide the full range of IoT solutions. endToEndH3=3. Expertise from end-to-end to help you stay connected endToEndP1=Our professionals and solution experts are focused on providing you with tailor-made IoT solutions that fit your unique business needs. ReferralRequestSectionOne=We look forward to assisting you with an IoT Starter Kit. Please fill out the form below and a Bell representative will get back to you within 10 business days. ReferralRequestLegaltext=Legal disclaimers: (*) Based on total sq KMs on the shared LTE network from Bell vs. Rogers\u2019 LTE network; bell.ca/LTE referralrequestCheckBox=By checking here, you are providing consent for Bell to send you communications via electronic means, which will include information we think may be of interest to you about Bell's products and services and the products and services of our marketing partners. If at any time you wish to stop getting communications, visit bell.ca/communicationpreferences. FirstName=Gokul LastName=Ramanan CompanyName=Testing Team 11.1 Position=Testing PhoneNumber=8220119412 E-mailAddress=<EMAIL> ModuleData=testing Module BusinessType=Finance - ATM SimType=Nano SIM TimeFrame=6-12 months VolumeToDeploy=111 Description=Test Data ReferralRequestThankYouPara=An email has been sent to you to confirm your request has been received. You will receive a response within 10 business days. TermsOfService=Confirm your review & acceptance of Terms of Service. ccUserName=Test78User34 ccPassword=<PASSWORD> ccConfirmPassword=<PASSWORD> Shipping.SectionOne=Please provide us with the details of your shipping address. Once your order has been completed, your IoT Starter Kit will be shipped to you at no charge. sameShippBillAddress=Yes shippingAddress1=shippingAddress1 shippingAddress2=shippingAddress2 ShippingCity=ShippingCity ShippingState=BC-British Columbia ShippingPostalCode=BELL54 ShippingCountry=Canada shippindAddress=shippingAddress1 shippingAddress2 ShippingCity British Columbia BELL54 Canada billingAddress1=billingAddress1 billingAddress2=billingAddress2 billingCity=billingCity billingState=ON-Ontario billingPostalCode=BELL23 billingCountry=Canada billingAddress=billingAddress1 billingAddress2 billingCity Ontario BELL23 Canada Billing.SectionOne=We are pleased to offer you the IoT Starter Kit as a complimentary offer (retail value: $199) and no payment details will be necessary. Shipping.BillandShip=My shipping and billing information are the same. TrackOrder.validTrackOrderEmailID=<EMAIL> TrackOrder.InvalidTrackOrderEmailID=<EMAIL> ValidFirstName=a,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs,abcdef123456,12345,123!@#$,xyx,new ValidLastName=a,abcdefghijklmnopqrstuvwxyzabcdefghijkl,abcdef123456,12345,123!@#$,xyx,new ValidCompanyName=abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrs ValidPosition=a,abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvw ValidPhoneNumber=01234567890,1234567890123,12345678901234 ValidEmailId=<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL> ValidModule=a,abcd,abcedf,abcefd1234,12345abcdef,abcde123!@#$,12345 ValidVolumeToDeploy=0,1,11,123,1234,12345,123456 ValidDescription=a,abc,abcd,abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz InvalidInput=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy InvalidCompanyName=abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyza Invalidphonenumber=1234567890123456789012345678,12345678901234567121323132156465 InvalidDescription=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw InvalidMinInput=a,ab,abcde,abcd InvalidMinphonenumber=1,123,123456,123456789 InvalidEmailID=abc<EMAIL>,#@%^%#$@#$@#.com,email.example.com,<EMAIL> InvalidPhoneNumber=12356.97401,-985263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvadildNumbericField=abc,abc123,abc12!,12356.974,-5263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvalidCity=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw deliveryDate=10/10/2017;<file_sep>Broswer=Firefox BaseURl=http://m2m-test.10646.cn/?clLocaleCode=en CCURL =http://m2m-test.10646.cn/home/XUrHjVTX/?clLocaleCode=en sameShippBillAddress=No UnicomLogo=http://chinaun9c0nd.devm2m.com/img/unicom/logo.png ciscoLogo=http://chinaun9c0nd.devm2m.com/img/bell/jasper-logo.png UnicomSimIcon=http://chinaun9c0nd.devm2m.com/img/unicom/icons/sim.png UnicomToolIcon=http://chinaun9c0nd.devm2m.com/img/unicom/icons/tools.png UnicomCenterIcon=http://chinaun9c0nd.devm2m.com/img/unicom/icons/access.png UnicomSupportIcon=http://chinaun9c0nd.devm2m.com/img/unicom/icons/support.png whatIsIot=http://chinaun9c0nd.devm2m.com/img/unicom/whatisiot.png sectionOneH1=Start your IoT journey from China Unicom sectionOneH3=IoT Starter Kit sectionOneP1=Begin your IoT journey today by ordering an IoT Starter Kit which includes everything you need to connect and manage your devices on the China Unicom network. sectionOneP2=To order an IoT Starter Kit you must have a referral code. If you don't have a code, please request one below. whatTheKitIncludesSimh1=3 SIMS whatTheKitIncludesSimh2=50 MB/SIM whatTheKitIncludesSimh3=30 SMS whatTheKitIncludesSimp1=With China Unicom Connectivity whatTheKitIncludesSimp2=per month for 3 months whatTheKitIncludesSimp3=messages per SIM per month whatTheKitIncludesToolc1=Real-Time Testing Tool whatTheKitIncludesToolc2=Test-as-you-build for fast, quality development whatTheKitIncludesToolc3=Visibility into device and network behavior whatTheKitIncludesToolc4=Diagnostics and troubleshooting help whatTheKitIncludescenterc1=Full Access to China Unicom M2M Control Center whatTheKitIncludescenterc2=Complete suite of developer tools whatTheKitIncludescenterc3=User logins for everyone on your team whatTheKitIncludescenterc4=Same environment for testing and deployment whatTheKitIncludesSupportc1=Exceptional Developer Support whatTheKitIncludesSupportc2=Developer guidelines and M2M.com forum whatTheKitIncludesSupportc3=Access to APIs whatTheKitIncludesSupportc4=Developer guidelines howItWorksText1=Place an order for the IoT Starter Kit using your referral code. howItWorksText2=Once your order is accepted, your SIMs will be shipped to you and you will receive access credentials to the Control Center platform for managing device connectivity. howItWorksText3=Install the SIMs in your test devices and use Control Center's management features, rules and APIs to connect those devices to the network and your IoT applications. howItWorksText4=After completing your tests, you are now ready to launch your connected device services. whatIsIoTP1=As connected devices proliferate, industry leaders understand that the true value of the Internet of Things (IoT) is not in device itself, but in the services they enabled - and the new, often recurring, sources of revenue generated by services . whatIsIoTP2=China Unicom is focusing on IoT strategy to accelerates the innovation of networking technology, support platform, operation mode, marketing organization and customer service, specially on the core competitiveness about self-service connection management, open application integration and one-point access to global deployment. whatIsIoTP3=China Unicom provides comprehensive end-to-end IoT connection, application and device solutions and services, to help customers transform business from traditional product manufacturers and sellers into service providers and operators, and continue to create new values for customers. ReferralRequestSectionOne=We look forward to assisting you with an IoT Starter Kit. Please fill out the form below and a China Unicom representative will get back to you within 3 business days. FirstName=Test 1 LastName=Test 3 CompanyName=<NAME> Position=Testing PhoneNumber=8220119412 E-mailAddress=<EMAIL> Module=testing Module BusinessType=Finance - ATM SimType=Nano SIM TimeFrame=6-12 months VolumeToDeploy=111 Description=Test Data Provinces=CU Beijing CompName= Team Test ReferralRequestThankYouHeader=Thank you for your request! ReferralRequestThankYouPara=An email has been sent to you to confirm your request has been received. You will receive a response within 3 business days. TermsOfService=Confirm your review & acceptance of Terms of Service. ccUserName=TestUser ccPassword=<PASSWORD> ccConfirmPassword=<PASSWORD> Shipping.SectionOne=Please provide us with the details of your shipping address. Once your order has been completed, your IoT Starter Kit will be shipped to you at no charge. shippingAddress1=shippingAddress1 shippingAddress2=shippingAddress2 ShippingCity=ShippingCity ShippingState=BC-British Columbia ShippingPostalCode=CHN78 ShippingCountry=Republic of China shippindAddress=shippingAddress1 shippingAddress2 ShippingCity British Columbia CHN78 Republic of China billingAddress1=billingAddress1 billingAddress2=billingAddress2 billingCity=billingCity billingState=ON-Ontario billingPostalCode=CHN44 billingCountry=Republic of China billingAddress=billingAddress1 billingAddress2 billingCity Ontario CHN44 Republic of China Billing.SectionOne=We are pleased to offer you the IoT Starter Kit as a complimentary offer (retail value: $199) and no payment details will be necessary. Shipping.BillandShip=My shipping and billing information are the same. TrackOrder.validTrackOrderEmailID=<EMAIL> TrackOrder.InvalidTrackOrderEmailID=<EMAIL> ValidFirstName=a,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs,abcdef123456,12345,123!@#$,xyx,new ValidLastName=a,abcdefghijklmnopqrstuvwxyzabcdefghijkl,abcdef123456,12345,123!@#$,xyx,new ValidCompanyName=abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrs ValidPosition=a,abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvw ValidPhoneNumber=01234567890,1234567890123,12345678901234 ValidEmailId=<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL> ValidModule=a,abcd,abcedf,abcefd1234,12345abcdef,abcde123!@#$,12345 ValidVolumeToDeploy=0,1,11,123,1234,12345,123456 ValidDescription=a,abc,abcd,abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz InvalidInput=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy InvalidCompanyName=abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyza Invalidphonenumber=1234567890123456789012345678,12345678901234567121323132156465 InvalidDescription=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw InvalidMinInput=a,ab,abcde,abcd InvalidMinphonenumber=1,123,123456,123456789 InvalidEmailID=<EMAIL>,#@%^%#$@#$@#.com,email.<EMAIL>,Abc..<EMAIL> InvalidPhoneNumber=12356.97401,-985263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvadildNumbericField=abc,abc123,abc12!,12356.974,-5263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvalidCity=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw deliveryDate=10/10/2017; <file_sep>package pages; import java.io.IOException; import java.util.List; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import utilitymethods.UtilityMethods; public class EmailIntegration { static Properties allInputValue; public static String BrowserForUse; public static WebDriver driver; public static String OldURL="https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1#identifier"; public static String NewURL="https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"; public static void DeleteAllEmail() { try {allInputValue=UtilityMethods.getPropValues();} catch (IOException e) {e.printStackTrace();} BrowserForUse=allInputValue.getProperty("Broswer"); if (BrowserForUse.equals("FireFox")) { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Mozilla FireFox browser launched"); } else if (BrowserForUse.equals("Chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\libs\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); System.out.println("Chrome browser launched"); } else if (BrowserForUse.equals("IE")) { System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+ "\\libs\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.manage().window().maximize(); System.out.println("Internet Explorer browser launched"); } else { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Default browser is Mozilla FireFox is launched"); } driver.get(allInputValue.getProperty("EmailURl")); UtilityMethods.sleep(4000); System.out.println("Current Url ::"+driver.getCurrentUrl()+""); driver.findElement(By.xpath("//input[@type='email']")).sendKeys(allInputValue.getProperty("EmailID")); String URL=driver.getCurrentUrl(); if(URL.equals(NewURL)) { System.out.println("New URL ::"+URL+""); driver.findElement(By.xpath("//div[@id='identifierNext']")).click(); UtilityMethods.sleep(2000); driver.findElement(By.xpath("//input[@type='password']")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.xpath("//div[@id='passwordNext']")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } else if(URL.equals(OldURL)) { System.out.println("Old URL ::"+URL+""); driver.findElement(By.id("next")).click(); UtilityMethods.sleep(2000); driver.findElement(By.id("Passwd")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.id("signIn")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } System.out.println("Delete all check box is displayed :: "+driver.findElement(By.xpath("//div[@aria-label='Select']")).isDisplayed()+""); System.out.println("Delete all check box is Enabled :: "+driver.findElement(By.xpath("//div[@aria-label='Select']")).isEnabled()+""); List<WebElement> unreademeil = driver.findElements(By.xpath("//*[@class='zF']")); String MyMailer = "orders"; for(int i=0;i<unreademeil.size();i++) { if(unreademeil.get(i).isDisplayed()==true) { if(unreademeil.get(i).getText().equals(MyMailer)) { driver.findElement(By.xpath("//div[@aria-label='Select']")).click(); UtilityMethods.sleep(4000); System.out.println("Check box selected"); System.out.println("Yes we have got mail form " + MyMailer); System.out.println("Delet button is displayed :: "+driver.findElement(By.xpath("//div[@aria-label='Delete']")).isDisplayed()+""); System.out.println("Delete button is Enabled :: "+driver.findElement(By.xpath("//div[@aria-label='Delete']")).isEnabled()+""); driver.findElement(By.xpath("//div[@aria-label='Delete']")).click(); UtilityMethods.sleep(4000); System.out.println("Delete Button Clicked"); System.out.println("Deleted All Unread Inbox Emails"); } else { System.out.println("No unread mail form " + MyMailer); } } else { //System.out.println("No unread mail form " + MyMailer); } } System.out.println("No unread mail form " + MyMailer); List<WebElement> reademeil = driver.findElements(By.xpath("//*[@class='yP']")); if(reademeil.size()>0) { driver.findElement(By.xpath("//div[@aria-label='Select']")).click(); UtilityMethods.sleep(4000); System.out.println("Check box selected"); System.out.println("Yes we have got mail form " + MyMailer); System.out.println("Delet button is displayed :: "+driver.findElement(By.xpath("//div[@aria-label='Delete']")).isDisplayed()+""); System.out.println("Delete button is Enabled :: "+driver.findElement(By.xpath("//div[@aria-label='Delete']")).isEnabled()+""); driver.findElement(By.xpath("//div[@aria-label='Delete']")).click(); UtilityMethods.sleep(4000); System.out.println("Delete Button Clicked"); System.out.println("Deleted All read Inbox Emails"); driver.close(); } else { driver.close(); } } @Test(priority=1) public static void CheckEmailReceived() { try {allInputValue=UtilityMethods.getPropValues();} catch (IOException e) {e.printStackTrace();} BrowserForUse=allInputValue.getProperty("Broswer"); if (BrowserForUse.equals("FireFox")) { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Mozilla FireFox browser launched"); } else if (BrowserForUse.equals("Chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\libs\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); System.out.println("Chrome browser launched"); } else if (BrowserForUse.equals("IE")) { System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+ "\\libs\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.manage().window().maximize(); System.out.println("Internet Explorer browser launched"); } else { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Default browser is Mozilla FireFox is launched"); } driver.get(allInputValue.getProperty("EmailURl")); UtilityMethods.sleep(4000); System.out.println("Current Url ::"+driver.getCurrentUrl()+""); driver.findElement(By.xpath("//input[@type='email']")).sendKeys(allInputValue.getProperty("EmailID")); String URL=driver.getCurrentUrl(); if(URL.equals(NewURL)) { System.out.println("New URL ::"+URL+""); driver.findElement(By.xpath("//div[@id='identifierNext']")).click(); UtilityMethods.sleep(2000); driver.findElement(By.xpath("//input[@type='password']")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.xpath("//div[@id='passwordNext']")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } else if(URL.equals(OldURL)) { System.out.println("Old URL ::"+URL+""); driver.findElement(By.id("next")).click(); UtilityMethods.sleep(2000); driver.findElement(By.id("Passwd")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.id("signIn")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } List<WebElement> unreademeil = driver.findElements(By.xpath("//*[@class='zF']")); String MyMailer = "orders"; for(int i=0;i<unreademeil.size();i++) { if(unreademeil.get(i).isDisplayed()==true) { if(unreademeil.get(i).getText().equals(MyMailer)) { System.out.println("Yes we have got mail form " + MyMailer); } else { System.out.println("No mail form " + MyMailer); } } else { System.out.println("No mail form " + MyMailer); } } driver.close(); } @BeforeTest public static String ccURL() { try {allInputValue=UtilityMethods.getPropValues();} catch (IOException e) {e.printStackTrace();} BrowserForUse=allInputValue.getProperty("Broswer"); if (BrowserForUse.equals("FireFox")) { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Mozilla FireFox browser launched"); } else if (BrowserForUse.equals("Chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\libs\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); System.out.println("Chrome browser launched"); } else if (BrowserForUse.equals("IE")) { System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+ "\\libs\\IEDriverServer.exe"); driver = new InternetExplorerDriver(); driver.manage().window().maximize(); System.out.println("Internet Explorer browser launched"); } else { System.setProperty("webdriver.firefox.marionette", System.getProperty("user.dir")+ "\\libs\\geckodriver.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println("Default browser is Mozilla FireFox is launched"); } driver.get(allInputValue.getProperty("EmailURl")); UtilityMethods.sleep(4000); System.out.println("Current Url ::"+driver.getCurrentUrl()+""); driver.findElement(By.xpath("//input[@type='email']")).sendKeys(allInputValue.getProperty("EmailID")); String URL=driver.getCurrentUrl(); if(URL.equals(NewURL)) { System.out.println("New URL ::"+URL+""); driver.findElement(By.xpath("//div[@id='identifierNext']")).click(); UtilityMethods.sleep(2000); driver.findElement(By.xpath("//input[@type='password']")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.xpath("//div[@id='passwordNext']")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } else if(URL.equals(OldURL)) { System.out.println("Old URL ::"+URL+""); driver.findElement(By.id("next")).click(); UtilityMethods.sleep(2000); driver.findElement(By.id("Passwd")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.id("signIn")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } /* System.out.println("Is New Next Button Displayed ::"+driver.findElement(By.xpath("//div[@id='identifierNext']")).isDisplayed()+""); System.out.println("Is Old Next Button Displayed ::"+driver.findElement(By.id("next")).isDisplayed()+""); Boolean Result = false; Result = driver.findElement(By.xpath("//div[@id='identifierNext']")).isDisplayed(); if(Result==true) { driver.findElement(By.xpath("//div[@id='identifierNext']")).click(); UtilityMethods.sleep(2000); driver.findElement(By.xpath("//input[@type='<PASSWORD>']")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.xpath("//div[@id='passwordNext']")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } else { driver.findElement(By.id("next")).click(); UtilityMethods.sleep(2000); driver.findElement(By.id("Passwd")).sendKeys(allInputValue.getProperty("EmailPassword")); driver.findElement(By.id("signIn")).click(); UtilityMethods.sleep(20000); System.out.println("INBOX Opened"); } */ System.out.println("the Xpath is 33::"+allInputValue.getProperty("FindURL")+""); String Test=allInputValue.getProperty("FindURL"); System.out.println("Order Mail is displayed :: "+driver.findElement(By.xpath("//div[@class='UI']")).isDisplayed()+""); System.out.println("Order Mail is Enabled :: "+driver.findElement(By.xpath("//div[@class='UI']")).isEnabled()+""); driver.findElement(By.xpath("//div[@class='UI']")).click(); System.out.println("Mail Opened"); UtilityMethods.sleep(5000); System.out.println("the Xpath is ::"+allInputValue.getProperty("FindURL")+""); System.out.println("sub Mail is displayed :: "+driver.findElement(By.xpath(Test)).isDisplayed()+""); System.out.println("sub Mail is Enabled :: "+driver.findElement(By.xpath(Test)).isEnabled()+""); String CCURL = driver.findElement(By.xpath(Test)).getAttribute("href"); System.out.println("Control Center URL ::"+CCURL+""); driver.close(); return CCURL; } }<file_sep>package pageobjects; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import driver.BaseDriver; public class BellOrderSummaryPO extends BaseDriver { @FindBy(how=How.XPATH,using="//img[@alt='Bell']") public static WebElement BellLogo; @FindBy(how=How.XPATH,using="//img[@alt='Cisco Jasper']") public static WebElement CiscoLogo; @FindBy(how=How.XPATH,using="//h2") public static WebElement SectionOneHead1; @FindBy(how=How.XPATH,using="//p[contains(.,'Please')]") public static WebElement Para1Text; @FindBy(how=How.XPATH,using="//p[contains(.,'review')]") public static WebElement Para2Text; @FindBy(how=How.XPATH,using="//span[text()='bell.devm2m.com']") public static WebElement HomePageLink; @FindBy(how=How.XPATH,using="//img[@title='What is IoT']") public static WebElement homepageLinkFindElement; @FindBy(how=How.XPATH,using="//p[contains(.,'contact')]") public static WebElement Para3Text; @FindBy(how=How.XPATH,using="//a[text()='Back to IoT Starter Kit Page']") public static WebElement BactToIOTButton; @FindBy(how=How.XPATH,using="//img[@title='What is IoT']") public static WebElement BactToIOTFindElement; @FindBy(how=How.XPATH,using="//a[text()='Track Order']") public static WebElement TrackOrderButton; @FindBy(how=How.XPATH,using="//img[@title='What is IoT']") public static WebElement TrackOrderFindElement; @FindBy(how=How.XPATH,using="//p[contains(.,'Date')]") public static WebElement DateText; @FindBy(how=How.XPATH,using="//h2") public static WebElement OrderSummaryHeaderText; @FindBy(how=How.XPATH,using="//p[contains(.,'IoT')]") public static WebElement IOTText; @FindBy(how=How.XPATH,using="//li[contains(.,'Test')]") public static WebElement TestSimText; @FindBy(how=How.XPATH,using="//li[contains(.,'30')]") public static WebElement MBPerSimTextl; @FindBy(how=How.XPATH,using="//li[contains(.,'50')]") public static WebElement SMSPerSimText; @FindBy(how=How.XPATH,using="//li[contains(.,'Bell')]") public static WebElement FullAcessText; @FindBy(how=How.XPATH,using="//div[@class='col-xs-8 clr-black']") public static WebElement ShippingTotalText; @FindBy(how=How.XPATH,using="//p[text()='Included']") public static WebElement IncludeText; @FindBy(how=How.XPATH,using="//div[@class='ship_wrap clearfix']//address") public static WebElement ShippingAddress; @FindBy(how=How.XPATH,using="//div[@class='payment_wrap clearfix']//address") public static WebElement BillingAddress; } <file_sep>package pages; import java.util.Properties; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import pageobjects.PostHomePagePO; import pageobjects.Tele2HomePagePO; import utilitymethods.UtilityMethods; import driver.BaseDriver; public class Tele2HomePage extends BaseDriver { public static FirefoxDriver driver; static Properties allInputValue; public static ExtentReports extent; public static ExtentTest testcase; @BeforeTest public static void Start() throws IOException { driver = launchApp(); System.out.println("done"); allInputValue = UtilityMethods.getTele2PropValues(); PageFactory.initElements(driver, Tele2HomePagePO.class); extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/Advanced.html", true ); } private static FirefoxDriver launchApp() { // TODO Auto-generated method stub return null; } @AfterMethod public static void getResult(ITestResult result) { if(result.getStatus()==ITestResult.FAILURE) { testcase.log(LogStatus.FAIL, result.getTestName()); } if(result.getStatus()==ITestResult.SUCCESS) { testcase.log(LogStatus.PASS, result.getTestName()); } extent.endTest(testcase); } @Test(priority=1) public static void validateOperatorLogo() throws InterruptedException { testcase = extent.startTest("Check Operator Logo", "Checking Wether The Operator Logo is Diplayed,Enabled."); testcase.log(LogStatus.INFO, "Validaion Operator Logo is displayed properly"); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.Tele2Logo, "NotEqual","Tele2 Operator Logo in IoT Starter Kit"); testcase.log(LogStatus.PASS, "Validaion Operator Logo is displayed,enabled is sucessfull"); testcase.log(LogStatus.INFO, "Validaion Operator Logo is displayed from correct source path"); UtilityMethods.Imagevalidation(Tele2HomePagePO.Tele2Logo,"src",allInputValue.getProperty("tele2Logo"),"Tele2 Operator Logo"); testcase.log(LogStatus.PASS, "Validaion Operator Logo is displayed from correct source path is sucessfull"); } @Test(priority=2) public static void operatorLogoPageRedirection() throws Exception { testcase = extent.startTest("Check Operator Logo", "Checking Wether The Operator Logo Page Navigation"); testcase.log(LogStatus.INFO, "on button Click same Page to be loaded"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.Tele2Logo,Tele2HomePagePO.WhatIsIotImage,"Tele2"); testcase.log(LogStatus.PASS, "Operator logo page redirection is sucessfull"); } public static void companyLogoPageRedirection() throws Exception { testcase = extent.startTest("Check company Logo", "Checking Wether The company Logo Page Navigation"); testcase.log(LogStatus.INFO, "On button Click page should be redirected to jasper home page"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.CiscoLogo,Tele2HomePagePO.JasperDotComFindElement,"IoT Connectivity Management Platform | Cisco Jasper"); testcase.log(LogStatus.PASS, "company logo page redirection Failed"); } @Test(priority=3) public static void validateCompanyLogo() { testcase = extent.startTest("Check Company Logo", "Checking Wether The Company Logo is Diplayed & Enabled."); testcase.log(LogStatus.INFO, "Validaion Company Logo is displayed properly"); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); testcase.log(LogStatus.PASS, "Validaion Company Logo is displayed,enabled is sucessfull"); testcase.log(LogStatus.INFO, "Validaion Company Logo is displayed from correct source path"); UtilityMethods.Imagevalidation(Tele2HomePagePO.CiscoLogo,"src",allInputValue.getProperty("tele2CompanyLogo"),"Cisco Jasper Company Logo"); testcase.log(LogStatus.PASS, "Validaion Company Logo is displayed from correct source path is sucessfull"); } @Test(priority=4) public static void sectionOneIotStarterKitTele2Validation() { testcase = extent.startTest("Section 1 Banner text 1", "Text Displayed and content Validation"); testcase.log(LogStatus.INFO, "check Section one Banner text is displayed properly"); UtilityMethods.StringValidation(Tele2HomePagePO.TextBannerh1.getText().replace("\n", " "), allInputValue.getProperty("HomePage.Bannerh1"), "equalsignorecase"); testcase.log(LogStatus.PASS, "Section one Banner text is displayed properly"); UtilityMethods.StringValidation(Tele2HomePagePO.TextBannerh2.getText(), allInputValue.getProperty("HomePage.Bannerh2"), "equalsignorecase"); testcase.log(LogStatus.PASS, "Section one Banner text is displayed properly"); UtilityMethods.StringValidation(Tele2HomePagePO.TextBannerp1.getText().replace("\n", " "),allInputValue.getProperty("HomePage.Bannerp1"), "equalsignorecase"); testcase.log(LogStatus.PASS, "Section one Banner text is displayed properly"); UtilityMethods.StringValidation(Tele2HomePagePO.TextBannerp2.getText(), allInputValue.getProperty("HomePage.Bannerp2"), "equalsignorecase"); testcase.log(LogStatus.PASS, "Section one Banner text is displayed properly"); } public static void sectionOneIotStarterKitTrackOrderValidation() throws InterruptedException { Thread.sleep(3000); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneTrackOrderButton, "NotEqual","Track Order Button in IoT Starter Kit banner"); Tele2HomePagePO.SectionOneTrackOrderButton.click(); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneTrackOrderPRButton, "NotEqual","Track Order on click Button in IoT Starter Kit Track Order"); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneTrackOrderText, "NotEqual","Track Order on Click Text in IoT Starter Kit Track Order"); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.TrackOrderEmailID, "NotEqual","Enter Email ID Text Box in IoT Starter Kit Track Order"); UtilityMethods.PlaceholderValidation(Tele2HomePagePO.TrackOrderEmailID, "Enter Email Address", "Track Order Email ID"); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.TrackOrderCloseIcon, "NotEqual","Track Order Close Button in IoT Starter Kit"); Tele2HomePagePO.TrackOrderCloseIcon.click(); } public static void sectionOneIotStarterKitEnterReferralCodeValidation() throws InterruptedException {Thread.sleep(3000); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneEnterReferralCodeButton, "NotEqual","Enter Referral Code Button in IoT Starter Kit"); Tele2HomePagePO.SectionOneTrackOrderButton.click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace();} UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneOrderKitButton, "NotEqual","OrderKit Button in IoT Starter Kit "); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneEnterReferralCodeText, "NotEqual","Enter Referral Code Text in IoT Starter Kit "); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.EnterReferralCode, "NotEqual","Enter Referral Code Text Box in IoT Starter Kit Track Order"); UtilityMethods.PlaceholderValidation(Tele2HomePagePO.EnterReferralCode, "Enter Referral Code", "Enter Referral Code"); UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.EnterReferralCodeCloseIcon, "NotEqual","Enter Referral Code Close Button in IoT Starter Kit"); //Tele2HomePagePO.EnterReferralCodeCloseIcon.click(); } public static void sectionTwoWhatThekitIncludesContentvalidation() { UtilityMethods.Imagevalidation(Tele2HomePagePO.SimIcon, "src",allInputValue.getProperty("tele2SimIcon"), "Tele2 Sim Icon"); UtilityMethods.StringValidation(Tele2HomePagePO.TextSimh1.getText(), "5 SIMS", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.TextSimh2.getText(), "30 MB per SIM", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.TextSimh3.getText(), "50 SMS", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.TextSimp1.getText(), "with Tele2 Connectivity", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.TextSimp2.getText(), "per month for 6 months", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.TextSimp3.getText(), "messages per SIM per month", "equalsignorecase"); } public static void sectionTwoWhatThekitIncludesToolsvalidation() { UtilityMethods.whatTheKitIncludesImageAndTextValidation(Tele2HomePagePO.ToolIcon, allInputValue.getProperty("tele2ToolIcon"), Tele2HomePagePO.ToolText, "Real-Time Testing Tool"); UtilityMethods.whatThekitIncludesTextValidation(Tele2HomePagePO.ToolListText,"Test-as-you-build for fast, quality development","Visibility into device and network behavior","Diagnostics and troubleshooting help"); } public static void sectionTwoWhatThekitIncludesCentervalidation() { UtilityMethods.whatTheKitIncludesImageAndTextValidation(Tele2HomePagePO.CenterIcon, allInputValue.getProperty("tele2CenterIcon"), Tele2HomePagePO.CenterText,"Full Access to Tele2 M2M Control Center"); UtilityMethods.whatThekitIncludesTextValidation(Tele2HomePagePO.CenterListText, "Complete suite of developer tools", "User logins for everyone on your team","Same environment for testing and deployment"); } public static void sectionTwoWhatThekitIncludesSuppportvalidation() { UtilityMethods.whatTheKitIncludesImageAndTextValidation(Tele2HomePagePO.SupportIcon, allInputValue.getProperty("tele2SupportIcon"), Tele2HomePagePO.SupportText,"Exceptional Developer Support"); UtilityMethods.whatThekitIncludesTextValidation(Tele2HomePagePO.SupportListText, "Developer guidelines", "Full access to APIs","M2M.com forum"); } public static void sectionThreeHowItWorksValidation() { UtilityMethods.StringValidation(Tele2HomePagePO.HowItWorksText.getText(), "How it Works", "equalsignorecase"); UtilityMethods.howItWorksValidation(Tele2HomePagePO.HowItWorksOrder, "1", "Order", "Enter your Referral Code and order a kit."); UtilityMethods.howItWorksValidation(Tele2HomePagePO.HowItWorksActivate, "2", "Activate", "Follow the steps and activate your kit."); UtilityMethods.howItWorksValidation(Tele2HomePagePO.HowItWorksExplore, "3", "Explore", "Amaze yourself with the possibilities."); UtilityMethods.howItWorksValidation(Tele2HomePagePO.HowItWorksMonetize, "4", "Monetize", "Start your IoT journey."); } public static void sectionFourWhatIsIotValidation() { UtilityMethods.Imagevalidation(Tele2HomePagePO.WhatIsIotImage, "src" , "http://tele2.devm2m.com/img/tele2/whatisiot.png", "What is IoT?"); UtilityMethods.StringValidation(Tele2HomePagePO.WhatIsIotText.getText(), "What is IoT?", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.WhatIsIotParaText1.getText(), "As connected devices proliferate, industry leaders understand that the real value of the Internet of Thinks (IoT) is not in the devices themselves, it's in the services they enable — and the new, often recurring sources of revenue these services generate.", "equalsignorecase"); UtilityMethods.StringValidation(Tele2HomePagePO.WhatIsIotParaText2.getText(), "Learn more at jasper.com", "equalsignorecase"); } public static void sectionOneLinkvalidation() throws Exception { UtilityMethods.sectionOneLinkvalidation(PostHomePagePO.WhattheKitIncludeLink); UtilityMethods.sectionOneLinkvalidation(PostHomePagePO.HowItWorkslink); UtilityMethods.sectionOneLinkvalidation(PostHomePagePO.WhatIsIotLink); } public static void SectionThreeLearnMore() throws InterruptedException { UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.HowItWorksLearnMore, "NotEqual", "M2MDotCom Link Button"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.HowItWorksLearnMore,Tele2HomePagePO.M2MDotComFindElement,"Tel"); } public static void TrackOrderValidPageRedirection() throws InterruptedException { Tele2HomePagePO.SectionOneTrackOrderButton.click(); Tele2HomePagePO.TrackOrderEmailID.sendKeys(allInputValue.getProperty("TrackOrder.validTrackOrderEmailID")); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.SectionOneTrackOrderPRButton, Tele2HomePagePO.SectionOneTrackOrderFindElement, "Tele2"); } public static void TrackOrderInValidPageRedirection() throws InterruptedException { Tele2HomePagePO.SectionOneTrackOrderButton.click(); Tele2HomePagePO.TrackOrderEmailID.sendKeys(allInputValue.getProperty("TrackOrder.InvalidTrackOrderEmailID")); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.SectionOneTrackOrderPRButton, Tele2HomePagePO.WhatIsIotImage, "Tele2"); } public static void SectionOTwoReferralRequestvalidation() throws InterruptedException { UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionTwoReferralRrequestButton, "NotEqual", "Section Two Referral Request Button"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.SectionTwoReferralRrequestButton,Tele2HomePagePO.ReferrralRequestFindElement,"Tele2"); } public static void SectionOneReferralRequestvalidation() throws InterruptedException { UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.SectionOneReferralRrequestButton, "NotEqual", "Section One Referral Request Button"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.SectionOneReferralRrequestButton,Tele2HomePagePO.ReferrralRequestFindElement,"Tele2"); } public static void sectionTwoM2MDotCom() throws InterruptedException { UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.M2mDotCom, "NotEqual", "M2MDotCom Link Button"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.M2mDotCom,Tele2HomePagePO.M2MDotComFindElement,"M2M Developer Kits from the World’s Leading Mobile Operators"); } public static void sectionTwoM2MdotCo() { try { Thread.sleep(4500); } catch (InterruptedException e){ e.printStackTrace();} WebElement referralrequest= driver.findElement(By.xpath("//a[text()='M2M.com']")); UtilityMethods.DisplayEnableValidator(referralrequest, "NotEqual", "M2M.com Link Button"); referralrequest.click(); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace();} try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); WebElement FindElement= driver.findElement(By.xpath("//div[@id='footer_wrap']")); if (!FindElement.isDisplayed()) { System.out.println("The Page Redirection Error in Request Referral Code"); } } } catch(Exception e) { System.out.println("Condition fail for M2M.com link"); } driver.navigate().back(); } //Failed public static void sectionFourJasperdotCom() throws InterruptedException { UtilityMethods.DisplayEnableValidator(Tele2HomePagePO.JasperDotCom, "NotEqual", "JasperDotCom Link Button"); UtilityMethods.PageNavigationValidation(Tele2HomePagePO.JasperDotCom, Tele2HomePagePO.JasperDotComFindElement, "IoT Connectivity Management Platform | Cisco Jasper"); } //failed public static void sectionFourJasperdotCo() throws InterruptedException { Thread.sleep(2000); WebElement referralrequest= driver.findElement(By.xpath("//section[@id='what-iot']//a")); UtilityMethods.DisplayEnableValidator(referralrequest, "NotEqual", "Jasper.com Link Button"); referralrequest.click(); Thread.sleep(5000); try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); WebElement FindElement= driver.findElement(By.xpath("//footer")); if (!FindElement.isDisplayed()) { System.out.println("The Page Redirection Error in Request Referral Code"); } } } catch(Exception e) { System.out.println("Condition fail for jasper.com link"); } driver.navigate().back(); } public static void sectionTwoReferralRequestButton() { try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace();} WebElement referralrequest= driver.findElement(By.xpath("//section[@id='kit-inc']//a[text()='Request Referral Code']")); UtilityMethods.DisplayEnableValidator(referralrequest, "NotEqual", "Referral Request Button"); referralrequest.click(); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace();} try { for(String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); WebElement FindElement= driver.findElement(By.xpath("//input[@value='Request']")); if (!FindElement.isDisplayed()) { System.out.println("The Page Redirection Error in Request Referral Code"); } } } catch(Exception e) { System.out.println("Condition fail for Referral request in section 2"); } driver.navigate().back(); } @AfterTest public static void Exit() { extent.endTest(testcase); extent.flush(); driver.close(); } } <file_sep>package pages; public class PostYourInfoPage { } <file_sep>package pageobjects; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import driver.BaseDriver; public class BellReferralRequestThankYouPO extends BaseDriver { @FindBy(how=How.XPATH,using="//img[@alt='Bell']") public static WebElement BellLogo; @FindBy(how=How.XPATH,using="//img[@alt='C<NAME>']") public static WebElement CiscoLogo; @FindBy(how=How.XPATH,using="//h2") public static WebElement SectionOneHead1; @FindBy(how=How.XPATH,using="//p") public static WebElement ParagraphText; @FindBy(how=How.XPATH,using="//img[@title='What is IoT']") public static WebElement WhatIsIotImage; @FindBy(how=How.XPATH,using="//div[@class='text-center']//a") public static WebElement BackToIOT; } <file_sep>package pageobjects; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import driver.BaseDriver; public class BellShippingInfoPO extends BaseDriver { @FindBy(how=How.XPATH,using="//img[@alt='Bell']") public static WebElement BellLogo; @FindBy(how=How.XPATH,using="//img[@alt='Cisco Jasper']") public static WebElement CiscoLogo; @FindBy(how=How.XPATH,using="//h4") public static WebElement SectionOneHead4; @FindBy(how=How.XPATH,using="//p") public static WebElement ParagraphText; @FindBy(how=How.XPATH,using="//h2") public static WebElement OrderIotHeaderText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-info']//span[@class='bl-status']") public static WebElement YourInfoText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-ship']//span[@class='bl-status']") public static WebElement ShppingText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-pay']//span[@class='bl-status']") public static WebElement PaymentText; @FindBy(how=How.XPATH,using="//div[@class='order-status iot-kit-rc']//span[@class='bl-status']") public static WebElement ReviewConfirmText; @FindBy(how=How.XPATH,using="//form/div[@class='clearfix frm-in-field']//label[text()='Address']") public static WebElement ShipAddressLabel; @FindBy(how=How.XPATH,using="//form/div[@class='clearfix frm-in-field']//label[text()='Apt/Suite']") public static WebElement ShipAptLabel; @FindBy(how=How.XPATH,using="//form/div[@class='clearfix frm-in-field']//label[text()='City']") public static WebElement ShipCityLabel; @FindBy(how=How.XPATH,using="//form/div[@class='clearfix frm-in-field']//label[text()='State/Province']") public static WebElement ShipProvinceLabel; @FindBy(how=How.XPATH,using="//form/div[@class='clearfix frm-in-field']//label[text()='Postal Code']") public static WebElement ShipPostLabel; @FindBy(how=How.XPATH,using="//form/div[@class='clearfix frm-in-field']//label[text()='Country']") public static WebElement ShipCountryLabel; @FindBy(how=How.XPATH,using="//input[@name='shipAddress.addressLine1']") public static WebElement ShipAddressInput; @FindBy(how=How.XPATH,using="//input[@name='shipAddress.addressLine2']") public static WebElement ShipAptInput; @FindBy(how=How.XPATH,using="//input[@name='shipAddress.cityTown']") public static WebElement ShipCityInput; @FindBy(how=How.XPATH,using="//select[@id='state']") public static WebElement ShipProvinceInput; @FindBy(how=How.XPATH,using="//input[@name='shipAddress.zipPostalCode']") public static WebElement ShipPostInput; @FindBy(how=How.XPATH,using="//select[@id='country']") public static WebElement ShipCountryInput; @FindBy(how=How.XPATH,using="//div[@id='address-error']") public static WebElement ShipAddressError; @FindBy(how=How.XPATH,using="//div[@id='citydown-error']") public static WebElement ShipCityError; @FindBy(how=How.XPATH,using="//div[@id='state-error']") public static WebElement ShipProvinceError; @FindBy(how=How.XPATH,using="//div[@id='pscode-error']") public static WebElement ShipPostError; @FindBy(how=How.XPATH,using="//div[@id='country-error']") public static WebElement ShipCountryError; @FindBy(how=How.XPATH,using="//input[@value='Continue']") public static WebElement ContinueButton; @FindBy(how=How.XPATH,using="//a[@value='Cancel']") public static WebElement CancelButton; @FindBy(how=How.XPATH,using="//a[text()='Back']") public static WebElement BackButton; @FindBy(how=How.XPATH,using="//img[@title='What is IoT']") public static WebElement CancelButtonFindElement; @FindBy(how=How.XPATH,using="//input[@value='Continue']") public static WebElement BackFindElement; } <file_sep>package pages; import java.util.Properties; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import driver.BaseDriver; import pageobjects.BellReferralRequestThankYouPO; import utilitymethods.UtilityMethods; public class BellReferralRequestThankYou extends BaseDriver { public static WebDriver driver; public static Properties allInputValue; //@BeforeTest public static void BrowserIntilation() throws Exception { allInputValue = UtilityMethods.getBellPropValues(); driver = BaseDriver.driver; } @Test(priority=1) public static void validateOperatorLogo() { PageFactory.initElements(driver, BellReferralRequestThankYouPO.class); UtilityMethods.DisplayEnableValidator(BellReferralRequestThankYouPO.BellLogo, "NotEqual","Bell Operator Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellReferralRequestThankYouPO.BellLogo,"src",allInputValue.getProperty("bellLogo"),"Bell Operator Logo"); System.out.println("RRTY001"); } @Test(priority=2) public static void validateCompanyLogo() { PageFactory.initElements(driver, BellReferralRequestThankYouPO.class); UtilityMethods.DisplayEnableValidator(BellReferralRequestThankYouPO.CiscoLogo, "NotEqual","Cisco Jasper Company Logo in IoT Starter Kit"); UtilityMethods.Imagevalidation(BellReferralRequestThankYouPO.CiscoLogo,"src",allInputValue.getProperty("ciscoLogo"),"Cisco Jasper Company Logo"); System.out.println("RRTY002");} @Test(priority=3) public static void ThankYouTextValidation() { PageFactory.initElements(driver, BellReferralRequestThankYouPO.class); UtilityMethods.StringValidation(BellReferralRequestThankYouPO.SectionOneHead1.getText(), "Thank you for your request!", "equalsignorecase"); UtilityMethods.StringValidation(BellReferralRequestThankYouPO.ParagraphText.getText(), allInputValue.getProperty("ReferralRequestThankYouPara"), "equalsignorecase"); System.out.println("RRTY003"); } @Test(priority=4) public static void bellLogoValidation() throws InterruptedException { UtilityMethods.ThankYouPageRedirection(BellReferralRequestThankYouPO.BellLogo, BellReferralRequestThankYouPO.WhatIsIotImage); System.out.println("RRTY004"); } @Test(priority=5) public static void backToIOT() throws InterruptedException { UtilityMethods.StringValidation(BellReferralRequestThankYouPO.BackToIOT.getText(), "Back to IoT Starter Kit Page", "equalsignorecase"); UtilityMethods.DisplayEnableValidator(BellReferralRequestThankYouPO.BackToIOT, "NotEqual","Back To IoT Starter Kit"); System.out.println("RRTY005"); } @Test(priority=6) public static void backToIOTPageValidation() throws InterruptedException { UtilityMethods.ThankYouPageRedirection(BellReferralRequestThankYouPO.BackToIOT,BellReferralRequestThankYouPO.WhatIsIotImage); System.out.println("RRTY006"); } } <file_sep>tele2Logo=http://tele2.devm2m.com/img/tele2/tele2logo.png tele2CompanyLogo=http://tele2.devm2m.com/img/bell/jasper-logo.png tele2SimIcon=http://tele2.devm2m.com/img/tele2/icons/tele-sim.png tele2ToolIcon=http://tele2.devm2m.com/img/tele2/icons/tele-tools.png tele2CenterIcon=http://tele2.devm2m.com/img/tele2/icons/tele-access.png tele2SupportIcon=http://tele2.devm2m.com/img/tele2/icons/tele-support.png HomePage.Bannerh1=A WORLD WITHOUT IOT IS IDIOTIC HomePage.Bannerh2=Don\u2019t be an idiot, let\u2019s get IoT started! HomePage.Bannerp1=We offer global connectivity for IoT with full visibility, flexibility and control. Order our starter kit and start exploring the endless possibilities of IoT. HomePage.Bannerp2=To order a complimentary kit you must have a referral code. HomePage.WhatTheKitIncludesToolc1=Real-Time Testing Tool HomePage.WhatTheKitIncludesToolc2=Test-as-you-build for fast, quality development HomePage.WhatTheKitIncludesToolc3=Visibility into device and network behavior HomePage.WhatTheKitIncludesToolc4=Diagnostics and troubleshooting help HomePage.WhatTheKitIncludescenterc1=Full Access to Tele2 M2M Control Center HomePage.WhatTheKitIncludescenterc2=Complete suite of developer tools HomePage.WhatTheKitIncludescenterc3=User logins for everyone on your team HomePage.WhatTheKitIncludescenterc4=Same environment for testing and deployment HomePage.WhatTheKitIncludesSupportc1=Exceptional Developer Support HomePage.WhatTheKitIncludesSupportc2=Developer guidelines HomePage.WhatTheKitIncludesSupportc3=Full access to APIs HomePage.WhatTheKitIncludesSupportc4=M2M.com forum ReferralRequest.sectionOne=We look forward to assisting you with an IoT Starter Kit. Please fill out the form below and a Tele2 representative will get back to you within 3 business days. TrackOrder.validTrackOrderEmailID=<EMAIL> TrackOrder.InvalidTrackOrderEmailID=<EMAIL> ValidFirstName=a,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs,abcdef123456,12345,123!@#$,xyx,new ValidLastName=a,abcdefghijklmnopqrstuvwxyzabcdefghijkl,abcdef123456,12345,123!@#$,xyx,new ValidCompanyName=abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrs ValidPosition=a,abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvw ValidPhoneNumber=01234567890,1234567890123,12345678901234 ValidEmailId=<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL> ValidModule=a,abcd,abcedf,abcefd1234,12345abcdef,abcde123!@#$,12345 ValidVolumeToDeploy=0,1,11,123,1234,12345,123456 ValidDescription=a,abc,abcd,abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz InvalidInput=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy InvalidCompanyName=abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyza Invalidphonenumber=1234567890123456,12345678901234567 InvalidDescription=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw InvalidMinInput=a,ab InvalidMinphonenumber=1,123,123456,123456789 InvalidEmailID=abc@.com,#@%^%#$@#$@#.com,email.example.com,Abc..<EMAIL> InvalidPhoneNumber=12356.97401,-985263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvadildNumbericField=abc,abc123,abc12!,12356.974,-5263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 <file_sep>Broswer=FireFox AdminURL=http://starterkit-dev.devm2m.com/admin/internal/login AdminUserName=venkatesh.s EmailURl=http://gmail.com/ EmailID=automateselenium1 EmailPassword=<PASSWORD> FindURL=//a[text()='https://chinaunicom.m2m.com'] Dummy =http://gmail.com/https://mail.google.com/mail/?tab=wm<file_sep>postLogo=http://postdevfortesting.devm2m.com/img/post/post-logo.png ciscoLogo=http://postdevfortesting.devm2m.com/img/bell/jasper-logo.png postSimIcon=http://postdevfortesting.devm2m.com/img/post/icons/sim.png postToolIcon=http://postdevfortesting.devm2m.com/img/post/icons/tools.png postCenterIcon=http://postdevfortesting.devm2m.com/img/post/icons/access.png postSupportIcon=http://postdevfortesting.devm2m.com/img/post/icons/support.png whatIsIot=http://postdevfortesting.devm2m.com/img/post/whatisiot.png HomePage.Bannerh1=Start your IoT journey with Post Telecom HomePage.Bannerh3=IoT Starter Kit HomePage.Bannerp1=Begin your IoT journey today by ordering an IoT Starter Kit which includes everything you need to connect and manage your devices on the POST Telecom's network. HomePage.Bannerp2=To order an IoT Starter Kit you must have a referral code. If you don\u2019t have a code, please request one below. HomePage.WhatTheKitIncludesSimh1=5 SIMS HomePage.WhatTheKitIncludesSimh2=30 MB per SIM HomePage.WhatTheKitIncludesSimh3=50 SMS HomePage.WhatTheKitIncludesSimh4=\u20AC80 HomePage.WhatTheKitIncludesSimp1=with Post Connectivity HomePage.WhatTheKitIncludesSimp2=per month for 3 months HomePage.WhatTheKitIncludesSimp3=messages per SIM per month HomePage.WhatTheKitIncludesToolc1=Real-Time Testing Tool HomePage.WhatTheKitIncludesToolc2=Test-as-you-build for fast, quality development HomePage.WhatTheKitIncludesToolc3=Visibility into device and network behavior HomePage.WhatTheKitIncludesToolc4=Diagnostics and troubleshooting help HomePage.WhatTheKitIncludescenterc1=Full Access to Tele2 M2M Control Center HomePage.WhatTheKitIncludescenterc2=Complete suite of developer tools HomePage.WhatTheKitIncludescenterc3=User logins for everyone on your team HomePage.WhatTheKitIncludescenterc4=Same environment for testing and deployment HomePage.WhatTheKitIncludesSupportc1=Exceptional Developer Support HomePage.WhatTheKitIncludesSupportc2=Developer guidelines and M2M.com forum HomePage.WhatTheKitIncludesSupportc3=Access to APIs HomePage.WhatTheKitIncludesSupportc4=Accelerated device certification HomePage.HowItWorksText1=Place an order for the IoT Starter Kit using your referral code. HomePage.HowItWorksText2=Once your order is accepted, your SIMs will be shipped to you and you will receive access credentials to the Control Center platform for managing device connectivity. HomePage.HowItWorksText3=Install the SIMs in your test devices and use Control Center\u2019s management features, rules and APIs to connect those devices to the network and your IoT applications. HomePage.HowItWorksText4=After completing your tests, you are now ready to launch your connected device services. HomePage.WhatIsIoTP1=As connected devices proliferate, industry leaders understand that the real value of the Internet of Thinks (IoT) is not in the devices themselves, it's in the services they enable \u2014 and the new, often recurring sources of revenue those services generate. HomePage.WhatIsIoTP2=Learn more at jasper.com ReferralRequest.sectionOne=We look forward to assisting you with an IoT Starter Kit. Please fill out the form below and a Tele2 representative will get back to you within 3 business days. Shipping.SectionOne=Please provide us with the details of your shipping address. Once your order has been completed, your IoT Starter Kit will be shipped to you at no charge. Shipping.BillandShip=My shipping and billing information are the same. TrackOrder.validTrackOrderEmailID=<EMAIL> TrackOrder.InvalidTrackOrderEmailID=<EMAIL> ValidFirstName=a,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrs,abcdef123456,12345,123!@#$,xyx,new ValidLastName=a,abcdefghijklmnopqrstuvwxyzabcdefghijkl,abcdef123456,12345,123!@#$,xyx,new ValidCompanyName=abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrs ValidPosition=a,abc,abcdef,abcdef123456,abce123!@#,abcdef!@#$%,abcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvw ValidPhoneNumber=01234567890,1234567890123,12345678901234 ValidEmailId=<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL>,<EMAIL> ValidModule=a,abcd,abcedf,abcefd1234,12345abcdef,abcde123!@#$,12345 ValidVolumeToDeploy=0,1,11,123,1234,12345,123456 ValidDescription=a,abc,abcd,abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz InvalidInput=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxy InvalidCompanyName=abcdefghijklmnopqrstuvwxyz,abcdefghijklmnopqrstuvwxyza Invalidphonenumber=1234567890123456,12345678901234567 InvalidDescription=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw InvalidMinInput=a,ab InvalidMinphonenumber=1,123,123456,123456789 InvalidEmailID=<EMAIL>,#@%^%#$@#$@#.com,<EMAIL>,Abc..<EMAIL> InvalidPhoneNumber=12356.97401,-985263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvadildNumbericField=abc,abc123,abc12!,12356.974,-5263.251,#@$#$@^$^&@$@$^&$@#$^&,#$#%^dfddf2435 InvalidCity=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw
e7f4094c334156652c06834a9b658ffd4d62de56
[ "Java", "INI" ]
30
Java
Gokulcse/Automation
6f4d7412b8e9099c6bae81ed8ea82db52f9ebbcd
2028708ad56276b7f421977c9c45a03a82eee45d
refs/heads/master
<repo_name>afornah/ulrick<file_sep>/test1.sh hello Ulrick I love you <file_sep>/test2.sh miss you my son
9ff33801cfdf4cd4ddf33baca194440bc1f28bd2
[ "Shell" ]
2
Shell
afornah/ulrick
190cf1cf38db7f5925ca165ce8c504c7d658c589
dfe682274e3b45c64a5d2a731419da0d068f82f2
refs/heads/master
<file_sep>$hobos = Hobos::Api.new 1000.times do |t| $page.store._hobos << { name: $hobos.hobo } end <file_sep># Volt-Hobos Trivially generate hobo names in your volt controllers. Simply call `@hobo_generator.hobo` and you will be given a hobo name string! ## Installation Add this line to your application's Gemfile: gem 'volt-hobos' And then execute: $ bundle Or install it yourself as: $ gem install volt-hobos ## Usage `@hobo_generator.hobo` in any controller. Or, you are afforded a `$hobos` global variable you may also call `.hobo` on for a random hobo name. ## Contributing 1. Fork it ( http://github.com/[my-github-username]/volt-hobos/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request <file_sep>module VoltHobos class MainController < Volt::ModelController attr_accessor :hobo_generator def initialize @hobo_generator = Hobos::Api.new end end end
83d0137f61c2cb3c11dc05f2969debae82d76d1e
[ "Markdown", "Ruby" ]
3
Ruby
ybur-yug/volt-hobos
cec09898c1310495e5d2ded4105368de53863e6f
ba8cd7dac1a0f25de92fc0d0a41094d3adbf1384
refs/heads/master
<repo_name>danail97/Tic-Tac-Toe<file_sep>/src/client/GameClient.java package client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; import server.Server; public class GameClient { private static final String MENU_HEADER = "Available commands :"; private static final String MENU_CREATE_GAME = "create-game <game-name>"; private static final String MENU_LIST_GAMES = "list-games"; private static final String MENU_JOIN_GAME = "join-game [<game-name>]"; private static final String MENU_EXIT = "exit"; private static final String HOST = "localhost"; private static final String UNKNOWN_HOST = "Unknown host!"; private static final String SOCKET_PROBLEM = "There is a problem with the socket!"; private String name; public GameClient(String name) { this.name = name; } public String getName() { return name; } public void printMenu() { System.out.println(MENU_HEADER); System.out.println(MENU_CREATE_GAME); System.out.println(MENU_LIST_GAMES); System.out.println(MENU_JOIN_GAME); System.out.println(MENU_EXIT); } public void connect() { try (Socket s = new Socket(HOST, Server.SERVER_PORT); PrintWriter pw = new PrintWriter(s.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));) { printMenu(); sendNameToServer(pw); MsgReciever msgReciever = new MsgReciever(br); msgReciever.start(); while (msgReciever.isAlive()) { sendCommand(pw); } } catch (UnknownHostException e) { System.out.println(UNKNOWN_HOST); e.printStackTrace(); } catch (IOException e) { System.out.println(SOCKET_PROBLEM); e.printStackTrace(); } } public void sendNameToServer(PrintWriter pw) { pw.println(name); pw.flush(); } @SuppressWarnings("resource") public void sendCommand(PrintWriter pw) { Scanner sc = new Scanner(System.in); String command = sc.nextLine(); pw.println(command); pw.flush(); } } <file_sep>/test/game/GameRoomTest.java package game; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class GameRoomTest { private GameRoom gameRoom; @Mock BufferedReader activePlayerBr; @Mock PrintWriter activePlayerPw; @Mock PrintWriter waitingPlayerPw; @Before public void setUp() { gameRoom = new GameRoom("room", activePlayerPw, activePlayerBr); } @Test public void makeMoveShouldPlaceSymbolWhereThePlayerChooses() throws IOException { // Given when(activePlayerBr.readLine()).thenReturn(GameBoardTest.B2); // When gameRoom.makeMove(activePlayerPw, activePlayerBr, waitingPlayerPw, GameBoardTest.SYMBOL_X); // Then assertTrue("Field " + GameBoardTest.B2 + " does not contain symbol " + GameBoardTest.SYMBOL_X, gameRoom.getGameBoard().getBoard()[3][5] == GameBoardTest.SYMBOL_X); } @Test public void checkIfWonShouldReturnTrueWhenSomeoneWon() { gameRoom.getGameBoard().placeSymbol(GameBoardTest.C1, GameBoardTest.SYMBOL_X); gameRoom.getGameBoard().placeSymbol(GameBoardTest.B2, GameBoardTest.SYMBOL_X); gameRoom.getGameBoard().placeSymbol(GameBoardTest.A3, GameBoardTest.SYMBOL_X); gameRoom.checkIfWon(activePlayerPw, waitingPlayerPw, GameBoardTest.SYMBOL_X); assertTrue("Noone has won yet", gameRoom.checkIfWon(activePlayerPw, waitingPlayerPw, GameBoardTest.SYMBOL_X)); } } <file_sep>/src/server/ServerThread.java package server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import game.GameRoom; public class ServerThread extends Thread { private static final String DISCONNECTED = " disconnected"; private static final String READING_EXCEPTION = "An error occurred while reading!"; private static final String USER_ALLREADY_CONNECTED = "User already connected!"; private static final String CREATE_GAME = "create-game"; private static final String LIST_GAMES = "list-games"; private static final String JOIN_GAME = "join-game"; private static final String EXIT = "exit"; private static final String INVALID_COMMAND = "Invalid command!"; private static final String GAME_CREATED = "Created game "; private static final String WAITING_FOR_SECOUND_PLAYER = "Waiting for secound player..."; private static final String THREAD_INTERUPTED = "Thread interupted!"; private static final String ROOM_ALLREADY_EXISTS = "There is a room with this name!"; private static final String NO_SUCH_ROOM = "This room doesn't exist!"; private static final String NO_GAMES_AVAILABLE = "No games available."; private static final String GOODBYE = "Goodbye."; private Socket socket; private String player; private String roomName; private boolean inGame; private BufferedReader bufferedReader; private PrintWriter printWriter; public ServerThread(Socket socket) { this.socket = socket; addUser(); } public synchronized void addUser() { inGame = true; try{ bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); printWriter = new PrintWriter(socket.getOutputStream()); player = bufferedReader.readLine(); if (Server.users.contains(player)) { printWriter.println(USER_ALLREADY_CONNECTED); return; } else { Server.users.add(player); } } catch (IOException e) { System.out.println(player + DISCONNECTED); e.printStackTrace(); }finally { cleanUpAfterUser(); } } public void run() { while (inGame) { try { String clientMsg = bufferedReader.readLine(); String[] words = clientMsg.split(" "); String command = words[0]; if (words.length > 1) { roomName = clientMsg.substring(words[0].length() + 1); } runCommand(command); } catch (IOException e) { System.out.println(READING_EXCEPTION); e.printStackTrace(); } finally { cleanUpAfterUser(); } } } public void runCommand(String command) { switch (command) { case CREATE_GAME: { createGame(); break; } case LIST_GAMES: { listGames(); break; } case JOIN_GAME: { joinGame(); break; } case EXIT: { exit(); break; } default: { printWriter.println(INVALID_COMMAND); printWriter.flush(); } } } public boolean createGame() { if (roomName != null && !Server.rooms.containsKey(roomName)) { Server.rooms.put(roomName, new GameRoom(roomName, printWriter, bufferedReader)); printWriter.println(GAME_CREATED + roomName); printWriter.println(WAITING_FOR_SECOUND_PLAYER); printWriter.flush(); synchronized (this) { try { this.wait(); } catch (InterruptedException e) { System.out.println(THREAD_INTERUPTED); e.printStackTrace(); } } return true; } else { printWriter.println(ROOM_ALLREADY_EXISTS); printWriter.flush(); return false; } } public void joinGame() { if (!Server.rooms.containsKey(roomName)) { printWriter.println(NO_SUCH_ROOM); printWriter.flush(); } Server.rooms.get(roomName).joinRoom(printWriter, bufferedReader); } public void listGames() { if (!Server.rooms.isEmpty()) { for (GameRoom room : Server.rooms.values()) { printWriter.println(room.getRoomName()); } } else { printWriter.println(NO_GAMES_AVAILABLE); } printWriter.flush(); } public void exit() { inGame = false; printWriter.println(GOODBYE); printWriter.flush(); } public void deletePlayer(String player) { if (Server.users.contains(player)) { Server.users.remove(player); } } public void deleteRoom(String currentGame) { if (!currentGame.equals(null)) { if (Server.rooms.containsKey(currentGame)) { Server.rooms.remove(currentGame); } } } public void cleanUpAfterUser() { deletePlayer(player); if (roomName != null) { deleteRoom(roomName); } } } <file_sep>/test/game/GameBoardTest.java package game; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class GameBoardTest { public static final String C1 = "C1"; public static final String B2 = "B2"; public static final String A3 = "A3"; public static final char SYMBOL_X = 'X'; private GameBoard gameBoard; @Before public void setUp() { gameBoard = new GameBoard(); } @Test public void isFieldValidShouldReturnTrueWhenTheFieldIsValid() { assertTrue("Field " + C1 + "is not valid", gameBoard.isFieldValid(C1)); } @Test public void placeSymbolShouldPlaceSymbolInGivenField() { gameBoard.placeSymbol(B2, SYMBOL_X); assertTrue("Field " + B2 + " does not contain symbol " + SYMBOL_X , gameBoard.getBoard()[3][5] == SYMBOL_X); } @Test public void hasLineShouldReturnTrueIfThereIsALine() { gameBoard.placeSymbol(C1,SYMBOL_X); gameBoard.placeSymbol(B2,SYMBOL_X); gameBoard.placeSymbol(A3,SYMBOL_X); assertTrue("The board does not contain a line", gameBoard.hasLine(SYMBOL_X)); } @Test public void isFullShouldReturnFalseIfThereIsAnEmptyField() { gameBoard.placeSymbol(C1,SYMBOL_X); assertTrue("The board is full", !gameBoard.isFull()); } } <file_sep>/src/server/Server.java package server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import game.GameRoom; public class Server { public static final String SERVER_SOCKET_ERROR = "There is a problem with the server socket!"; public static final int SERVER_PORT = 1234; public static Set<String> users = new HashSet<>(); public static Map<String, GameRoom> rooms = new ConcurrentHashMap<>(); public static void main(String[] args) throws InterruptedException { try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT);) { while (true) { Socket socket = serverSocket.accept(); new ServerThread(socket).start(); } } catch (IOException e) { System.out.println(SERVER_SOCKET_ERROR); e.printStackTrace(); } } }
439aedc37f63b9e0f7be226865632c0141aa7341
[ "Java" ]
5
Java
danail97/Tic-Tac-Toe
4f986d43e495eef0939a3afa4b9158f55ba67cbb
f2b95b6bda2ef3c28461305537f4664cdd82f190
refs/heads/master
<repo_name>tspenido/mc<file_sep>/NPS/js/novo.nps.js function sendPass() { var nemail = $(".ipt-email").val(); var nmsg = $(".text-mensagem").val(); var nradio = $(".nota-selecionada").attr("rel"); if ((nemail == "") || (validateEmail(nemail) == false)) { alerta("Por favor, coloque um email válido."); } else if (nradio == undefined) { alerta("Por favor, atribua uma nota o quanto você indicaria nossa empresa para um amigo."); } else { var date = new Date; var dataHora = date.toLocaleString(); var ndataHora = dataHora.split(" "); var datos = {}; datos.email = nemail; datos.resposta = nradio; datos.data = ndataHora[0]; datos.observacoes = nmsg; $.ajax({ headers: { Accept: "application/vnd.vtex.ds.v10+json", "x-vtex-api-appKey": "vtexappkey-montecarlojoais-XCNQYA", "x-vtex-api-appToken": "<KEY>", "Content-Type": "application/json" }, data: JSON.stringify(datos), type: "POST", url: "/api/dataentities/NP/documents", beforeSend: function(xhr) { $(".overlay-alert").css("display", "inline") }, success: function(data) { console.log(data), alerta("Obrigado por responder nossa pesquisa."), $(".alertClose").click((function(e) { location.href = "https://www.montecarlo.com.br/" })) }, error: function(data) { alerta("Ops! Ocorreu algum erro, por favor tente novamente.") } }) } } function validateEmail(email) { var re; return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email) } function alerta(texto) { $(".overlay-alert,#modalAlert").fadeIn(500), $(".alertMessage").text(texto), $(".alertClose").click((function() { $(".overlay-alert,#modalAlert").fadeOut(500) })) } $(document).ready((function() { $(".nps-button-enviar").click((function() { sendPass() })), $(".nps-notas").click((function() { $(".nps-notas").removeClass("nota-selecionada"), $(this).addClass("nota-selecionada") })) }));
93ced1649a41d89317c9949f65bc8f3c39848418
[ "JavaScript" ]
1
JavaScript
tspenido/mc
b0119ae56732dbd63028f9f697bf96e0a9e3c6ce
10d856bbae984d910b7ef7d7f89fc6ee8c1d8988
refs/heads/master
<file_sep>#!/bin/bash if [ ! -e /var/lib/pgsql/9.6/data/postgresql.conf ] then su postgres -c '/usr/pgsql-9.6/bin/initdb -D /var/lib/pgsql/9.6/data --locale=ru_RU.UTF-8' fi <file_sep>#!/bin/bash if [ ! -e /mnt/data/pgsql ] then mv /var/lib/pgsql /mnt/data fi <file_sep>erp ------------ Установка сервера БД, 1С и сервера лицензий Роль подходит как для сервера ERP, так и для обычного сервера 1С Требования ------------ CentOS 7, postinstall script Т.к. подключение через ssh осуществляется с использованием ключей, нужно прописать параметры соединения в ~/.ssh/config Параметры в ansible.cfg (remote_user можно указать непосредственно в playbook, из которого вызывается роль) [defaults] remote_user = удаленный пользователь roles_path = ./roles Папка files: 1c - пакеты rpm 1С-сервера fonts - пакет rpm msttcorefonts hasp - пакет rpm aksusbd postgresql - пакеты rpm postgreSQL Переменные -------------- ip-aдрес сервера для файла hosts: 'erp_external_ip: 192.168.1.1' fqdn для файла hosts: 'erp_fqdn: erp.local' имя хоста: 'erp_hostname: erp' пароль пользователя postgres: 'postgres_password: <PASSWORD>' Пример playbook ---------------- ``` - name: Configure erp hosts: erp become: true vars: erp_external_ip: 192.168.1.1 erp_fqdn: lc-erp-test.local erp_hostname: lc-erp-test postgres_password: <PASSWORD> roles: - erp ```
6a97803b2fb319d07414f32afdf4b8a59ecdb389
[ "Markdown", "Shell" ]
3
Shell
ilya8008/erp
94706f0ec96d3cb8416e6cd74c2f6603c6a00568
2d64c21b0f2419bff500f804d5dc4733f190fda8
refs/heads/master
<file_sep>$('#search').keyup(function(){ var serchField = $('#search').val(); var myExp = new RegExp(serchField,'gim'); $.getJSON('data.json', function(data){ var output = '<ul class="searchresulr">'; $.each(data, function(key, val){ if((val.name.search(myExp) != -1) || (val.bio.search(myExp) != -1)) { output +='<li>' ; var namemodif = val.name.replace(myExp,'<SPAN style="background-color:yellow">'+serchField+'</SPAN></FONT>'); output += '<h2>' + namemodif + '</h2>'; output += '<img src="images/'+val.shortname+'_tn.jpg" alt="'+val.name+'" />'; var biomodif = val.bio.replace(myExp,'<SPAN style="background-color:yellow">'+serchField+'</SPAN></FONT>'); output += '<p>'+biomodif+'</p>'; output += '</li>'; } }); output +='</ul>'; $('#update').html(output); }); });
d04017012524edccf901131ba1255dc769fa3214
[ "JavaScript" ]
1
JavaScript
ahmedbenamor/AJAX_JSON
756d43cc7ef56fabb54406022e86ea0593b61e3f
0566294d23d2787ce162525df7fdcd42c77548ee
refs/heads/master
<file_sep># prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, RETURN the KEY for the SMALLEST VALUE # if hash = [] return nil. def key_for_min_value(name_hash) if name_hash == {} return nil else min_value_storage = [] # initial value for min. min_key_storage = [] # initial value for min. name_hash.each do |key, value| # go through each value and push the lowest. if min_value_storage == [] min_value_storage.push(value) min_key_storage.push(key) elsif value < min_value_storage[0] min_value_storage.replace([value]) min_key_storage.replace([key]) end # end of if statement using .each ## we now have an actual min. end # end of each statement. return min_key_storage[0] end end
3009bd4a6b9937c7653a8c13db8b8df00545be05
[ "Ruby" ]
1
Ruby
SwanHub/key-for-min-value-denver-web-060319
35ad4fc9278c235a9d33b6776f420a47695a8e2f
54501dbd427afa62dce55a2c81f4ce0a789b1940
refs/heads/master
<file_sep>class EventHallBooking < Booking validates_presence_of :period # 1 = First turn (08:00 to 15:00) ; 2 = Last turn (20:00 to 03:00) end <file_sep># Hotel Vale dos Campos Web App Web app for booking management. This project has educationa purposes. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system. ### Prerequisites Before all, you need to have Ruby installed in your computer. You can use [RVM](https://rvm.io/rvm/install) or [Rbenv](https://github.com/rbenv/rbenv). Besides this, you need to have the gem Bundler installed. To install, run in terminal: ``` gem install bundler ``` ### Installing First, clone the app with: ``` git clone <EMAIL>:MagnunFurtado/hotel.git ``` After, enter in the app folder and run in terminal: ``` make setup ``` ## To run local for development After install, run in terminal: ``` rails server ``` Now, go to url: ``` http://localhost:3000 ``` ## Running the tests The app uses Guard and Rspec to automated tests. To run the tests: run in terminal: ``` bundle exec guard init ``` After this, the Guard test environment are runing. To run all tests press **ENTER** two times. ## Deployment Not yet done ## Built With * [RubyOnRails](http://rubyonrails.org/) - The web framework used * [Devise](https://github.com/plataformatec/devise) - Gem for user authentication * [Semantic UI](https://semantic-ui.com) - Frontend framework * [Rspec](http://rspec.info/) - Testing tool * [Guard](https://github.com/guard/guard) - Gem for automated tests ## Contributing Only have to fork the project and make a pull request. ## Versioning We use [SemVer](http://semver.org/) for versioning. ## License This project is [Opensource](https://opensource.org/). <file_sep>class Room < Accommodation validates_presence_of :single_beds_number, :couple_beds_number validates_numericality_of :single_beds_number, :couple_beds_number end <file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? def after_sign_in_path_for(resource) if current_user.type == "Employee" employee_home_path else user_home_path end end def after_sign_out_path_for(resource) home_path end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :cpf, :address, :birthday, :email, :fone, :type]) end end <file_sep>print "*** Creating initial DB ***\n" print "Seeding DB ...\n" print "Creating Hotel Information\n" Hotelinformation.create( description: "Fundado em 1978, o hotel <NAME> Campos é uma referência na serra gaúcha. Nossa infraestrutura conta com 122 quartos, 12 ​salas de reunião, 2 ​salões de eventos, com capacidade para 100 pessoas cada, restaurante e áreas de lazer. Aqui recebemos diversos hóspedes durante todo o ano, os quais vêm tanto para diversão e turismo quanto para reuniões de negócio.", email:"<EMAIL>", address: "Rua X num 123", fone: 51934772233 ) print "Creating Accommodations ...\n" number_fixture = 1 # boolean_fixture = true boolean_fixture = false print "Creating Rooms \n" for i in 1..50 Room.create( number: number_fixture, capacity: 2, description: "Quarto regular para casal", price: 170.00, occupied: boolean_fixture, single_beds_number: 0, couple_beds_number: 1 ) number_fixture += 1 # boolean_fixture = !boolean_fixture end for i in 1..30 Room.create( number: number_fixture, capacity: 2, description: "Quarto regular", price: 180.00, occupied: boolean_fixture, single_beds_number: 2, couple_beds_number: 0 ) number_fixture += 1 # boolean_fixture = !boolean_fixture end for i in 1..30 Room.create( number: number_fixture, capacity: 4, description: "Quarto Familiar", price: 240.00, occupied: boolean_fixture, single_beds_number: 2, couple_beds_number: 1 ) number_fixture += 1 # boolean_fixture = !boolean_fixture end for i in 1..12 Room.create( number: number_fixture, capacity: 4, description: "Quarto familiar com 2 camas de casal", price: 220.00, occupied: boolean_fixture, single_beds_number: 0, couple_beds_number: 2 ) number_fixture += 1 # boolean_fixture = !boolean_fixture end print "Creating Meeting Rooms\n" for i in 1..10 MeetingRoom.create( number: number_fixture, capacity: 25, description: "Sala de reuniões com computador, projetor e uma mesa redonda", price: 200.00, occupied: boolean_fixture, videoconf: false ) number_fixture += 1 # boolean_fixture = !boolean_fixture end for i in 1..2 MeetingRoom.create( number: number_fixture, capacity: 25, description: "Sala de reuniões para videoconferência com computador, projetor, 3 câmeras e uma grande mesa redonda com entradas de audio", price: 300.00, occupied: boolean_fixture, videoconf: true ) number_fixture += 1 # boolean_fixture = !boolean_fixture end print "Creating Event Hall\n" for i in 1..2 EventHall.create( number: number_fixture, capacity: 100, description: "Salão de eventos com 80 m2. Por padrão, sem serviço de buffet personalizado.", price: 600.00, occupied: boolean_fixture, tables_number: 20 ) number_fixture += 1 # boolean_fixture = !boolean_fixture end print "Creating users ...\n" print "Creating Employee\n" employee01 = Employee.create( name: "<NAME>", cpf: 33340077831, address: "Rua Riachuelo 345, apt 404", birthday: Date.parse('1970-01-20'), fone: 51987342211, email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", registrationID: "REC001", ) print "Creating Clients\n" client01 = Client.create( name: "<NAME>", cpf: 99940072221, address: "Rua João V 257", birthday: Date.parse('1950-08-12'), fone: 51888348866, email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", ) client02 = Client.create( name: "<NAME>", cpf: 99977222999, address: "Rua Marechal Hermes 12", birthday: Date.parse('1990-03-27'), fone: 51888348866, email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>", ) print "Creating Bookings ...\n" # bookings for Roberto Marinho RoomBooking.create( client: client01, employee: employee01, accommodation: Room.first, description: "Reserva regular. Nenhum pedido especial.", start_date: Date.current, end_date: Date.current + 5, active: true ) MeetingRoomBooking.create( client: client01, employee: employee01, accommodation: MeetingRoom.find(134), description: "Preparar a sala 10 minutos antes", start_date: Date.current, start_time: DateTime.now.change({ hour: 9, min: 0, sec: 0 }), active: true ) # bookings for <NAME> RoomBooking.create( client: client02, employee: employee01, accommodation: Room.second, description: "As toalhas devem ser trocadas todo turno", start_date: Date.current, end_date: Date.current + 15, active: true ) MeetingRoomBooking.create( client: client02, employee: employee01, accommodation: MeetingRoom.find(130), description: "Preparar atas para a reunião", start_date: Date.current, start_time: DateTime.now.change({ hour: 15, min: 0, sec: 0 }), active: true ) EventHallBooking.create( client: client02, employee: employee01, accommodation: EventHall.find(136), description: "Festa pós reunião", start_date: Date.current, period: 2, active: true ) print "Alterations after bookings" accommodation = Room.all.first accommodation.occupied = true accommodation.save accommodation = Room.all.second accommodation.occupied = true accommodation.save accommodation = EventHall.find(136) accommodation.occupied = true accommodation.save print "Done! DB populated ! \n" <file_sep>class HotelinformationsController < ApplicationController before_action :set_hotelinformation, only: [:home, :show, :edit, :update] def home end def show end def edit end def update if @hotelinformation.update(hotelinformation_params) redirect_to @hotelinformation, notice: 'Informações do Hotel atualizadas com sucesso!' else render :edit end end private def set_hotelinformation # Hotelinformation is a Singleton, only one exists ! @hotelinformation = Hotelinformation.all.first end def hotelinformation_params params.require(:hotelinformation).permit(:description, :email, :fone, :address) end end <file_sep>class AddOccupiedToAccommodation < ActiveRecord::Migration[5.0] def change add_column :accommodations, :occupied, :boolean end end <file_sep>FactoryGirl.define do factory :client, class: Client do name Faker::GameOfThrones.character cpf Faker::Number.unique.number(11) address Faker::Address.street_name birthday Faker::Date.birthday(18, 65) fone Faker::Number.number(11) email Faker::Internet.unique.email password <PASSWORD>.password end factory :employee, class: Employee do name Faker::GameOfThrones.character cpf Faker::Number.unique.number(11) address Faker::Address.street_name birthday Faker::Date.birthday(18, 65) fone Faker::Number.number(11) email Faker::Internet.unique.email password <PASSWORD> registrationID "REC001" end factory :room, class: Room do number 1 capacity 2 description "Quarto regular para casal" price 170.00 single_beds_number 0 couple_beds_number 1 trait :occupied do occupied true end trait :free do occupied false end end factory :meeting_room, class: MeetingRoom do number 3 capacity 25 description "Sala de reuniões com computador, projetor e uma mesa redonda" price 200.00 videoconf false trait :occupied do occupied true end trait :free do occupied false end end factory :event_hall, class: EventHall do number 5 capacity 100 description "Salão de eventos com 80 m2. Por padrão, sem serviço de buffet personalizado." price 600.00 tables_number 20 trait :occupied do occupied true end trait :free do occupied false end end factory :future_room_booking, class: RoomBooking do before(:create) do |room_booking| room_booking.client = FactoryGirl.create :client room_booking.employee = FactoryGirl.create :employee room_booking.accommodation = FactoryGirl.create :room, :free end description "As toalhas devem ser trocadas todo turno" start_date Date.current + 5 end_date Date.current + 10 active true end factory :present_room_booking, class: RoomBooking do before(:create) do |room_booking| room_booking.client = FactoryGirl.create :client room_booking.employee = FactoryGirl.create :employee room_booking.accommodation = FactoryGirl.create :room, :occupied end description "As toalhas devem ser trocadas todo turno" start_date Date.current end_date Date.current + 3 active true end factory :future_meeting_room_booking, class: MeetingRoomBooking do before(:create) do |meeting_room_booking| meeting_room_booking.client = FactoryGirl.create :client meeting_room_booking.employee = FactoryGirl.create :employee meeting_room_booking.accommodation = FactoryGirl.create :meeting_room, :free end description "Preparar atas para a reunião" start_date Date.current + 5 start_time DateTime.now + 5.days active true end factory :present_meeting_room_booking, class: MeetingRoomBooking do before(:create) do |meeting_room_booking| meeting_room_booking.client = FactoryGirl.create :client meeting_room_booking.employee = FactoryGirl.create :employee meeting_room_booking.accommodation = FactoryGirl.create :meeting_room, :occupied end description "Preparar atas para a reunião" start_date Date.current start_time DateTime.now active true end factory :future_event_hall_booking, class: EventHallBooking do before(:create) do |event_hall_booking| event_hall_booking.client = FactoryGirl.create :client event_hall_booking.employee = FactoryGirl.create :employee event_hall_booking.accommodation = FactoryGirl.create :event_hall, :free end description "Preparar atas para a reunião" start_date Date.current + 5 period 2 active true end factory :present_event_hall_booking, class: EventHallBooking do before(:create) do |event_hall_booking| event_hall_booking.client = FactoryGirl.create :client event_hall_booking.employee = FactoryGirl.create :employee event_hall_booking.accommodation = FactoryGirl.create :event_hall, :occupied end description "Preparar atas para a reunião" start_date Date.current period 2 active true end end <file_sep>class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy] def index @users = User.all @clients = Client.all @employees = Employee.all end def show end def search_client end def search_client_results @clients = Client.where(cpf: params[:cpf], type: "Client").order(created_at: :asc) end def new @user = User.new @type = params[:type] end def edit @type = params[:type] end def create @user = User.new(user_params) if @user.save redirect_to @user, notice: 'Usuário criado com sucesso.' else render :new end end def update if @user.update(user_params) redirect_to @user, notice: 'Usuário atualizado co sucesso.' else render :edit end end def destroy @user.destroy redirect_to users_url, notice: 'Usuário deletado com sucesso.' end private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit(:name, :cpf, :address, :birthday, :email, :fone, :type, :registrationID) end end <file_sep>class CreateHotelinformations < ActiveRecord::Migration[5.0] def change create_table :hotelinformations do |t| t.string :description t.string :email t.string :fone t.string :address t.timestamps end end end <file_sep>Rails.application.routes.draw do devise_for :users root "home#home" resources :hotelinformations, only: [:show, :edit, :update] resources :bookings resources :room_bookings, :controller => "bookings", :type => "RoomBooking" resources :meeting_room_bookings, :controller => "bookings", :type => "MeetingRoomBooking" resources :event_hall_bookings, :controller => "bookings", :type => "EventHallBooking" resources :accommodations resources :rooms, :controller => "accommodations", :type => "Room" resources :meeting_rooms, :controller => "accommodations", :type => "MeetingRoom" resources :event_halls, :controller => "accommodations", :type => "EventHall" resources :users resources :clients, :controller => "users", :type => "Client" resources :employees, :controller => "users", :type => "Employee" get "/select_new_booking" => "bookings#select_new" get "/user_bookings" => "bookings#user_bookings" get "/home" => "home#home" get "/user_home" => "home#user_home" get "/employee_home" => "home#employee_home" get "/main_search" => "accommodations#main_search" get "/search_rooms" => "accommodations#search_rooms" get "/search_meeting_rooms" => "accommodations#search_meeting_rooms" get "/search_event_halls" => "accommodations#search_event_halls" get "/accommodations_situation" => "accommodations#accommodations_situation" get "/accommodations_situation_detailed" => "accommodations#accommodations_situation_detailed" get "/search_client" => "users#search_client" get "/search_client_results" => "users#search_client_results" get "/checkin" => "bookings#checkin" get "/checkout" => "bookings#checkout" end <file_sep>class HomeController < ApplicationController def home end def client_home end def employee_home end end <file_sep>require "rails_helper" include AccommodationsHelper RSpec.describe AccommodationsHelper do describe ".search_reserved_rooms" do it "finds all reserved rooms" do room_booking = FactoryGirl.create :present_room_booking result = search_reserved_rooms(Date.current, Date.current + 5) expect(result).to eq([room_booking.accommodation]) end it "DOES NOT find reserved rooms" do room_booking = FactoryGirl.create :future_room_booking result = search_reserved_rooms(Date.current + 30, Date.current + 35) expect(result).to eq([]) end end describe ".search_reserved_meeting_rooms" do it "finds all reserved meeting rooms" do meeting_room_booking = FactoryGirl.create :present_meeting_room_booking result = search_reserved_meeting_rooms(Date.current, DateTime.now + 1.hour) expect(result).to eq([meeting_room_booking.accommodation]) end it "DOES NOT find reserved meeting rooms" do meeting_room_booking = FactoryGirl.create :present_meeting_room_booking result = search_reserved_rooms(Date.current , DateTime.now + 10.hour) expect(result).to eq([]) end end describe ".search_reserved_event_halls" do it "finds all reserved event halls" do event_hall_booking = FactoryGirl.create :present_event_hall_booking result = search_reserved_event_halls(Date.current, 2) expect(result).to eq([event_hall_booking.accommodation]) end it "DOES NOT find reserved event halls" do event_hall_booking = FactoryGirl.create :future_event_hall_booking result = search_reserved_event_halls(Date.current + 3, 1) expect(result).to eq([]) end end describe ".available_room?" do it "room is available" do room_booking = FactoryGirl.create :future_room_booking result = available_room?(room_booking.accommodation , Date.current + 1, Date.current + 3) expect(result).to eq(true) end it "room IS NOT available today" do room_booking = FactoryGirl.create :present_room_booking result = available_room?(room_booking.accommodation , Date.current, Date.current + 3) expect(result).to eq(false) end end describe ".available_meeting_room?" do it "meeting room is available" do meeting_room_booking = FactoryGirl.create :future_meeting_room_booking result = available_meeting_room?(meeting_room_booking.accommodation , Date.current + 5, DateTime.now + 5.days + 10.hour) expect(result).to eq(true) end it "meeting room IS NOT available" do meeting_room_booking = FactoryGirl.create :present_meeting_room_booking result = available_meeting_room?(meeting_room_booking.accommodation , Date.current, DateTime.now + 2.hour) expect(result).to eq(false) end end describe ".available_event_hall?" do it "event hall is available" do event_hall_booking = FactoryGirl.create :future_event_hall_booking result = available_event_hall?(event_hall_booking.accommodation , Date.current + 5.days, 1) expect(result).to eq(true) end it "event hall IS NOT available today" do event_hall_booking = FactoryGirl.create :present_event_hall_booking result = available_event_hall?(event_hall_booking.accommodation , Date.current, 2) expect(result).to eq(false) end end end <file_sep>class AddVideoconfToAccommodation < ActiveRecord::Migration[5.0] def change add_column :accommodations, :videoconf, :boolean end end <file_sep>class AccommodationsController < ApplicationController include AccommodationsHelper include BookingsHelper before_action :set_accommodation, only: [:show, :edit, :update, :destroy] def index @accommodations = Accommodation.all end def main_search end def search_rooms start_date = params[:start_date] end_date = params[:end_date] searched_start_date = Date.new(start_date["start_date(1i)"].to_i, start_date["start_date(2i)"].to_i, start_date["start_date(3i)"].to_i) searched_end_date = Date.new(end_date["end_date(1i)"].to_i, end_date["end_date(2i)"].to_i, end_date["end_date(3i)"].to_i) @rooms = Room.all - search_reserved_rooms(searched_start_date, searched_end_date) end def search_event_halls searched_period = params[:period] start_date = params[:start_date] searched_start_date = Date.new(start_date["start_date(1i)"].to_i, start_date["start_date(2i)"].to_i, start_date["start_date(3i)"].to_i) @event_halls = EventHall.all - search_reserved_event_halls(searched_start_date, searched_period) end def search_meeting_rooms start_date = params[:start_date] start_time = params[:start_time] searched_start_date = Date.new(start_date["start_date(1i)"].to_i, start_date["start_date(2i)"].to_i, start_date["start_date(3i)"].to_i) searched_start_timedate = DateTime.new(start_time["start_time(1i)"].to_i, start_time["start_time(2i)"].to_i, start_time["start_time(3i)"].to_i,start_time["start_time(4i)"].to_i, start_time["start_time(5i)"].to_i, start_time["start_time(6i)"].to_i) @meeting_rooms = MeetingRoom.all - search_reserved_meeting_rooms(searched_start_date, searched_start_timedate) end def accommodations_situation @rooms = Room.where(occupied: true) @meeting_rooms = MeetingRoom.where(occupied: true) @event_halls = EventHall.where(occupied: true) end def accommodations_situation_detailed @rooms = Room.where(occupied: true) @meeting_rooms = MeetingRoom.where(occupied: true) @event_halls = EventHall.where(occupied: true) end def show if @accommodation.type=="Room" @room = @accommodation else if @accommodation.type=="EventHall" @event_hall = @accommodation else @meeting_room = @accommodation end end end def new @accommodation = Accommodation.new end def edit end def create @accommodation = Accommodation.new(accommodation_params) if @accommodation.save redirect_to @accommodation, notice: 'Cômodo criado com sucesso.' else render :new end end def update if @accommodation.update(accommodation_params) redirect_to @accommodation, notice: 'Cômodo atualizado com sucesso.' else render :edit end end def destroy @accommodation.destroy redirect_to accommodations_url, notice: 'Cômodo deletado com sucesso.' end private def set_accommodation @accommodation = Accommodation.find(params[:id]) end def accommodation_params params.require(:accommodation).permit(:number, :capacity, :price, :type, :description, :occupied, :single_beds_number, :couple_beds_number, :videoconf, :tables_number, :period, :start_time => [], :start_date => [], :end_date => []) end end <file_sep>class EventHall < Accommodation validates_presence_of :tables_number validates_numericality_of :tables_number end <file_sep>class Accommodation < ApplicationRecord validates_presence_of :number, :capacity, :description, :price validates_numericality_of :number, :capacity, :price validates_uniqueness_of :number validates :occupied, inclusion: { in: [ true, false ] } has_many :bookings end <file_sep>require "rails_helper" include BookingsHelper RSpec.describe BookingsHelper do describe ".find_current_booking" do describe "searching for room: " do it "finds room's current booking" do room_booking = FactoryGirl.create :present_room_booking result = find_current_booking(room_booking.accommodation.id) expect(result).to eq(room_booking) end it "finds room's current booking" do room_booking = FactoryGirl.create :future_room_booking result = find_current_booking(room_booking.accommodation.id) expect(result).to eq(nil) end end describe "searching for meeting room: " do it "finds meeting room's current booking" do meeting_room_booking = FactoryGirl.create :present_meeting_room_booking result = find_current_booking(meeting_room_booking.accommodation.id) expect(result).to eq(meeting_room_booking) end it "finds meeting room's current booking" do meeting_room_booking = FactoryGirl.create :future_meeting_room_booking result = find_current_booking(meeting_room_booking.accommodation.id) expect(result).to eq(nil) end end describe "searching for event hall: " do it "finds event hall's current booking" do event_hall_booking = FactoryGirl.create :present_event_hall_booking result = find_current_booking(event_hall_booking.accommodation.id) expect(result).to eq(event_hall_booking) end it "finds event hall's current booking" do event_hall_booking = FactoryGirl.create :future_event_hall_booking result = find_current_booking(event_hall_booking.accommodation.id) expect(result).to eq(nil) end end end end <file_sep>class MeetingRoom < Accommodation validates :occupied, inclusion: { in: [ true, false ] } end <file_sep>class RoomBooking < Booking validates_presence_of :end_date end <file_sep>class Booking < ApplicationRecord belongs_to :client belongs_to :employee belongs_to :accommodation validates_presence_of :description, :start_date end <file_sep>require 'test_helper' class HotelinformationsControllerTest < ActionDispatch::IntegrationTest setup do @hotelinformation = hotelinformations(:one) end test "should get index" do get hotelinformations_url assert_response :success end test "should get new" do get new_hotelinformation_url assert_response :success end test "should create hotelinformation" do assert_difference('Hotelinformation.count') do post hotelinformations_url, params: { hotelinformation: { address: @hotelinformation.address, description: @hotelinformation.description, email: @hotelinformation.email, fone: @hotelinformation.fone } } end assert_redirected_to hotelinformation_url(Hotelinformation.last) end test "should show hotelinformation" do get hotelinformation_url(@hotelinformation) assert_response :success end test "should get edit" do get edit_hotelinformation_url(@hotelinformation) assert_response :success end test "should update hotelinformation" do patch hotelinformation_url(@hotelinformation), params: { hotelinformation: { address: @hotelinformation.address, description: @hotelinformation.description, email: @hotelinformation.email, fone: @hotelinformation.fone } } assert_redirected_to hotelinformation_url(@hotelinformation) end test "should destroy hotelinformation" do assert_difference('Hotelinformation.count', -1) do delete hotelinformation_url(@hotelinformation) end assert_redirected_to hotelinformations_url end end <file_sep>class Employee < User validates_presence_of :registrationID end <file_sep>class AddTablesNumberToAccommodation < ActiveRecord::Migration[5.0] def change add_column :accommodations, :tables_number, :integer end end <file_sep>class AddEmployeeToBooking < ActiveRecord::Migration[5.0] def change add_reference :bookings, :employee, foreign_key: true end end <file_sep>module AccommodationsHelper def search_reserved_rooms(start_date, end_date) reserved_rooms = [] RoomBooking.all.each do |booking| if booking.active && (booking.start_date..booking.end_date).overlaps?(start_date..end_date) reserved_rooms.append(Room.find(booking.accommodation_id)) end end return reserved_rooms end def search_reserved_meeting_rooms(start_date, start_time) reserved_meeting_rooms = [] MeetingRoomBooking.all.each do |booking| if booking.active && start_date.strftime("%Y-%m-%d")==booking.start_date.strftime("%Y-%m-%d") && ((start_time.strftime("%H:%M:%S")..(start_time + 6.hours).strftime("%H:%M:%S")).overlaps?(booking.start_time.strftime("%H:%M:%S")..(booking.start_time + 6.hours).strftime("%H:%M:%S") )) reserved_meeting_rooms.append(MeetingRoom.find(booking.accommodation_id)) end end return reserved_meeting_rooms end def search_reserved_event_halls(start_date, period) reserved_eventhalls = [] EventHallBooking.all.each do |booking| if booking.active && start_date.strftime("%Y-%m-%d")==booking.start_date.strftime("%Y-%m-%d") && booking.period.to_i == period.to_i reserved_eventhalls.append(EventHall.find(booking.accommodation_id)) end end return reserved_eventhalls end def available_room?(room, start_date, end_date) if (room.occupied && start_date == Date.current) || search_reserved_rooms(start_date, end_date).include?(room) return false else return true end end def available_meeting_room?(meeting_room, start_date, start_time) if (meeting_room.occupied && start_date == Date.current) || search_reserved_meeting_rooms(start_date, start_time).include?(meeting_room) return false else return true end end def available_event_hall?(event_hall, start_date, period) if (event_hall.occupied && start_date == Date.current) || search_reserved_event_halls(start_date, period).include?(event_hall) return false else return true end end end <file_sep>require 'test_helper' class AccommodationsControllerTest < ActionDispatch::IntegrationTest setup do @accommodation = accommodations(:one) end test "should get index" do get accommodations_url assert_response :success end test "should get new" do get new_accommodation_url assert_response :success end test "should create accommodation" do assert_difference('Accommodation.count') do post accommodations_url, params: { accommodation: { capacity: @accommodation.capacity, number: @accommodation.number, price: @accommodation.price } } end assert_redirected_to accommodation_url(Accommodation.last) end test "should show accommodation" do get accommodation_url(@accommodation) assert_response :success end test "should get edit" do get edit_accommodation_url(@accommodation) assert_response :success end test "should update accommodation" do patch accommodation_url(@accommodation), params: { accommodation: { capacity: @accommodation.capacity, number: @accommodation.number, price: @accommodation.price } } assert_redirected_to accommodation_url(@accommodation) end test "should destroy accommodation" do assert_difference('Accommodation.count', -1) do delete accommodation_url(@accommodation) end assert_redirected_to accommodations_url end end <file_sep>module BookingsHelper def find_current_booking(accomodation_id) bookings = Booking.where(accommodation_id: accomodation_id).order(created_at: :asc) accommodation = Accommodation.find(accomodation_id) result_booking = nil if accommodation.type=="Room" bookings.each do |booking| if (booking.start_date..booking.end_date).cover?(Date.current) result_booking = booking end end else if accommodation.type=="EventHall" current_period = 0 if (DateTime.now.change({ hour: 0, min: 0, sec: 1 })..DateTime.now.change({ hour: 12, min: 0, sec: 0 })).cover?(Time.now) current_period = 1 else current_period = 2 end bookings.each do |booking| if ((booking.start_date.compare_without_coercion(Date.current) == 0) && (booking.period == current_period)) result_booking = booking end end else bookings.each do |booking| if ((booking.start_date.compare_without_coercion(Date.current) == 0) && (booking.start_time..booking.start_time + 6.hours).cover?(Time.now)) result_booking = booking end end end end return result_booking end end <file_sep>class MeetingRoomBooking < Booking validates_presence_of :start_time end <file_sep>class AddSingleBedsNumberToAccommodation < ActiveRecord::Migration[5.0] def change add_column :accommodations, :single_beds_number, :integer end end <file_sep>setup: bundle install rake db:create rake db:migrate rake db:seed rake assets:precompile <file_sep>class Hotelinformation < ApplicationRecord end <file_sep>class BookingsController < ApplicationController include AccommodationsHelper before_action :authenticate_user! before_action :set_booking, only: [:show, :edit, :update, :destroy] def index @bookings = Booking.all @rooms_bookings = RoomBooking.all.order(created_at: :desc) @meeting_rooms_bookings = MeetingRoomBooking.all.order(created_at: :desc) @event_halls_bookings = EventHallBooking.all.order(created_at: :desc) end def checkin @booking = Booking.find(params[:booking_id]) @booking.active = true @booking.accommodation.occupied = true @booking.save redirect_to bookings_path end def checkout @booking = Booking.find(params[:booking_id]) @booking.active = false @booking.accommodation.occupied = false @booking.save redirect_to bookings_path end def show end def new @booking = Booking.new @booking_type = params[:type] end def select_new end def edit end def user_bookings @bookings = Booking.where(client_id: current_user.id).order(created_at: :desc) @rooms_bookings = RoomBooking.where(client_id: current_user.id).order(created_at: :desc) @meeting_rooms_bookings = MeetingRoomBooking.where(client_id: current_user.id).order(created_at: :desc) @event_halls_bookings = EventHallBooking.where(client_id: current_user.id).order(created_at: :desc) end def create @booking = Booking.new(booking_params) @booking.accommodation = Accommodation.find_by_number(params[:accommodation_number]) @booking.active = true if current_user.type == "Employee" @booking.employee = current_user @booking.client = Client.find_by_cpf(params[:client_cpf]) else @booking.client = current_user @booking.employee = Employee.first end if @booking.accommodation.type == "Room" accommodation_available = available_room?(@booking.accommodation, @booking.start_date, @booking.end_date) else if @booking.accommodation.type == "MeetingRoom" accommodation_available = available_meeting_room?(@booking.accommodation, @booking.start_date, @booking.start_time) else accommodation_available = available_event_hall?(@booking.accommodation, @booking.start_date, @booking.period) end end if not accommodation_available flash.now[:notice] = 'Cômodo já ocupado ou reservado !' render :new else if @booking.save redirect_to @booking, notice: 'Reserva criada com sucesso.' else render :new end end end def update if @booking.update(booking_params) redirect_to @booking, notice: 'Reserva foi atualizada com sucesso.' else render :edit end end def destroy @booking.destroy redirect_to bookings_url, notice: 'Reserva deletada com sucesso.' end private def set_booking @booking = Booking.find(params[:id]) end def booking_params params.require(:booking).permit(:description, :start_date, :end_date, :start_time, :period, :client_id, :employee_id, :accommodation_id, :type, :client_cpf, :accommodation_number, :booking_id, :active) end end
d0f955cd615497f26f62c2d0e9d170b336115be5
[ "Markdown", "Ruby", "Makefile" ]
33
Ruby
MagnunAVF/hotel-vale-dos-campos
ddfa057f195fe77e05bbaf0da28f61693e93e5c5
ac498266c3873be7d2bb41fcedc8c2ae17728197
refs/heads/master
<repo_name>librallu/UQAC-algo-01<file_sep>/dbinom2.c #include <stdio.h> #define N 10 print_tab(int* tab, int n){ int i; for (i = 0; i < n; i++){ if (tab[i] != 0) printf("%d ", tab[i]); } printf("\n"); } // copie from dans to int copy(int* from, int* to, int n){ int i; for ( i = 0; i < n; i++ ){ to[i] = from[i]; } } int dbinom1(int n, int k){ /* On initialise le premier tableau à 1,0, ... */ int newTab[N] = {0}; newTab[0] = 1; int oldTab[N]; print_tab(newTab, N); int i,j; for ( i = 1 ; i <= n ; i++ ){ copy(newTab, oldTab, N); newTab[0] = 1; // calcul de la nouvelle ligne for ( j = 1 ; j <= i ; j++ ){ newTab[j] = oldTab[j-1]+oldTab[j]; } print_tab(newTab, N); } return newTab[k]; } int main(){ printf("Value: %d\n", dbinom1(N, 2)); return 0; } <file_sep>/README.md # UQAC-algo-01 source files for 8INF840 <file_sep>/dbinom1.c #include <stdio.h> int dbinom1(int n, int k){ if ( n == k ){ return 1; } else if ( k == 1 ){ return 1; } else { return dbinom1(n-1, k) + dbinom1(n-1, k-1); } } int main(){ int n = 33; int k = n/2; printf("value: %d\n", dbinom1(n,k)); return 0; }
a514d35c5a4f0d84baa52c44ca741e0b61d759e1
[ "Markdown", "C" ]
3
C
librallu/UQAC-algo-01
d4ae99e32c7e6eeb6fb1ed86fa6c69ea3160d4f9
54a627fbac7b9e5d8590b3207dfd73ca55c1c650
refs/heads/master
<file_sep>import os import json import re import nltk import urllib import cv2 import numpy as np from bs4 import BeautifulSoup from nltk.sentiment.vader import SentimentIntensityAnalyzer class PersonalityAnalysis: def __init__(self, path, name): self.file_path = os.path.join(path, 'Source Data/Likes/like.js') self.image_path = os.path.join(path, 'Processed Images') self.name = name self.images = [] self.popularity_dict = {} self.punctuation = re.compile(r'[-.?,:;()|0-9]') self.emojis = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE) self.urls = re.compile('(?P<url>https?://[^\s]+)') def load_twitter_data(self): with open(self.file_path,'r',encoding="utf8") as js_file: data_string = js_file.read().replace('\n', '') data_string = data_string[data_string.index('=') + 1:] self.like_dict = json.loads(data_string) def load_yolo(self): self.net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg") self.classes = [] with open('coco.names', "r") as f: self.classes = [line.strip() for line in f.readlines()] self.popularity_dict = dict((label,0) for label in self.classes) self.layer_names = self.net.getLayerNames() self.output_layers = [self.layer_names[i[0] - 1] for i in self.net.getUnconnectedOutLayers()] self.colors = np.random.uniform(0, 255, size=(len(self.classes), 3)) def url_to_image(self, url): # download the image, convert it to a NumPy array, and then read # it into OpenCV format resp = urllib.request.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image def analyze_images(self): # parse json string for like in self.like_dict: like_text = like['like']['fullText'] tweet_id = like['like']['tweetId'] tweet_url = like['like']['expandedUrl'] score_text = self.punctuation.sub(r'', like_text) score_text = self.emojis.sub(r'', score_text) score = SentimentIntensityAnalyzer().polarity_scores(score_text) try: # check if tweet contains attachment if re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', like_text): page_data = urllib.request.urlopen(tweet_url).read() scraper = BeautifulSoup(page_data, 'html.parser') image_tag = scraper.find_all('img', {'alt': True, 'src': True})[4] link = image_tag.get('src') # check if image is media image (vs profile image) if 'media' in link: print(score_text) image = self.url_to_image(link) self.detect_objects(image, tweet_id, score) except Exception as e: print(e) def detect_objects(self, image, image_id, score): image = cv2.resize(image, None, fx=0.4, fy=0.4) height, width, channels = image.shape blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False) self.net.setInput(blob) outs = self.net.forward(self.output_layers) pos_score = score['pos'] neg_score = score['neg'] tot_score = pos_score - neg_score print(tot_score) class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: # Object detected center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # Rectangle coordinates x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) font = cv2.FONT_HERSHEY_PLAIN for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(self.classes[class_ids[i]]) self.popularity_dict[label] += tot_score color = self.colors[i] cv2.rectangle(image, (x, y), (x + w, y + h), color, 2) cv2.putText(image, label, (x, y + 30), font, 3, color, 3) cv2.imwrite(os.path.join(self.image_path , "Image" + image_id + '.jpg'), image) def print_personality(self): sorted_labels = sorted(self.popularity_dict.items(), key = lambda x :x[1], reverse=True) top5 = sorted_labels[:5] bottom5 = sorted_labels[-5:] print(f'Hi, my name is {self.name}, and I like ', end =" ") for rank in top5: label = rank[0] # get plural form if(label[-1] == 's'): label = label + 'es' else: label = label + 's' # print list with oxford comma if rank == top5[-1]: print(f' and {label}.' ) else: print(f'{label}, ' , end =" ") print("However, I don't like ", end =" ") for rank in bottom5: label = rank[0] # get plural form if(label[-1] == 's'): label = label + 'es' else: label = label + 's' # print list with oxford comma if rank == bottom5[-1]: print(f' and {label}.', end =" " ) else: print(f'{label}, ' , end =" ") gage_analysis = PersonalityAnalysis("D:\Documents\Side Projects (CS)\Python\Visa Intro", "<NAME>") gage_analysis.load_twitter_data() gage_analysis.load_yolo() gage_analysis.analyze_images() gage_analysis.print_personality() <file_sep>from nltk.sentiment.vader import SentimentIntensityAnalyzer score_text = "I just love when people don't comment in their code." score = SentimentIntensityAnalyzer().polarity_scores(score_text) #represents the "positivity" score of the text print(score['pos']) <file_sep>import os import json import nltk import re from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.tokenize import word_tokenize from nltk.probability import FreqDist from nltk.stem import wordnet from nltk.stem import WordNetLemmatizer from nltk import ne_chunk nltk.download('vader_lexicon') #nltk.download('words') #nltk.download('maxent_ne_chunker') #nltk.download('averaged_perceptron_tagger') #nltk.download('punkt') messages = [] # identify digits/special characters for later removal punctuation = re.compile(r'[-.?,:;()|0-9]') emojis = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE) threshold = .3 with open("D:\Documents\Side Projects (CS)\Python\Visa Intro\Source Data\Direct Messages\messages.json", encoding='utf-8') as json_file: data = json.load(json_file) for direct_messages in data: conversation = direct_messages['conversation'] for message in conversation: if(message['sender'] == "gage_e_benham"): try: messages.append(message['text']) except: print(message) for message in messages: score = SentimentIntensityAnalyzer().polarity_scores(message) if score['pos'] > threshold: print(message)
13ce3de52356aa8d7dd7fb269f2256b5d293ec6a
[ "Python" ]
3
Python
GB1999/Visa_Internship_Intro
5c92bd224c627a10afec8502655c6345c46204b2
12f760254a82ed0dd9b92e255ddb84b5f6ab5c01
refs/heads/main
<file_sep>from django.shortcuts import render # Create your views here. def index(request): return render(request, "index.html") def blog(request): return render(request, "blog.html") def projects(request): return render(request, "projects.html") def photography(request): return render(request, "photography.html") def about(request): return render(request, "about.html")<file_sep># AppMaths ### Personal Website Written in Python Django and Django REST framework <file_sep>document.addEventListener("DOMContentLoaded", ()=>{ const _CONTENT = [ 'Hello', 'My name is David', 'And I am a Full Stack Developer', 'Check out some of my projects', 'Welcome to my home on the internet!' ]; var _PART = 0; // Character number of the current sentence being processed var _PART_INDEX = 0; // Holds the handle returned from setInterval var _INTERVAL_VAL; // Element that holds the text var _ELEMENT = document.querySelector("#text"); // Implements typing effect function Type() { // Get substring with 1 characater added var text = _CONTENT[_PART].substring(0, _PART_INDEX + 1); _ELEMENT.innerHTML = text; _PART_INDEX++; // If full sentence has been displayed then start to delete the sentence after some time if(text === _CONTENT[_PART]) { clearInterval(_INTERVAL_VAL); setTimeout(function() { _INTERVAL_VAL = setInterval(Delete, 50); }, 500); } } // Implements deleting effect function Delete() { // Get substring with 1 characater deleted var text = _CONTENT[_PART].substring(0, _PART_INDEX - 1); _ELEMENT.innerHTML = text; _PART_INDEX--; // If sentence has been deleted then start to display the next sentence if(text === '') { clearInterval(_INTERVAL_VAL); // If current sentence was last then display the first one, else move to the next if(_PART == (_CONTENT.length - 1)) _PART = 0; else _PART++; _PART_INDEX = 0; // Start to display the next sentence after some time setTimeout(function() { _INTERVAL_VAL = setInterval(Type, 100); }, 200); } } // Start the typing effect on load _INTERVAL_VAL = setInterval(Type, 100); }); <file_sep>from . import views from django.urls import path urlpatterns = [ path('', views.index, name='index'), path('blog', views.blog, name='blog'), path('projects', views.projects, name='projects'), path('photography', views.photography, name='photography'), path('about', views.about, name='about') ]
fa4741905b63f755c95e47e8c32122c77d500e9b
[ "Markdown", "Python", "JavaScript" ]
4
Python
Davidg384/AppMathsSite
939eb997519923b370b8482788024f6ba1c14df1
19934f0e2a0f6a70a56e0700623e44645862a446
refs/heads/master
<repo_name>tinnightcap/nubis-junkheap<file_sep>/regions.py #!/usr/bin/env python import boto import boto.ec2 regions = [region.name for region in boto.ec2.regions()] for region in regions: print region <file_sep>/duo/README.md Configuring duo on a nubis jumphost #### Pre-req 1. Make sure that consul has all the k/v it needs to configure pam_duo. The k/v layout needs these keys (Naturally if its a prod subnet use jumphost-prod instead) ```bash jumphost-stage/stage/config/host jumphost-stage/stage/config/ikey jumphost-stage/stage/config/ldap-basedn jumphost-stage/stage/config/ldap-binddn jumphost-stage/stage/config/ldap-bindpassword jumphost-stage/stage/config/ldap-server jumphost-stage/stage/config/ldap-smartfail-domain jumphost-stage/stage/config/skey ``` 2. Make sure that we have the latest AMI build that includes the duo package 3. Make sure you have an ssh connection open to the jumphost before configuring duo ### Configuring Duo on nubis-jumphost Here are the steps to configure a nubis-jumphost to use duo: 1. Create user accounts you need. There is a helper script [here](https://github.com/nubisproject/nubis-junkheap/blob/master/create-users) 2. Run this script to create the user accounts and copy SSH keys, however you need to make sure that you have a gpg encrypted file that contains your LDAP password located in `~/.passwd/mozilla.gpg` and have `gpg-agent` configured. You will also need to be connected to the VPN 3. Once accounts are all create ssh to the jumphost and then run the following command ```bash # wget https://raw.githubusercontent.com/nubisproject/nubis-junkheap/master/duo/configure-duo # ./configure-duo ``` 4. Test to see if duo works <file_sep>/install-duo #!/bin/bash if [[ -z "$1" ]]; then echo "Usage: $0 [jumphost]"; exit 1; fi jumphost=$1 duo_version="1.9.11-1" basedir=$(dirname $0) function download_and_install { if [[ -z "$1" ]]; then echo "Usage: ${FUNCNAME} [jumphost hostname]"; return 1; fi local jumphost=$1 ssh -t ec2-user@${jumphost} "sudo wget -P /usr/local/src https://s3-us-west-2.amazonaws.com/nubis-stacks/packages/rpm/duo_unix-${duo_version}.x86_64.rpm" > /dev/null 2>&1 ssh -t ec2-user@${jumphost} "sudo rpm --import https://www.duosecurity.com/RPM-GPG-KEY-DUO" > /dev/null 2>&1 ssh -t ec2-user@${jumphost} "sudo rpm -i /usr/local/src/duo_unix-${duo_version}.x86_64.rpm" > /dev/null 2>&1 ssh -t ec2-user@${jumphost} "sudo chmod 0600 /etc/duo/*.conf" > /dev/null 2>&1 } function copy_duo_puppet_module { if [[ -z "$1" ]]; then echo "Usage: ${FUNCNAME} [jumphost hostname]"; return 1; fi local jumphost=$1 echo "Copying duo folder to ${jumphost} /tmp" scp -q -pr ${basedir}/duo ec2-user@${jumphost}:/tmp local RV=$? return ${RV} } download_and_install "${jumphost}" <file_sep>/configuring-duo.md #### Installing duo package In order to install you will need to run the `install-duo` script, the script takes one argument which is the jumphost hostname Usage: ```bash ./install-duo <jumphost hostname> ``` What this does is installs a special version of `duo_unix` that is patched to talk to LDAP #### Configuring duo Once that is all done you will need to configure duo, the file that we care about is located in `/etc/duo/pam_duo.conf` You will need an `ikey`, `skey` and `host` information all of which you can get from the duosecurity admin panel. DO NOT GO PAST THIS POINT IF UNLESS YOU HAVE A ROOT CONSOLE TO THE HOST OPENED #### Configuring SSHD Edit `/etc/ssh/sshd_config` and add the following lines: ```bash UsePAM yes UseDNS no ChallengeResponseAuthentication yes AuthenticationMethods "publickey,keyboard-interactive" PubkeyAuthentication yes PasswordAuthentication no ``` #### Configuring Pam Edit `/etc/pam.d/system-auth`, note you only need to add the auth line for duo and not delete anything. Before: ```bash auth required pam_env.so auth sufficient pam_unix.so nullok try_first_pass auth requisite pam_succeed_if.so uid >= 500 quiet auth required pam_deny.so ``` After: ```bash auth required pam_env.so auth requisite pam_unix.so nullok try_first_pass auth sufficient pam_duo.so auth requisite pam_succeed_if.so uid >= 500 quiet auth required pam_deny.so ``` Edit `/etc/pam.d/sshd` and same as about just add the auth pam_duo.so line Before: ```bash auth required pam_sepermit.so auth substack password-auth ``` After: ```bash auth required pam_sepermit.so auth required pam_duo.so ``` At this point you are done and you just need to restart sshd by running `service sshd restart` and try logging in from a seperate terminal to your account. #### WIP I'm working on writing some puppet modules for this. <file_sep>/docker/tools/Dockerfile FROM centos:7 RUN yum -y install epel-release centos-release-scl-rh centos-release-scl RUN yum -y update RUN yum -y install curl python2-pip unzip git ARG packer_version=0.12.1 ARG github_changelog_generator_version=1.14.2 ARG librarian_puppet_version=2.2.3 ARG puppet_version=4.8.1 # Install packer RUN curl -L -o /tmp/packer.zip https://releases.hashicorp.com/packer/${packer_version}/packer_${packer_version}_linux_amd64.zip RUN cd /usr/local/bin && unzip /tmp/packer.zip && rm /tmp/packer.zip # Install jq RUN yum -y install jq-1.5 # Install AWS CLI RUN yum -y install awscli-1.11.10-1.el7 # Install nubis-builder RUN git clone https://github.com/nubisproject/nubis-builder.git /opt/nubis-builder ADD variables.json /opt/nubis-builder/secrets/variables.json # Install Ruby for gems RUN yum --enablerepo=centos-sclo-rh -y install rh-ruby22 rh-ruby22-rubygems ADD rh-ruby22.sh /etc/profile.d/rh-ruby22.sh # Install github changelog generator RUN source scl_source enable rh-ruby22 && gem install -V github_changelog_generator -v ${github_changelog_generator_version} # Install librarian puppet RUN source scl_source enable rh-ruby22 && gem install -V librarian-puppet -v ${librarian_puppet_version} RUN source scl_source enable rh-ruby22 && gem install -V puppet -v ${puppet_version} ENV PATH=/bin:/usr/bin:/usr/local/bin:/opt/nubis-builder/bin RUN mkdir /code ADD nubis-clone /usr/bin/nubis-clone RUN yum clean all RUN rm /root/anaconda-ks.cfg <file_sep>/docker/tools/rh-ruby22.sh #!/bin/bash source /opt/rh/rh-ruby22/enable export X_SCLS="`scl enable rh-ruby22 'echo $X_SCLS'`" export PATH=$PATH:/opt/rh/rh-ruby22/root/usr/local/bin <file_sep>/create-users #!/bin/bash # quick and dirty way to create a user account on bastion host and adds ssh keys # Add user we want to add here declare -a user_accounts=(elim jcrowe pchiasson) #declare -a no_sudo=(scabral mpressman dlawrence) # useful stuff jumphost=$1 basedir=$(dirname $0) # Do we care to generate keys from my script? gen_key=true if [[ -z "${jumphost}" ]]; then echo "Usage: $0 [jumphost hostname]" exit 1 fi # Check if user exists function __check_user { if [[ -z "$1" || -z "$2" ]]; then echo "Usage: ${FUNCNAME} [jumphost hostname] [username]"; return 1; fi local jumphost=$1 local username=$2 getent_data=$(ssh ec2-user@${jumphost} getent passwd ${username}) echo -n "Checking if ${username} exists on host ${jumphost} ... " if [[ -z ${getent_data} ]]; then echo "Nope" return 1 else echo "Yep" return 0 fi } function __add_to_sudo { if [[ -z "$1" || -z "$2" ]]; then echo "Usage: ${FUNCNAME} [jumphost hostname] [username]"; return 1; fi local jumphost=$1 local username=$2 ssh -t ec2-user@${jumphost} "sudo su - root -c 'echo \"${username} ALL=(ALL) NOPASSWD: ALL\" > /etc/sudoers.d/${username}'" > /dev/null 2>&1 ssh -t ec2-user@${jumphost} "sudo chown root:root /etc/sudoers.d/${username} && sudo chmod 0440 /etc/sudoers.d/${username}" > /dev/null 2>&1 } # do the deed: # 1. create user but checks if user exists first # 2. create .ssh folder and chowns it to the right owner # 3. Create sudoers file # 4. copies ssh key to server function do_stuff { if [[ -z "$1" || -z "$2" ]]; then echo "Usage: ${FUNCNAME} [jumphost hostname] [username]"; return 1; fi local jumphost=$1 local username=$2 __check_user "${jumphost}" "${username}" RV=$? if [[ ${RV} != 0 ]]; then echo -n "Doing stuff for ${username} on ${jumphost} ... " ssh -t ec2-user@${jumphost} "sudo adduser ${username}" > /dev/null 2>&1 ssh -t ec2-user@${jumphost} "sudo mkdir /home/${username}/.ssh && sudo chown -R ${username}:${username} /home/${username}/.ssh" > /dev/null 2>&1 ssh -t ec2-user@${jumphost} "sudo touch /home/${username}/.ssh/authorized_keys" > /dev/null 2>&1 echo "Done" # if no_sudo array is empty just add users to sudo otherwise do comparison if [[ -z "${no_sudo}" ]]; then __add_to_sudo "${jumphost}" "${username}" else for nolove in ${no_sudo[@]}; do if [[ "${nolove}" == "$username" ]]; then echo "User: ${username} gets no sudo love" else __add_to_sudo "${jumphost}" "${username}" fi done fi if $gen_key; then user_pub_key=$(mktemp ${username}.XXXXXXXX) trap "rm -f ${user_pub_key}" EXIT echo "Generating key with limed's awesome script" ${basedir}/keys.sh ${<EMAIL> > ${user_pub_key} #cat ${user_pub_key} | ssh -t -t ec2-user@${jumphost} "sudo su - root -c 'cat >> /home/${username}/.ssh/authorized_keys'" scp -pr ${user_pub_key} ec2-user@${jumphost}:/tmp/${username}.pub ssh -t ec2-user@${jumphost} "sudo mv /tmp/${username}.pub /home/${username}/.ssh/authorized_keys" > /dev/null 2>&1 rm -f ${user_pub_key} else echo "Nope, no love for limed" if [[ ! -d "${basedir}/ssh_keys" ]]; then echo "Directory where we store ssh keys ${basedir}/ssh_keys does not exist" else scp -pr ${basedir}/ssh_keys/${username}.pub ec2-user@${jumphost}:/tmp/${username}.pub ssh -t ec2-user@${jumphost} "sudo mv /tmp/${username}.pub /home/${username}/.ssh/authorized_keys" > /dev/null 2>&1 #cat ${basedir}/ssh_keys/${username}.pub | ssh -t -t ec2-user@${jumphost} "sudo su - root -c 'cat >> /home/${username}/.ssh/authorized_keys'" fi fi ssh -t ec2-user@${jumphost} "sudo chown ${username}:${username} /home/${username}/.ssh/authorized_keys && sudo chmod 0600 /home/${username}/.ssh/authorized_keys" > /dev/null 2>&1 return 0 else echo "I think user ${username} already exists so I'm not doing anything" return 1 fi } # create group for duo-users ssh -t ec2-user@${jumphost} "sudo groupadd duo-users" > /dev/null 2>&1 # The real deal boys and girls for user in ${user_accounts[@]}; do do_stuff "${jumphost}" "${user}" ssh -t ec2-user@${jumphost} "sudo usermod -a -G duo-users ${user}" > /dev/null 2>&1 done <file_sep>/get-profiles.py #!/usr/bin/env python import os import ConfigParser def get_profiles(): credentials = os.environ['HOME'] + '/.aws/credentials' config = ConfigParser.ConfigParser() config.read(credentials) for profile in config.sections(): print profile if __name__ == '__main__': get_profiles() <file_sep>/terraform_resource_table.sh #!/bin/bash FILE=$1 if [ ${#1} == 0 ]; then if [ -f 'nubis/terraform/main.tf' ]; then FILE='nubis/terraform/main.tf' else echo "ERROR: You must specify the location of your 'main.tf' file." echo "USAGE: $0 path/to/main.tf" exit 1 fi fi echo '|Resource Type|Resource Title|Code Location|' echo '|-------------|--------------|-------------|' COUNT=0 RESOURCE_COUNT=0 while read -r LINE; do case "$LINE" in resource* ) ((RESOURCE_COUNT++)) ((COUNT++)) RESOURCE_TYPE=$(echo $LINE | cut -d' ' -f 2 | cut -d'"' -f 2 | cut -d'"' -f 1) RESOURCE_NAME=$(echo $LINE | cut -d' ' -f 3 | cut -d'"' -f 2 | cut -d'"' -f 1) LINE_LINK="[$FILE#L$COUNT]($FILE#L$COUNT)" echo "|$RESOURCE_TYPE|$RESOURCE_NAME|$LINE_LINK|" ;; * ) ((COUNT++)) ;; esac done < "$FILE" #echo "Resource count: $RESOURCE_COUNT" # fin <file_sep>/aws_create_iam_user.py #!/usr/bin/python # Script to create user and generate access key # This script assumes a bunch of things and is by no way # perfect import boto.iam import boto.exception import os import sys import argparse home_path = os.getenv("HOME") cfg_files = [ home_path + "/.boto", home_path + "/.aws/credentials", "/etc/boto.cfg" ] for cfg in cfg_files: if os.path.isfile(cfg): try: # If the file exist we just assume it will load the config # doesn't do any sanity check to see if file is legit pass except: print ("Failed to load config, please configure boto") print ("More information on configuring boto here: http://boto.readthedocs.org/en/latest/getting_started.html") sys.exit(1) try: cfn = boto.connect_iam() except Exception, e: print e sys.exit(1) # Assume you have made a connection def is_user(aws_user): users = cfn.get_all_users('/')['list_users_response']['list_users_result']['users'] for user in users: if user['user_name'] == aws_user: return True return False def create_user(aws_user, group): try: response = cfn.create_user(aws_user) user = response.user #print user response = cfn.add_user_to_group(group, aws_user) except boto.exception.BotoClientError, e: print ("Error creating user %s: %s" % (aws_user, e)) sys.exit(1) def generate_keys(aws_user): try: response = cfn.create_access_key(aws_user) print ("Access key: %s" % response.access_key_id) print ("Secret key: %s" % response.secret_access_key) except boto.exceptionBotoClientError, e: print("Error generating keys for user %s: %s" % (aws_user,e)) sys.exit(1) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create an IAM user and generates access key") parser.add_argument('--region', '-r', help="Region to add user") parser.add_argument('--group', '-g', default='Admin', help="Group to add user to, defaults to admin") parser.add_argument('username', help="Username to add") args = parser.parse_args() username = args.username group = args.group if not is_user(username): print ("Creating IAM user: %s" % username) create_user(username, group) generate_keys(username) else: print ("IAM user %s already exist, not doing anything" % username) sys.exit(0) <file_sep>/deploy-jumphost #!/bin/bash # Mass deploy jumphosts environments=(admin stage prod) profile_name=$1 if [[ -z "${profile_name}" ]]; then echo "Usage: ${0} [aws credential profile name]" exit 1 fi for environment in ${environments[@]}; do for region in us-west-2 us-east-1; do echo "Creating jumphost-${environment} in ${region}" aws cloudformation create-stack --stack-name jumphost-${environment} \ --template-body file://nubis/cloudformation/main.json\ --parameters file://nubis/cloudformation/parameters.${environment}.${region}.json\ --region ${region} --profile ${profile_name} --capabilities CAPABILITY_IAM done done <file_sep>/account.sh #!/bin/bash # # Crappy script to create VPCs and such in an aws account # # To create a new domain in inventory # https://inventory.mozilla.org/en-US/mozdns/record/create/DOMAIN/ # Soa: SOA for allizom.org # Name: ACCOUNT_NAME.nubis.allizom.org # https://inventory.mozilla.org/en-US/mozdns/record/create/DOMAIN/ # Soa: SOA for allizom.org # Name: REGION.ACCOUNT_NAME.nubis.allizom.org # https://inventory.mozilla.org/en-US/mozdns/record/create/NS/ # Domain: REGION.ACCOUNT_NAME.nubis.allizom.org # Server: 1 of 4 AWS NameServers for the HostedZones # Views: # check private # check public # # https://app.datadoghq.com/account/settings#integrations/amazon_web_services # #PROFILE='mozilla-sandbox' #PROFILE='nubis-lab' #PROFILE='nubis-market' #PROFILE='plan-b-ldap-master' #PROFILE='plan-b-okta-ldap-gateway' #PROFILE='plan-b-bugzilla' #PROFILE='plan-b-akamai-edns-slave' #REGION='us-east-1' #REGION='us-west-2' NUBIS_PATH="/home/jason/projects/mozilla/projects/nubis" #declare -a PROFILES_ARRAY=( mozilla-sandbox nubis-lab nubis-market plan-b-ldap-master plan-b-okta-ldap-gateway plan-b-bugzilla plan-b-akamai-edns-slave ) declare -a PROFILES_ARRAY=( nubis-lab ) declare -a REGIONS_ARRAY=( us-east-1 us-west-2 ) declare -a ENVIRONMENTS_ARRAY=( admin stage prod ) create_stack () { # Detect if we are working in the sandbox and select the appropriate template if [ ${PROFILE} == 'mozilla-sandbox' ]; then VPC_TEMPLATE='vpc-sandbox.template' else VPC_TEMPLATE='vpc-account.template' fi STACK_NAME="${REGION}-vpc" aws cloudformation create-stack --template-body file://${NUBIS_PATH}/nubis-vpc/${VPC_TEMPLATE} --parameters file://${NUBIS_PATH}/nubis-vpc/parameters/parameters-${REGION}-${PROFILE}.json --capabilities CAPABILITY_IAM --profile ${PROFILE} --region ${REGION} --stack-name ${STACK_NAME} watch -n 1 "echo 'Container Stack'; aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --query 'Stacks[*].[StackName, StackStatus]' --output text --stack-name ${STACK_NAME}; echo \"\nStack Resources\"; aws cloudformation describe-stack-resources --region ${REGION} --profile ${PROFILE} --stack-name ${STACK_NAME} --query 'StackResources[*].[LogicalResourceId, ResourceStatus]' --output text" VPC_META_STACK=$(aws cloudformation describe-stack-resources --region ${REGION} --profile ${PROFILE} --stack-name ${STACK_NAME} --query 'StackResources[?LogicalResourceId==`VPCMetaStack`].PhysicalResourceId' --output text) echo -e "\nVPC Meta Stack Id:\n$VPC_META_STACK" LAMBDA_ROLL_ARN=$(aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --stack-name $VPC_META_STACK --query 'Stacks[*].Outputs[?OutputKey == `IamRollArn`].OutputValue' --output text) echo -e "\nLambda ARN:\n$LAMBDA_ROLL_ARN" ZONE_ID=$(aws cloudformation describe-stack-resources --region ${REGION} --profile ${PROFILE} --stack-name $VPC_META_STACK --query 'StackResources[?LogicalResourceId == `HostedZone`].PhysicalResourceId' --output text) echo -e "\nZone Id:\n$ZONE_ID" echo -e "\nUploading LookupStackOutputs Function" aws lambda upload-function --region ${REGION} --profile ${PROFILE} --function-name LookupStackOutputs --function-zip ${NUBIS_PATH}/nubis-stacks/lambda/LookupStackOutputs/LookupStackOutputs.zip --runtime nodejs --role ${LAMBDA_ROLL_ARN} --handler index.handler --mode event --timeout 10 --memory-size 128 --description 'Gather outputs from Cloudformation stacks to be used in other Cloudformation stacks' echo -e "\nUploading LookupNestedStackOutputs Function" aws lambda upload-function --region ${REGION} --profile ${PROFILE} --function-name LookupNestedStackOutputs --function-zip ${NUBIS_PATH}/nubis-stacks/lambda/LookupNestedStackOutputs/LookupNestedStackOutputs.zip --runtime nodejs --role ${LAMBDA_ROLL_ARN} --handler index.handler --mode event --timeout 10 --memory-size 128 --description 'Gather outputs from Cloudformation enviroment specific nested stacks to be used in other Cloudformation stacks' DATADOGACCESSKEY=$(aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --stack-name $VPC_META_STACK --query 'Stacks[*].Outputs[?OutputKey == `DatadogAccessKey`].OutputValue' --output text) DATADOGSECRETKEY=$(aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --stack-name $VPC_META_STACK --query 'Stacks[*].Outputs[?OutputKey == `DatadogSecretKey`].OutputValue' --output text) echo -e "\nDataDog Access Key: $DATADOGACCESSKEY\nDataDog SecretKey: $DATADOGSECRETKEY\n" aws route53 get-hosted-zone --region ${REGION} --profile ${PROFILE} --id $ZONE_ID --query DelegationSet.NameServers --output table } update_stack () { # Detect if we are working in the sandbox and select the appropriate template if [ ${PROFILE} == 'mozilla-sandbox' ]; then VPC_TEMPLATE='vpc-sandbox.template' else VPC_TEMPLATE='vpc-account.template' fi STACK_NAME="${REGION}-vpc" echo -n " Updating \"${STACK_NAME}\" in \"${PROFILE}\" " $(aws cloudformation update-stack --template-body file://${NUBIS_PATH}/nubis-vpc/${VPC_TEMPLATE} --parameters file://${NUBIS_PATH}/nubis-vpc/parameters/parameters-${REGION}-${PROFILE}.json --capabilities CAPABILITY_IAM --profile ${PROFILE} --region ${REGION} --stack-name ${STACK_NAME} 2>&1) 2> /dev/null # Pause to let the status update before we start to check sleep 5 # Wait here till the stack update is complete until [ ${STACK_STATE:-NULL} == 'CREATE_COMPLETE' ] || [ ${STACK_STATE:-NULL} == 'UPDATE_COMPLETE' ]; do echo -n '.' STACK_STATE=$(aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --query 'Stacks[*].[StackStatus]' --output text --stack-name ${STACK_NAME}) sleep 2 done echo -ne "\n" unset STACK_STATE } replace_jumphost () { STACK_NAME="jumphost-${ENVIRONMENT}" # Remove the known_hosts fingerprint for the jumphost JUMPHOST_NAME="jumphost.${ENVIRONMENT}.${REGION}.${PROFILE}.nubis.allizom.org" JUMPHOST_IP=$(dig +short ${JUMPHOST_NAME}) if [ $(dig +short ${JUMPHOST_NAME} | grep -c ^) != 0 ]; then if [ $(ssh-keygen -F ${JUMPHOST_IP} | grep -c ^) != 0 ]; then $(ssh-keygen -qR ${JUMPHOST_IP} 2>&1) 2> /dev/null fi fi if [ $(ssh-keygen -F ${JUMPHOST_NAME} | grep -c ^) != 0 ]; then $(ssh-keygen -qR ${JUMPHOST_NAME} 2>&1) 2> /dev/null fi echo -n " Deleting \"${STACK_NAME}\" from \"${REGION}\" in \"${PROFILE}\" " $(aws cloudformation delete-stack --profile ${PROFILE} --region ${REGION} --stack-name ${STACK_NAME} 2>&1) 2> /dev/null # Pause to let the status update before we start to check sleep 5 # Wait here till the stack delete is complete until [ ${RV:-NULL} == '255' ]; do echo -n '.' STACK_STATE=$(aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --query 'Stacks[*].[StackStatus]' --output text --stack-name ${STACK_NAME} 2>&1) 2> /dev/null RV=$? sleep 2 done echo -ne "\n" unset STACK_STATE RV echo -n " Creating \"${STACK_NAME}\" for \"${REGION}\" in \"${PROFILE}\" " $(aws cloudformation create-stack --template-body "file://${NUBIS_PATH}/nubis-jumphost/nubis/cloudformation/main.json" --parameters "file://${NUBIS_PATH}/nubis-jumphost/nubis/cloudformation/parameters-${REGION}-${ENVIRONMENT}.json" --capabilities CAPABILITY_IAM --profile ${PROFILE} --region ${REGION} --stack-name ${STACK_NAME} 2>&1) 2> /dev/null # Pause to let the status update before we start to check sleep 5 # Wait here till the stack delete is complete until [ ${STACK_STATE:-NULL} == 'CREATE_COMPLETE' ] || [ ${STACK_STATE:-NULL} == 'UPDATE_COMPLETE' ]; do echo -n '.' STACK_STATE=$(aws cloudformation describe-stacks --region ${REGION} --profile ${PROFILE} --query 'Stacks[*].[StackStatus]' --output text --stack-name ${STACK_NAME}) sleep 2 done echo -ne "\n" unset STACK_STATE echo " Uploading ssh keys to \"${JUMPHOST_NAME}\"" # Wait until we have dns resolution while [ ${COUNT:-0} == 0 ]; do COUNT=$(dig +short ${JUMPHOST_NAME} | grep -c ^) done # Wait until dns is updated with the new jumphost IP NEW_JUMPHOST_IP=$(dig +short ${JUMPHOST_NAME}) until [ ${NEW_JUMPHOST_IP:-NULL} != ${JUMPHOST_IP:-NULL} ]; do NEW_JUMPHOST_IP=$(dig +short ${JUMPHOST_NAME}) done JUMPHOST_IP=$(dig +short ${JUMPHOST_NAME}) # Add the new known_hosts fingerprints before we attempt the upload to avoid the 'yes' dialoge $(ssh-keyscan -H ${JUMPHOST_IP} >> ~/.ssh/known_hosts 2>&1) 2> /dev/null $(ssh-keyscan -H ${JUMPHOST_NAME} >> ~/.ssh/known_hosts 2>&1) 2> /dev/null cat ${NUBIS_PATH}/nubis-junkheap/authorized_keys_admins.pub | ssh -oStrictHostKeyChecking=no ec2-user@${JUMPHOST_NAME} 'cat >> .ssh/authorized_keys' # Detect if we are working in the sandbox and upload devs ssh keys as well if [ ${PROFILE} == 'mozilla-sandbox' ]; then cat ${NUBIS_PATH}/nubis-junkheap/authorized_keys_devs_sandbox.pub | ssh -oStrictHostKeyChecking=no ec2-user@${JUMPHOST_NAME} 'cat >> .ssh/authorized_keys' fi } update_all_accounts () { for PROFILE in ${PROFILES_ARRAY[*]}; do for REGION in ${REGIONS_ARRAY[*]}; do echo -e "\n ### Updating account \"${PROFILE}\" in \"${REGION}\" ###\n" update_stack # If we are working in the sandbox we have only one custom environment if [ ${PROFILE} == 'mozilla-sandbox' ]; then ENVIRONMENT='sandbox' replace_jumphost # The nubis-market account does not have jumphosts ATM elif [ ${PROFILE} == 'nubis-market' ]; then echo " Not replacing jumphosts in the \"${PROFILE}\" account." else for ENVIRONMENT in ${ENVIRONMENTS_ARRAY[*]}; do replace_jumphost done fi done done } # jd likes to have a testing function for, well for testing stuff. testing () { echo "Testing" } # Grab and setup called options while [ "$1" != "" ]; do case $1 in -v | --verbose ) # For this simple script this will basicaly set -x set -x ;; -p | --path ) # The path to where the nubis repositories are checked out NUBIS_PATH=$2 shift ;; -P | --profile ) # The profile to use to upload the files PROFILE=$2 shift ;; -r | --region ) # The region we are deploying to REGION=$2 shift ;; -h | -H | --help ) echo -en "$0\n\n" echo -en "Usage: $0 [options] command [file]\n\n" echo -en "Commands:\n" echo -en " create Create account resources\n" echo -en " At a minimum creates a VPC stack\n" echo -en " You must have a parameters file set up already\n" echo -en " update Update account resources\n" echo -en " create-dummies N Create dummy VPN Connections\n" echo -en " Pass the number of dummy connections to create\n" echo -en "Options:\n" echo -en " --help -h Print this help information and exit\n" echo -en " --path -p Specify a path where your nubis repositories are checked out\n" echo -en " Defaults to '$NUBIS_PATH'\n" echo -en " --profile -P Specify a profile to use when uploading the files\n" echo -en " Defaults to '${PROFILE}'\n" echo -en " --region -r Specify a region to deploy to\n" echo -en " Defaults to '${REGION}'\n" echo -en " --verbose -v Turn on verbosity, this should be set as the first argument\n" echo -en " Basically set -x\n\n" exit 0 ;; create ) create_stack GOT_COMMAND=1 ;; update ) update_stack GOT_COMMAND=1 ;; update-all ) update_all_accounts GOT_COMMAND=1 ;; create-dummies ) DUMMY_COUNT=$2 shift create_dummy_connections GOT_COMMAND=1 ;; testing ) testing GOT_COMMAND=1 ;; esac shift done # If we did not get a valid command print the help message if [ ${GOT_COMMAND:-0} == 0 ]; then $0 --help fi # fin <file_sep>/keys.sh #!/bin/bash # Search ldap for ssh keys and spits them out if [[ $# -lt 1 ]]; then echo "This script will query ldap for an ssh key" echo "Usage: $0 <ldap email>" exit 1 fi # Gets ldap password from gpg file function get_ldap_passwd() { gpg --use-agent --batch -q -d ~/.passwd/mozilla.gpg } [ ! -f variables ] && { echo "Variables file does not exist"; exit 1; } # config . variables bind_password="$(get_ldap_passwd)" [ -z "${ldap_server}" ] && { echo "LDAP server setting not set"; exit 1; } [ -z "${bind_dn}" ] && { echo "Bind DN setting not set"; exit 1; } [ -z "${bind_password}" ] && { echo "Bind password setting not set"; exit 1; } ldapsearch -LLL -x -D "${bind_dn}" -w "${bind_password}" -h ${ldap_server} -b ${search_base} -o ldif-wrap=no mail=${1} sshPublicKey | sed -n 's/^[ \t]*sshPublicKey:[ \t]*\(.*\)/\1/p' <file_sep>/get_account_id.py #!/usr/bin/env python # prints out aws account ID, thats about it import boto import argparse def get_options(): parser = argparse.ArgumentParser(description="Prints out account ID") parser.add_argument('--profile', '-p', default='default', help='Name of AWS profile, defaults to default') return parser.parse_args() def get_account_id(args): try: return boto.connect_iam(profile_name=args.profile).get_user().arn.split(':')[4] except: return False if __name__ == '__main__': args = get_options() print get_account_id(args) <file_sep>/duo/configure-duo #!/bin/bash # Configuring duo function configure_duo() { echo "Configuring pam for duo" for file in 01_configure_sshd.pp 02_configure_pam.pp; do wget -P /tmp https://raw.githubusercontent.com/nubisproject/nubis-junkheap/master/duo/${file} RV=$? if [ ${RV} -ne 0 ]; then echo "Could not download ${file}" exit 1 fi done if [ $? -ne 0 ]; then echo "Something happened, can't configure duo" exit 1 fi puppet apply /tmp/01_configure_sshd.pp puppet apply /tmp/02_configure_pam.pp } whoami=$(whoami) if [ "${whoami}" != root ]; then echo "Please run as root" exit 1 fi duo_package=$(/bin/rpm -qa | grep duo_unix | grep -v grep) if [ -z "${duo_package}" ]; then echo "Duo package not installed" exit 1 fi if [ ! -f "/etc/confd/conf.d/duo.toml" ]; then echo "confd duo.toml file doesn't exist" exit 1 fi if [ ! -f "/etc/confd/templates/duo.tmpl" ]; then echo "confd duo.tmpl doesn't exist" exit 1 fi echo "Stop! before you do anything else please make sure you have an existing non duo connection open to the server" sleep 3 echo -n "Ok, now do you have a connection open? [y/n]: " read answer if echo "$answer" | grep -iq "^y" ;then configure_duo else echo "Can't configure duo" exit 1 fi <file_sep>/docker/tools/nubis-clone #!/bin/bash repo=$1 shift git clone https://github.com/nubisproject/nubis-$repo.git /code/$repo <file_sep>/deploy-keys #!/bin/bash # Mass deploy ssh keys to jumphost, old school config management baby! # # NOTE: _MUST_ run script on the same directory as keys.sh [ ! -f variables ] && { echo "Variables file does not exist"; exit 1; } . variables # Helpful stuff basedir=$(dirname $0) admin_pubkey_file=$(mktemp) trap "rm -f ${admin_pubkey_file}" EXIT # Dump all ssh key file for i in ${admins[@]}; do ${basedir}/keys.sh ${i} >> ${admin_pubkey_file} done # This is some O(n^3) shit going on here for account in ${accounts[@]}; do for environment in ${environments[@]}; do for region in ${regions[@]}; do echo "Deploying ssh keys to jumphost.${environment}.${region}.${account}.nubis.allizom.org" cat ${admin_pubkey_file} | ssh -l ec2-user -i ${nubis_key_location} jumphost.${environment}.${region}.${account}.nubis.allizom.org 'cat >> .ssh/authorized_keys' done done done
3c5561e6a80f8d063d5ba3bc92ecb4140fbc1ac0
[ "Markdown", "Python", "Dockerfile", "Shell" ]
17
Python
tinnightcap/nubis-junkheap
7efe08a823142705c02bca5fead30d8ca21473c5
ba2ced78b5f29e04add97f2abbfe06f7b4bb194e
refs/heads/master
<repo_name>jjcollinge/AzureBot<file_sep>/AzureBot/Model/VirtualMachine.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AzureBot { public class VirtualMachine : Resource { public string Address { get; set; } public bool Start() { return true; } public bool Stop() { return true; } } }<file_sep>/AzureBot/Model/User.cs namespace AzureBot.Model { public class User { public User(string id) { Id = id; } public string Token { get; set; } public string Id { get; } public string Name { get; set; } } }<file_sep>/AzureBot/Services/Chat/IChatService.cs using AzureBot.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.Services.Interfaces { public interface IChatService { string PromptUserLogin(User user); string NoIdProvided(); string GreetUser(string username); string InvalidMessage(); string UnsupportedIntent(); string RenderResourceList(List<Resource> resources); string RenderSubscriptionList(IDictionary<string, string> subscriptions); } } <file_sep>/README.md # AzureBot AzureBot is a chat bot for your Azure account. The idea is that you will be able to control your Azure resources through a familiar channel such as Skype, Slack or Messenger. This will allow you to easily query the current state of your resources and then instruct Azure to perform certain tasks. The end goal is that this can become a natural interface to the cloud, allowing free speech and text input. # Notes Due to certain values being pulled from the enviroment, you must ensure they are set before running either the bot or the unit tests. <file_sep>/AzureBot/Services/Logging/StringLoggerService.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AzureBot.Services.Impl { public class StringLoggerService : ILoggerService { public int LogLevel { get; set; } = 1; private IStringLogger _logger; public StringLoggerService(IStringLogger logger) { _logger = logger; } //TODO: Add culture aware formatting private string CurrentTime { get { return DateTime.Now.ToString(); } } public void LogError(string logMessage) { if (LogLevel >= 3) _logger.LogString($"[{CurrentTime}] ERROR: {logMessage}"); } public void LogWarning(string logMessage) { if (LogLevel >= 2) _logger.LogString($"[{CurrentTime}] WARNING: {logMessage}"); } public void LogInfo(string logMessage) { if (LogLevel >= 1) _logger.LogString($"[{CurrentTime}] INFO: {logMessage}"); } public void LogVerbose(string logMessage) { if (LogLevel >= 0) _logger.LogString($"[{CurrentTime}] VERBOSE: {logMessage}"); } } }<file_sep>/AzureBot.UnitTests/Tests/ValidationTest.cs using AzureBot.Services.Impl; using AzureBot.Services.Interfaces; using AzureBot.UnitTests.Mocks; using Microsoft.Bot.Connector; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.UnitTests.Tests { [TestClass] public class ValidationTest { private IValidationService _validationService; private int MAX_MESSAGE_LENGTH = 500; private int MIN_MESSAGE_LENGTH = 1; public ValidationTest() { _validationService = new ValidationService(MIN_MESSAGE_LENGTH, MAX_MESSAGE_LENGTH); } [TestMethod] public async Task TestMaxiumumMessageLength() { var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName } }; for (int i = 0; i < MAX_MESSAGE_LENGTH + 1; i++) { message.Text += "a"; } var actualResponse = await _validationService.IsValidMessage(message); var expectedResponse = false; Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestMinimumMessageLength() { var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName }, Text = "" }; var actualResponse = await _validationService.IsValidMessage(message); var expectedResponse = false; Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestValidMessageLength() { var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName } }; // Assumes MAX_MESSAGE_LENGTH > MIN_MESSAGE_LENGTH + 1 for(int i = 0; i <= MIN_MESSAGE_LENGTH; i++) { message.Text += "a"; } var actualResponse = await _validationService.IsValidMessage(message); var expectedResponse = true; Assert.IsTrue(actualResponse == expectedResponse); } } } <file_sep>/AzureBot/Services/Logging/ILoggerService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.Services.Interfaces { public interface ILoggerService { void LogVerbose(string logMessage); void LogInfo(string logMessage); void LogWarning(string logMessage); void LogError(string logMessage); } } <file_sep>/AzureBot/Services/Azure/RESTAzureService.cs using AzureBot.Controllers; using AzureBot.Services.Interfaces; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Security; using System.Security.Claims; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AzureBot.Services.Impl { public class RESTAzureService : IAzureService { private string _apiVersion; public string CurrentSubscriptionId { get; set; } public RESTAzureService(string apiVersion) { _apiVersion = apiVersion; } public async Task<IDictionary<string, string>> GetSubscriptions(string token) { Dictionary<string, string> subscriptions = new Dictionary<string, string>(); using (var http = new HttpClient()) { var uri = $"https://management.azure.com/subscriptions?&api-version={_apiVersion}"; http.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); var res = await http.GetAsync(uri); res.EnsureSuccessStatusCode(); var strRes = await res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject<dynamic>(strRes); foreach (var element in data.value) { // Convert from dynamic to strongly typed string name = element.displayName; string subId = element.subscriptionId; subscriptions.Add(name, subId); } } if (CurrentSubscriptionId == null) { CurrentSubscriptionId = subscriptions.First().Value; } return subscriptions; } public async Task<List<Resource>> GetResources(string token) { var uriExtension = "resources"; var resources = await GetResources(uriExtension, token); return resources; } public async Task<List<Resource>> GetResourceGroups(string token) { var uriExtension = "resourcegroups"; var resourceGroups = await GetResources(uriExtension, token); return resourceGroups; } private async Task<List<Resource>> GetResources(string uriExtension, string token) { if (CurrentSubscriptionId == null) { await GetSubscriptions(token); } var uri = $"https://management.azure.com/subscriptions/{CurrentSubscriptionId}/{uriExtension}?&api-version={_apiVersion}"; List<Resource> resources = new List<Resource>(); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); var res = await http.GetAsync(uri); res.EnsureSuccessStatusCode(); var strRes = await res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject<dynamic>(strRes); foreach (var element in data.value) { // Convert from dynamic to strongly typed Resource resource = new Resource(); resource.Id = element.id; resource.Name = element.name; resource.Type = element.type; resource.Location = element.location; resource.SubscriptionId = CurrentSubscriptionId; resources.Add(resource); } } return resources; } } }<file_sep>/AzureBot/Services/Chat/EnglishChatService.cs using AzureBot.Model; using AzureBot.Services.Impl; using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web; namespace AzureBot.Services.Impl { public class EnglishChatService : IChatService { private CultureInfo _culture; public EnglishChatService(string cultureName) { _culture = new CultureInfo(cultureName); } public string PromptUserLogin(User user) { var loginUri = new Uri($"http://localhost:3978/api/auth/home?UserId={user.Id}"); var greeting = GreetUser(user.Name); greeting = greeting.TrimEnd('.'); // Trim the trailing period return String.Format(_culture, "{0}, Please login to your Azure account at {1}.", greeting, loginUri.ToString()); } public string NoIdProvided() { return String.Format(_culture, "Sorry, you haven't provided an ID. Please restart the conversation."); } public string GreetUser(string username) { return String.Format(_culture, "Hello {0}.", username); } public string InvalidMessage() { return String.Format(_culture, "Sorry, your message doesn't make sense."); } public string UnsupportedIntent() { return String.Format(_culture, "Sorry, I don't understand your message."); } public string RenderResourceList(List<Resource> resources) { StringBuilder response = new StringBuilder(); foreach (var res in resources) { response.AppendLine($"**Name:** {res.Name}"); response.AppendLine(" "); response.AppendLine($"**ResourceId:** {res.Id}"); response.AppendLine(" "); response.AppendLine($"**ResourceType:** {res.Type}"); response.AppendLine(" "); response.AppendLine($"**Location:** {res.Location}"); response.AppendLine(" "); response.AppendLine($"**SubscriptionId:** {res.SubscriptionId}"); response.AppendLine(" "); response.AppendLine("-_-_-_-_-_"); response.AppendLine(" "); } return response.ToString(); } public string RenderSubscriptionList(IDictionary<string, string> subscriptions) { StringBuilder response = new StringBuilder(); foreach (var sub in subscriptions) { response.AppendLine($"**{sub.Key}:** + {sub.Value}"); response.AppendLine(" "); } return response.ToString(); } } }<file_sep>/AzureBot/Services/Logging/IStringLogger.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.Services.Interfaces { public interface IStringLogger { void LogString(string stringLogMessage); } } <file_sep>/AzureBot.UnitTests/Mocks/MockAuthenticationService.cs using AzureBot.Services; using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.UnitTests.Mocks { class MockAuthenticationService : IAuthenticationService { public Uri GetAuthenticationUri(string userId) { return null; } public Task<string> GetToken(object[] args) { return null; } } } <file_sep>/AzureBot.UnitTests/Tests/AuthenticationTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AzureBot.Controllers; using System.Net; using AzureBot.Services; using AzureBot.UnitTests.Mocks; using System.Web.Http.Hosting; using System.Net.Http; using System.Web.Http; using System.Threading.Tasks; using System.IO.Compression; using System.IO; namespace AzureBot.UnitTests { [TestClass] public class AuthenticationTest { [TestMethod] public void TestAuthenticationURIGeneration() { //TODO... } } } <file_sep>/AzureBot/Services/Authentication/OAuthAuthenticationService.cs using AzureBot.Model; using AzureBot.Services.Interfaces; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; namespace AzureBot.Services.Impl { public class OAuthAuthenticationService : IAuthenticationService { private string _clientId; private string _clientSecret; private string _tenantId; private string _redirectUri; public OAuthAuthenticationService() { // Environment vars _clientId = Environment.GetEnvironmentVariable("ARM_API_CLIENTID"); _clientSecret = Environment.GetEnvironmentVariable("ARM_API_CLIENTSECRET"); // App settings _tenantId = ConfigurationManager.AppSettings["TenantId"]; var baseUri = ConfigurationManager.AppSettings["RedirectBaseUri"]; _redirectUri = baseUri + "/api/auth/receivetoken"; } public async Task<string> GetToken(object[] args) { string authenticationCode = (string)args[0]; string userId = (string)args[1]; string token = string.Empty; if (!string.IsNullOrEmpty(authenticationCode) && !string.IsNullOrEmpty(userId)) { var tokenUri = BuildOAuthTokenRequestUri(authenticationCode); string result = null; using (var http = new HttpClient()) { var c = tokenUri.Query.Remove(0, 1); var content = new StringContent(c); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var resp = await http.PostAsync(new Uri($"https://login.microsoftonline.com/{_tenantId}/oauth2/token"), content); result = await resp.Content.ReadAsStringAsync(); } dynamic res = JsonConvert.DeserializeObject<dynamic>(result); token = res.access_token.ToString(); } return token; } public Uri GetAuthenticationUri(string userId) { return BuildOAuthCodeRequestUri(userId); } private Uri BuildOAuthCodeRequestUri(string userId) { UriBuilder uriBuilder = new UriBuilder($"https://login.microsoftonline.com/{_tenantId}/oauth2/authorize"); var query = new StringBuilder(); query.AppendFormat("redirect_uri={0}", Uri.EscapeUriString(_redirectUri)); query.AppendFormat("&client_id={0}", Uri.EscapeUriString(_clientId)); query.AppendFormat("&client_secret={0}", Uri.EscapeUriString(_clientSecret)); query.Append("&response_type=code"); if (!string.IsNullOrEmpty(userId)) query.Append($"&state={userId}"); uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } private Uri BuildOAuthTokenRequestUri(string code, string refreshToken = "") { UriBuilder uriBuilder = new UriBuilder($"https://login.microsoftonline.com/{_tenantId}/oauth2/token"); var query = new StringBuilder(); query.AppendFormat("redirect_uri={0}", Uri.EscapeUriString(_redirectUri)); query.AppendFormat("&client_id={0}", Uri.EscapeUriString(_clientId)); query.AppendFormat("&client_secret={0}", Uri.EscapeUriString(_clientSecret)); string grant = "authorization_code"; if (!string.IsNullOrEmpty(refreshToken)) { grant = "refresh_token"; query.AppendFormat("&refresh_token={0}", Uri.EscapeUriString(refreshToken)); } else { query.AppendFormat("&code={0}", Uri.EscapeUriString(code)); } query.AppendFormat("&grant_type={0}", grant); query.AppendFormat("&resource={0}", "https://management.azure.com/"); uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } } } <file_sep>/AzureBot.UnitTests/Tests/MessageControllerTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AzureBot.Controllers; using AzureBot.UnitTests.Mocks; using Microsoft.Bot.Connector; using AzureBot.Services.Impl; using System.Collections.Generic; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace AzureBot.UnitTests.Tests { [TestClass] public class MessagesControllerTest { private MockAzureService _azureService; private MockIntentService _intentService; private MockValidationService _validationService; private MockLogger _logger; public MessagesControllerTest() { _intentService = new MockIntentService(); _azureService = new MockAzureService(); _validationService = new MockValidationService(); _logger = new MockLogger(); InitialiseTestData(_azureService); } [TestMethod] public async Task TestMessageWithNoUserId() { var userRepo = new UserRepository(); var controller = new MessagesController(userRepo, _azureService, _intentService, _validationService, _logger); var message = new Message() { Type = "Message", Language = "en" }; var chatService = new EnglishChatService("en-GB"); var responseMessage = await controller.Post(message); var expectedResponse = EscapeString(chatService.NoIdProvided()); var actualResponse = EscapeString(responseMessage.Text); Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestNotloggedInMessage() { var userRepo = new UserRepository(); var azureService = new MockAzureService(); var controller = new MessagesController(userRepo, _azureService, _intentService, _validationService, _logger); var testUserName = "TestUser"; var testUserId = "0"; var message = new Message() { Type = "Message", Language = "en", From = new ChannelAccount { Id = testUserId, Name = testUserName } }; var chatService = new EnglishChatService("en-GB"); var responseMessage = await controller.Post(message); var user = new Model.User("0"); user.Name = testUserName; var expectedResponse = EscapeString(chatService.PromptUserLogin(user)); var actualResponse = EscapeString(responseMessage.Text); Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestNonSupportedMessageIntent() { var username = "TestUser"; var userId = "0"; var user = new Model.User("0"); user.Name = username; user.Token = "<PASSWORD>"; var userRepo = new UserRepository(); userRepo.Add(user); var controller = new MessagesController(userRepo, _azureService, _intentService, _validationService, _logger); var message = new Message() { Type = "Message", Language = "en", Text = "This is an unsupported message intent", From = new ChannelAccount { Id = userId, Name = username } }; var chatService = new EnglishChatService("en-GB"); var responseMessage = await controller.Post(message); var expectedResponse = EscapeString(chatService.UnsupportedIntent()); var actualResponse = EscapeString(responseMessage.Text); Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestMessageIntentGetSubscription() { var username = "TestUser"; var userId = "0"; var user = new Model.User("0"); user.Name = username; user.Token = "<PASSWORD>"; var userRepo = new UserRepository(); userRepo.Add(user); var controller = new MessagesController(userRepo, _azureService, _intentService, _validationService, _logger); var message = new Message() { Type = "Message", Language = "en", Text = "subscriptions", From = new ChannelAccount { Id = userId, Name = username } }; var chatService = new EnglishChatService("en-GB"); var responseMessage = await controller.Post(message); //TODO: This should test against the static data and not rely on these message calls. var expectedResponse = EscapeString(chatService.RenderSubscriptionList(await _azureService.GetSubscriptions(""))); var actualResponse = EscapeString(responseMessage.Text); Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestMessageIntentGetResources() { var username = "TestUser"; var userId = "0"; var user = new Model.User("0"); user.Name = username; user.Token = "<PASSWORD>"; var userRepo = new UserRepository(); userRepo.Add(user); var controller = new MessagesController(userRepo, _azureService, _intentService, _validationService, _logger); var message = new Message() { Type = "Message", Language = "en", Text = "resources", From = new ChannelAccount { Id = userId, Name = username } }; var chatService = new EnglishChatService("en-GB"); var responseMessage = await controller.Post(message); //TODO: This should test against the static data and not rely on these message calls. var expectedResponse = EscapeString(chatService.RenderResourceList(await _azureService.GetResources(""))); var actualResponse = EscapeString(responseMessage.Text); Assert.IsTrue(actualResponse == expectedResponse); } [TestMethod] public async Task TestMessageIntentGetResourceGroups() { var username = "TestUser"; var userId = "0"; var user = new Model.User("0"); user.Name = username; user.Token = "<PASSWORD>"; var userRepo = new UserRepository(); userRepo.Add(user); var controller = new MessagesController(userRepo, _azureService, _intentService, _validationService, _logger); var message = new Message() { Type = "Message", Language = "en", Text = "resource_groups", From = new ChannelAccount { Id = userId, Name = username } }; var chatService = new EnglishChatService("en-GB"); var responseMessage = await controller.Post(message); //TODO: This should test against the static data and not rely on these message calls. var expectedResponse = EscapeString(chatService.RenderResourceList(await _azureService.GetResourceGroups(""))); var actualResponse = EscapeString(responseMessage.Text); Assert.IsTrue(actualResponse == expectedResponse); } private static void InitialiseTestData(MockAzureService azureService) { var resGroup = InitialiseResourceGroups(); var res = InitialiseResources(); var subs = InitialiseSubscriptions(); azureService.LoadTestData(resGroup, res, subs); } private static Dictionary<string, string> InitialiseSubscriptions() { var subscriptions = new Dictionary<string, string>(); for (int i = 0; i < 3; i++) { subscriptions.Add($"MySubName{i}", $"MySubId{i}"); } return subscriptions; } private static List<Resource> InitialiseResources() { var resources = new List<Resource>(); for (int i = 0; i < 10; i++) { resources.Add(new Resource() { Id = i.ToString(), Name = $"Resource{i}", Location = "West Europe", GroupName = $"MyResourceGroup{i}", Type = "Resource Group", SubscriptionId = "1" }); } return resources; } private static List<Resource> InitialiseResourceGroups() { var resourceGroups = new List<Resource>(); for (int i = 0; i < 10; i++) { resourceGroups.Add(new Resource() { Id = i.ToString(), Name = $"Resource{i}", Location = "West Europe", GroupName = $"MyResourceGroup{i}", Type = "Resource Group", SubscriptionId = "1" }); } return resourceGroups; } private static string EscapeString(string inputText) { return Regex.Replace(inputText, @"\r\n?|\n", ""); } } } <file_sep>/AzureBot/App_Start/WebApiConfig.cs using AzureBot.Controllers; using AzureBot.Model; using AzureBot.Repos; using AzureBot.Services; using AzureBot.Services.Impl; using AzureBot.Services.Interfaces; using AzureBot.Services.Logging; using Microsoft.Practices.Unity; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web.Http; namespace AzureBot { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Json settings config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Newtonsoft.Json.Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, }; // Environment variables // TODO: Read logging folder location from env val // App settings var apiVersion = ConfigurationManager.AppSettings["AzureAPIVersion"]; // Web API configuration and services var container = new UnityContainer(); container.RegisterInstance<IUserRepository>(new UserRepository()); container.RegisterType<IAuthenticationService, OAuthAuthenticationService>(); container.RegisterType<IAzureService, RESTAzureService>(new InjectionConstructor(apiVersion)); container.RegisterType<IIntentService, LUISIntentService>(); container.RegisterType<IValidationService, ValidationService>(new InjectionConstructor(1, 500)); container.RegisterType<IStringLogger, FileLogger>(new InjectionConstructor("\\src\\temp\\test.log")); container.RegisterType<ILoggerService, StringLoggerService>(); config.DependencyResolver = new UnityResolver(container); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } } <file_sep>/AzureBot/Services/Logging/DebugLogger.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Web; namespace AzureBot.Services.Impl { public class DebugLogger : IStringLogger { public void LogString(string stringLogMessage) { Debug.WriteLine(stringLogMessage); } } }<file_sep>/AzureBot/Services/Validation/ValidationService.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Bot.Connector; using System.Threading.Tasks; namespace AzureBot.Services.Impl { public class ValidationService : IValidationService { private int MIN_MESSAGE_LENGTH; private int MAX_MESSAGE_LENGTH; public ValidationService() { MIN_MESSAGE_LENGTH = 1; MAX_MESSAGE_LENGTH = 500; } public ValidationService(int minMessageTextSize, int maxMessageTextSize) { MIN_MESSAGE_LENGTH = minMessageTextSize; MAX_MESSAGE_LENGTH = maxMessageTextSize; } public Task<bool> IsValidMessage(Message message) { var messageText = message.Text; var isValid = true; if(messageText.Length >= MAX_MESSAGE_LENGTH) { isValid = false; } if (messageText.Length < MIN_MESSAGE_LENGTH) { isValid = false; } return Task.FromResult(isValid); } } }<file_sep>/AzureBot/Services/Logging/ConsoleLogger.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AzureBot.Services.Impl { public class ConsoleLogger : IStringLogger { public void LogString(string stringLogMessage) { Console.WriteLine(stringLogMessage); } } }<file_sep>/AzureBot/Repositories/IUserRepository.cs using AzureBot.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.Repos { public interface IUserRepository { void Add(User user); User GetById(string id); IEnumerable<User> GetAll(); bool Remove(string id); void Clear(); } } <file_sep>/AzureBot/Factories/IChatServiceFactory.cs using AzureBot.Services.Impl; using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AzureBot.Services { public class IChatServiceFactory { public static IChatService Create(string language) { switch (language) { case "en": return new EnglishChatService("en-GB"); default: return new EnglishChatService("en-GB"); } } } }<file_sep>/AzureBot.UnitTests/Tests/UserRepositoryTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AzureBot.Repos; using AzureBot.Model; using System.Collections.Generic; namespace AzureBot.UnitTests.Tests { [TestClass] public class UserRepositoryTest { [TestMethod] public void TestClearingAllUsers() { IUserRepository users = new UserRepository(); for (int i = 0; i < 10; i++) { User newUser = new User(i.ToString()); users.Add(newUser); } users.Clear(); var userList = new List<User>(users.GetAll()); Assert.AreEqual(0, userList.Count); } [TestMethod] public void TestAddingNewUser() { IUserRepository users = new UserRepository(); User newUser = new User("0"); users.Add(newUser); Assert.IsNotNull(users.GetById(newUser.Id)); } [TestMethod] public void TestRemovingExistingUser() { IUserRepository users = new UserRepository(); User newUser = new User("0"); users.Add(newUser); users.Remove(newUser.Id); Assert.IsNull(users.GetById(newUser.Id)); } } } <file_sep>/AzureBot/Controllers/MessagesController.cs using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using Microsoft.Bot.Connector; using Microsoft.Bot.Connector.Utilities; using Newtonsoft.Json; using System.Text; using System.Security; using AzureBot.Model; using AzureBot.Services; using System.Globalization; using AzureBot.Services.Interfaces; using AzureBot.Repos; namespace AzureBot.Controllers { [BotAuthentication] public class MessagesController : ApiController { //TODO: Add user resource caching private IAzureService _azure; private IUserRepository _users; private IIntentService _intentService; private IValidationService _validationService; private ILoggerService _logger; public MessagesController(IUserRepository users, IAzureService azureService, IIntentService intentService, IValidationService validationService, ILoggerService logger) { _users = users; _azure = azureService; _intentService = intentService; _validationService = validationService; _logger = logger; } /// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task<Message> Post([FromBody]Message message) { _logger.LogVerbose("New message received."); // Initialise a chat service to match the input language var chat = IChatServiceFactory.Create(message.Language); if (message.Type == "Message") { var id = message?.From?.Id; _logger.LogInfo($"New message Id: {id}"); // Check message has sender Id if (string.IsNullOrEmpty(id)) return message.CreateReplyMessage(chat.NoIdProvided()); // Get or create user User user = GetOrCreateUser(id); // If user info isn't initialised, do it now if (string.IsNullOrEmpty(user.Name)) user.Name = message.From.Name; // Return the response return message.CreateReplyMessage(await HandleUserMessage(chat, message, user)); } else { return HandleSystemMessage(message); } } private async Task<string> HandleUserMessage(IChatService chat, Message message, User user) { StringBuilder response = new StringBuilder(); // Check if user has logged into Azure if (String.IsNullOrEmpty(user.Token)) { response.AppendLine(chat.PromptUserLogin(user)); _logger.LogInfo($"User with id [{user.Id}] is not logged in"); } else { // User is logged in... // Check message is valid if (!(await _validationService.IsValidMessage(message))) { response.AppendLine(chat.InvalidMessage()); _logger.LogInfo($"User with id [{user.Id}] sent an invalid message"); } else { // Implement all other chat logic here... string inputText = Uri.EscapeDataString(message.Text); string intent = await _intentService.GetIntentAsync(inputText); switch (intent) { case "GetSubscriptions": response.Append(chat.RenderSubscriptionList(await _azure.GetSubscriptions(user.Token))); _logger.LogInfo($"User with id [{user.Id}] requested their subscriptions"); break; case "GetResources": response.Append(chat.RenderResourceList(await _azure.GetResources(user.Token))); _logger.LogInfo($"User with id [{user.Id}] requested their resources"); break; case "GetResourceGroups": response.Append(chat.RenderResourceList(await _azure.GetResourceGroups(user.Token))); _logger.LogInfo($"User with id [{user.Id}] requested their resource groups"); break; default: response.AppendLine(chat.UnsupportedIntent()); _logger.LogInfo($"User with id [{user.Id}] requested an unsupported intent"); break; } } } return response.ToString(); } private User GetOrCreateUser(string id) { User user = _users.GetById(id); // If the user doesn't exist if (user == null) { // Create new users user = new Model.User(id); _users.Add(user); _logger.LogInfo($"Created new user"); } else { _logger.LogInfo($"Existing user {user.Name}"); } return user; } private Message HandleSystemMessage(Message message) { if (message.Type == "Ping") { Message reply = message.CreateReplyMessage(); reply.Type = "Ping"; return reply; } else if (message.Type == "DeleteUserData") { // Implement user deletion here // If we handle user deletion, return a real message _logger.LogVerbose($"Delete user data request"); } else if (message.Type == "BotAddedToConversation") { _logger.LogVerbose($"Bot added to conversation"); } else if (message.Type == "BotRemovedFromConversation") { _logger.LogVerbose($"Bot removed from conversation"); } else if (message.Type == "UserAddedToConversation") { _logger.LogVerbose($"User added to conversation"); } else if (message.Type == "UserRemovedFromConversation") { _logger.LogVerbose($"User removed from conversation"); } else if (message.Type == "EndOfConversation") { _logger.LogVerbose($"Conversation has ended"); } return null; } } }<file_sep>/AzureBot/Model/Resource.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AzureBot { public class Resource { public Resource() { Tags = new List<string>(); } public string Name { get; set; } public string Id { get; set; } public string Type { get; set; } public string GroupName { get; set; } public string Location { get; set; } public string SubscriptionId { get; set; } public List<string> Tags { get; set; } } }<file_sep>/AzureBot/Repositories/UserRepository.cs using AzureBot.Model; using AzureBot.Repos; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; namespace AzureBot { public class UserRepository : IUserRepository { IDictionary<string, User> _users; public UserRepository() { _users = new Dictionary<string, User>(); } public void Add(User user) { _users.Add(user.Id, user); } public void Clear() { _users.Clear(); } public IEnumerable<User> GetAll() { return _users.Cast<User>().ToList(); } public User GetById(string id) { User user = null; if(_users.ContainsKey(id)) user = _users[id]; return user; } public bool Remove(string id) { return _users.Remove(id); } } }<file_sep>/AzureBot.UnitTests/Mocks/MockAzureService.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.UnitTests.Mocks { class MockAzureService : IAzureService { private List<Resource> _resourceGroups; private List<Resource> _resources; private IDictionary<string, string> _subscriptions; public void LoadTestData(List<Resource> resourceGroups, List<Resource> resources, IDictionary<string, string> subscriptions) { _resourceGroups = resourceGroups; _resources = resources; _subscriptions = subscriptions; } public Task<List<Resource>> GetResourceGroups(string token) { return Task.FromResult(_resourceGroups); } public Task<List<Resource>> GetResources(string token) { return Task.FromResult(_resources); } public Task<IDictionary<string, string>> GetSubscriptions(string token) { return Task.FromResult(_subscriptions); } } } <file_sep>/AzureBot/Services/Authentication/IAuthenticationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace AzureBot.Services.Interfaces { public interface IAuthenticationService { Task<string> GetToken(object[] args); Uri GetAuthenticationUri(string userId); } }<file_sep>/AzureBot.UnitTests/Mocks/MockUserRepository.cs using AzureBot.Repos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AzureBot.Model; namespace AzureBot.UnitTests.Mocks { class MockUserRepository : IUserRepository { public void Add(User user) { } public void Clear() { } public IEnumerable<User> GetAll() { return null; } public User GetById(string id) { return null; } public bool Remove(string id) { return true; } } } <file_sep>/AzureBot/Services/Logging/FileLogger.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; namespace AzureBot.Services.Logging { public class FileLogger : IStringLogger { private string _logFilePath; public FileLogger(string filePath) { _logFilePath = filePath; } public void LogString(string stringLogMessage) { if (File.Exists(_logFilePath)) { stringLogMessage += Environment.NewLine; File.AppendAllText(_logFilePath, stringLogMessage); } else { using (FileStream fs = File.Create(_logFilePath)) { stringLogMessage += Environment.NewLine; Byte[] log = new UTF8Encoding(true).GetBytes(stringLogMessage); fs.Write(log, 0, log.Length); } } } } }<file_sep>/AzureBot/Services/Azure/IAzureService.cs using System.Collections.Generic; using System.Threading.Tasks; namespace AzureBot.Services.Interfaces { public interface IAzureService { Task<IDictionary<string, string>> GetSubscriptions(string token); Task<List<Resource>> GetResources(string token); Task<List<Resource>> GetResourceGroups(string token); } }<file_sep>/AzureBot.UnitTests/Mocks/MockLogger.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.UnitTests.Mocks { class MockLogger : ILoggerService { public void LogError(string logMessage) { } public void LogInfo(string logMessage) { } public void LogVerbose(string logMessage) { } public void LogWarning(string logMessage) { } } } <file_sep>/AzureBot/Controllers/AuthController.cs using AzureBot.Model; using AzureBot.Repos; using AzureBot.Services; using AzureBot.Services.Interfaces; using Newtonsoft.Json; using System; using System.Configuration; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace AzureBot.Controllers { public class AuthController : ApiController { private IAuthenticationService _authService; private IUserRepository _users; public AuthController(IUserRepository users, IAuthenticationService authService) { _authService = authService; _users = users; } [Route("api/auth/home")] [HttpGet] public HttpResponseMessage Home(string UserId) { var response = Request.CreateResponse(HttpStatusCode.Found); response.Headers.Location = _authService.GetAuthenticationUri(UserId); return response; } [Route("api/auth/receivetoken")] [HttpGet()] public async Task<string> ReceiveToken(string code = null, string state = null) { // Get the token from the authentication service var token = await _authService.GetToken(new object[] {code, state}); // Attempt to retrieve an existing user var user = _users.GetById(state); // Create user if one doesn't exist if (user == null) { user = new Model.User(state); _users.Add(user); } // Assign token user.Token = token; return String.IsNullOrEmpty(token) ? "Failed" : "Success"; } } }<file_sep>/AzureBot.UnitTests/Mocks/MockValidationService.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Bot.Connector; namespace AzureBot.UnitTests.Mocks { class MockValidationService : IValidationService { public Task<bool> IsValidMessage(Message message) { return Task.FromResult(true); } } } <file_sep>/AzureBot/Services/Intent/LUISIntentService.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading.Tasks; using Newtonsoft.Json; using System.Net.Http; using AzureBot.Model; namespace AzureBot.Services.Impl { public class LUISIntentService : IIntentService { public async Task<string> GetIntentAsync(string inputText) { // Get the most confident intent var intent = await GetIntent(inputText); return intent.intent; } private async Task<IntentRoot> GetIntent(string inputText) { IntentRoot intent = new IntentRoot(); using (var http = new HttpClient()) { string key = Environment.GetEnvironmentVariable("AZUREBOT_LUIS_API_KEY"); string id = Environment.GetEnvironmentVariable("AZUREBOT_LUIS_API_ID"); string uri = $"https://api.projectoxford.ai/luis/v1/application?id={id}&subscription-key={key}&q={inputText}"; var res = await http.GetAsync(uri); res.EnsureSuccessStatusCode(); var strRes = await res.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject<dynamic>(strRes); // Get top intent intent.intent = data.intents[0].intent; intent.score = data.intents[0].score; intent.actions = data.intents[0].actions; } return intent; } } }<file_sep>/AzureBot.UnitTests/Mocks/MockIntentService.cs using AzureBot.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.UnitTests.Mocks { class MockIntentService : IIntentService { public Task<string> GetIntentAsync(string inputText) { switch(inputText) { case "subscriptions": return Task.FromResult("GetSubscriptions"); case "resources": return Task.FromResult("GetResources"); case "resource_groups": return Task.FromResult("GetResourceGroups"); default: return Task.FromResult("Unsupported intent"); } } } } <file_sep>/AzureBot/Services/Validation/IValidationService.cs using Microsoft.Bot.Connector; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AzureBot.Services.Interfaces { public interface IValidationService { Task<bool> IsValidMessage(Message message); } } <file_sep>/AzureBot/Services/Intent/IIntentService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; namespace AzureBot.Services.Interfaces { public interface IIntentService { Task<string> GetIntentAsync(string inputText); } }
ea57cf70006c33b96a681eaae28db8b831b374e4
[ "Markdown", "C#" ]
36
C#
jjcollinge/AzureBot
4cdf799003c908312141d0225ac0abfd04ce261a
84cdee68fa5ac4b8edd1272703b9d7d78cf5d339
refs/heads/main
<repo_name>szabodev/JS-Halado1<file_sep>/JS/main.js function multiplier(arr) { let sum = 0; for (let i = 0; i<arr.length; i++) { let num = arr[i]; num *= 1.27; // arr[i] = num; sum += num; } return sum; } const numArr = [1, 1, 10]; // Task 1.: // console.log(multiplier(numArr)); // Task 2.: let result = { exists: false, index: -1, allElementIsANumber: true, someElementIsANumber: false } function checkArray(arr, primitive) { // let typeOfPrimitive = typeof(primitive); for(let i = 0; i < arr.length; i++) { if(arr[i] === primitive) { result.exists = true; result.index = i; } if(typeof(arr[i]) === 'number') { result.someElementIsANumber = true; } else { result.allElementIsANumber = false; } } return result; } // let miscArr = [true, 'af', 23, false]; // const miscArr = [33, 44, false, 88]; // console.log(checkArray(miscArr, 23)); // Task 3. function generateHtml(content) { result = '<ul>'; for(let i = 0; i < content.length; i++) { result += '<li>' + content[i] + '</li>'; } result+='</ul>'; return result; } const content = ['első', 'második', 'harmadik']; console.log(generateHtml(content)); window.document.body.innerHTML = (generateHtml(content));
4bc5a0b5c4f6983a27f42e42418b8552e8f82c7d
[ "JavaScript" ]
1
JavaScript
szabodev/JS-Halado1
e9b12560c7171c7fc393a5b78a5192a3d58569a3
a9a18dfd22e60b5e70d074f4bdf2ebe08d092694
refs/heads/master
<file_sep>// // MarkItemViewModelTests.swift // dooit // // Created by <NAME> on 08/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest @testable import dooit class MarkItemViewModelTests: XCTestCase { var viewModel: MarkItemViewModel? var delegate: MarkItemViewModelDelegateDouble? var list: List? override func setUp() { super.setUp() delegate = MarkItemViewModelDelegateDouble() viewModel = MarkItemViewModel(delegate: delegate!, managedObjectContext: InMemoryCoreDataStack.sharedInstance.managedObjectContext) list = CoreDataHelpers.createListWithTitle("Build a boat 🚣") } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testItemChangedToMarkedStatusTrue() { let item = CoreDataHelpers.createItemForList(list!, withTitle: "Make a sandwich", andMarked: false) viewModel!.changeMarkedStatusForItem(item) let items = CoreDataHelpers.retrieveAllItemsForList(list!) XCTAssertTrue(delegate!.setMarkedCallBackCalled) XCTAssertTrue(items[0].marked) } func testItemChangedToMarkedStatusFalse() { let item = CoreDataHelpers.createItemForList(list!, withTitle: "Make a sandwich", andMarked: true) viewModel!.changeMarkedStatusForItem(item) let items = CoreDataHelpers.retrieveAllItemsForList(list!) XCTAssertTrue(delegate!.setUnmarkedCallBackCalled) XCTAssertFalse(items[0].marked) } } class MarkItemViewModelDelegateDouble: MarkItemViewModelDelegate { var setMarkedCallBackCalled = false var setUnmarkedCallBackCalled = false func setMarkedCallBack(item: Item) { setMarkedCallBackCalled = true } func setUnmarkedCallBack(item: Item) { setUnmarkedCallBackCalled = true } }<file_sep>// // RoundedButton.swift // dooit // // Created by <NAME> on 30/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class RoundedButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { backgroundColor = UIColor.blueColor() layer.masksToBounds = true layer.cornerRadius = 4.0 } } <file_sep>// // ShowWithFadeAnimationSegue.swift // dooit // // Created by <NAME> on 13/07/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class ShowWithFadeAnimationSegue: UIStoryboardSegue, UIViewControllerTransitioningDelegate { override func perform() { destinationViewController.transitioningDelegate = self sourceViewController.presentViewController(destinationViewController, animated: true, completion: nil) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return FadePresentationAnimationController(isPresenting: true) } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return FadePresentationAnimationController(isPresenting: false) } } <file_sep>// // ViewController.swift // dooit // // Created by <NAME> on 12/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class ListsTableViewController: UITableViewController, ShowListsViewModelDelegate, DeleteListViewModelDelegate { @IBOutlet var blankStateView: UIView! var showListsViewModel: ShowListsViewModel? // MARK: - UIViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() setUpTitle() setUpViewModel() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) showListsViewModel!.fetchLists() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "List Selected" { let itemsViewController = segue.destinationViewController as! ItemsTableViewController let list = showListsViewModel!.lists[tableView.indexPathForSelectedRow!.row] itemsViewController.title = list.title itemsViewController.list = list } else if segue.identifier == "Edit Existing List" { let editListNavigationController = segue.destinationViewController as! UINavigationController let editListViewController = editListNavigationController.topViewController as! EditListTableViewController editListViewController.dismissCallback = showListsViewModel!.fetchLists let cell = sender as! UITableViewCell let indexPath = tableView.indexPathForCell(cell) let list = showListsViewModel!.lists[indexPath!.row] editListViewController.list = list } else if segue.identifier == "New List" { let editListNavigationController = segue.destinationViewController as! UINavigationController let editListViewController = editListNavigationController.topViewController as! EditListTableViewController editListViewController.dismissCallback = showListsViewModel!.fetchLists } } func showLists() { tableView.backgroundView = nil tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine tableView.reloadData() } func showBlankstate() { tableView.backgroundView = blankStateView tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.reloadData() } func setUpTitle() { let titleLabel = UILabel() titleLabel.attributedText = GUIHelpers.setUpTitle() titleLabel.sizeToFit() navigationItem.titleView = titleLabel } func setUpViewModel() { showListsViewModel = ShowListsViewModel(delegate: self, managedObjectContext: SQLiteCoreDataStack.sharedInstance.managedObjectContext) } func deleteListSuccessCallback() { showListsViewModel!.fetchLists() } func deleteListErrorCallback() { let alert = UIAlertController(title: "Warning!", message: "Error on deleting list", preferredStyle: .Alert) let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(okAction) presentViewController(alert, animated: true, completion: nil) } // MARK: - UITableView DataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return showListsViewModel!.lists.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("List Cell") let list = showListsViewModel!.lists[indexPath.row] cell!.textLabel!.textColor = UIColor.whiteColor() cell!.textLabel!.text = list.title return cell! } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .Default, title: "Delete") { (action, indexPath) in let list = self.showListsViewModel!.lists[indexPath.row] self.deleteList(list) } let editAction = UITableViewRowAction(style: .Normal, title: "Edit") { (action, indexPath) in let cell = tableView.cellForRowAtIndexPath(indexPath) self.performSegueWithIdentifier("Edit Existing List", sender: cell) } return [deleteAction, editAction] } func deleteList(list: List) { let deleteListViewModel = DeleteListViewModel(delegate: self, managedObjectContext: SQLiteCoreDataStack.sharedInstance.managedObjectContext) deleteListViewModel.deleteList(list) } } <file_sep>// // SaveItemForListViewModel.swift // dooit // // Created by <NAME> on 08/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class SaveItemForListViewModel { let emptyTitleErrorMessage = "You must provide a title for the item" let savingSuccessMessage = "Item saved" var delegate: SaveItemForListViewModelDelegate var managedObjectContext: NSManagedObjectContext var list: List init(delegate: SaveItemForListViewModelDelegate, managedObjectContext: NSManagedObjectContext, list: List) { self.delegate = delegate self.managedObjectContext = managedObjectContext self.list = list } func saveNewItemWithTitle(title: String) { let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext: managedObjectContext) let item = NSManagedObject.init(entity: entity!, insertIntoManagedObjectContext: managedObjectContext) as! Item item.title = title list.addItemsObject(item) do { try managedObjectContext.save() delegate.showSaveItemSuccessMessage(savingSuccessMessage) } catch _ as NSError { delegate.showSaveItemErrorMessage(emptyTitleErrorMessage) } } } protocol SaveItemForListViewModelDelegate { func showSaveItemSuccessMessage(message: String) func showSaveItemErrorMessage(message: String) } <file_sep>![dooit](icon/small-icon.png) [![Build Status](https://travis-ci.org/ricardo0100/dooit-iOS.svg?branch=master)](https://travis-ci.org/ricardo0100/dooit-iOS) [![codecov](https://codecov.io/gh/ricardo0100/dooit/branch/master/graph/badge.svg?precision=2)](https://codecov.io/gh/ricardo0100/dooit) [![Code Climate](https://codeclimate.com/github/ricardo0100/dooit/badges/gpa.svg)](https://codeclimate.com/github/ricardo0100/dooit) ### What is this? This is a MVVM based project used for practicing iOS development including the following concepts: - Core Data - Presentation Controllers - Unit Testing - UI Testing - Auto Layout - Size Classes - UIKit - Publication in App Store including TestFlight The app goal is to be a simple, but awesome, to do list app. ### Project Structure - **Model**: Data model and some data rules validation - **ViewModel**: Business rules - **View**: View Controllers and Views - **Dependency manager**: For now I'm trying not to use external libraries so I can learn the core concepts. But I'll probably have to use CocoaPods or Carthage soon ### Tests and CI All the business rules are contained in the ViewModel layer and unit tested. The View layer is going to be test covered by the XCode UI Tests. The goal is 100% test coverage 🎯 Travis CI is used for Continuous Integration Codecov for test coverage analysis Code Climate for code quality ### Future - [ ] UI improvements for iPad - [ ] Animations - [ ] Custom colors defined by the user - [ ] Alarms - [ ] Integration with REST API ### Data Model Core Data is used for persistence and migrations. The model evolution is represented bellow: ##### Version 1 - List - __title__: String - __items__: [Item] - Item - __title__: String - __marked__: Bool ##### Version 2 - List - __title__: String - __items__: [Item] - __updateTime__: NSDate - __creationTime__: NSDate - Item - __title__: String - __marked__: Bool - __updateTime__: NSDate - __creationTime__: NSDate <file_sep>// // ShowListsViewModel.swift // dooit // // Created by <NAME> on 25/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class ShowListsViewModel { var delegate: ShowListsViewModelDelegate var managedObjectContext: NSManagedObjectContext var lists: [List] = [] init(delegate: ShowListsViewModelDelegate, managedObjectContext: NSManagedObjectContext) { self.delegate = delegate self.managedObjectContext = managedObjectContext } func fetchLists() { let fetchRequest = NSFetchRequest(entityName: "List") do { let results = try managedObjectContext.executeFetchRequest(fetchRequest) lists = results as! [List] presentLists() } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } private func presentLists() { if lists.count == 0 { delegate.showBlankstate() } else { delegate.showLists() } } } protocol ShowListsViewModelDelegate { func showLists() func showBlankstate() } <file_sep>// // dooitTests.swift // dooitTests // // Created by <NAME> on 23/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest import CoreData @testable import dooit class ShowListsViewModelTests: XCTestCase { var viewModel: ShowListsViewModel? var viewModelDelegate: ShowListsViewModelDelegateDouble? var managedObjectContext: NSManagedObjectContext? override func setUp() { super.setUp() viewModelDelegate = ShowListsViewModelDelegateDouble() managedObjectContext = InMemoryCoreDataStack.sharedInstance.managedObjectContext viewModel = ShowListsViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testShouldPresentBlankState() { viewModel?.fetchLists() XCTAssertTrue(viewModelDelegate!.showBlankstateCalled) } func testShouldPresentOneList() { let listName = "Open a hotel" CoreDataHelpers.createListWithTitle(listName) viewModel?.fetchLists() XCTAssertTrue(viewModelDelegate!.showListsCalled) XCTAssertEqual(viewModel?.lists.count, 1) XCTAssertEqual(viewModel?.lists[0].title, listName) } func testShouldPresentTwoLists() { CoreDataHelpers.createListWithTitle("Make cookies") CoreDataHelpers.createListWithTitle("Make apple juice") viewModel?.fetchLists() XCTAssertTrue(viewModelDelegate!.showListsCalled) XCTAssertEqual(viewModel?.lists.count, 2) } } class ShowListsViewModelDelegateDouble: ShowListsViewModelDelegate { var showListsCalled = false var showBlankstateCalled = false func showLists() { showListsCalled = true } func showBlankstate() { showBlankstateCalled = true } } <file_sep>// // EditListViewModel.swift // dooit // // Created by <NAME> on 28/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class EditListViewModel { let emptyTitleErrorMessage = "You must provide a title for the list" let savingSuccessMessage = "List saved" var delegate: EditListViewModelDelegate var managedObjectContext: NSManagedObjectContext var list: List init (delegate: EditListViewModelDelegate, managedObjectContext: NSManagedObjectContext) { self.delegate = delegate self.managedObjectContext = managedObjectContext let entity = NSEntityDescription.entityForName("List", inManagedObjectContext:managedObjectContext) list = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext) as! List } init (delegate: EditListViewModelDelegate, managedObjectContext: NSManagedObjectContext, list: List) { self.delegate = delegate self.managedObjectContext = managedObjectContext self.list = list delegate.presentExistingListForEditing() } func saveList() { do { try managedObjectContext.save() delegate.showSaveListSuccessMessage(savingSuccessMessage) } catch _ as NSError { delegate.showSaveListErrorMessage(emptyTitleErrorMessage) } } func cancelEditing() { managedObjectContext.reset() delegate.cancelEditingCallBack() } } protocol EditListViewModelDelegate { func showSaveListSuccessMessage(message: String) func showSaveListErrorMessage(message: String) func presentExistingListForEditing() func cancelEditingCallBack() } <file_sep>// // Item.swift // dooit // // Created by <NAME> on 26/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData @objc(Item) class Item: NSManagedObject { override func willSave() { if self.updateTime == nil { self.updateTime = NSDate() } } } <file_sep>// // ShowItemsForListViewModelTests.swift // dooit // // Created by <NAME> on 02/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest import CoreData @testable import dooit class ShowItemsForListViewModelTests: XCTestCase { var viewModel: ShowItemsForListViewModel? var viewModelDelegate: ShowItemsForListViewModelDelegateDouble? var list: List? override func setUp() { super.setUp() viewModelDelegate = ShowItemsForListViewModelDelegateDouble() list = CoreDataHelpers.createListWithTitle("Eat bacon 🐽") let moc = InMemoryCoreDataStack.sharedInstance.managedObjectContext viewModel = ShowItemsForListViewModel(delegate: viewModelDelegate!, managedObjectContext: moc, list: list!) } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testPresentBlankState() { viewModel!.fetchItems() XCTAssertTrue(viewModelDelegate!.presentBlankStateCalled) } func testPresentOneItemForList() { CoreDataHelpers.createItemForList(list!, withTitle: "Buy land") viewModel!.fetchItems() XCTAssertTrue(viewModelDelegate!.presentItemsCalled) XCTAssertEqual(viewModel!.items.count, 1) } func testPresentTwoItemsForList() { CoreDataHelpers.createItemForList(list!, withTitle: "Write a book") CoreDataHelpers.createItemForList(list!, withTitle: "Hire an architect") viewModel!.fetchItems() XCTAssertTrue(viewModelDelegate!.presentItemsCalled) XCTAssertEqual(viewModel!.items.count, 2) } } class ShowItemsForListViewModelDelegateDouble: ShowItemsForListViewModelDelegate { var presentItemsCalled = false var presentBlankStateCalled = false func presentItems() { presentItemsCalled = true } func presentBlankState() { presentBlankStateCalled = true } }<file_sep>// // ShowItemsForListViewModel.swift // dooit // // Created by <NAME> on 02/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class ShowItemsForListViewModel { var delegate: ShowItemsForListViewModelDelegate var managedObjectContext: NSManagedObjectContext var list: List var items: [Item] = [] init(delegate: ShowItemsForListViewModelDelegate, managedObjectContext: NSManagedObjectContext, list: List) { self.delegate = delegate self.managedObjectContext = managedObjectContext self.list = list } func fetchItems() { items = Array(list.items) if items.count == 0 { delegate.presentBlankState() } else { delegate.presentItems() } } } protocol ShowItemsForListViewModelDelegate { func presentItems() func presentBlankState() }<file_sep>// // EditListTableViewController.swift // dooit // // Created by <NAME> on 12/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class EditListTableViewController: UIViewController, EditListViewModelDelegate { var list: List? var editListViewModel: EditListViewModel! var dismissCallback: ((Void) -> Void)! @IBOutlet weak var listTitleTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() setUpViewModel() } func setUpViewModel() { if let existingList = list { editListViewModel = EditListViewModel(delegate: self, managedObjectContext: SQLiteCoreDataStack.sharedInstance.managedObjectContext, list: existingList) } else { editListViewModel = EditListViewModel(delegate: self, managedObjectContext: SQLiteCoreDataStack.sharedInstance.managedObjectContext) } } @IBAction func saveList(sender: AnyObject) { editListViewModel.list.title = listTitleTextField.text editListViewModel.saveList() } @IBAction func cancelEditing(sender: AnyObject) { editListViewModel.cancelEditing() } func showSaveListSuccessMessage(message: String) { dismissViewControllerAnimated(true, completion: nil) dismissCallback() } func showSaveListErrorMessage(message: String) { let alert = UIAlertController(title: "Warning!", message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(okAction) presentViewController(alert, animated: true, completion: nil) } func cancelEditingCallBack() { dismissViewControllerAnimated(true, completion: nil) dismissCallback() } func presentExistingListForEditing() { listTitleTextField.text = list!.title } } <file_sep>// // GUIHelpers.swift // dooit // // Created by <NAME> on 28/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import UIKit class GUIHelpers { static func setUpTitle() -> NSAttributedString { let attributedText = NSMutableAttributedString(string: "dooit") let color = UIColor.whiteColor() let blackFont = UIFont(name: "Avenir-Black", size: 20)! let attributeBlack = [NSForegroundColorAttributeName: color, NSFontAttributeName: blackFont] attributedText.addAttributes(attributeBlack, range: NSRange(location: 0, length: 3)) let blackLight = UIFont(name: "Avenir-Light", size: 24)! let attributeLight = [NSForegroundColorAttributeName: color, NSFontAttributeName: blackLight] attributedText.addAttributes(attributeLight, range: NSRange(location: 3, length: 2)) return attributedText } } <file_sep>// // DeleteListViewModelTests.swift // dooit // // Created by <NAME> on 31/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest import CoreData @testable import dooit class DeleteListViewModelTests: XCTestCase { var viewModel: DeleteListViewModel? var viewModelDelegate: DeleteListViewModelDelegateDouble? var managedObjectContext: NSManagedObjectContext? override func setUp() { super.setUp() viewModelDelegate = DeleteListViewModelDelegateDouble() managedObjectContext = InMemoryCoreDataStack.sharedInstance.managedObjectContext viewModel = DeleteListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testDeleteListInPersistenceStoreSuccess() { let list = CoreDataHelpers.createListWithTitle("Find a planet") viewModel!.deleteList(list) let lists = CoreDataHelpers.retrieveAllLists() XCTAssertTrue(viewModelDelegate!.deleteListSuccessCallbackCalled) XCTAssertEqual(lists.count, 0) } } class DeleteListViewModelDelegateDouble: DeleteListViewModelDelegate { var deleteListSuccessCallbackCalled = false var deleteListErrorCallbackCalled = false func deleteListSuccessCallback() { deleteListSuccessCallbackCalled = true } func deleteListErrorCallback() { deleteListErrorCallbackCalled = true } }<file_sep>// // DeleteListViewModel.swift // dooit // // Created by <NAME> on 31/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class DeleteListViewModel { var delegate: DeleteListViewModelDelegate var managedObjectContext: NSManagedObjectContext init (delegate: DeleteListViewModelDelegate, managedObjectContext: NSManagedObjectContext) { self.delegate = delegate self.managedObjectContext = managedObjectContext } func deleteList(list: List) { managedObjectContext.deleteObject(list) do { try SQLiteCoreDataStack.sharedInstance.managedObjectContext.save() delegate.deleteListSuccessCallback() } catch _ as NSError { delegate.deleteListErrorCallback() } } } protocol DeleteListViewModelDelegate { func deleteListSuccessCallback() func deleteListErrorCallback() } <file_sep>// // InitialViewController.swift // dooit // // Created by <NAME> on 11/07/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class AnimatedLaunchScreenViewController: UIViewController { @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label3: UILabel! @IBOutlet weak var label4: UILabel! override func viewDidLoad() { super.viewDidLoad() self.label1.transform = CGAffineTransformScale(self.label1.transform, 1, 1) UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.label1.transform = CGAffineTransformScale(self.label1.transform, 0.5, 0.5) self.label1.alpha = 0.0 }, completion: nil) self.label2.transform = CGAffineTransformScale(self.label2.transform, 1, 1) UIView.animateWithDuration(0.5, delay: 0.7, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.label2.transform = CGAffineTransformScale(self.label2.transform, 0.5, 0.5) self.label2.alpha = 0.0 }, completion: nil) self.label3.transform = CGAffineTransformScale(self.label3.transform, 1, 1) UIView.animateWithDuration(0.5, delay: 0.9, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.label3.transform = CGAffineTransformScale(self.label3.transform, 0.5, 0.5) self.label3.alpha = 0.0 }, completion: nil) self.label4.transform = CGAffineTransformScale(self.label4.transform, 1, 1) UIView.animateWithDuration(0.5, delay: 1.1, options: UIViewAnimationOptions.CurveLinear, animations: { self.label4.transform = CGAffineTransformScale(self.label4.transform, 3.5, 3.5) self.label4.alpha = 0.0 }) { (finished) in self.performSegueWithIdentifier("Start App", sender: nil) } } func launchShowListsViewController(timer : NSTimer) { performSegueWithIdentifier("Show Lists", sender: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } } <file_sep>// // ReasonsTableViewController.swift // dooit // // Created by <NAME> on 19/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import CoreData class ItemsTableViewController: UITableViewController, ShowItemsForListViewModelDelegate, MarkItemViewModelDelegate, SaveItemForListViewModelDelegate, DeleteItemFromListViewModelDelegate { @IBOutlet var blankStateView: UIView! var list: List? var showItemsForListViewModel: ShowItemsForListViewModel? var markItemViewModel: MarkItemViewModel? var saveItemForListViewModel: SaveItemForListViewModel? var deleteItemFromListViewModel: DeleteItemFromListViewModel? // MARK: - UIViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() setUpViewModel() } func setUpViewModel() { let moc = SQLiteCoreDataStack.sharedInstance.managedObjectContext showItemsForListViewModel = ShowItemsForListViewModel(delegate: self, managedObjectContext: moc, list: list!) markItemViewModel = MarkItemViewModel(delegate: self, managedObjectContext: moc) saveItemForListViewModel = SaveItemForListViewModel(delegate: self, managedObjectContext: moc, list: list!) deleteItemFromListViewModel = DeleteItemFromListViewModel(delegate: self, managedObjectContext: moc, list: list!) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) showItemsForListViewModel!.fetchItems() } // MARK: - UITableView DataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return showItemsForListViewModel!.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Item Cell", forIndexPath: indexPath) as! ItemTableViewCell let item = showItemsForListViewModel!.items[indexPath.row] cell.item = item cell.markedTapped = setMarkedTapped return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let item = showItemsForListViewModel!.items[indexPath.row] deleteItem(item) showItemsForListViewModel!.fetchItems() } } func presentItems() { tableView.backgroundView = nil tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine tableView.reloadData() } func presentBlankState() { tableView.backgroundView = blankStateView tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.reloadData() } func showSaveItemSuccessMessage(message: String) { showItemsForListViewModel?.fetchItems() } func showSaveItemErrorMessage(message: String) { } func deleteItemFromListSuccessCallback() { } func deleteItemFromListErrorCallback() { } func setMarkedCallBack(item: Item) { let index = showItemsForListViewModel!.items.indexOf(item) let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index!, inSection: 0)) as! ItemTableViewCell cell.marked = true } func setUnmarkedCallBack(item: Item) { let index = showItemsForListViewModel!.items.indexOf(item) let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index!, inSection: 0)) as! ItemTableViewCell cell.marked = false } @IBAction func newItemClicked(sender: AnyObject) { let alert = UIAlertController(title: "New Item", message: "Add a new item", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action:UIAlertAction) -> Void in let textField = alert.textFields!.first self.saveItemWithTitle(textField!.text!) self.tableView.reloadData() }) let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) alert.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in } alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } func saveItemWithTitle(title: String) { saveItemForListViewModel!.saveNewItemWithTitle(title) } func setMarkedTapped(item: Item) { markItemViewModel!.changeMarkedStatusForItem(item) } func deleteItem(item: Item) { deleteItemFromListViewModel!.deleteItem(item) } } <file_sep>// // Created by <NAME> on 26/06/2014. // Copyright (c) 2014 Dative Studios. All rights reserved. // import UIKit class CustomPresentationController: UIPresentationController { lazy var dimmingView: UIView = { let effect = UIBlurEffect(style: UIBlurEffectStyle.Light) let view = UIVisualEffectView(effect: effect) view.alpha = 0.0 return view }() override func presentationTransitionWillBegin() { dimmingView.frame = containerView!.bounds containerView!.addSubview(dimmingView) let pv = presentedView() pv?.layer.masksToBounds = true pv?.layer.cornerRadius = 6.0 if let transitionCoordinator = self.presentingViewController.transitionCoordinator() { transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.dimmingView.alpha = 1.0 }, completion:nil) } } override func presentationTransitionDidEnd(completed: Bool) { if !completed { self.dimmingView.removeFromSuperview() } } override func dismissalTransitionWillBegin() { if let transitionCoordinator = self.presentingViewController.transitionCoordinator() { transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.dimmingView.alpha = 0.0 }, completion:nil) } } override func dismissalTransitionDidEnd(completed: Bool) { if completed { self.dimmingView.removeFromSuperview() } } override func frameOfPresentedViewInContainerView() -> CGRect { var frame = containerView!.bounds frame = CGRectInset(frame, 20.0, 100.0) frame.size = CGSize(width: frame.width, height: 110.0) return frame } // ---- UIContentContainer protocol methods override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator transitionCoordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: transitionCoordinator) transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.dimmingView.frame = self.containerView!.bounds }, completion:nil) } } <file_sep>// // SaveListViewModelTests.swift // dooitTests // // Created by <NAME> on 28/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest import CoreData @testable import dooit class EditListViewModelTests: XCTestCase { var viewModel: EditListViewModel? var viewModelDelegate: EditListViewModelDelegateDouble? var managedObjectContext: NSManagedObjectContext? override func setUp() { super.setUp() viewModelDelegate = EditListViewModelDelegateDouble() managedObjectContext = InMemoryCoreDataStack.sharedInstance.managedObjectContext } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testNewListShouldCreateNewEntity() { viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) XCTAssertNotNil(viewModel!.list) } func testNewListShouldHaveCreationTime() { viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) XCTAssertNotNil(viewModel!.list.creationTime) } func testBlankTitleShouldPresentErrorMessage() { viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) viewModel!.saveList() XCTAssertTrue(viewModelDelegate!.showErrorMessageCalled) XCTAssertEqual(viewModelDelegate!.errorMessage, viewModel?.emptyTitleErrorMessage) } func testSaveListShouldShowSuccessMessage() { viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) viewModel!.list.title = "Go to gym" viewModel!.saveList() XCTAssertTrue(viewModelDelegate!.showSuccessMessageCalled) XCTAssertEqual(viewModelDelegate!.successMessage, viewModel?.savingSuccessMessage) } func testSaveListShouldPersistInStore() { let title = "Make a cake" viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) viewModel!.list.title = title viewModel!.saveList() let lists = CoreDataHelpers.retrieveAllLists() XCTAssertEqual(lists.count, 1) XCTAssertEqual(lists[0].title, title) } func testCancelEditingNewListShouldDiscardNewEntity() { viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!) viewModel!.list.title = "Go to Japan" viewModel!.cancelEditing() let lists = CoreDataHelpers.retrieveAllLists() XCTAssertEqual(lists.count, 0) XCTAssertTrue(viewModelDelegate!.cancelEditingCallBackCalled) } func testPresentExistingList() { let list = CoreDataHelpers.createListWithTitle("Eat Sushi") viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!, list: list) XCTAssertTrue(viewModelDelegate!.presentExistingListForEditingCalled) } func testEditExistingListShouldSaveChangesInStore() { let newTitle = "Play Soccer" let list = CoreDataHelpers.createListWithTitle("Play Hockey") viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!, list: list) viewModel!.list.title = newTitle viewModel!.saveList() let lists = CoreDataHelpers.retrieveAllLists() XCTAssertEqual(lists.count, 1) XCTAssertEqual(lists[0].title, newTitle) } func testCancelEditingExistingListShouldNotSaveChanges() { let title = "Move to Floripa" let newTitle = "Move to Palhoça" let list = CoreDataHelpers.createListWithTitle(title) viewModel = EditListViewModel(delegate: viewModelDelegate!, managedObjectContext: managedObjectContext!, list: list) viewModel!.list.title = newTitle viewModel!.cancelEditing() let lists = CoreDataHelpers.retrieveAllLists() XCTAssertEqual(lists.count, 1) XCTAssertEqual(lists[0].title, title) } } class EditListViewModelDelegateDouble: EditListViewModelDelegate { var showErrorMessageCalled = false var showSuccessMessageCalled = false var cancelEditingCallBackCalled = false var presentExistingListForEditingCalled = false var errorMessage = "" var successMessage = "" func showSaveListErrorMessage(message: String) { showErrorMessageCalled = true errorMessage = message } func showSaveListSuccessMessage(message: String) { showSuccessMessageCalled = true successMessage = message } func cancelEditingCallBack() { cancelEditingCallBackCalled = true } func presentExistingListForEditing() { presentExistingListForEditingCalled = true } } <file_sep>// // CoreDataHelpers.swift // dooit // // Created by <NAME> on 02/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData @testable import dooit class CoreDataHelpers { static func createListWithTitle(title: String) -> List { let moc = InMemoryCoreDataStack.sharedInstance.managedObjectContext let entity = NSEntityDescription.entityForName("List", inManagedObjectContext: moc) let list = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! List list.title = title try! moc.save() return list } static func createItemForList(list: List, withTitle title: String) -> Item { let moc = InMemoryCoreDataStack.sharedInstance.managedObjectContext let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext:moc) let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! Item item.title = title list.addItemsObject(item) try! moc.save() return item } static func createItemForList(list: List, withTitle title: String, andMarked marked: Bool) -> Item { let moc = InMemoryCoreDataStack.sharedInstance.managedObjectContext let entity = NSEntityDescription.entityForName("Item", inManagedObjectContext:moc) let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! Item item.title = title item.marked = marked list.addItemsObject(item) try! moc.save() return item } static func retrieveAllLists() -> [List] { let moc = InMemoryCoreDataStack.sharedInstance.managedObjectContext let results = try! moc.executeFetchRequest(NSFetchRequest(entityName: "List")) let lists = results as! [List] return lists } static func retrieveAllItemsForList(list: List) -> [Item] { let moc = InMemoryCoreDataStack.sharedInstance.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Item") let results = try! moc.executeFetchRequest(fetchRequest) let items = results as! [Item] return items } } <file_sep>// // List.swift // dooit // // Created by <NAME> on 26/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData @objc(List) class List: NSManagedObject { @NSManaged func addItemsObject(value: Item) @NSManaged func removeItemsObject(value: Item) override func awakeFromInsert() { creationTime = NSDate() } override func willSave() { if updateTime == nil { updateTime = NSDate() } } } <file_sep>// // SaveItemForListViewModelTests.swift // dooit // // Created by <NAME> on 08/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest @testable import dooit class SaveItemForListViewModelTests: XCTestCase { var viewModel: SaveItemForListViewModel? var delegate: SaveItemForListViewModelDelegateDouble? override func setUp() { super.setUp() let list = CoreDataHelpers.createListWithTitle("Go to the gym 🏋🏻") delegate = SaveItemForListViewModelDelegateDouble() viewModel = SaveItemForListViewModel(delegate: delegate!, managedObjectContext: InMemoryCoreDataStack.sharedInstance.managedObjectContext, list: list) } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testBlankTitleErrorMessagePresentation() { viewModel!.saveNewItemWithTitle("") XCTAssertTrue(delegate!.showSaveItemErrorMessageCalled) } func testSuccessMessagePresentation() { viewModel!.saveNewItemWithTitle("Eat burgers") XCTAssertTrue(delegate!.showSaveItemSuccessMessageCalled) } } class SaveItemForListViewModelDelegateDouble: SaveItemForListViewModelDelegate { var showSaveItemSuccessMessageCalled = false var showSaveItemErrorMessageCalled = false func showSaveItemSuccessMessage(message: String) { showSaveItemSuccessMessageCalled = true } func showSaveItemErrorMessage(message: String) { showSaveItemErrorMessageCalled = true } } <file_sep>// // ReasonTableViewCell.swift // dooit // // Created by <NAME> on 19/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class ItemTableViewCell: UITableViewCell { @IBOutlet weak var radioButton: UIImageView! @IBOutlet weak var name: UILabel! let selectedRadioImage = UIImage(named: "ic_radio_button_checked")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) let unselectedRadioImage = UIImage(named: "ic_radio_button_unchecked")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) var markedTapped: ((Item) -> Void)? = nil var item: Item? { didSet { marked = item!.marked name.text = item!.title } } var marked = false { didSet { if marked { radioButton.image = selectedRadioImage } else { radioButton.image = unselectedRadioImage } } } override func awakeFromNib() { super.awakeFromNib() radioButton.image = unselectedRadioImage radioButton.tintColor = UIColor.whiteColor() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ItemTableViewCell.radioButtonTaped)) radioButton.addGestureRecognizer(tapGesture) } func radioButtonTaped() { markedTapped!(item!) } } <file_sep>// // DeleteItemFromListViewModelTests.swift // dooit // // Created by <NAME> on 09/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import XCTest @testable import dooit class DeleteItemFromListViewModelTests: XCTestCase { var delegate: DeleteItemFromListViewModelDelegateDouble? var viewModel: DeleteItemFromListViewModel? var list: List? override func setUp() { super.setUp() list = CoreDataHelpers.createListWithTitle("Go to Rio de Janeiro") delegate = DeleteItemFromListViewModelDelegateDouble() viewModel = DeleteItemFromListViewModel(delegate: delegate!, managedObjectContext: InMemoryCoreDataStack.sharedInstance.managedObjectContext, list: list!) } override func tearDown() { InMemoryCoreDataStack.sharedInstance.clearStore() super.tearDown() } func testItemDeletedFromListInPersistenceStore() { let item = CoreDataHelpers.createItemForList(list!, withTitle: "Build a plane") var lists = CoreDataHelpers.retrieveAllItemsForList(list!) XCTAssertEqual(lists.count, 1) viewModel!.deleteItem(item) lists = CoreDataHelpers.retrieveAllItemsForList(list!) XCTAssertEqual(lists.count, 0) XCTAssertTrue(delegate!.deleteItemFromListSuccessCallbackCalled) } } class DeleteItemFromListViewModelDelegateDouble: DeleteItemFromListViewModelDelegate { var deleteItemFromListSuccessCallbackCalled = false var deleteItemFromListErrorCallbackCalled = false func deleteItemFromListSuccessCallback() { deleteItemFromListSuccessCallbackCalled = true } func deleteItemFromListErrorCallback() { deleteItemFromListErrorCallbackCalled = true } } <file_sep>// // ShowAsPopoverSegue.swift // dooit // // Created by <NAME> on 30/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class ShowAsPopoverSegue: UIStoryboardSegue, UIViewControllerTransitioningDelegate { override func perform() { destinationViewController.modalPresentationStyle = .Custom destinationViewController.transitioningDelegate = self sourceViewController.presentViewController(destinationViewController, animated: true, completion: nil) } func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { return CustomPresentationController(presentedViewController: presented, presentingViewController: presenting) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CustomPresentationAnimationController(isPresenting: true) } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return CustomPresentationAnimationController(isPresenting: false) } } <file_sep>// // InMemoryCoreDataStack.swift // dooit // // Created by <NAME> on 26/05/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class InMemoryCoreDataStack: NSObject { static let sharedInstance = InMemoryCoreDataStack() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() func clearStore() { let fetchRequest = NSFetchRequest(entityName: "List") let lists = try! managedObjectContext.executeFetchRequest(fetchRequest) as! [NSManagedObject] for list in lists { managedObjectContext.deleteObject(list) } try! managedObjectContext.save() } }<file_sep>// // MarkItemViewModel.swift // dooit // // Created by <NAME> on 08/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class MarkItemViewModel { var managedObjectContext: NSManagedObjectContext var delegate: MarkItemViewModelDelegate init(delegate: MarkItemViewModelDelegate, managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext self.delegate = delegate } func changeMarkedStatusForItem(item: Item) { item.marked = !item.marked do { try managedObjectContext.save() if item.marked { delegate.setMarkedCallBack(item) } else { delegate.setUnmarkedCallBack(item) } } catch (_ as NSError) { } } } protocol MarkItemViewModelDelegate { func setMarkedCallBack(item: Item) func setUnmarkedCallBack(item: Item) }<file_sep>// // DeleteItemFromListViewModel.swift // dooit // // Created by <NAME> on 08/06/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation import CoreData class DeleteItemFromListViewModel { var managedObjectContext: NSManagedObjectContext var delegate: DeleteItemFromListViewModelDelegate var list: List init(delegate: DeleteItemFromListViewModelDelegate, managedObjectContext: NSManagedObjectContext, list: List) { self.managedObjectContext = managedObjectContext self.delegate = delegate self.list = list } func deleteItem(item: Item) { managedObjectContext.deleteObject(item) do { try managedObjectContext.save() delegate.deleteItemFromListSuccessCallback() } catch _ as NSError { delegate.deleteItemFromListErrorCallback() } } } protocol DeleteItemFromListViewModelDelegate { func deleteItemFromListSuccessCallback() func deleteItemFromListErrorCallback() } <file_sep>// // FadePresentationAnimationController.swift // dooit // // Created by <NAME> on 13/07/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class FadePresentationAnimationController: NSObject, UIViewControllerAnimatedTransitioning { let isPresenting :Bool let duration :NSTimeInterval = 1.5 init(isPresenting: Bool) { self.isPresenting = isPresenting super.init() } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return self.duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let presentedControllerView = transitionContext.viewForKey(UITransitionContextToViewKey), let containerView = transitionContext.containerView() else { return } presentedControllerView.alpha = 0 containerView.addSubview(presentedControllerView) UIView.animateWithDuration(self.duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .AllowUserInteraction, animations: { presentedControllerView.alpha = 1 }, completion: {(completed: Bool) -> Void in transitionContext.completeTransition(completed) }) } }
c5e8e501c730f7f6e14eda99abb4da0484593933
[ "Swift", "Markdown" ]
30
Swift
ricardo0100/BlackList
3f48b048f6d991d6a69db0772ee0870df92133c9
84ee59223321ef24c673c8f4d97856674ebafa8c
refs/heads/master
<file_sep># SSMMJ 框架集成:spring+springMVC+mybatis * 完成系统模块整个流程 * 完成登录验证 <file_sep>/* * Generated by the Jasper component of Apache Tomcat * Version: jetty/9.3.7.v20160115 * Generated at: 2016-12-06 13:04:46 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class codes_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final java.lang.String _jspx_method = request.getMethod(); if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD"); return; } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html lang=\"en\">\r\n"); out.write("<head>\r\n"); out.write("<title>Short codes</title>\r\n"); out.write("<!-- for-mobile-apps -->\r\n"); out.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n"); out.write("<meta name=\"keywords\" content=\"\" />\r\n"); out.write("<script type=\"application/x-javascript\"> addEventListener(\"load\", function() { setTimeout(hideURLbar, 0); }, false);\r\n"); out.write("\t\tfunction hideURLbar(){ window.scrollTo(0,1); } </script>\r\n"); out.write("<!-- //for-mobile-apps -->\r\n"); out.write("<link href=\"css/bootstrap.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />\r\n"); out.write("<link href=\"css/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />\r\n"); out.write("<link href=\"css/font-awesome.css\" rel=\"stylesheet\"> \r\n"); out.write("\r\n"); out.write("<!--web-fonts-->\r\n"); out.write("<link href=\"http://fonts.googleapis.com/css?family=Open+Sans:400,600,700,800\" rel=\"stylesheet\">\r\n"); out.write("<link href=\"http://fonts.googleapis.com/css?family=Lato:300,400,700\" rel=\"stylesheet\">\r\n"); out.write("<!--//web-fonts-->\r\n"); out.write("<!--//fonts-->\r\n"); out.write("<!-- js -->\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("<!-- banner -->\r\n"); out.write("\t<div class=\"banner about-banner-w3ls \" id=\"home\">\r\n"); out.write("\t\t<!-- header -->\r\n"); out.write("\t\t<header>\r\n"); out.write("\t\t\t<div class=\"container\">\r\n"); out.write("\r\n"); out.write("\t\t\t<!-- navigation -->\r\n"); out.write("\t\t\t<nav class=\"navbar navbar-default\">\r\n"); out.write("\t\t\t\t<!-- Brand and toggle get grouped for better mobile display -->\r\n"); out.write("\t\t\t\t<div class=\"navbar-header\">\r\n"); out.write("\t\t\t\t <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">\r\n"); out.write("\t\t\t\t\t<span class=\"sr-only\">Toggle navigation</span>\r\n"); out.write("\t\t\t\t\t<span class=\"icon-bar\"></span>\r\n"); out.write("\t\t\t\t\t<span class=\"icon-bar\"></span>\r\n"); out.write("\t\t\t\t\t<span class=\"icon-bar\"></span>\r\n"); out.write("\t\t\t\t </button>\t\t\t\t \r\n"); out.write("\t\t\t\t<div class=\"w3-logo\">\r\n"); out.write("\t\t\t\t\t<h1><a href=\"index.jsp\">Educative</a></h1>\r\n"); out.write("\t\t\t\t\t<label></label>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\r\n"); out.write("\t\t\t\t<!-- Collect the nav links, forms, and other content for toggling -->\r\n"); out.write("\t\t\t\t<div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">\r\n"); out.write("\t\t\t\t <ul class=\"nav navbar-nav\">\r\n"); out.write("\t\t\t\t\t<li><a href=\"index.jsp\">Home</a></li>\r\n"); out.write("\t\t\t\t\t<li><a href=\"about.jsp\">About</a></li>\r\n"); out.write("\t\t\t\t\t<li><a href=\"gallery.jsp\">Gallery</a></li>\r\n"); out.write("\t\t\t\t\t<li class=\"dropdown\">\r\n"); out.write("\t\t\t\t\t <a href=\"#\" class=\"dropdown-toggle active\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\">Pages<span class=\"caret\"></span></a>\r\n"); out.write("\t\t\t\t\t <ul class=\"dropdown-menu\">\r\n"); out.write("\t\t\t\t\t\t<li><a href=\"codes.jsp\">Short Codes</a></li>\r\n"); out.write("\t\t\t\t\t\t<li><a href=\"icons.jsp\">Icons</a></li>\r\n"); out.write("\t\t\t\t\t </ul>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<li><a href=\"contact.jsp\">Contact</a></li>\r\n"); out.write("\t\t\t\t </ul>\r\n"); out.write("\t\t\t\t <div class=\"subscribe\">\r\n"); out.write("\t\t\t\t\t<form>\r\n"); out.write("\t\t\t\t\t\t<input type=\"search\" class=\"sub-email\" name=\"Search\" required=\"\">\r\n"); out.write("\t\t\t\t\t\t<input type=\"submit\" value=\"\">\r\n"); out.write("\t\t\t\t\t</form>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t\t</div><!-- /.navbar-collapse -->\r\n"); out.write("\t\t\t\t \r\n"); out.write("\t\t\t</nav>\r\n"); out.write("\t\t\t<div class=\"clearfix\"></div>\r\n"); out.write("\t\t<!-- //navigation -->\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\t\t</header>\r\n"); out.write("\t<!-- //header -->\r\n"); out.write("\t<h2>Short codes</h2>\r\n"); out.write("\t</div>\r\n"); out.write("<!-- //banner -->\r\n"); out.write("<!-- typography -->\r\n"); out.write("\t<div class=\"typography services-w3layouts\">\r\n"); out.write("\t\t\t\t<div class=\"container\">\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_4\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Headings</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"bs-example\">\r\n"); out.write("\t\t\t\t\t\t\t<table class=\"table\">\r\n"); out.write("\t\t\t\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><h1 id=\"h1.-bootstrap-heading\">h1. Bootstrap heading<a class=\"anchorjs-link\" href=\"#h1.-bootstrap-heading\"><span class=\"anchorjs-icon\"></span></a></h1></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"type-info\">Semibold 36px</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><h2 id=\"h2.-bootstrap-heading\">h2. Bootstrap heading<a class=\"anchorjs-link\" href=\"#h2.-bootstrap-heading\"><span class=\"anchorjs-icon\"></span></a></h2></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"type-info\">Semibold 30px</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><h3 id=\"h3.-bootstrap-heading\">h3. Bootstrap heading<a class=\"anchorjs-link\" href=\"#h3.-bootstrap-heading\"><span class=\"anchorjs-icon\"></span></a></h3></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"type-info\">Semibold 24px</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><h4 id=\"h4.-bootstrap-heading\">h4. Bootstrap heading<a class=\"anchorjs-link\" href=\"#h4.-bootstrap-heading\"><span class=\"anchorjs-icon\"></span></a></h4></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"type-info\">Semibold 18px</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><h5 id=\"h5.-bootstrap-heading\">h5. Bootstrap heading<a class=\"anchorjs-link\" href=\"#h5.-bootstrap-heading\"><span class=\"anchorjs-icon\"></span></a></h5></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"type-info\">Semibold 14px</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><h6>h6. Bootstrap heading</h6></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"type-info\">Semibold 12px</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t\t\t\t</table>\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Buttons</h3>\r\n"); out.write("\t\t\t\t\t\t<h1>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-default\">Default</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-primary\">Primary</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-success\">Success</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-info\">Info</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-warning\">Warning</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-danger\">Danger</span></a>\r\n"); out.write("\t\t\t\t\t\t</h1>\r\n"); out.write("\t\t\t\t\t\t<h2>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-default\">Default</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-primary\">Primary</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-success\">Success</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-info\">Info</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-warning\">Warning</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-danger\">Danger</span></a>\r\n"); out.write("\t\t\t\t\t\t</h2>\r\n"); out.write("\t\t\t\t\t\t<h3>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-default\">Default</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-primary\">Primary</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-success\">Success</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-info\">Info</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-warning\">Warning</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-danger\">Danger</span></a>\r\n"); out.write("\t\t\t\t\t\t</h3>\r\n"); out.write("\t\t\t\t\t\t<h4>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-default\">Default</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-primary\">Primary</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-success\">Success</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-info\">Info</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-warning\">Warning</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-danger\">Danger</span></a>\r\n"); out.write("\t\t\t\t\t\t</h4>\r\n"); out.write("\t\t\t\t\t\t<h5>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-default\">Default</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-primary\">Primary</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-success\">Success</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-info\">Info</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-warning\">Warning</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-danger\">Danger</span></a>\r\n"); out.write("\t\t\t\t\t\t</h5>\r\n"); out.write("\t\t\t\t\t\t<h6>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-default\">Default</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-primary\">Primary</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-success\">Success</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-info\">Info</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-warning\">Warning</span></a>\r\n"); out.write("\t\t\t\t\t\t\t<a href=\"#\"><span class=\"label label-danger\">Danger</span></a>\r\n"); out.write("\t\t\t\t\t\t</h6>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Progress Bars</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"tab-content\">\r\n"); out.write("\t\t\t\t\t\t\t<div class=\"tab-pane active\" id=\"domprogress\">\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\"> \r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-primary\" style=\"width: 20%\"></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<p>Info with <code>progress-bar-info</code> class.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\"> \r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-info\" style=\"width: 60%\"></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<p>Success with <code>progress-bar-success</code> class.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-success\" style=\"width: 30%\"></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<p>Warning with <code>progress-bar-warning</code> class.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-warning\" style=\"width: 70%\"></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<p>Danger with <code>progress-bar-danger</code> class.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-danger\" style=\"width: 50%\"></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<p>Inverse with <code>progress-bar-inverse</code> class.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-inverse\" style=\"width: 40%\"></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<p>Inverse with <code>progress-bar-inverse</code> class.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t<div class=\"progress\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-success\" style=\"width: 35%\"><span class=\"sr-only\">35% Complete (success)</span></div>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-warning\" style=\"width: 20%\"><span class=\"sr-only\">20% Complete (warning)</span></div>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<div class=\"progress-bar progress-bar-danger\" style=\"width: 10%\"><span class=\"sr-only\">10% Complete (danger)</span></div>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Alerts</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"alert alert-success\" role=\"alert\">\r\n"); out.write("\t\t\t\t\t\t\t<strong>Well done!</strong> You successfully read this important alert message.\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"alert alert-info\" role=\"alert\">\r\n"); out.write("\t\t\t\t\t\t\t<strong>Heads up!</strong> This alert needs your attention, but it's not super important.\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"alert alert-warning\" role=\"alert\">\r\n"); out.write("\t\t\t\t\t\t\t<strong>Warning!</strong> Best check yo self, you're not looking too good.\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"alert alert-danger\" role=\"alert\">\r\n"); out.write("\t\t\t\t\t\t\t<strong>Oh snap!</strong> Change a few things up and try submitting again.\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Pagination</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"col-md-6\">\r\n"); out.write("\t\t\t\t\t\t\t<nav>\r\n"); out.write("\t\t\t\t\t\t\t\t<ul class=\"pagination pagination-lg\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">1</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">2</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">3</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">4</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">5</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t</nav>\r\n"); out.write("\t\t\t\t\t\t\t<nav>\r\n"); out.write("\t\t\t\t\t\t\t\t<ul class=\"pagination\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">1</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">2</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">3</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">4</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">5</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t</nav>\r\n"); out.write("\t\t\t\t\t\t\t<nav>\r\n"); out.write("\t\t\t\t\t\t\t\t<ul class=\"pagination pagination-sm\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">1</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">2</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">3</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">4</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">5</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t</nav>\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"col-md-6\">\r\n"); out.write("\t\t\t\t\t\t\t<ul class=\"pagination pagination-lg\">\r\n"); out.write("\t\t\t\t\t\t\t\t<li class=\"disabled\"><a href=\"#\"><i class=\"fa fa-angle-left\">«</i></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li class=\"active\"><a href=\"#\">1</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">2</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">3</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">4</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">5</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\"><i class=\"fa fa-angle-right\">»</i></a></li>\r\n"); out.write("\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t<nav>\r\n"); out.write("\t\t\t\t\t\t\t\t<ul class=\"pagination\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li class=\"disabled\"><a href=\"#\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li class=\"active\"><a href=\"#\">1 <span class=\"sr-only\">(current)</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">2</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">3</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">4</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\">5</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<li><a href=\"#\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t</nav>\r\n"); out.write("\t\t\t\t\t\t\t<ul class=\"pagination pagination-sm\">\r\n"); out.write("\t\t\t\t\t\t\t\t<li class=\"disabled\"><a href=\"#\"><i class=\"fa fa-angle-left\">«</i></a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li class=\"active\"><a href=\"#\">1</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">2</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">3</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">4</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\">5</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li><a href=\"#\"><i class=\"fa fa-angle-right\">»</i></a></li>\r\n"); out.write("\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"clearfix\"> </div>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Breadcrumbs</h3>\r\n"); out.write("\t\t\t\t\t\t<ol class=\"breadcrumb\">\r\n"); out.write("\t\t\t\t\t\t\t<li class=\"active\">Home</li>\r\n"); out.write("\t\t\t\t\t\t</ol>\r\n"); out.write("\t\t\t\t\t\t<ol class=\"breadcrumb\">\r\n"); out.write("\t\t\t\t\t\t\t<li><a href=\"#\">Home</a></li>\r\n"); out.write("\t\t\t\t\t\t\t<li class=\"active\">Library</li>\r\n"); out.write("\t\t\t\t\t\t</ol>\r\n"); out.write("\t\t\t\t\t\t<ol class=\"breadcrumb\">\r\n"); out.write("\t\t\t\t\t\t\t<li><a href=\"#\">Home</a></li>\r\n"); out.write("\t\t\t\t\t\t\t<li><a href=\"#\">Library</a></li>\r\n"); out.write("\t\t\t\t\t\t\t<li class=\"active\">Data</li>\r\n"); out.write("\t\t\t\t\t\t</ol>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Badges</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"col-md-6\">\r\n"); out.write("\t\t\t\t\t\t\t<p>Add modifier classes to change the appearance of a badge.</p>\r\n"); out.write("\t\t\t\t\t\t\t<table class=\"table table-bordered\">\r\n"); out.write("\t\t\t\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<th>Classes</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<th>Badges</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td>No modifiers</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><span class=\"badge\">42</span></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><code>.badge-primary</code></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><span class=\"badge badge-primary\">1</span></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><code>.badge-success</code></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><span class=\"badge badge-success\">22</span></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><code>.badge-info</code></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><span class=\"badge badge-info\">30</span></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><code>.badge-warning</code></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><span class=\"badge badge-warning\">412</span></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><code>.badge-danger</code></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<td><span class=\"badge badge-danger\">999</span></td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t\t\t\t</table> \r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"col-md-6\">\r\n"); out.write("\t\t\t\t\t\t\t<p>Easily highlight new or unread items with the <code>.badge</code> class</p>\r\n"); out.write("\t\t\t\t\t\t\t<div class=\"list-group list-group-alternate\"> \r\n"); out.write("\t\t\t\t\t\t\t\t<a href=\"#\" class=\"list-group-item\"><span class=\"badge\">201</span> <i class=\"ti ti-email\"></i> Inbox </a> \r\n"); out.write("\t\t\t\t\t\t\t\t<a href=\"#\" class=\"list-group-item\"><span class=\"badge badge-primary\">5021</span> <i class=\"ti ti-eye\"></i> Profile visits </a> \r\n"); out.write("\t\t\t\t\t\t\t\t<a href=\"#\" class=\"list-group-item\"><span class=\"badge\">14</span> <i class=\"ti ti-headphone-alt\"></i> Call </a> \r\n"); out.write("\t\t\t\t\t\t\t\t<a href=\"#\" class=\"list-group-item\"><span class=\"badge\">20</span> <i class=\"ti ti-comments\"></i> Messages </a> \r\n"); out.write("\t\t\t\t\t\t\t\t<a href=\"#\" class=\"list-group-item\"><span class=\"badge badge-warning\">14</span> <i class=\"ti ti-bookmark\"></i> Bookmarks </a> \r\n"); out.write("\t\t\t\t\t\t\t\t<a href=\"#\" class=\"list-group-item\"><span class=\"badge badge-danger\">30</span> <i class=\"ti ti-bell\"></i> Notifications </a> \r\n"); out.write("\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t <div class=\"clearfix\"> </div>\r\n"); out.write("\t\t\t\t\t</div>\t \r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Wells</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"well\">\r\n"); out.write("\t\t\t\t\t\t\tThere are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"well\">\r\n"); out.write("\t\t\t\t\t\t\tIt is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t<div class=\"well\">\r\n"); out.write("\t\t\t\t\t\t\t\tLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"grid_3 grid_5 wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Tabs</h3>\r\n"); out.write("\t\t\t\t\t\t<div class=\"bs-example bs-example-tabs\" role=\"tabpanel\" data-example-id=\"togglable-tabs\">\r\n"); out.write("\t\t\t\t\t\t\t<ul id=\"myTab\" class=\"nav nav-tabs\" role=\"tablist\">\r\n"); out.write("\t\t\t\t\t\t\t\t<li role=\"presentation\" class=\"active\"><a href=\"#home\" id=\"home-tab\" role=\"tab\" data-toggle=\"tab\" aria-controls=\"home\" aria-expanded=\"true\">Home</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li role=\"presentation\"><a href=\"#profile\" role=\"tab\" id=\"profile-tab\" data-toggle=\"tab\" aria-controls=\"profile\">Profile</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t<li role=\"presentation\" class=\"dropdown\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<a href=\"#\" id=\"myTabDrop1\" class=\"dropdown-toggle\" data-toggle=\"dropdown\" aria-controls=\"myTabDrop1-contents\">Dropdown <span class=\"caret\"></span></a>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"myTabDrop1\" id=\"myTabDrop1-contents\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<li><a href=\"#dropdown1\" tabindex=\"-1\" role=\"tab\" id=\"dropdown1-tab\" data-toggle=\"tab\" aria-controls=\"dropdown1\">@fat</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t\t<li><a href=\"#dropdown2\" tabindex=\"-1\" role=\"tab\" id=\"dropdown2-tab\" data-toggle=\"tab\" aria-controls=\"dropdown2\">@mdo</a></li>\r\n"); out.write("\t\t\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t\t\t<div id=\"myTabContent\" class=\"tab-content\">\r\n"); out.write("\t\t\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane fade in active\" id=\"home\" aria-labelledby=\"home-tab\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure <NAME> ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane fade\" id=\"profile\" aria-labelledby=\"profile-tab\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<p>Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa <NAME> biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane fade\" id=\"dropdown1\" aria-labelledby=\"dropdown1-tab\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<p>Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane fade\" id=\"dropdown2\" aria-labelledby=\"dropdown2-tab\">\r\n"); out.write("\t\t\t\t\t\t\t\t\t<p>Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.</p>\r\n"); out.write("\t\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<h3 class=\"hdg wow fadeInUp animated\" data-wow-delay=\".5s\">Unordered List</h3>\r\n"); out.write("\t\t\t\t\t<ul class=\"list-group wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t <li class=\"list-group-item\">Cras justo odio</li>\r\n"); out.write("\t\t\t\t\t <li class=\"list-group-item\">Dapibus ac facilisis in</li>\r\n"); out.write("\t\t\t\t\t <li class=\"list-group-item\">Morbi leo risus</li>\r\n"); out.write("\t\t\t\t\t <li class=\"list-group-item\">Porta ac consectetur ac</li>\r\n"); out.write("\t\t\t\t\t <li class=\"list-group-item\">Vestibulum at eros</li>\r\n"); out.write("\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\t<h3 class=\"hdg wow fadeInUp animated\" data-wow-delay=\".5s\">Ordered List</h3>\r\n"); out.write("\t\t\t\t\t<ol class=\"wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<li class=\"list-group-item1\">Cras justo odio</li>\r\n"); out.write("\t\t\t\t\t\t<li class=\"list-group-item1\">Dapibus ac facilisis in</li>\r\n"); out.write("\t\t\t\t\t\t<li class=\"list-group-item1\">Morbi leo risus</li>\r\n"); out.write("\t\t\t\t\t\t<li class=\"list-group-item1\">Porta ac consectetur ac</li>\r\n"); out.write("\t\t\t\t\t\t<li class=\"list-group-item1\">Vestibulum at eros</li>\r\n"); out.write("\t\t\t\t\t</ol>\r\n"); out.write("\t\t\t\t\t<h3 class=\"hdg wow fadeInUp animated\" data-wow-delay=\".5s\">Forms</h3>\r\n"); out.write("\t\t\t\t\t<div class=\"input-group wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\" id=\"basic-addon1\">@</span>\r\n"); out.write("\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" placeholder=\"Username\" aria-describedby=\"basic-addon1\">\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"input-group wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" placeholder=\"Recipient's username\" aria-describedby=\"basic-addon2\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\" id=\"basic-addon2\">@example.com</span>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"input-group wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\">$</span>\r\n"); out.write("\t\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" aria-label=\"Amount (to the nearest dollar)\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\">.00</span>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"input-group input-group-lg wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\" id=\"sizing-addon1\">@</span>\r\n"); out.write("\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" placeholder=\"Username\" aria-describedby=\"sizing-addon1\">\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"input-group wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\" id=\"sizing-addon2\">@</span>\r\n"); out.write("\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" placeholder=\"Username\" aria-describedby=\"sizing-addon2\">\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<div class=\"input-group input-group-sm wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<span class=\"input-group-addon\" id=\"sizing-addon3\">@</span>\r\n"); out.write("\t\t\t\t\t\t<input type=\"text\" class=\"form-control\" placeholder=\"Username\" aria-describedby=\"sizing-addon3\">\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t\r\n"); out.write("\t\t\t\t\t\r\n"); out.write("\t\t\t\t\t<div class=\"page-header wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<h3 class=\"hdg\">Tables</h3>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<h2 class=\"typoh2 wow fadeInUp animated\" data-wow-delay=\".5s\">Default styles</h2>\r\n"); out.write("\t\t\t\t\t<p class=\"wow fadeInUp animated\" data-wow-delay=\".5s\">For basic stylinglight padding and only horizontal add the base class <code>.table</code> to any <code>&lt;table&gt;</code>.</p>\r\n"); out.write("\t\t\t\t\t<div class=\"bs-docs-example wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<table class=\"table\">\r\n"); out.write("\t\t\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>#</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>First Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>Last Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>Username</th>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>1</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Mark</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Otto</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@mdo</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>2</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Jacob</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Thornton</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@fat</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>3</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Larry</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>the Bird</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@twitter</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t\t\t</table>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<hr class=\"bs-docs-separator\">\r\n"); out.write("\t\t\t\t\t<p class=\"wow fadeInUp animated\" data-wow-delay=\".5s\">Add any of the following classes to the <code>.table</code> base class.</p>\r\n"); out.write("\t\t\t\t\t<p class=\"wow fadeInUp animated\" data-wow-delay=\".5s\">Adds zebra-striping to any table row within the <code>&lt;tbody&gt;</code> via the <code>:nth-child</code> CSS selector (not available in IE7-8).</p>\r\n"); out.write("\t\t\t\t\t<div class=\"bs-docs-example wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<table class=\"table table-striped\">\r\n"); out.write("\t\t\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>#</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>First Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>Last Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>Username</th>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>1</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Mark</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Otto</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@mdo</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>2</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Jacob</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Thornton</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@fat</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>3</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Larry</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>the Bird</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@twitter</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t\t\t</table>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<p class=\"wow fadeInUp animated\" data-wow-delay=\".5s\">Add borders and rounded corners to the table.</p>\r\n"); out.write("\t\t\t\t\t<div class=\"bs-docs-example wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<table class=\"table table-bordered\">\r\n"); out.write("\t\t\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>#</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>First Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>Last Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<th>Username</th>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td rowspan=\"2\">1</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Mark</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Otto</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@mdo</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Mark</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Otto</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@getbootstrap</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>2</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Jacob</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>Thornton</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@fat</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>3</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td colspan=\"2\">Larry the Bird</td>\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td>@twitter</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t\t\t</table>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<p class=\"wow fadeInUp animated\" data-wow-delay=\".5s\">Enable a hover state on table rows within a <code>&lt;tbody&gt;</code>.</p>\r\n"); out.write("\t\t\t\t\t<div class=\"bs-docs-example wow fadeInUp animated\" data-wow-delay=\".5s\">\r\n"); out.write("\t\t\t\t\t\t<table class=\"table table-hover\">\r\n"); out.write("\t\t\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t <th>#</th>\r\n"); out.write("\t\t\t\t\t\t\t\t <th>First Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t <th>Last Name</th>\r\n"); out.write("\t\t\t\t\t\t\t\t <th>Username</th>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>1</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>Mark</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>Otto</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>@mdo</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>2</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>Jacob</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>Thornton</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>@fat</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>3</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td colspan=\"2\">Larry the Bird</td>\r\n"); out.write("\t\t\t\t\t\t\t\t <td>@twitter</td>\r\n"); out.write("\t\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t\t\t</table>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t</div>\r\n"); out.write("\t<!-- //typography -->\r\n"); out.write("<!-- Footer -->\r\n"); out.write("\r\n"); out.write("\t\t\t<div class=\"copyright-wthree\">\r\n"); out.write("\t\t\t\t<p>Copyright &copy; 2017.Company name All rights reserved.<a target=\"_blank\" href=\"http://sc.chinaz.com/moban/\">&#x7F51;&#x9875;&#x6A21;&#x677F;</a></p>\r\n"); out.write("\t\t\t</div>\r\n"); out.write("<!-- //Footer -->\r\n"); out.write("\t<a href=\"#home\" class=\"scroll\" id=\"toTop\" style=\"display: block;\"> <span id=\"toTopHover\" style=\"opacity: 1;\"> </span></a>\r\n"); out.write("<!-- //smooth scrolling -->\r\n"); out.write("\r\n"); out.write("\t\r\n"); out.write("<script type=\"text/javascript\" src=\"js/jquery-2.1.4.min.js\"></script>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" <!-- start-smoth-scrolling -->\r\n"); out.write("<script type=\"text/javascript\" src=\"js/move-top.js\"></script>\r\n"); out.write("<script type=\"text/javascript\" src=\"js/easing.js\"></script>\r\n"); out.write("<script type=\"text/javascript\">\r\n"); out.write("\tjQuery(document).ready(function($) {\r\n"); out.write("\t\t$(\".scroll\").click(function(event){\t\t\r\n"); out.write("\t\t\tevent.preventDefault();\r\n"); out.write("\t\t\t$('html,body').animate({scrollTop:$(this.hash).offset().top},1000);\r\n"); out.write("\t\t});\r\n"); out.write("\t});\r\n"); out.write("</script>\r\n"); out.write("<!-- start-smoth-scrolling -->\r\n"); out.write("<!-- here stars scrolling icon -->\r\n"); out.write("\t<script type=\"text/javascript\">\r\n"); out.write("\t\t$(document).ready(function() {\r\n"); out.write("\t\t\t/*\r\n"); out.write("\t\t\t\tvar defaults = {\r\n"); out.write("\t\t\t\tcontainerID: 'toTop', // fading element id\r\n"); out.write("\t\t\t\tcontainerHoverID: 'toTopHover', // fading element hover id\r\n"); out.write("\t\t\t\tscrollSpeed: 1200,\r\n"); out.write("\t\t\t\teasingType: 'linear' \r\n"); out.write("\t\t\t\t};\r\n"); out.write("\t\t\t*/\r\n"); out.write("\t\t\t\t\t\t\t\t\r\n"); out.write("\t\t\t$().UItoTop({ easingType: 'easeOutQuart' });\r\n"); out.write("\t\t\t\t\t\t\t\t\r\n"); out.write("\t\t\t});\r\n"); out.write("\t</script>\r\n"); out.write("<!-- //here ends scrolling icon -->\r\n"); out.write("\t\t\r\n"); out.write("<!--js for bootstrap working-->\r\n"); out.write("\t<script src=\"js/bootstrap.js\"></script>\r\n"); out.write("<!-- //for bootstrap working -->\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("<!-- script-for-menu -->\r\n"); out.write("\t\t\t\t\t<script>\t\t\t\t\t\r\n"); out.write("\t\t\t\t\t\t$(\"span.menu\").click(function(){\r\n"); out.write("\t\t\t\t\t\t\t$(\".top-nav ul\").slideToggle(\"slow\" , function(){\r\n"); out.write("\t\t\t\t\t\t\t});\r\n"); out.write("\t\t\t\t\t\t});\r\n"); out.write("\t\t\t\t\t</script>\r\n"); out.write("\t\t\t\t\t<!-- script-for-menu -->\r\n"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
d51af4ec4cc2fdf32f2622cae41a851e489d1b4f
[ "Markdown", "Java" ]
2
Markdown
heartqiuchao/SSMMJ
21046fea0123d87cfddb36b0d4271a44b4727634
3e256985263532e77ec0539ee57deb2bf1abaab7
refs/heads/main
<file_sep>"use strict"; /** * using watch mode * tsc index.ts -w * tsc index.ts --watch * when you would like to stop, Ctrl + c * * compile all files * tsc --init * this command generate tsconfig.json */ <file_sep>var priceA = { unit: 'JPY', amount: 1000 }; var priceB = { unit: 'USD', amount: 10 }; <file_sep>const Person = function (name) { this.name = name; return this; }; const kanae = Person.call({ gender: "f" }, "Kanae"); //{gender:'f'}をthisとして渡す console.log(kanae); //{gender:'f',name:'Kanae'} /** * thisの中身4つのパターン * 1. new 演算子をつけて呼び出したとき: 新規生成されるオブジェクト * 2. メソッドとして実行されたとき: その所属するオブジェクト * 3. 1・2 以外の関数[非 Strict モード]: グローバルオブジェクト * 4. 1・2 以外の関数[Strict モード]:undefined * */ // 1. new 演算子をつけて呼び出したとき: 新規生成されるオブジェクト // new演算子は const dump = function () { console.log("`this` is", this); }; const obj = new dump(); // `this` is dump {} console.log(obj); // dump {} console.log(dump.prototype); // dump {} console.log(obj !== dump.prototype); // true objはdumpとアドレスを共有しない新規のオブジェクト // 2. メソッドとして実行されたとき: その所属するオブジェクト const foo = { name: "Foo Object", dump() { console.log(this); }, }; foo.dump(); //{name:'FooObject',dump:[Function:dump]} // 3. 1・2 以外の関数[非 Strict モード]: グローバルオブジェクト //dump(); /** { name: 'Foo Object', dump: [Function: dump] } `this` is <ref *1> Object [global] { global: [Circular *1], clearInterval: [Function: clearInterval], clearTimeout: [Function: clearTimeout], setInterval: [Function: setInterval], setTimeout: [Function: setTimeout] { [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)] }, queueMicrotask: [Function: queueMicrotask], clearImmediate: [Function: clearImmediate], setImmediate: [Function: setImmediate] { [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)] } } * */ // 4. 1・2 以外の関数[Strict モード]:undefined const Person2 = function (name) { this.name = name; return this; }; console.log(Person2('somebody')); // グローバルオブジェクトにnameプロパティが追加されてしまう const Person3 = function (name) { 'use strict'; this.name = name; return this; }; console.log(Person3('somebody')); <file_sep>/** * カリー化 * 複数の引数をとる関数で * ・引数が「元の関数の最初の引数」 * ・戻り地が「元の関数の残りの引数を取り、それを使って結果を返す関数」 * にすること * */ // Pre-curried { const multiply = (n, m) => n * m; console.log(multiply(2, 4)); // 8 } // Curried // Pre-curriedでn, m2つの引数をとってn * mしていたものを // mを引数にとって、n * mする関数にした { const withMultiple = (n) => { return (m) => n * m; }; console.log(withMultiple(2)(4)); // 8 } // Curried with double arrow // 上のものがreturnのみなので、ブロックごと省略 { const withMultiple = (n) => (m) => n * m; console.log(withMultiple(2)(4)); // 8 } <file_sep>const arr = [1,2,3,4,5,6,7,8,9]; // 対象の配列の要素ひとつひとつを任意に加工した新しい配列を返す console.log(arr.map((n) => n * 2)); // 与えた条件に適合する要素だけを抽出した新しい配列を返す console.log(arr.filter((n) => n % 3 === 0)); // 与えた条件に適合した最初の要素を返す。見つからなかった場合は undefind を返す console.log(arr.find((n) => n > 4)); // 与えた条件に適合した最初の要素のインデックスを返す。見つからなかった場 合は -1 を返す console.log(arr.findIndex((n) => n > 4)); // 「与えた条件をすべての要素が満たすか」を真偽値で返す console.log(arr.every((n) => n !== 0)); // 「与えた条件を満たす要素がひとつでもあるか」を真偽値で返す console.log(arr.some((n) => n >= 10)); const arr2 = [1,2,3,4,5]; // 第2引数にはarrの各要素が順番に入る。第1引数には前回の関数の実行結果が入る console.log(arr2.reduce((n, m) => n + m)); console.log(arr2.sort((n, m) => n > m ? -1 : 1)); <file_sep>class Person { // default is public // name: string // private age: number // readonly readonly id: number = 32; // omit initilize process constructor(public readonly name: string, private age: number) { // readonly can overwrite in constructor. this.id = 45; } greeting(this: Person) { console.log(`Hello! My name is ${this.name}. I'm ${this.age} years old.`); } incrementAge() { this.age += 1; // not overwrite readonly //this.id = 0; } } const steve = new Person('Steve', 32); steve.greeting(); steve.incrementAge(); steve.greeting(); console.log(steve.id); <file_sep>const greeter = (target) => { const sayHello = () => { console.log(`Hi, ${target}!`); }; return sayHello; }; const greet = greeter("Jun"); greet(); //Hi,Jun! // 不要な代入を省く const greeter2 = (target) => { return () => { console.log(`Hi, ${target}`); }; } // returnのみなのでブロックごと省略 const greeter3 = (target) => () => console.log(`Hi, ${target}`); <file_sep>type A2 = { foo: number }; type B2 = { bar: string }; type C2 = { foo?: number; baz: boolean; }; type AnB = A2 & B2; type AnC = A2 & C2; type CnAorB = C2 & (A2 | B2); <file_sep>// Nullish Coalescing と Optional Chaining const users = [ { name: "<NAME>", address: { town: "Maple Town", }, }, { name: "<NAME>", address: {}, }, null, ]; for (u of users) { const user = u ?? { name: "(Somebody)" }; /** * nullish-coalescing -> ?? * 左辺がnullまたはundefineのときだけ右辺が評価される * OR演算子でも似たようなことができるが、orの場合は0や空文字もスルーされてしまうので、 * より厳密なこちらを使うほうがよい * * Optional Chaining -> ?. * 指定したキーのプロパティ・メソッドが存在しない場合、undefinedを返す(TypeErrorにならず、if文での判定を減らせる) **/ const town = user?.address?.town ?? "(Somewhere)"; console.log(`${user.name} lives in ${town}`); } <file_sep>var Square = /** @class */ (function () { function Square(side) { var _this = this; this.name = 'square'; this.getArea = function () { return new Rectangle(_this.side, _this.side).getArea(); }; this.side = side; } return Square; }()); <file_sep>// 以下はshallow copyのため、プロパティ値がさらに配列・オブジェクトだった場合はそれらの値まではコピーしてくれない const original = { a:1, b:2, c:3}; const copy = {...original}; console.log(original); // { a: 1, b: 2, c: 3 } console.log(copy === original); // false const assigned = {...original, ...{c:10, d:50}, d: 100}; console.log(assigned); // { a: 1, b: 2, c: 10, d: 100 } console.log(original); // { a: 1, b: 2, c: 3 } <file_sep>// function declaration statement { function add(n, m) { return n + m; } console.log(add(2, 4)); } // function keyword expression { var add_1 = function (n, m) { return n + m; }; console.log(add_1(5, 7)); } // arrow function expression { var add_2 = function (n, m) { return n + m; }; var hello = function () { console.log('Hello!'); }; console.log(add_2(8, 1)); hello(); } <file_sep>// スプレッド構文 // レストパラメータと同じ const arr1 = ['A', 'B', 'C']; const arr2 = [...arr1, 'D', 'E']; console.log(arr2); // [ 'A', 'B', 'C', 'D', 'E' ] const obj1={a:1,b:2,c:3,d:4}; const obj2 = { ...obj1, d: 99, e: 5 }; console.log(obj2); //{a:1,b:2,c:4,d:99,e:5} <file_sep>type A = { foo: number; bar?: string; }; type B = { foo: string }; type C = { bar: string }; type D = { baz: boolean }; type AorB = A | B; //{foo:number|string;bar?:string} type AorC = A | C; //{foo:number;bar?:string}or{bar:string} type AorD = A | D; //{foo:number;bar?:string}or{baz:boolean} <file_sep>"use strict"; // 型 // 型注釈つき var hello = 'hello'; var double = "hello"; var back = "hello"; var hasValue = true; var count = 10; var negative = -0.12; console.log(hello); // 型推論 var hello2 = 'hello2'; var hasValue2 = true; var count2 = 10; // 型推論が効かない場合もある // オブジェクト // person: object, person:{} はだいたい同じ意味。 // 上記は省略して型推論でよい var person = { name: 'Jack', age: 21 }; console.log(person.name); // 配列に型 var fruits = ['apple', 'banana', 'orange']; // Tuple型 // 複数種類の型をひとかたまりで扱う // 型注釈が必要になる var book = ['business', 1280, true]; // pushは可能。参照時にはエラー book.push(21); // Enum var CoffeeSize; (function (CoffeeSize) { CoffeeSize["SHORT"] = "SHORT"; CoffeeSize["TALL"] = "TALL"; CoffeeSize["GRANDE"] = "GRANDE"; CoffeeSize["VENTI"] = "VENTI"; })(CoffeeSize || (CoffeeSize = {})); // 以下のようにも書ける。それぞれ0からの連番が入る var NewCoffeeSize; (function (NewCoffeeSize) { NewCoffeeSize[NewCoffeeSize["SHORT"] = 0] = "SHORT"; NewCoffeeSize[NewCoffeeSize["TALL"] = 1] = "TALL"; NewCoffeeSize[NewCoffeeSize["GRANDE"] = 2] = "GRANDE"; NewCoffeeSize[NewCoffeeSize["VENTI"] = 3] = "VENTI"; })(NewCoffeeSize || (NewCoffeeSize = {})); console.log(CoffeeSize.GRANDE); // -> GRANDE console.log(NewCoffeeSize.GRANDE); // -> 2 var coffee = { hot: true, size: CoffeeSize.TALL }; coffee.size = CoffeeSize.SHORT; // any // どんな型にもなる。基本使わないほうがよい。 var anything = true; anything = 'hello'; /** * Union * 複数の型のうちどれか * Tuppleは型の組み合わせ * Unionはor? * 2つ以上の型もできる */ var unionType = 10; // 数値を入れている場合はnumberのメソッドが使える unionType.toString(); console.log(unionType); // stringを入れるとstringのメソッドが使える unionType = 'test'; unionType = unionType.toUpperCase(); console.log(unionType); var unionTypeArray = [30, 'array']; console.log(unionTypeArray[0]); /** * Literal Type * TypeScriptはletではstring, constではLiteralを採用する * 型としてリテラルを使える */ var clothSize = 'large'; var cloth = { color: 'white', size: clothSize }; var clothSize2 = 'large'; /** * 関数に型をつける * 引数、戻り値に型をつける * 引数は型注釈をつけないと、anyになってしまうので必ずつけたほうがよい */ function add(num1, num2) { return num1 + num2; } // 戻り値なし(returnなし)はvoid function sayHello() { console.log('Hello'); } /** * 関数型を使う * 型注釈か、無名関数のどちらかに型注釈があればよい */ var anotheradd = add; // アロー関数 var doubleNumber = function (num) { return num * 2; }; // コールバック関数 function doubleAndHandle(num, cb) { var doubleNum = cb(num * 2); console.log(doubleNum); } doubleAndHandle(10, function (doubleNum) { return doubleNum; }); /** * unknown型 * anyと同じくなんでも代入できるが、使うときにtype ofで型をチェックする必要がある */ var unknownInput; var anyInput; var text; unknownInput = 'hello!'; unknownInput = 21; unknownInput = true; if (typeof unknownInput === 'string') { text = unknownInput; } /** * never型 * 戻り値を絶対に返さないことを表す */ function error(message) { throw new Error(message); } console.log(error('This is an Error!')); <file_sep>// 型 // 型注釈つき let hello: string = 'hello'; let double: string = "hello"; let back: string = `hello`; let hasValue: boolean = true; let count: number = 10; let negative: number = -0.12; console.log(hello); // 型推論 let hello2 = 'hello2'; let hasValue2 = true; let count2 = 10; // 型推論が効かない場合もある // オブジェクト // person: object, person:{} はだいたい同じ意味。 // 上記は省略して型推論でよい const person: { name: string; age: number; } = { name: 'Jack', age: 21 } console.log(person.name); // 配列に型 const fruits: string[] = ['apple','banana','orange']; // Tuple型 // 複数種類の型をひとかたまりで扱う // 型注釈が必要になる const book: [string, number, boolean] = ['business', 1280, true]; // pushは可能。参照時にはエラー book.push(21) // Enum enum CoffeeSize { SHORT = 'SHORT', TALL = 'TALL', GRANDE = 'GRANDE', VENTI = 'VENTI' } // 以下のようにも書ける。それぞれ0からの連番が入る enum NewCoffeeSize { SHORT, TALL, GRANDE, VENTI } console.log(CoffeeSize.GRANDE) // -> GRANDE console.log(NewCoffeeSize.GRANDE) // -> 2 const coffee = { hot: true, size: CoffeeSize.TALL } coffee.size = CoffeeSize.SHORT; // any // どんな型にもなる。基本使わないほうがよい。 let anything: any = true; anything = 'hello'; /** * Union * 複数の型のうちどれか * Tuppleは型の組み合わせ * Unionはor? * 2つ以上の型もできる */ let unionType: number | string = 10; // 数値を入れている場合はnumberのメソッドが使える unionType.toString(); console.log(unionType); // stringを入れるとstringのメソッドが使える unionType = 'test' unionType = unionType.toUpperCase(); console.log(unionType); let unionTypeArray: (string | number)[] = [30, 'array']; console.log(unionTypeArray[0]); /** * Literal Type * TypeScriptはletではstring, constではLiteralを採用する * 型としてリテラルを使える */ let clothSize: 'small' | 'medium' | 'large' = 'large'; const cloth: { color: string, size: 'small' | 'medium' | 'large' } = { color: 'white', size: clothSize } /** * 型エイリアス * 型を変数のように扱える */ type ClothSize = 'small' | 'medium' | 'large'; let clothSize2: ClothSize = 'large'; /** * 関数に型をつける * 引数、戻り値に型をつける * 引数は型注釈をつけないと、anyになってしまうので必ずつけたほうがよい */ function add(num1:number, num2:number):number { return num1 + num2; } // 戻り値なし(returnなし)はvoid function sayHello(): void { console.log('Hello'); } /** * 関数型を使う * 型注釈か、無名関数のどちらかに型注釈があればよい */ const anotheradd: (n1: number, n2: number) => number = add; // アロー関数 const doubleNumber: (num: number) => number = num => num * 2; // コールバック関数 function doubleAndHandle(num: number, cb: (num: number) => number): void { const doubleNum = cb(num * 2); console.log(doubleNum); } doubleAndHandle(10, doubleNum => { return doubleNum; }) /** * unknown型 * anyと同じくなんでも代入できるが、使うときにtype ofで型をチェックする必要がある */ let unknownInput: unknown; let anyInput: any; let text: string; unknownInput = 'hello!'; unknownInput = 21; unknownInput = true; if (typeof unknownInput === 'string') { text = unknownInput; } /** * never型 * 戻り値を絶対に返さないことを表す */ function error(message: string): never { throw new Error(message); } console.log(error('This is an Error!')); <file_sep>const withMultiple = (n) => (m) => n * m; console.log(withMultiple(3)(5)) // 15 /** * 関数の部分適用 * カリー化されたことで、3倍する関数をつくっている * 一部を固定にして関数を使い回せる * withMultiple(3)(x)よりも、3倍部分を部分適用して、withMultiple(x)とすれば無駄がない */ const triple = withMultiple(3); console.log(triple(4)); // 12 <file_sep>// callable object type { var add = function (n, m) { return n + m; }; var subtract = function (n, m) { return n - m; }; console.log(add(1, 2)); console.log(subtract(7, 2)); } // in-line { var add = function (n, m) { return n + m; }; var subtract = function (n, m) { return n - m; }; console.log(add(3, 7)); console.log(subtract(10, 8)); } <file_sep>var Point = /** @class */ (function () { function Point() { this.x = 0; this.y = 0; } return Point; }()); var pointA = new Point(); var pointB = { x: 2, y: 4 }; var pointC = { x: 5, y: 5, z: 10 }; <file_sep>// 分割代入 const [n, m] = [1, 4]; console.log(n, m); // 1 4 const obj = {name: 'Kanae', age:24}; const { name, age } = obj; console.log(name, age); // kanae 24 <file_sep>/** * using watch mode * tsc index.ts -w * tsc index.ts --watch * when you would like to stop, Ctrl + c * * compile all files * tsc --init * this command generate tsconfig.json * * select compile file * add 'include', 'exclude', 'files' in tsconfig.json * * ex. * "exclude": [ * "compile-section.ts", * "*.spec.ts" * ] * * note: * "compile-section.ts" apply to root directory. * you'd like to apply to any directory, use "**" * * default: "node_modules" is excluded. * ※ writing new exclude settings, you have to add "node_modules", because default setting is overwrote * * files * * target * specify ECMAScript target version. * * lib * Specify library files to be included in the compilation * * sourceMap * Debbuging TypeScript in Browser, sourceMap true */ <file_sep>const user = { id: 3, name: "<NAME>", username: "bobby", email: "<EMAIL>", }; console.log(Object.keys(user)); // [ 'id', 'name', 'username', 'email' ] console.log(Object.values(user)); // [ 3, '<NAME>', 'bobby', '<EMAIL>' ] console.log(Object.entries(user)); //[ // ['id',3], // ['name','BobbyKumanov'], // ['username','bobby'], // ['email','<EMAIL>'] //] <file_sep>var date = new Date('2020-09-01T12:00+0900'); var payA = { unit: 'JPY', amount: 10000, date: date }; var payB = { unit: 'USD', amount: 100, date: date }; console.log(payA); console.log(payB); <file_sep>const message: string = 'compile-test'; console.log(message); <file_sep>// スプレッド構文と分割代入の組み合わせ const user = { id: 1, name: '<NAME>', email: '<EMAIL>', age: 8, }; const {id, ...withoutId} = user; console.log(id, withoutId);
717e7df85c4e6d2a3d9bb9608213b5de1a827d44
[ "JavaScript", "TypeScript" ]
25
JavaScript
captain-blue210/typescript-lesson
bd8dda906f94a9a872ef622996515d0eabf2e5fd
fd9ff88d0b63e1e1fcc9b1228a0219fd7b4a4d2f
refs/heads/master
<file_sep>package org.universitas.parent.domain; import java.util.List; public class Content { List<Topic> topicList; private class Topic { String subject; /** * Books, papers, etc. Bibliography to cover the topic. */ String description; } public List<Topic> getTopicList() { return topicList; } public void setTopicList(List<Topic> topicList) { this.topicList = topicList; } } <file_sep>package org.universitas.parent.domain; import java.util.Set; public class City extends LocationImpl { Set<String> postalCodes; public void setPostalCodes(Set<String> postalCodes) { this.postalCodes = postalCodes; } @Override public Set<String> getPostalCodes() { // TODO Auto-generated method stub return super.getPostalCodes(); } } <file_sep>package org.universitas.parent.domain; public class Adress { String street; String number; City city; State state; Country country; public State getState() { return state; } public void setState(State state) { this.state = state; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public void setCity(City city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Location getCity() { return city; } } <file_sep>package org.universitas.parent.domain; public class Phone { String areaCode; String internationalCode; String phoneNumber; public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getInternationalCode() { return internationalCode; } public void setInternationalCode(String internationalCode) { this.internationalCode = internationalCode; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } } <file_sep>personal ======== Repository of my personal projects. <file_sep>package org.universitas.parent.domain; import java.util.Set; public class Subject { String name; String description; Content content; /** * Diferent names of the same subject. */ Set<String> otherNames; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } public Set<String> getOtherNames() { return otherNames; } public void setOtherNames(Set<String> otherNames) { this.otherNames = otherNames; } } <file_sep>package org.universitas.parent.domain; import java.util.Set; public class State extends LocationImpl { Set<City> cities; public void setCities(Set<City> cities) { this.cities = cities; } @Override public Set<City> getCities() { // TODO Auto-generated method stub return super.getCities(); } } <file_sep>package org.universitas.parent.domain; import java.util.Set; public interface Location { Set<State> getStates(); Set<String> getPostalCodes(); Set<City> getCities(); Country getCountry(); } <file_sep>package org.universitas.parent.domain; import java.util.Set; import javax.persistence.Entity; import javax.persistence.ManyToMany; @Entity public class Career { static enum FIELD_OF_STUDY {HUMANITIES,SOCIAL_SCIENCES,NATURAL_SCIENCES,FORMAL_SCIENCES}; String name; /** * Diferent names of the same career. */ Set<String> otherNames; String description; FIELD_OF_STUDY fieldOfStudy; @ManyToMany(targetEntity=University.class, mappedBy="careerList") Set<University> universities; public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<String> getOtherNames() { return otherNames; } public void setOtherNames(Set<String> otherNames) { this.otherNames = otherNames; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public FIELD_OF_STUDY getFieldOfStudy() { return fieldOfStudy; } public void setFieldOfStudy(FIELD_OF_STUDY fieldOfStudy) { this.fieldOfStudy = fieldOfStudy; } public Set<University> getUniversities() { return universities; } public void setUniversities(Set<University> universities) { this.universities = universities; } }
d5aab37817bb0bfb3cd3b9998a2c82d86c2990e9
[ "Markdown", "Java" ]
9
Java
YerbaMate/personal
203dade5b00bebcd6ad28e0122ac5397d54f9ce4
52b30b2679f5e651eef5dc5ba9994bf9be9d611b