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>mbloomfi/piston-rocket-parts<file_sep>/public/js/app.js var app = angular.module('pistonRocket', ['ui.router']); console.log("I'm alive"); app.config(function($stateProvider, $urlRouterProvider) { // // For any unmatched url, redirect to /state1 $urlRouterProvider.otherwise("/"); // // Now set up the states $stateProvider .state('main', { url: "/", templateUrl: "views/main.html", controller: "mainCtrl" }) }); <file_sep>/public/js/ctrl/mainCtrl.js app.controller('mainCtrl', function($scope, $http) { $scope.name = "I am the main Controller"; $scope.makes = [ "Chevrolet", "Toyota", "Ford" ] $scope.models = [ "Impala", "Tacoma", "Escort" ] $scope.years = [ "2001", "2002", "2003" ] $scope.getCarParts = function(data) { $scope.videoIds = []; console.log(data); console.log("Getting some parts for a " + data.year + " " + data.make + " " + data.model); $http.get("https://www.googleapis.com/youtube/v3/search?part=snippet&q=2002+toyota+tacoma+water+pump&key=<KEY>") .then(function(data) { console.log(data); $scope.videos = data.data.items; for (var i=0; i<$scope.videos.length; i++) { $scope.videos[i].videoUrl = "https://www.youtube.com/embed/" + $scope.videos[i].id.videoId; } }) } });
ec0da25aa65ec39bf36718bde12072c231c0d95f
[ "JavaScript" ]
2
JavaScript
mbloomfi/piston-rocket-parts
0f82a80fb80594a3ab0ddd4a480dea24d274d017
416ab0d39fb7fe2270e7b352d989dd6d352941d9
refs/heads/master
<file_sep>INSERT INTO TBL_USERS (first_name, last_name) VALUES ('Vikram', 'Deshmukh'), ('Parth', 'Deshmukh');<file_sep>package com.magicsoft.usersservice.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.magicsoft.usersservice.model.Users; import com.magicsoft.usersservice.services.UsersService; @CrossOrigin(origins = "http://localhost:4200") @RestController public class UsersController { @Autowired private UsersService usersService = null; @RequestMapping(value = "/users" , method = RequestMethod.POST , produces = "application/json") public Users createUser( @RequestBody Users user) { return usersService.saveOrUpdateUser(user); } @RequestMapping(value = "/users", method = RequestMethod.GET, produces = "application/json") public List<Users> getUsers() { List<Users> list = usersService.getUsers(); System.out.println(" List "+list); return list; } } <file_sep>package com.magicsoft.usersservice.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.magicsoft.usersservice.model.Users; import com.magicsoft.usersservice.repository.UsersRepository; @Service public class UsersService { @Autowired private UsersRepository usersRepository = null; public Users saveOrUpdateUser( Users user) { return usersRepository.save(user); } public List<Users> getUsers() { return usersRepository.findAll(); } } <file_sep>package com.magicsoft.usersservice.repository; import com.magicsoft.usersservice.model.Users; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UsersRepository extends JpaRepository<Users, String>{ } <file_sep>DROP TABLE IF EXISTS TBL_EMPLOYEES; CREATE TABLE TBL_USERS ( first_name VARCHAR(250) NOT NULL, last_name VARCHAR(250) NOT NULL );
8451620d656daa665e7679d547df283d699571e0
[ "Java", "SQL" ]
5
SQL
virkam/FullStackAppMagicSoft
d5526572fa052a53866e4dc00a136d725a91b366
d5c95a8ae97549187517a26ab9a01927e69ff360
refs/heads/main
<file_sep>module.exports = { upload: { breakpoints: { xxl: 1920, xl: 1440, lg: 1024, md: 800, sm: 600 } } }<file_sep>module.exports = { jwtSecret: process.env.JWT_SECRET || '<KEY>' };
954f5ac8c6e2965dea83487cbd1704580860da21
[ "JavaScript" ]
2
JavaScript
dijitaq/strapi
a9f4adcb4ff5ba8decb9c85d04f9982135c9b639
58a884161593daf2d43c981d766680056add3a7f
refs/heads/main
<repo_name>brank12345/GithubSearch<file_sep>/app/src/main/java/com/example/githubsearch/utils/NetworkUtils.kt package com.example.githubsearch.utils import com.example.githubsearch.datamodel.NetworkErrorException import com.example.githubsearch.datamodel.Result import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext suspend fun <T : Any> safeApiCall(call: suspend () -> Result<T>): Result<T> { return try { withContext(Dispatchers.IO) { call() } } catch (e: Exception) { e.printStackTrace() // An exception was thrown when calling the API so we're converting this to NetworkErrorException Result.Error(NetworkErrorException) } }<file_sep>/app/src/main/java/com/example/githubsearch/api/Api.kt package com.example.githubsearch.api import com.example.githubsearch.datamodel.UserList import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query interface Api { @GET("search/users") suspend fun getSearchUsers( @Query("q") q: String, @Query("page") page: Int, ): Response<UserList> companion object { fun create() : Api { return Retrofit.Builder() .baseUrl("https://api.github.com/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(Api::class.java) } } }<file_sep>/app/src/main/java/com/example/githubsearch/datamodel/Result.kt package com.example.githubsearch.datamodel sealed class Result<out R> { data class Success<out T>(val data: T) : Result<T>() data class Error(val exception: Exception) : Result<Nothing>() override fun toString(): String { return when (this) { is Success<*> -> "Success[data=$data]" is Error -> "Error[exception=$exception]" } } } class ServerErrorException(val errorCode: String?, message: String?): Exception(message) { override fun toString() = "ServerErrorException(errorCode=$errorCode, message=$message)" } object NetworkErrorException: Exception()<file_sep>/app/src/main/java/com/example/githubsearch/MainRemoteDataSource.kt package com.example.githubsearch import com.example.githubsearch.api.Api import com.example.githubsearch.utils.getResult import com.example.githubsearch.utils.safeApiCall class MainRemoteDataSource { private val api get() = Api.create() suspend fun getSearchUsers(searchKey: String, currentPage: Int) = safeApiCall { api.getSearchUsers(searchKey, currentPage).getResult() } }<file_sep>/app/src/main/java/com/example/githubsearch/MainAdapter.kt package com.example.githubsearch import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.example.githubsearch.base.SingleLiveEvent import com.example.githubsearch.utils.inflate class MainAdapter( private val needToLoadNextEvent : SingleLiveEvent<Void> ) : RecyclerView.Adapter<MainViewHolder<*>>() { private var dataList = listOf<SearchUiModel>() fun setData(userList: List<SearchUiModel>) { val diffCallback = SearchDiffCallback(dataList, userList) val result = DiffUtil.calculateDiff(diffCallback) result.dispatchUpdatesTo(this) dataList = userList } override fun getItemViewType(position: Int): Int { return when(dataList[position]) { is SearchUiModel.UserUiModel -> USER_VIEW_TYPE is SearchUiModel.LoadingUiModel -> LOADING_VIEW_TYPE } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder<*> { return when(viewType) { USER_VIEW_TYPE -> UserViewHolder(parent.inflate(R.layout.item_user)) LOADING_VIEW_TYPE -> LoadingViewHolder(parent.inflate(R.layout.item_loading)) else -> LoadingViewHolder(parent.inflate(R.layout.item_loading)) } } override fun onBindViewHolder(holder: MainViewHolder<*>, position: Int) { when(holder) { is UserViewHolder -> holder.onBind(dataList[position] as SearchUiModel.UserUiModel) } } override fun getItemCount(): Int { return dataList.size } override fun onViewAttachedToWindow(holder: MainViewHolder<*>) { super.onViewAttachedToWindow(holder) if (holder.bindingAdapterPosition == itemCount - LOAD_NEXT_BUFFER) needToLoadNextEvent.call() } inner class SearchDiffCallback( private val oldList: List<SearchUiModel>, private val newList: List<SearchUiModel> ) : DiffUtil.Callback() { override fun getOldListSize() = oldList.size override fun getNewListSize() = newList.size override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = oldList[oldItemPosition] val newItem = newList[newItemPosition] return (oldItem is SearchUiModel.UserUiModel && newItem is SearchUiModel.UserUiModel) || (oldItem is SearchUiModel.LoadingUiModel && newItem is SearchUiModel.LoadingUiModel) } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = oldList[oldItemPosition] val newItem = newList[newItemPosition] return when { oldItem is SearchUiModel.UserUiModel && newItem is SearchUiModel.UserUiModel -> { oldItem.user == newItem.user } oldItem is SearchUiModel.LoadingUiModel && newItem is SearchUiModel.LoadingUiModel -> true else -> false } } } companion object { private const val USER_VIEW_TYPE = 1 private const val LOADING_VIEW_TYPE = 2 private const val LOAD_NEXT_BUFFER = 10 } }<file_sep>/app/src/main/java/com/example/githubsearch/utils/ResultUtils.kt package com.example.githubsearch.utils import retrofit2.Response import com.example.githubsearch.datamodel.Result import com.example.githubsearch.datamodel.ServerErrorException import com.google.gson.Gson import com.google.gson.annotations.SerializedName fun <T : Any> Response<T>.getResult(): Result<T> { return if (isSuccessful) { val body = body() if (body != null) { Result.Success(body) } else { Result.Error(ServerErrorException(code().toString(), "Unexpected response body: null")) } } else { val error = Gson().fromJson(errorBody()?.string(), ErrorResponse::class.java) Result.Error(ServerErrorException(code().toString(), error?.message)) } } data class ErrorResponse( @SerializedName("message") val message: String )<file_sep>/app/src/main/java/com/example/githubsearch/base/BaseLoadingViewModel.kt package com.example.githubsearch.base import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.example.githubsearch.datamodel.NetworkErrorException import com.example.githubsearch.datamodel.Result import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch abstract class BaseLoadingViewModel(application: Application) : AndroidViewModel(application) { val errorMsgEvent = SingleLiveEvent<String>() val noInternetEvent = SingleLiveEvent<Void>() val isLoading = SingleLiveEvent<Boolean>() protected fun sendApi(apiAction: suspend CoroutineScope.() -> Unit) { viewModelScope.launch { isLoading.postValue(true) apiAction() isLoading.postValue(false) } } protected fun <T> Result<T>.handleResult(successAction: (T) -> Unit = {}) { when (this) { is Result.Success -> { successAction(data) } is Result.Error -> { handleError() } } } protected fun List<Result<Any>>.handleResults(successAction: () -> Unit) { when { all { it is Result.Success } -> successAction() else -> (find { it is Result.Error } as? Result.Error)?.handleError() } } protected open fun Result.Error.handleError() { when(exception) { is NetworkErrorException -> noInternetEvent.call() else -> errorMsgEvent.postValue(exception.message) } } }<file_sep>/app/src/main/java/com/example/githubsearch/utils/ImageUtils.kt package com.example.githubsearch.utils import android.widget.ImageView import com.example.githubsearch.R import com.squareup.picasso.Picasso fun ImageView.setAvatarUrl(imageUrl: String) { if (imageUrl.isNotEmpty()) { Picasso.get() .load(imageUrl) .fit() .centerCrop() .transform(CircleTransform()) .placeholder(R.mipmap.ic_launcher_round) .into(this) } else { setImageResource(R.mipmap.ic_launcher_round) } }<file_sep>/app/src/main/java/com/example/githubsearch/ErrorDialog.kt package com.example.githubsearch import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.example.githubsearch.databinding.LayoutErrorDialogBinding class ErrorDialog( private val description : String, private val positiveAction : (() -> Unit)? = null ) : DialogFragment() { private lateinit var binding: LayoutErrorDialogBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.TransparentDialog) isCancelable = false } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = LayoutErrorDialogBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.description.text = description binding.positiveButton.setOnClickListener { positiveAction?.invoke() dismiss() } binding.cancelButton.setOnClickListener { dismiss() } } }<file_sep>/app/src/main/java/com/example/githubsearch/utils/AppCompatActivityUtils.kt package com.example.githubsearch.utils import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.LiveData import androidx.lifecycle.Observer inline fun <T> AppCompatActivity.observe(data: LiveData<T>, crossinline action: (T?) -> Unit) { data.observe(this, Observer { action(it) }) }<file_sep>/app/src/main/java/com/example/githubsearch/MainActivity.kt package com.example.githubsearch import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.view.inputmethod.EditorInfo import androidx.core.widget.doOnTextChanged import com.example.githubsearch.databinding.ActivityMainBinding import com.example.githubsearch.utils.closeKeyboard import com.example.githubsearch.utils.getViewModel import com.example.githubsearch.utils.observe class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val viewModel by lazy { getViewModel<MainViewModel>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) initView() viewModel.observeData() } private fun initView() { with(binding) { editor.setOnEditorActionListener { textView, actionId, keyEvent -> when (actionId) { EditorInfo.IME_ACTION_SEARCH -> { closeKeyboard(this@MainActivity, binding.root) viewModel.searchUsers() } } return@setOnEditorActionListener false } editor.doOnTextChanged { text, start, before, count -> text?.also { viewModel.searchKey = it.toString() } } recyclerView.adapter = MainAdapter(viewModel.needToLoadNextEvent) } } private fun MainViewModel.observeData() { observe(useListLiveData) { it ?: return@observe (binding.recyclerView.adapter as MainAdapter?)?.setData(it) } observe(needToLoadNextEvent) { viewModel.loadNextPage() } observe(noInternetEvent) { openErrorDialog("Internet connect fail!!") } observe(errorMsgEvent) { it ?: return@observe openErrorDialog(it) } observe(isLoading) { binding.progressBar.visibility = if (it==true) View.VISIBLE else View.GONE } } private fun openErrorDialog(description: String) { supportFragmentManager.beginTransaction().add( ErrorDialog(description) { viewModel.searchUsers() }, null ).commitAllowingStateLoss() } }<file_sep>/app/src/main/java/com/example/githubsearch/MainViewModel.kt package com.example.githubsearch import android.app.Application import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.githubsearch.base.BaseLoadingViewModel import com.example.githubsearch.base.SingleLiveEvent import com.example.githubsearch.datamodel.User import kotlinx.coroutines.launch class MainViewModel(application: Application) : BaseLoadingViewModel(application) { private val remoteDataSource = MainRemoteDataSource() private var currentPage = 1 var searchKey = "" val needToLoadNextEvent = SingleLiveEvent<Void>() val useListLiveData = MutableLiveData<List<SearchUiModel>>() fun searchUsers() { useListLiveData.value = listOf() currentPage = 1 sendApi { getSearchUsers().handleResult { data -> useListLiveData.value = mutableListOf<SearchUiModel>().apply { addAll(data.users.map { user -> SearchUiModel.UserUiModel(user) }) if (size < data.totalCount) add(SearchUiModel.LoadingUiModel) } } } } fun loadNextPage() { currentPage++ viewModelScope.launch { getSearchUsers().handleResult { data -> useListLiveData.value = mutableListOf<SearchUiModel>().apply { useListLiveData.value?.also { addAll(it.subList(0, it.size-1)) } addAll(data.users.map { user -> SearchUiModel.UserUiModel(user) }) if (size < data.totalCount) add(SearchUiModel.LoadingUiModel) } } } } private suspend fun getSearchUsers() = remoteDataSource.getSearchUsers(searchKey, currentPage) } sealed class SearchUiModel { class UserUiModel(val user: User) : SearchUiModel() object LoadingUiModel : SearchUiModel() }<file_sep>/app/src/main/java/com/example/githubsearch/MainViewHolder.kt package com.example.githubsearch import android.view.View import androidx.recyclerview.widget.RecyclerView import com.example.githubsearch.utils.setAvatarUrl import kotlinx.android.synthetic.main.item_user.view.* abstract class MainViewHolder<T: SearchUiModel>(view: View) : RecyclerView.ViewHolder(view) { abstract fun onBind(data: T) } class UserViewHolder(view: View) : MainViewHolder<SearchUiModel.UserUiModel>(view) { override fun onBind(data: SearchUiModel.UserUiModel) { with(itemView) { avatar.setAvatarUrl(data.user.avatarUrl) name.text = data.user.name } } } class LoadingViewHolder(view: View) : MainViewHolder<SearchUiModel.LoadingUiModel>(view) { override fun onBind(data: SearchUiModel.LoadingUiModel) = Unit }
dda21dc9756a3fe08ba46a961b754f6d8733331b
[ "Kotlin" ]
13
Kotlin
brank12345/GithubSearch
021548b90a7dd90b508422216804156f87b6cdd5
095948ed223668364da39dfff07858f96eb96085
refs/heads/master
<file_sep># Instructions for Ubuntu 1. Install the CUDA toolkit * sudo apt-get install nvidia-cuda-toolkit * or follow this [post](http://www.r-tutor.com/gpu-computing/cuda-installation/cuda7.5-ubuntu) for cuda 7.5 * or get the las version [here](https://developer.nvidia.com/cuda-toolkit) 2. Check your version (nvcc --version), should be at least the one required by [cutorch's CMAKELists](https://github.com/torch/cutorch/blob/master/CMakeLists.txt#L7) 3. Install packages: * luarocks install cutorch * luarocks install image * luarocks install cunn # Reference * [Deep learning with Torch](https://github.com/soumith/cvpr2015/blob/master/Deep%20Learning%20with%20Torch.ipynb) # For problems with Nvidia drivers 1. Find out the model of the graphic card: lspci | grep VGA 2. Download the driver from the [nvidia website](https://www.nvidia.com/Download/index.aspx) 3. Or, maybe follow [this answer](http://askubuntu.com/questions/672047/anyone-has-successfully-installed-cuda-7-5-on-ubuntu-14-04-3-lts-x86-64). # To visualize the images * Run the scripts with qlua instead of th. <file_sep>require 'nn' -- Constructing a network net = nn.Sequential() net:add(nn.SpatialConvolution(1,6,5,5)) -- 1 input image channel, 6 output channels, 5x5 convolution kernel net:add(nn.ReLU()) -- non-linearity net:add(nn.SpatialMaxPooling(2,2,2,2)) -- A max-pooling operation that look at 2x2 windows and finds the max net:add(nn.SpatialConvolution(6,16,5,5)) net:add(nn.ReLU()) net:add(nn.SpatialMaxPooling(2,2,2,2)) net:add(nn.View(16*5*5)) -- reshapes from a 3D tensor of 16x5x5 into a 1D tensor of 16*5*5 net:add(nn.Linear(16*5*5,120)) -- fully connected layer net:add(nn.ReLU()) net:add(nn.Linear(120,84)) net:add(nn.ReLU()) net:add(nn.Linear(84,10)) -- 10 is the number of outputs of the network net:add(nn.LogSoftMax()) -- converts the output to a log-probability. Useful for classification problems print('Lenet5\n' .. net:__tostring()) -- Forward, Backward input = torch.rand(1,32,32) output = net:forward(input) print(output) net:zeroGradParameters() -- zero the internal gradient buffers of the network gradInput = net:backward(input, torch.rand(10)) print(#gradInput) -- Loss function criterion = nn.ClassNLLCriterion() -- negative log-likelihood criterion for multi-class classification criterion:forward(output,3) -- let's say the groundtruth was class number: 3 gradients = criterion:backward(output,3) gradInput = net:backward(input, gradients) -- Parameters m = nn.SpatialConvolution(1,3,2,2) -- learn 3 2x2 kernels print(m.weight) -- initially, the weights are randomly initialized print(m.bias) -- the operation in a convolution layer is: output = convolution(input, weight) + bias <file_sep>-- Strings, numbers, tables print('1. Strings, numbers, tables') a = 'hello' print(a) b = {} b[1] = a print(b) b[2] = 30 for i = 1, #b do print(b[i]) end -- Tensors print('2. Tensors') a = torch.Tensor(5,3) -- 5 x 3 matrix, uninitialized a = torch.rand(5,3) print(a) b = torch.rand(3,4) -- matrix multiplication 1 print(a * b) -- matrix multiplication 2 print(torch.mm(a,b)) -- matrix multiplication 3 c = torch.Tensor(5,4) print(c:mm(a,b)) -- store result in c print(c) -- CUDA Tensors print('3. CUDA Tensors') require 'cutorch'; a = a:cuda() b = b:cuda() c = c:cuda() c:mm(a,b) -- done on GPU print(c) -- Exercise: Add two tensors print('Exercise: Add two tensors') function addTensors(a,b) return torch.add(a,b) end a = torch.ones(5,2) b = torch.Tensor(2,5):fill(4) print(addTensors(a,b)) <file_sep>require 'paths' require 'image' if(not paths.filep('cifar10torchsmall.zip')) then os.execute('wget -c https://s3.amazonaws.com/torch7/data/cifar10torchsmall.zip') os.execute('unzip cifar10torchsmall.zip') end trainset = torch.load('cifar10-train.t7') testset = torch.load('cifar10-test.t7') classes = {'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'} -- print(#trainset.data) -- image.display(trainset.data[100]) -- print(classes[trainset.label[100]]) -- to prepare the dataset to be used with nn.StochasticGradient -- 1. the dataset has to have a :size() function -- 2. the dataset has to have [i] index operator, so that dataset[i] returns the ith sample in the dataset setmetatable(trainset, {__index = function(t,i) return {t.data[i], t.label[i]} end} ); trainset.data = trainset.data:double() -- convert the data from a ByteTensor to a DoubleTensor function trainset:size() return self.data:size(1) end -- print(trainset:size()) -- image.display(trainset[33][1]) -- print(classes[trainset[33][2]]) -- Normalization -- redChannel = trainset.data[{ {}, {1}, {}, {} }] -- this picks {all images, 1st channel, all vertical pixels, all horizontal pixels} -- print(#redChannel) mean = {} stdv = {} for i=1,3 do mean[i] = trainset.data[{ {}, {i}, {}, {} }]:mean() trainset.data[{ {}, {i}, {}, {} }]:add(-mean[i]) stdv[i] = trainset.data[{ {}, {i}, {}, {} }]:std() trainset.data[{ {}, {i}, {}, {} }]:div(stdv[i]) end -- Constructing the neural network require 'nn' net = nn.Sequential() net:add(nn.SpatialConvolution(3,6,5,5)) -- 1 input image channel, 6 output channels, 5x5 convolution kernel net:add(nn.ReLU()) -- non-linearity net:add(nn.SpatialMaxPooling(2,2,2,2)) -- A max-pooling operation that look at 2x2 windows and finds the max net:add(nn.SpatialConvolution(6,16,5,5)) net:add(nn.ReLU()) net:add(nn.SpatialMaxPooling(2,2,2,2)) net:add(nn.View(16*5*5)) -- reshapes from a 3D tensor of 16x5x5 into a 1D tensor of 16*5*5 net:add(nn.Linear(16*5*5,120)) -- fully connected layer net:add(nn.ReLU()) net:add(nn.Linear(120,84)) net:add(nn.ReLU()) net:add(nn.Linear(84,10)) -- 10 is the number of outputs of the network net:add(nn.LogSoftMax()) -- converts the output to a log-probability. Useful for classification problems -- Loss function criterion = nn.ClassNLLCriterion() -- Using CUDA require 'cunn' net = net:cuda() criterion = criterion:cuda() trainset.data = trainset.data:cuda() trainset.label = trainset.label:cuda() -- Train the neural network trainer = nn.StochasticGradient(net, criterion) trainer.learningRate = 0.001 trainer.maxIteration = 10 trainer:train(trainset) -- Test the network testset.data = testset.data:double() testset.data = testset.data:cuda() testset.label = testset.label:cuda() for i = 1,3 do testset.data[{ {}, {i}, {}, {} }]:add(-mean[i]) testset.data[{ {}, {i}, {}, {} }]:div(stdv[i]) end print('Label : ' .. classes[testset.label[100]]) -- image.display(testset.data[100]) predicted = net:forward(testset.data[100]) predicted:exp() -- convert log-probability to probability for i = 1,predicted:size(1) do print(classes[i], predicted[i]) end correct = 0 for i=1,testset.data:size(1) do local groundtruth = testset.label[i] local prediction = net:forward(testset.data[i]) local confidences, indices = torch.sort(prediction, true) -- sort in descending order if groundtruth == indices[1] then correct = correct + 1 end end print('\nCorrect = ' .. correct .. ', Accuracy = ' .. 100*correct/10000 .. ' %\n') class_performance = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} for i=1,testset.data:size(1) do local groundtruth = testset.label[i] local prediction = net:forward(testset.data[i]) local confidences, indices = torch.sort(prediction,true) if groundtruth == indices[1] then class_performance[groundtruth] = class_performance[groundtruth] + 1 end end print('Accuracy by class') for i=1,#classes do print(classes[i], 100*class_performance[i]/1000 .. '%') end
2f7de551fc537e31dd464d5c4305fed224d90bf4
[ "Markdown", "Lua" ]
4
Markdown
marioyc/Deep-learning
7e64402410fa2bab2ed78632b0e32ca8c0628400
64d56114c9ee3b266e107361071601ee7aad6bda
refs/heads/master
<file_sep>require 'pry' class String def sentence? self.end_with?('!', '.', '?') end def question? self.end_with?('?') end def exclamation? self.end_with?('!') ? true : false end def count_sentences self.split(/[.?!]+/).grep(/\S/).count end end #'Hi, my name is Sophie'.sentence? #"What's your name?".question? #'Happy Halloween!'.question? #'Hi, my name is Sophie!'.exclamation? # true #'Hi, my name is Sophie'.exclamation? # false #'one. two. three?'.count_sentences # 3 #"".count_sentences # 0 complex_string = "This, well, is a sentence. This is too!! And so is this, I think? Woo..." complex_string.count_sentences # 4
75ea97a22a717d51837051af9ec01278953d9b18
[ "Ruby" ]
1
Ruby
theHeadTy/oo-counting-sentences-online-web-sp-000
0cab63f65ee991278200843a800d9974be45e22c
9d0d4ba2e61938687be67ca4b135641f34609069
refs/heads/master
<repo_name>sushilvarma2/sushildevops<file_sep>/cookbooks/apache/attributes/default.rb default["apache"]["sites"]["sushil2"] = { "site_title" => "Sushil2s website coming soon", "port" => 80, "domain" => "sushilvarma2-gmail-com4.mylabserver.com" } default["apache"]["sites"]["sushil2b"] = { "site_title" => "Sushil2bs website coming soon", "port" => 80, "domain" => "sushilvarma2-gmail-com4b.mylabserver.com" } default["apache"]["sites"]["sushil4"] = { "site_title" => "Sushil4 website", "port" => 80, "domain" => "sushilvarma2-gmail-com5.mylabserver.com" } case node["platform"] when "centos" default["apache"]["package"] = "httpd" when "ubuntu" default["apache"]["package"] = "apache2" end
9f418af401175fa82897a9d1521cdd1e051e30af
[ "Ruby" ]
1
Ruby
sushilvarma2/sushildevops
26f465922a825ad58f672794d602eec2779ad2dc
d3d8ceab6826f7f99c9d3ab41218fa69052fb63b
refs/heads/master
<repo_name>zeljkoprsa/powerRanger<file_sep>/README.md # POWER **input** RANGER! Tired of **BORING** number inputs that are hard to see when the numbers are too long? Tired of numbers that are too small inside the box? Add some **POWER** to your inputs with **POWER [input] RANGER!** Works great for max/min number inputs, part of the **SWEET** html5 spec. ### How to use: Play around by adding and removing any number of items from each input box. For example, try adding 1, 99, 999, or even something over 9,000! Get crazy! ``` // make sure to cache your dom elements! var inputs = $('#demo-section').find('input'); inputs.powerRangeIt(); ``` ### Options 1. **scale_factor: 12** | subtracted from total font size -- adjust to your liking 2. **cutoff_length: 7** | number of letters before resizing stops 3. **cutoff_size: 20** | default font size of non-resized letters ### Support Tested in **Firefox 22**, **Chrome 28.0.1500.95** and **Safari 6.0.5 (8536.30.1)** ## demo: http://dxdstudio.com/labs/powerRanger/ <file_sep>/jquery.powerRanger.js /*! * jquery power ranger - A jQuery plugin to resize number (ranged) inputs based on length of characters! * (c) 2013 <NAME> <<EMAIL>> * See license for information * <3 * http://dxdstudio.com/labs/powerRanger * http://github.com/christabor/powerRanger */ (function($){ $.fn.powerRangeIt = function(options) { var defaults = { // subtracted from total font size -- adjust to your liking scale_factor: 12, cutoff_length: 7, cutoff_size: 20, scrub_nan: true }, opts = $.extend(defaults, options); return this.each(function(k, elem){ $(elem).on('change.powerRangeIt keyup.powerRangeIt', function() { // get number values for formula var width = $(this).width(), _elem = $(this), value = _elem.val(), font_size = parseInt(_elem.css('font-size').replace('px', ''), 10), char_length = $(this).val().length, new_size = ((10-char_length)*10)-opts.scale_factor; // scrub bad inputs if((isNaN(value) || value === '') && opts.scrub_nan) { $(this).val('0'); } if(char_length >= opts.cutoff_length) { new_size = opts.cutoff_size; } // update css with calculation _elem.css('font-size', new_size+'px'); }); }); }; })(jQuery);
c830a4d13c5e20470fb438a3dfaf332b659b21fd
[ "Markdown", "JavaScript" ]
2
Markdown
zeljkoprsa/powerRanger
07485aa964fc6282cc177bd4f1f5756bb445d78d
b9388bab75d1ffe86171bc54f94c8eaedde7b9d7
refs/heads/master
<repo_name>Mafalda2417/AgenciadeViagens<file_sep>/agenciadeviagens.c #include <stdio.h> int main(){; int pacote; int viagens; int hotel; int aluguer; int tarifa; int pessoas; int quarto; int dias; int destino; float total; float total1; float totalpacote; float totalpacote1; printf("Agência de Viagens: FRAGOLARINHARCELALDALOURAPACHECO\n"); printf("Pacote:\n1- Viagem + Hotel\n2- Hotel + Aluguer\n3- Viagem + Aluguer\n4- Viagem + Hotel + Aluguer\n"); scanf("%d", &pacote); switch (pacote) { case 1: printf("Destino da Viagem?\n1- Lisboa\n2- Porto\n3- Rabo de Peixe\n"); scanf("%d", &destino); if(destino == 1){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.3; total1 = (620*pessoas) + total; printf("Preço da Viagem:%.2f€\n", total1); }else if(destino == 2){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.26; total1 = (620*pessoas) + total; printf("Preço da Viagem:%.2f€\n", total1); }else if(destino == 3){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.96; total1 = (620*pessoas) - total; printf("Preço da Viagem:%.2f€\n", total1); } printf("Hotel?\n1- Tivoli Lisboa\n2- Universidade do Porto\n3- Carangueijo\n"); scanf("%d", &hotel); if(hotel == 1){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.2; total1 = ((40*dias) + (40*pessoas)) + total; printf("Preço da Hotel:%.2f€\n", total1); }else if(hotel == 2){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.15; total1 = ((40*dias) + (40*pessoas)) + total; printf("Preço da Hotel:%.2f€", total1); }else if(hotel == 3){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.94; total1 = ((40*dias) + (40*pessoas)) - total; printf("Preço da Hotel:%.2f€\n", total1); } totalpacote = (destino + hotel) * 0.15; totalpacote1 = (destino + hotel) - totalpacote; printf("Total do pacote:%.2f\n", totalpacote1); case 2: printf("Hotel?\n1- Tivoli Lisboa\n2- Universidade do Porto\n3- Carangueijo\n"); scanf("%d", &hotel); if(hotel == 1){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.2; total1 = ((40*dias) + (40*pessoas)) + total; printf("Preço da Hotel:%.2f€\n", total1); }else if(hotel == 2){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.15; total1 = ((40*dias) + (40*pessoas)) + total; printf("Preço da Hotel:%.2f€\n", total1); }else if(hotel == 3){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.94; total1 = ((40*dias) + (40*pessoas)) - total; printf("Preço da Hotel:%.2f€\n", total1); } printf("Aluguer?\n1- Europcar\n2- Altis\n3- Carroça\n"); scanf("%d", &aluguer); if(aluguer == 1){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.15; total1 = (29*dias) + total; printf("Preço do Aluguer:%.2f€\n", total1); }else if(aluguer == 2){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.16; total1 = (29*dias) + total; printf("Preço do Aluguer:%.2f€\n", total1); }else if(aluguer == 3){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.98; total1 = (29*dias) - total; printf("Preço do Aluguer:%.2f€\n", total1); } totalpacote = (destino + hotel) * 0.05; totalpacote1 = (destino + hotel) - totalpacote; printf("Total do pacote:%.2f\n", totalpacote1); case 3: printf("Destino da Viagem?\n1- Lisboa\n2- Porto\n3- Rabo de Peixe\n"); scanf("%d", &destino); if(destino == 1){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.3; total1 = (620*pessoas) + total; printf("Preço da Viagem:%.2f€\n", total1); }else if(destino == 2){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.26; total1 = (620*pessoas) + total; printf("Preço da Viagem:%.2f€\n", total1); }else if(destino == 3){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.96; total1 = (620*pessoas) - total; printf("Preço da Viagem:%.2f€\n", total1); } printf("Aluguer?\n1- Europcar\n2- Altis\n3- Carroça\n"); scanf("%d", &aluguer); if(aluguer == 1){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.15; total1 = (29*dias) + total; printf("Preço do Aluguer:%.2f€\n", total1); }else if(aluguer == 2){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.16; total1 = (29*dias) + total; printf("Preço do Aluguer:%.2f€\n", total1); }else if(aluguer == 3){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.98; total1 = (29*dias) - total; printf("Preço do Aluguer:%.2f€\n", total1); } totalpacote = (destino + aluguer) * 0.075; totalpacote1 = (destino + aluguer) - totalpacote; printf("Total do pacote:%.2f\n", totalpacote1); case 4: printf("Destino da Viagem?\n1- Lisboa\n2- Porto\n3- Rabo de Peixe\n"); scanf("%d", &destino); if(destino == 1){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.3; total1 = (620*pessoas) + total; printf("Preço da Viagem:%.2f€\n", total1); }else if(destino == 2){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.26; total1 = (620*pessoas) + total; printf("Preço da Viagem:%.2f€\n", total1); }else if(destino == 3){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); total = (620*pessoas) * 0.96; total1 = (620*pessoas) - total; printf("Preço da Viagem:%.2f€\n", total1); } printf("Hotel?\n1- Tivoli Lisboa\n2- Universidade do Porto\n3- Carangueijo\n"); scanf("%d", &hotel); if(hotel == 1){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.2; total1 = ((40*dias) + (40*pessoas)) + total; printf("Preço da Hotel:%.2f€\n", total1); }else if(hotel == 2){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.15; total1 = ((40*dias) + (40*pessoas)) + total; printf("Preço da Hotel:%.2f€\n", total1); }else if(hotel == 3){ printf("Número de Pessoas?\n"); scanf("%d", &pessoas); printf("Número de Dias?\n"); scanf("%d", &dias); total = ((40*dias) + (40*pessoas)) * 0.94; total1 = ((40*dias) + (40*pessoas)) - total; printf("Preço da Hotel:%.2f€\n", total1); } printf("Aluguer?\n1- Europcar\n2- Altis\n3- Carroça\n"); scanf("%d", &aluguer); if(aluguer == 1){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.15; total1 = (29*dias) + total; printf("Preço do Aluguer:%.2f€\n", total1); }else if(aluguer == 2){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.16; total1 = (29*dias) + total; printf("Preço do Aluguer:%.2f€\n", total1); }else if(aluguer == 3){ printf("Número de Dias?\n"); scanf("%d", &aluguer); total = (29*dias) * 0.98; total1 = (29*dias) - total; printf("Preço do Aluguer:%.2f€\n", total1); } totalpacote = (destino + hotel + aluguer) * 0.25; totalpacote1 = (destino + hotel + aluguer) - totalpacote; printf("Total do pacote:%.2f\n", totalpacote1); default: break; } }
a2546af7b266cc8de817e0ccdaa19af1d6424b72
[ "C" ]
1
C
Mafalda2417/AgenciadeViagens
f94456b8ff913de9f962f4927f93765900ef41d7
e9311e5ebb6a7031b75b4d114d27d9a77b9312ed
refs/heads/master
<file_sep># Etch-a-Sketch This is an Etch-a-Sketch program you can play on your browser. Draw what you like and reset by pressing the button on top.<file_sep>function makeGrid(length) { let root = document.querySelector('#root'); for (let k = 0; k < length; k++) { let row = document.createElement('div'); row.classList.toggle('row'); for (let j = 0; j < length; j++) { let square = document.createElement('div'); square.classList.toggle('square'); square.addEventListener('mouseenter', (event) => { event.target.style.backgroundColor = 'black'; }); row.append(square); } root.append(row); } let button = document.createElement('button'); button.innerText = 'Reset'; button.classList.toggle('button'); button.addEventListener('click', () => { document.querySelectorAll('.square').forEach((square) => { square.style.backgroundColor = 'white'; }); }); root.insertBefore(button, document.querySelector('.row')); } let length = prompt("Enter how many squares you want on a side."); makeGrid(length);
b8ffbd96265fd50073f62d2dedc531cdcd166095
[ "Markdown", "JavaScript" ]
2
Markdown
hlee2542/Etch-a-Sketch
b01fbc3ef57b9b5f9f33fe76f6352c8bce24a809
9ac9c385cc94baaafecd2990fbf7c604cf17348d
refs/heads/master
<repo_name>rookiezmh/myJSLibs<file_sep>/helpers.js export function URLParser (URL) { // a helper funciton works well in browser var url = URL.toString(), a = document.createElement('a') // set a's href to url so that can also handle relative url a.href = url return { source: url, protocol: a.protocol.replace(':', ''), host: a.hostname, port: a.port, query: a.search, file: (a.pathname.match(/\/([^\/?#]+)$/i) || ['', ''])[1], relative: (a.href.match(/tps?:\/{2}[^\/]+(.+)/) || ['', ''])[1], segment: a.pathname.replace(/^\//, '').split('/'), params: (function() { var ret = {} var seg = a.search.replace(/^\?/, '').split('&').filter(function(v){ if (v !=='' && v.indexOf('=') > 0) { return true } }) seg.forEach( function(element) { var idx = element.indexOf('=') ret[element.slice(0, idx)] = element.slice(idx + 1) }) return ret })() } }<file_sep>/observer.js var Observable = { initObservable: function () { this.subscribers = {} }, subscribe: (function () { var nextGuid = 1; return function (type, cb) { var subscribers = this.subscribers; if (!subscribers[type]) { subscribers[type] = []; } subscribers[type].push(cb); if (!cb.guid) { cb.guid = nextGuid++; console.log(cb.guid); } } })(), unSubscribe: function (type, fn) { function isEmpty(object) { for (var prop in object) { return false; } return true; } function tidyUp(type) { var subscribers = self.subscribers; if (subscribers[type].length === 0) { delete subscribers[type]; } } function removeType(t) { subscribers[t] = []; tidyUp(self, t); } var subscribers = this.subscribers, self = this; if (isEmpty(subscribers)) return; if (!type) { for (var t in subscribers) removeType(t); return; } var handlers = subscribers[type]; if (!handlers) return; if (!fn) { removeType(type); return; } if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } tidyUp(type); }, publish: function (type) { var data = Array.prototype.slice.call(arguments, 1), i, t, subscribers = this.subscribers; if (!type) { for (t in subscribers) { for (i = 0; i < subscribers[t].length; i++) { subscribers[t][i](data); } } } else { for (i = 0; i < subscribers[type].length; i++) { subscribers[type][i](data); } } } };
915e862ca86dfbaa4d558b1a237eed26c4129072
[ "JavaScript" ]
2
JavaScript
rookiezmh/myJSLibs
9b0bc68fe7aebc5e405eadbc8e25577dc3b6d4d6
4e9ba0215272211beadff40242d864f1f246ffed
refs/heads/master
<file_sep>#include "ns3/core-module.h" #include "network-helper.h" #include "ns3/string.h" #include "ns3/inet-socket-address.h" #include "ns3/names.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/applications-module.h" // 此处需要改为具体协议的头文件 #include "../model/pbft-node.h" namespace ns3 { // 工厂模式生成app实例, 在NetworkNode中必须要 GetTypeId方法,否则出错 NetworkHelper::NetworkHelper(uint32_t totalNoNodes) { m_factory.SetTypeId ("ns3::PbftNode"); m_nodeNo = totalNoNodes; } ApplicationContainer NetworkHelper::Install (NodeContainer c) { ApplicationContainer apps; for (NodeContainer::Iterator i = c.Begin (); i != c.End (); i++) { // 此处需要改为具体协议的类 Ptr<PbftNode> app = m_factory.Create<PbftNode> (); uint32_t nodeId = (*i)->GetId(); app->m_id = nodeId; app->N = m_nodeNo; app->m_peersAddresses = m_nodesConnectionsIps[nodeId]; (*i)->AddApplication (app); apps.Add (app); } return apps; } }
c06adabf86b6f496fffc09b2e637968864125e65
[ "C++" ]
1
C++
aiyiyayayaya/blockchain-simulator-1
52213e0f6a23e0bf6b23e78958af5a5c71358880
eb14eb484217d39c656969650060d3141331ce6e
refs/heads/master
<repo_name>cwc845982120/Profession-app<file_sep>/src/js/module/demo/service/testSer.js /** * Created by yuting on 2016/11/17. */ var Config = require('../../../util/config'); module.exports = function(app){ app.service('testSer',['baseService',function(bs){ bs.setReqConfig({ url: Config.get(Config.business.query_welfare) }); this.fetch = bs.fetch; }]); }; <file_sep>/src/js/util/util.js var _ = require('underscore'); var Sms = require('./sms'); var util = { /** * 发送短信 * @param context * @param success_callback * @returns {Sms} * @constructor */ sms: function (context, success_callback) { return new Sms(context, success_callback); }, /** * 生成一个随机串码 * @returns {string} */ getUUID: function () { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; }, /** * 从url中获取参数 * @param name * @returns {*} */ getUrlParam: function (name) { if(!name) return null; var reg = new RegExp("" + name + "=([^&]*)", "i"); var r = window.location.search.substr(1).match(reg); if (r !== null) return decodeURIComponent(r[1]); return null; } }; module.exports = util;<file_sep>/src/js/module/demo/Init.js /** * Created by yuting on 2016/11/16. * */ /** * 模块名称 */ var moduleName = 'demo'; require('./' + moduleName + '.scss'); /** * 初始化一个模块名称,在当前位置进行路由的配置 */ var app = angular.module(moduleName, ['ui.router']); var G = require('./guidance')(app); /** * 子模块的路由配置 */ app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { //每个路由会对应一个控制器,与一个模版文件 $stateProvider.state('test', { url: '/test', controller: G.controllers.testCtrl, template: G.templates.testTpl }); //当路由为test2 的情况下 默认为page1 $urlRouterProvider.when('/test2', 'test2/page1'); //嵌套试图例子路由 $stateProvider.state('test2', { url: '/test2', controller: G.controllers.testCtrl2, template: G.templates.testTpl2 }) .state('test2.Page1', { url: '/page1', params : { attrs : null}, controller: G.controllers.pageCtrl1, template: G.templates.page1Tpl }) .state('test2.Page2', { url: '/page2', params : { attrs : null }, controller: G.controllers.pageCtrl2, template: G.templates.page2Tpl }) .state('test2.Page3', { url: '/page3', template: G.templates.page3Tpl }); }]); module.exports = app;<file_sep>/src/js/base/baseService.js /** * 初始化一些base对象使用时从此地导入 * @param app */ var headers = require('../util/httpHeaderConfig'); var _ = require('underscore'); var baseConfig = { retry: true, method: __LOCAL__ ? 'GET' : 'POST', timeout: 30000, responseType: "json", withCredentials: false, headers: headers }; module.exports = function (app) { app.service('baseService', ['$q', '$http', function ($q, $http) { var reqConfig = {}; var _this = this; _this.alert = function () { console.log('baseService'); }; _this.setReqConfig = function (configObj) { reqConfig = _.extend({}, baseConfig, configObj); }; _this.run = function (params) { var defer = $q.defer(); var _params = params; var httpConfig = { method: reqConfig.method, //POST withCredentials: reqConfig.withCredentials, //false headers: reqConfig.headers, url: reqConfig.url, //'/demo/queryComponents', timeout: 30000, responseType: "json" }; //get与post赋值 if (httpConfig.method.toUpperCase() != "GET" && httpConfig.method.toUpperCase() != "DELETE") { httpConfig.data = _params; } else { httpConfig.params = _params; } //参考网址http://www.cnblogs.com/ys-ys/p/4984639.html?utm_source=tuicool&utm_medium=referral $http(httpConfig) .success(function (data, status, headers, config) { console.log('[success ' + reqConfig.url + ' result]'); console.log(JSON.stringify(data)); defer.resolve(data); }) .error(function (data, status, headers, config) { defer.reject(data); }); return defer.promise; //返回承诺,返回获取数据的API }; _this.fetch = function (params) { var delay = $q.defer(); var promise = _this.run(params); promise.then(function (data) { delay.resolve(data); }, function (data) { delay.reject(data); }); return delay.promise; } }]); }; <file_sep>/src/js/util/httpHeaderConfig.js /** * Created by yuting on 2016/11/17. * 放置http请求头信息 */ var headers = {}; headers['Content-Type'] = 'application/json;charset=utf-8'; headers['XChannel'] = 'weixin'; module.exports = headers;<file_sep>/src/js/main.js /** * Created by yuting on 2016/11/14. */ require('../sass/main.scss'); var app = {}; //路由设置 //历史记录 app.init = function(){ //导入插件 require('angular'); require('angular-ui-router'); //导入app require('./app'); }; app.start = function(){ //手动启动应用 angular.element(document).ready(function() { angular.bootstrap(document, ['myApp']); }); }; app.init(); app.start(); <file_sep>/src/js/util/config.js /** * Created by yuting on 2016/11/17. */ var Config = { business: { "query_welfare": "api/business/queryWelfare", "login": "api/business/queryWelfare" }, host: '', //微信前置 wechat_host : '', get: function (url) { if (this.host) { return this.host.replace(/\/$/, '') + '/' + url.replace(/^\//, ''); } return url; } }; if (__PROD__) { Config.host = 'https://client.tycredit.com/'; } if (__DEV__) { Config.host = 'http://172.16.31.10:52021/'; } if (__LOCAL__) { Config.get = function (url) { console.assert(!/^\//.test(url), "请使用相对URL"); return url + '.json'; }; } module.exports = Config;<file_sep>/src/js/module/demo/guidance.js /** * Created by yuting on 2016/11/17. */ module.exports = function (app) { return { /** * 导入此模块所需要引用的 【service】 */ services: { testSer: require('./service/testSer')(app) }, /** * 导入此模块所需要引用的 【controllers】 */ controllers: { testCtrl: require('./controller/testCtrl')(app), testCtrl2: require('./controller/testCtrl2')(app), pageCtrl1: require('./controller/pageCtrl1')(app), pageCtrl2: require('./controller/pageCtrl2')(app) }, /** * 导入此模块所需要引用的 【templates】 */ templates: { testTpl: require('html!./template/testTpl.html'), testTpl2: require('html!./template/testTpl2.html'), page1Tpl: require('html!./template/page1.html'), page2Tpl: require('html!./template/page2.html'), page3Tpl: require('html!./template/page3.html') } } };<file_sep>/src/js/app.js /** * Created by yuting on 2016/11/16. */ /** * 依赖的子模块数组有多少子模块就加多少子模块 使用name关键字变成 ['demo','ui.router'] */ var relaArr = [ require('./module/demo/Init').name ]; var app = angular.module('myApp', relaArr); //模块 require('./base/baseService')(app); require('./base/baseController')(app); /** * 此地进行全局监控 */ app.run(['$rootScope', '$location', '$state', function($rootScope, $location, $state){ $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ //Todo: 加入历史记录操控 console.log('历史记录操作'); }); }]); module.exports = app;<file_sep>/webpack.config.js var path = require('path'); var webpack = require('webpack'); var HtmlwebpackPlugin = require('html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var ROOT_PATH = path.resolve(__dirname); var APP_PATH = path.resolve(ROOT_PATH, 'src'); var BUILD_PATH = path.resolve(ROOT_PATH, 'dist'); var LIB_PATH = path.resolve(APP_PATH, 'js/lib'); module.exports = { entry: { app : path.resolve(APP_PATH, 'js/main.js'), vendor: ['angular','angular-ui-router'] //需要进库的插件包 }, output: { path: BUILD_PATH, filename: '[name].js' }, resolve: { extensions: ['.js', ''], alias:{ 'anijs': path.resolve(APP_PATH,'js/lib/anijs') } }, plugins: [ new HtmlwebpackPlugin({ title: '机构平台', template: path.resolve(APP_PATH, 'main.html'), filename: 'main.html' }), new webpack.optimize.CommonsChunkPlugin({ name: "vendor", filename: "vendor.js" }), new CopyWebpackPlugin([ {from: path.resolve(ROOT_PATH, 'api'), to: 'api'} ]), new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')), __PROD__: JSON.stringify(JSON.parse(process.env.BUILD_PROD || 'false')), __LOCAL__: JSON.stringify(JSON.parse(process.env.BUILD_LOCAL || 'false')) }) ], // dev server devServer: { historyApiFallback: true, hot: true, inline: true, progress: true, port: 3333, contentBase: '/dist', colors: true }, module: { loaders: [ { test: /\.(css|scss)$/, loaders: ['style', 'css', 'sass'] //include:APP_PATH }, { test: /\.(png|jpg|woff|svg|ttf|eot)\??.*$/, loader: 'file-loader?name=img/[hash].[ext]' } ] }, eslint: { configFile: '.eslintrc' //Rules for eslint }, devtool: 'eval-source-map' }; <file_sep>/src/js/util/sms.js /** * Created by yuting on 2016/11/21. */ var Sms = function (context, success_callback) { this.success_callback = success_callback; this.context = context; this.contextTitle = context.text(); this.initVar(); }; Sms.prototype.initVar = function () { this.maxTime = 60; this.startTime = 60; this.endTime = 0; }; Sms.prototype.start = function () { if (this.checkEnd()) { this.success_callback(); } }; Sms.prototype.checkEnd = function () { if (this.startTime === this.maxTime) { return true; } return false; }; Sms.prototype.run = function () { var $sms = this.context; var _this = this; var cal = function cal() { if (_this.startTime === _this.endTime - 1) { _this.startTime = _this.maxTime; $sms.text(_this.contextTitle); clearInterval(time); return; } $sms.text(_this.startTime--); }; var time; time = setInterval(cal, 1000); }; module.exports = Sms;<file_sep>/README.md #目录结构说明 api 接口资源 dist 打包输出的目录 src 项目目录 base 放置各种继承模块(基础模块必须在app.js中导入) lib 放置第三方插件 anijs 模版事件动画插件(参考地址:http://anijs.github.io/#documentation) module 放置各个模块 demo 详情查看demo目录结构说明 util 工具类模块 #demo目录结构说明 (生成一个模块的时候请将init.js 导入至app.js) controller 放置本模块的所有控制器 pageCtrl1.js 最基本的写法 pageCtrl2.js 接收外部传递参数的写法 参照网址:http://www.cnblogs.com/jager/p/5293225.html testCtrl.js 使用继承的基本写法,还演示了 利用$state.go 传递参数或跳转的方式 testCtrl2.js 调用接口的基本写法 service 放置本模块的所有接口服务 testSer.js 基础接口写法 template 放置本模块的所有模版文件 page1.html page2.html page3.html testTpl2.html 以上4个模版 访问 #/test2 会展现tab的功能 加入了使用ui-sref进行参数传递的写法 testTpl.html 展示anijs动画插件模版的写法 demo.scss 放置本模块所有css样式 guidance.js 引导器 请将所有的 controller,service,template 按照引导器指定要求进行书写 init.js 进行模块初始化,以及路由配置<file_sep>/src/js/module/demo/controller/testCtrl2.js /** * Created by yuting on 2016/11/16. */ /** * 控制器引入当前模块依赖,对当前模块进行单独的控制器定义 * @returns {string} 返回控制器名称 */ module.exports = function(app){ var controllerName = 'testCtrl2'; app.controller(controllerName,['$scope','testSer',function($scope,model){ var success = function(data){ $scope.item = data.result; }; var fail = function(){ console.log('哥报错了'); }; model.fetch().then(success,fail); }]); return controllerName; };
19d8c12e7fbfd3ee728ea897f449e3687032733b
[ "JavaScript", "Markdown" ]
13
JavaScript
cwc845982120/Profession-app
6f7f35c4ee6be1659341fef9844909e1450dad63
4d45f5f0ad753e95040b162d24691407b3e4506a
refs/heads/master
<repo_name>pavel24071988/jsdevelopers<file_sep>/Turnstile/tests/TurnstileTest.php <?php require '../Turnstile.php'; /** * Tests for Turnstile class * * @author shcherbakov pavel */ class TurnstileTests extends PHPUnit_Framework_TestCase { private $turnstile; protected function setUp() { $this->turnstile = new Turnstile(); } protected function tearDown() { $this->turnstile = NULL; } public function testInsertCoin() { $this->assertTrue($this->turnstile->insertCoin(1)); } public function testInsertNoCoin() { $this->assertFalse($this->turnstile->insertCoin('garbage')); } public function testPassTroughTurnstileWithCoin() { $this->turnstile->insertCoin(1); $this->assertTrue($this->turnstile->checkUnLocked()); } public function testPassTroughTurnstileWithoutCoin() { $this->assertFalse($this->turnstile->checkUnLocked()); } public function testAlarmWithCoin() { $this->turnstile->insertCoin(1); $this->assertFalse($this->turnstile->checkIsAlarm()); } public function testAlarmWithNoCoin() { $this->turnstile->insertCoin('garbage'); $this->assertTrue($this->turnstile->checkIsAlarm()); } public function testEjectWithCoin() { $this->turnstile->insertCoin(1); $this->assertFalse($this->turnstile->ejectCoin()); } public function testEjectWithNoCoin() { $this->turnstile->insertCoin('garbage'); $this->assertFalse($this->turnstile->ejectCoin()); } } <file_sep>/Turnstile/nbproject/private/private.properties copy.src.files=false copy.src.on.open=false copy.src.target= index.file=Turnstile.php run.as=LOCAL url=http://turnstile/ <file_sep>/Turnstile/Turnstile.php <?php /** * Turnstile class * * @author shcherbakov pavel */ class Turnstile { private $messages = []; private $coin = 0; private $isUnlocked = false; private $isAlarm = false; public function __construct(){ $this->messages[] = 'turnstile is ready'; } public function __destruct(){ echo 'end of scenario'; } public function checkCoinExist(){ return $this->coin > 0 ? true : false; } public function checkUnLocked(){ return $this->isUnlocked; } public function checkIsAlarm(){ return $this->isAlarm; } public function validateCoin($coin){ return is_int($coin) ? true : false; } public function unlockedTurnstile(){ $this->messages[] = 'turnstile is unlocked'; return $this->isUnlocked = true; } public function lockedTurnstile(){ $this->messages[] = 'turnstile is locked'; return $this->isUnlocked = false; } public function startAlarmTurnstile(){ if($this->checkIsAlarm()){ $this->messages[] = 'alarm started before...'; return true; } $this->messages[] = 'alarm...'; return $this->isAlarm = true; } public function endAlarmTurnstile(){ if(!$this->checkIsAlarm()) return false; $this->messages[] = 'end of alarm'; return $this->isAlarm = false; } public function addCoin($coin){ return $this->coin = $this->coin + $coin; } public function removeCoin(){ return $this->coin--; } public function ejectCoin(){ $this->messages[] = 'you can`t eject a coin'; $this->startAlarmTurnstile(); $this->lockedTurnstile(); return false; } public function insertCoin($coin){ $this->messages[] = 'insert a coin: '. $coin; if(!$this->validateCoin($coin)){ $this->messages[] = 'is not a coin'; $this->startAlarmTurnstile(); $this->lockedTurnstile(); return false; } $coins = $this->addCoin($coin); if(!$this->checkCoinExist()){ $this->messages[] = 'no coins'; return false; } $this->messages[] = 'turnstile has '. $coins .' coin(s)'; $this->endAlarmTurnstile(); $this->unlockedTurnstile(); return true; } public function passTroughTurnstile(){ $this->messages[] = 'pass trough the turnstile'; if(!$this->isUnlocked){ $this->startAlarmTurnstile(); return false; }; $this->removeCoin(); $this->messages[] = 'success'; $this->lockedTurnstile(); return true; } public function showHistory(){ foreach($this->messages as $message){ echo $message ."<br/>"."\n"; } } } // User Story: Unlocking the turnstile $turnstile = new Turnstile(); $turnstile->lockedTurnstile(); $turnstile->insertCoin(1); $turnstile->showHistory(); $turnstile = null; echo "<br/>"."\n"; echo "<br/>"."\n"; // User Story: Locking the turnstile $turnstile = new Turnstile(); $turnstile->unlockedTurnstile(); $turnstile->passTroughTurnstile(); $turnstile->showHistory(); $turnstile = null; echo "<br/>"."\n"; echo "<br/>"."\n"; // User Story: Raising an alarm $turnstile = new Turnstile(); $turnstile->lockedTurnstile(); $turnstile->passTroughTurnstile(); $turnstile->insertCoin(1); $turnstile->showHistory(); $turnstile = null; echo "<br/>"."\n"; echo "<br/>"."\n"; // User Story: Gracefuly eating money $turnstile = new Turnstile(); $turnstile->lockedTurnstile(); $turnstile->insertCoin(1); $turnstile->insertCoin(1); $turnstile->passTroughTurnstile(); $turnstile->showHistory(); $turnstile = null;
549be93f5c1054ce28a31985fb7a78819bcb4b0a
[ "PHP", "INI" ]
3
PHP
pavel24071988/jsdevelopers
df1caddc4d25f4d36bccb95fa23170234ba8235a
add94057ed71b692ee6889d98efeb60d0a029836
refs/heads/master
<file_sep>import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.serialization.ObjectDecoder; public class Core { private static String loginTmp = "login"; private static String passwordTmp = "<PASSWORD>"; private static final Path root = Paths.get("SrvStorage"); Core(){ try { run(); } catch (Exception e) { e.printStackTrace(); } } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new AuthHandler()); } }); ChannelFuture f = b.bind(8888).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } private static class AuthHandler extends ChannelInboundHandlerAdapter { private boolean authOk = false; @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try { while (in.isReadable()) { System.out.print((char) in.readByte()); } } finally { in.release(); } /* if (authOk) { ctx.fireChannelRead(input); return; } if (input[0] == Patterns.LOGINCODE) { authOk = true; ctx.pipeline().addLast(new MainHandler(login)); System.out.println("hi"); } */ } } private static class MainHandler extends ChannelInboundHandlerAdapter { private String username; public MainHandler(String username) { this.username = username; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String input = (String) msg; System.out.println(username + ": " + input); } } public String[] checkCommand(ByteBuf command) throws UnsupportedEncodingException { byte[] tmp; switch(command.readByte()){ case Patterns.LOGINCODE: int loginLen = command.readInt(); tmp = new byte[loginLen]; command.readBytes(tmp); String login = new String(tmp, "UTF-8"); int passLen = command.readInt(); tmp = new byte[passLen]; command.readBytes(tmp); String password = new String(tmp, "UTF-8"); case Patterns.CHANGEDIR: int pathCDLen = command.readInt(); tmp = new byte[pathCDLen]; command.readBytes(tmp); String pathChange = new String(tmp, "UTF-8"); case Patterns.DOWNLOADFILE: int pathDWFLen = command.readInt(); tmp = new byte[pathDWFLen]; command.readBytes(tmp); String pathDWF = new String(tmp, "UTF-8"); int fileDWFLen = command.readInt(); tmp = new byte[fileDWFLen]; command.readBytes(tmp); String filenameDWF = new String(tmp, "UTF-8"); case Patterns.UPLOADFILE: int pathUPFLen = command.readInt(); tmp = new byte[pathUPFLen]; command.readBytes(tmp); String pathUPF = new String(tmp, "UTF-8"); int fileUPLen = command.readInt(); tmp = new byte[fileUPLen]; command.readBytes(tmp); String filenameUP = new String(tmp, "UTF-8"); //передача байтов самого файла case Patterns.DELETEFILE: int pathDFLen = command.readInt(); tmp = new byte[pathDFLen]; command.readBytes(tmp); String pathDF = new String(tmp, "UTF-8"); int fileDFLen = command.readInt(); tmp = new byte[fileDFLen]; command.readBytes(tmp); String filenameDF = new String(tmp, "UTF-8"); } } }<file_sep>public class Patterns { final static byte LOGINCODE = 10; final static byte CHANGEDIR = 12; final static byte DOWNLOADFILE = 13; final static byte UPLOADFILE = 14; final static byte DELETEFILE = 15; private void login(){ } }
890284ea26d8ea14dbb1951fed7c141c4ab58ff8
[ "Java" ]
2
Java
Cohcka/CloudStorage
63484bf0109fa2a7d050e99f1c75adfec7e271db
aa097418810c907eecfbdea9a5c7e454556e2a9d
refs/heads/master
<file_sep>using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; [Route("[controller]")] public class AuthController : Controller { private readonly IConfiguration _configuration; readonly DataContext _db; public AuthController(IConfiguration configuration, DataContext dataContext) { _configuration = configuration; _db = dataContext; } //https://localhost:5001/auth/login?UserId=admin&Password=<PASSWORD> [HttpPost] [Route("[action]")] public IActionResult Login(LoginViewModel model) { /* * Aquí deberá ir su lógica de validación, en nuestro ASP.NET Identity * y luego de verificar que sea una autenticación correcta vamos a proceder a * generar el token */ User user = null; if (model.UserId == "admin" && model.Password == "<PASSWORD>") { // Asumamos que tenemos un usuario válido user = new User { Name = "Alexis", Role = "Admin", UserId = "admin" }; } if (model.UserId == "user" && model.Password == "<PASSWORD>") { // Asumamos que tenemos un usuario válido user = new User { Name = "Usuario", Role = "User", UserId = "user" }; } if (user != null) { /* Creamos la información que queremos transportar en el token, * en nuestro los datos del usuario */ Claim[] claims = getClaims(user); // Generamos el Token JwtSecurityToken token = generateToken(claims); var _refreshTokenObj = new RefreshToken { Username = user.Name, UserData = JsonConvert.SerializeObject(user), Refreshtoken = Guid.NewGuid().ToString() }; _db.RefreshTokens.Add(_refreshTokenObj); _db.SaveChanges(); // Retornamos el token return Ok( new { response = new JwtSecurityTokenHandler().WriteToken(token), refreshToken = _refreshTokenObj.Refreshtoken } ); } else { return Unauthorized(); } } //https://localhost:44316/auth/1b5422eb-c738-4950-89d9-5ade1692e5de/refresh/ [HttpPost("{refreshToken}/refresh")] public IActionResult RefreshToken([FromRoute]string refreshToken) { var _refreshToken = _db.RefreshTokens.SingleOrDefault(m => m.Refreshtoken == refreshToken); if (_refreshToken == null) { return NotFound("Refresh token not found"); } var user = JsonConvert.DeserializeObject<User>(_refreshToken.UserData); Claim[] claims = getClaims(user); JwtSecurityToken token = generateToken(claims); _refreshToken.Refreshtoken = Guid.NewGuid().ToString(); _db.RefreshTokens.Update(_refreshToken); _db.SaveChanges(); return Ok( new { token = new JwtSecurityTokenHandler().WriteToken(token), refreshToken = _refreshToken.Refreshtoken }); } private JwtSecurityToken generateToken(Claim[] claims) { return new JwtSecurityToken ( issuer: _configuration["ApiAuth:Issuer"], audience: _configuration["ApiAuth:Audience"], claims: claims, //expires: DateTime.UtcNow.AddDays(60), expires: DateTime.UtcNow.AddMinutes(1), notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["ApiAuth:SecretKey"])), SecurityAlgorithms.HmacSha256) ); } private static Claim[] getClaims(User user) { return new[] { new Claim("UserData", JsonConvert.SerializeObject(user)), new Claim("Role", user.Role), new Claim("name", user.Name), new Claim("IsAdmin", user.Role=="Admin"?"IsAdmin":"NO"), }; } }<file_sep># Core.Net v2.2 WebApi (Base Solution) - JWT AUTHORIZATION + Refresh Token - DBCONTEXT - INMEMORY DATABASE - SWAGGER - EF 6 <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Swashbuckle.AspNetCore.Swagger; namespace corewebapi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DataContext>(options => options.UseInMemoryDatabase("MyDB")); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Configuring Authentication middleware for JWT // ValidateAudience: le decimos que debe validar el audience que hemos definido. // ValidateLifeTime: como bien sabes nuestro token puede tener un tiempo de expiración, por lo tanto le diremos que valide esto. // ValidateIssuerSigningKey: que tome en cuenta la validación de nuestro secretkey. // ValidIssuer: seteamos nuestro valor que definimos en el appsettings. // ValidAudience: seteamos nuestro valor que definimos en el appsettings. // IssuerSigningKey: seteamos nuestro secret key para generar un TOKEN único que evita que sea usado por otra persona. services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(jwtBearerOptions => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters() { ValidateActor = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["ApiAuth:Issuer"], ValidAudience = Configuration["ApiAuth:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["ApiAuth:SecretKey"])) }; }); //Adding CORS to enable authentiaction from other domain services.AddCors(options => { options.AddPolicy("EnableCORS", builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build(); }); }); // Adding authorization Policies services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => policy.RequireClaim("IsAdmin")); }); // Adding swagger service services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Core WebAPI", Description = "ASP.NET Core 2.2 Web API", TermsOfService = "None", Contact = new Contact() { Name = "<NAME>", Email = "<EMAIL>", Url = "https://github.com/alexizt/" } }); }); services.AddAuthorization(options => { // If Claim "IsAdmin" is "IsAdmin" or "Si" or "Yes" then autohrize Administrator Policy options.AddPolicy("Administrator", policy => policy.RequireClaim("IsAdmin", "IsAdmin", "Si", "Yes" )); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // Injected DataContext public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataContext dataContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // Seeding Datatabase DBSeeder.AddTestData(dataContext); // Adding JWT Authentication middleware app.UseAuthentication(); // Adding CORS middleware app.UseCors("EnableCORS"); app.UseHttpsRedirection(); app.UseMvc(); // Initializing Swagger Endpoint app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); } } } <file_sep>using Microsoft.EntityFrameworkCore; // DataBaseContext public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<RefreshToken> RefreshTokens { get; set; } }<file_sep>using System; // A blog entity for persistence on dbcontext public class Blog { public int ID { get; set; } public string Title { get; set; } public string Body { get; set; } public DateTime Date { get; set; } }<file_sep>public static class DBSeeder { static public void AddTestData(DataContext context) { var blog1 = new Blog { ID = 1, Title = "Titulo Blog I", Body = "Body Blog I" }; context.Blogs.Add(blog1); var blog2 = new Blog { ID = 2, Title = "Titulo Blog II", Body = "Body Blog II" }; context.Blogs.Add(blog2); context.SaveChanges(); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace corewebapi.Controllers { [Authorize(Policy = "Administrator")] // requiere header Authorization:<KEY> [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { readonly DataContext DataContext; public ValuesController(DataContext dataContext) { DataContext=dataContext; } // GET api/values [HttpGet] public ActionResult<IEnumerable<Blog>> Get() { return DataContext.Blogs.ToList(); } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
f7c73095e8fee66df1f1092976c0bfbe74564296
[ "Markdown", "C#" ]
7
C#
alexizt/Core.Net-v2.2-Base-WebApi
da183ec277d9b8adf40fc6b242a5a735aaf665f1
607b27b2a7c8382530f53a4a02a934521556a82b
refs/heads/master
<file_sep> window.i18n = (function (window) { 'use strict'; var $ = window.jQuery; var exports = function () {}; var i18nPt = exports.prototype; /** * Set the translation resource * @param {object} resource to set */ i18nPt.setResource = function (resource) { this.resource = resource; }; /** * Translate a key * @param {string} key to translate */ i18nPt.t = function (key) { var value = this.resource[key]; if (value != null) { return value; } return key; }; /** * Scan <t> tags and .t-text and .t-attr class elements and translate its contents * @return object * @subreturn {number} object['t-tag'] the count of translated <t> tags * @subreturn {number} object['t-text'] the count of translated .t-text tags * @subreturn {number} object['t-attr'] the count of translated .t-attr tags' attributes */ i18nPt.scan = function (dom) { var t = this.scanTTag(dom); var tText = this.scanTText(dom); var tAttr = this.scanTAttr(dom); return { 't-tag': t, 't-text': tText, 't-attr': tAttr }; }; /** * remove <t> tag and insert string for key * @return translated key count */ i18nPt.scanTTag = function (dom) { var self = this; var list = $('t', dom).each(function () { var t = $(this); t.after(self.t(t.text())).remove(); }); return list.length; }; /** * scan .t-text class and replace text with translated string * @return translated key count */ i18nPt.scanTText = function (dom) { var self = this; var count = 0; $('.t-text', dom).each(function () { var elm = $(this); // replace text with translated string elm.text(self.t(elm.text())); elm.removeClass('t-text').addClass('t-text-done'); // increment translation count count ++; }); return count; }; var T_ATTR_REGEXP = /^t:/; // translatable attribute starts with 't:' /** * scan .t-attr class and translate its attr starts with 't:' prefix * @return translated key count */ i18nPt.scanTAttr = function (dom) { var self = this; var count = 0; $('.t-attr', dom).each(function () { $.each(this.attributes, function (i, attr) { var label = attr.value; if (T_ATTR_REGEXP.test(label)) { label = label.replace(T_ATTR_REGEXP, ''); // replace attribute value with translated string attr.value = self.t(label); // increment translation count count ++; } }); $(this).removeClass('t-attr').addClass('t-attr-done'); }); return count; }; i18nPt.setAvailableLanguages = function (array) { this.availables = array; this.defaultLanguage = array[0]; }; i18nPt.setLanguage = function (language) { this.language = language; }; i18nPt.pickUsableLanguage = function (language) { language = language || this.language; if (language == null) { return this.defaultLanguage; } var select = null; for (var i = 0; i < this.availables.length; i++) { var available = this.availables[i]; var foundPos = language.indexOf(available); if (foundPos === 0) { if (select == null || select.length < available.length) { select = available; } } } if (select == null) { return this.defaultLanguage; } return select; }; i18nPt.loadScript = function (urlPattern) { return $.getScript(urlPattern.replace('{LANGUAGE}', this.pickUsableLanguage())); }; i18nPt.loadJson = function (urlPattern) { return $.getJSON(urlPattern.replace('{LANGUAGE}', this.pickUsableLanguage())).pipe(function (resource) { this.setResources(resource); }); }; return new exports(); }(window)); <file_sep>i18n.js v0.0.1 ============== translation for browser Usage ----- set translation resource: ```javascript i18n.setResource({ str_id: 'translated str_id' }); ``` perform translation on the document: ```javascript i18n.scan(); ``` ### *t* tag ```html ...<t>str_id</t>... ``` translated into: ```html ...translated str_id... ``` ### *.t-text* class ```html <span class="t-text">str_id</span> ``` translated into: ```html <span class="t-text-done">translated str_id</span> ``` ### *.t-attr* class ```html <input type="text" class="t-attr" placeholder="t:str_id" /> ``` translated into: ```html <input type="text" class="t-attr-done" placeholder="translated str_id" /> ``` HIDE UNTRANSLATED ----------------- Because the `<t>` tag and `.t-text` and `.t-attr` classes are replaced after translation, you can hide untranslated elements by following simple css: ```css t, .t-text, .t-attr { visibility: hidden; } ``` DPENDENCY --------- - jQuery LICENSE ------- MIT License (Yoshiya Hinosawa)
16b43472456e5ad26bc79cfd54b3b069aad0e4e3
[ "JavaScript", "Markdown" ]
2
JavaScript
kt3k/i18n.js
60f47bc72c9db4da2092981d77aa7fb26dc8aaf4
8dc14969e57f2f1b912946d4bb2c3fe87fc541f5
refs/heads/main
<repo_name>mairoky/jQuery<file_sep>/js/script.js $(document).ready(function () { // alert $('#click-btn').click(function(){ alert("Welcome"); }); // hide $('#hide-btn').click(function(){ $('#text').hide("slow"); }); // show $('#show-btn').click(function(){ $('#text').show("slow"); }); // toggle $('#toggle-btn').click(function(){ $('#text').toggle("slow"); }); // fadeout $('#fadeout-btn').click(function(){ $('#text').fadeOut("slow"); }); // fadein $('#fadein-btn').click(function(){ $('#text').fadeIn("slow"); }); // fade toggle $('#fadetoggle-btn').click(function(){ $('#text').fadeToggle("slow"); }); }); <file_sep>/README.md # jQuery Learn jQuery Basic https://mairoky.github.io/jQuery/
d4668885298b4e63d998dca55f13e089edaa2929
[ "JavaScript", "Markdown" ]
2
JavaScript
mairoky/jQuery
f70ed98a8d5fff756009851425d6597b6038c2a2
37d237c8f02a2e393fe2f40917fced1b95a72562
refs/heads/master
<repo_name>conceptslearningmachine-FEIN-85-1759293/generator-oraclejet<file_sep>/generators/restore-web/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const common = require('../../common'); const commonHookRunner = require('../../common/hookRunner'); const commonMessages = require('../../common/messages'); const commonRestore = require('../../common/restore'); const path = require('path'); /* * Generator for the restore step * Mainly to: * 1) invoke npm install * 2) write oraclejetconfig.json file */ const OracleJetWebRestoreGenerator = generators.Base.extend( { initializing: function () { //eslint-disable-line const done = this.async(); common.validateArgs(this) .then(common.validateFlags) .then(() => { done(); }) .catch((err) => { this.env.error(commonMessages.prefixError(err)); }); }, constructor: function() { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line }, install: function() { //eslint-disable-line // since both will be performing npm install initially just log here this.log('Performing npm install may take a bit.'); const done = this.async(); commonRestore.npmInstall({ generator: this }) .then(commonRestore.writeOracleJetConfigFile) .then(commonHookRunner.runAfterAppCreateHook) .then(() => { done(); }) .catch((err) => { if (err) { console.error(`\x1b[31mError: ${commonMessages.prefixError(err)}\x1b[0m`); process.exit(1); } }); }, end: function() { //eslint-disable-line this.log(commonMessages.restoreComplete( this.options.invokedByRestore, path.basename(this.env.cwd))); process.exit(0); } }); module.exports = OracleJetWebRestoreGenerator; <file_sep>/generators/app/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const common = require('../../common'); const commonComponent = require('../../common/component'); const commonMessages = require('../../common/messages'); const commonTest = require('../../common/test'); const templateHandler = require('../../common/template'); const path = require('path'); /* * Generator for the create step * Mainly to: * 1) copy the template in */ const OracleJetWebCreateGenerator = generators.Base.extend( { initializing: function () { //eslint-disable-line const done = this.async(); if (this.options.component) { this.appDir = this.options.component; } common.validateArgs(this) .then(common.validateFlags) .then(common.validateAppDirNotExistsOrIsEmpty) .then((validAppDir) => { this.appDir = path.basename(validAppDir); this.options.appname = this.appDir; return Promise.resolve(this); }) .then(() => { done(); }) .catch((err) => { console.error(`\x1b[31mError: ${commonMessages.prefixError(err)}\x1b[0m`); process.exit(1); }); }, constructor: function () { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line this.argument( 'appDir', { type: String, required: false, optional: true, defaults: '.', desc: 'Application directory to contain the scaffold content' }); this.option('template', { desc: 'blank, basic[:web|:hybrid], navbar[:web|:hybrid], navdrawer[:web|:hybrid], or <URL to zip file>' }); }, writing: function () { //eslint-disable-line const done = this.async(); const self = this; _writeTemplate(self) .then(common.switchToAppDirectory.bind(this)) .then(common.writeCommonTemplates) .then(common.writeGitIgnore) .then(common.updatePackageJSON) .then(() => { done(); }) .catch((err) => { if (err) { self.log.error(err); process.exit(1); } }); }, end: function () { //eslint-disable-line if (this.options.component) { this.log(`Your component ${this.options.component} project is scaffolded. Performing npm install may take a bit.`); } else { this.log(commonMessages.scaffoldComplete()); } if (!this.options.norestore) { this.composeWith('@oracle/oraclejet:restore-web', { options: this.options }); } } }); module.exports = OracleJetWebCreateGenerator; function _writeTemplate(generator) { return new Promise((resolve, reject) => { const appDirectory = generator.destinationPath(path.join(generator.appDir, 'src')); templateHandler.handleTemplate(generator, appDirectory) .then(commonComponent.writeComponentTemplate) .then(commonTest.writeTestTemplate) .then(() => { resolve(generator); }) .catch((err) => { reject(err); }); }); } <file_sep>/generators/add-component/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const common = require('../../common'); const commonComponent = require('../../common/component'); const commonHookRunner = require('../../common/hookRunner'); const commonMessages = require('../../common/messages'); const commonTest = require('../../common/test'); const fs2 = require('fs'); const path = require('path'); /* * Generator for the add-component step */ const OracleJetAddComponentGenerator = generators.Base.extend( { initializing: function () { //eslint-disable-line const done = this.async(); common.validateArgs(this) .then(common.validateFlags) .then(() => { done(); }) .catch((err) => { this.env.error(commonMessages.prefixError(err)); }); }, constructor: function() { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line try { this.argument('componentName', { type: String, required: true }); } catch (err) { this.env.error('Missing component name.'); } _validateComponentName(this); }, writing: function() { //eslint-disable-line const done = this.async(); this.options.component = this.componentName; commonComponent.writeComponentTemplate(this) .then(commonTest.writeTestTemplate) .then(commonHookRunner.runAfterComponentCreateHook) .then(() => { done(); }) .catch((err) => { if (err) { this.env.error(commonMessages.prefixError(err)); } }); }, end: function() { //eslint-disable-line const cwd = process.cwd(); const isApp = fs2.existsSync(path.join(cwd, 'oraclejetconfig.json')); if (!isApp) { this.composeWith('@oracle/oraclejet:app', { options: this.options }); } else { console.log(commonMessages.appendJETPrefix(`Add component ${this.componentName} finished.`)); } if (isApp) process.exit(0); } }); module.exports = OracleJetAddComponentGenerator; function _validateComponentName(generator) { const name = generator.componentName; if (name !== name.toLowerCase() || name.indexOf('-') < 0 || !/^[a-z]/.test(name)) { const message = 'Invalid component name. Must be all lowercase letters and contain at least one hyphen.'; generator.env.error(`\x1b[31m${new Error(message)}\x1b[0m`); //eslint-disable-line } } <file_sep>/generators/add-theme/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const fs = require('fs-extra'); const path = require('path'); const constants = require('../../util/constants'); const common = require('../../common'); const paths = require('../../util/paths'); const commonMessages = require('../../common/messages'); const DEFAULT_THEME = 'mytheme'; const JET_SCSS_SRC_PATH = 'node_modules/@oracle/oraclejet/dist/scss'; const PLATFORM_TOKEN = '<%= platform %>'; const JET_VERSION_TOKEN = '<%= jetversion %>'; const THEMENAME_TOKEN = '<%= themename %>'; /* * Generator for the add-theme step */ const OracleJetAddThemeGenerator = generators.Base.extend( { initializing: function () { //eslint-disable-line const done = this.async(); common.validateArgs(this) .then(common.validateFlags) .then(() => { done(); }) .catch((err) => { this.env.error(commonMessages.prefixError(err)); }); }, constructor: function () { //eslint-disable-line generators.Base.apply(this, arguments);//eslint-disable-line try { this.argument('themeName', { type: String, required: true }); } catch (err) { this.env.error(commonMessages.prefixError(err)); } if (this.themeName === constants.DEFAULT_THEME) { this.env.error(commonMessages.prefixError(`Theme ${constants.DEFAULT_THEME} is reserved.`)); } if (!_isValidThemeName(this.themeName)) { this.env.error(commonMessages.prefixError(`Special characters invalid in theme name ${this.themeName}.`)); } }, writing: function () { //eslint-disable-line const done = this.async(); _addSassTheme(this) .then(() => { done(); }) .catch((err) => { if (err) { this.env.error(commonMessages.prefixError(err)); } }); }, end: function () { //eslint-disable-line this.log(commonMessages.appendJETPrefix(`${this.themeName} theme added.`)); process.exit(0); } }); module.exports = OracleJetAddThemeGenerator; function _addSassTheme(generator) { const themeName = generator.themeName; const _configPaths = paths.getConfiguredPaths(generator.destinationPath()); const srcPath = _configPaths.source; const srcThemes = _configPaths.sourceThemes; const themeDestPath = path.resolve(srcPath, srcThemes, themeName); fs.ensureDirSync(themeDestPath); const source = generator.templatePath(DEFAULT_THEME); return new Promise((resolve, reject) => { try { // first copy over templates fs.copySync(source, themeDestPath); _copySettingsFilesFromJETSrc(themeName, themeDestPath, generator); _renameFilesAllPlatforms(themeName, themeDestPath, generator); return resolve(generator); } catch (err) { return reject(commonMessages.error(err, 'add-theme')); } }); } function _renameFilesAllPlatforms(themeName, dest, generator) { const platforms = _getAllSupportedPlatforms(); platforms.forEach((platform) => { _renameFileOnePlatform(themeName, dest, platform, generator); }); } function _getAllSupportedPlatforms() { return constants.SUPPORTED_PLATFORMS; } function _renameFileOnePlatform(themeName, dest, platform, generator) { const fileDir = path.join(dest, platform); const fileList = fs.readdirSync(fileDir); const scssFiles = fileList.filter(_isScssFile); scssFiles.forEach((file) => { const newPath = _renameFile(themeName, fileDir, file); _replaceTokens(newPath, generator, themeName, platform); }); } // replace mytheme.css to the actual themeName.css function _renameFile(themeName, fileDir, file) { const oldPath = path.join(fileDir, file); let newPath = file.replace(DEFAULT_THEME, themeName); newPath = path.join(fileDir, newPath); fs.renameSync(oldPath, newPath); return newPath; } function _isScssFile(file) { return /scss/.test(path.extname(file)); } function _isValidThemeName(string) { return !(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/.test(string)); //eslint-disable-line } function _getJetVersion(generator) { let packageJSON = generator.destinationPath('node_modules/@oracle/oraclejet/package.json'); packageJSON = fs.readJsonSync(packageJSON); return packageJSON.version; } // default marker <%= jetversion %> <%= themename %> <%= platform %> // are used to inject jet version and themename function _replaceTokens(filePath, generator, themeName, platform) { let fileContent = fs.readFileSync(filePath, 'utf-8'); const jetVersion = _getJetVersion(generator); fileContent = fileContent.replace(new RegExp(JET_VERSION_TOKEN, 'g'), jetVersion); fileContent = fileContent.replace(new RegExp(THEMENAME_TOKEN, 'g'), themeName); fileContent = fileContent.replace(new RegExp(PLATFORM_TOKEN, 'g'), platform); fs.outputFileSync(filePath, fileContent); } function _copySettingsFilesFromJETSrc(themeName, dest) { const settingsFileName = `_oj.alta.${PLATFORM_TOKEN}settings.scss`; constants.SUPPORTED_PLATFORMS.forEach((platform) => { const platformPath = _getPlatformPath(platform); const srcSettingFileName = _getSrcSettingFileName(platform); const srcPath = path.join(JET_SCSS_SRC_PATH, platformPath, srcSettingFileName); const destSettingFileName = _getDestSettingFileName(DEFAULT_THEME, platform); const destPath = path.join(dest, platform, destSettingFileName); fs.copySync(srcPath, destPath); _injectDefaultValues(destPath); }); function _getDestSettingFileName(name, platform) { return `_${name}.${platform}.settings.scss`; } function _getSrcSettingFileName(platform) { const platformName = (platform === 'web') ? '' : `${platform}.`; return settingsFileName.replace(PLATFORM_TOKEN, platformName); } function _getPlatformPath(platform) { return (platform === 'web') ? 'alta' : `alta-${platform}`; } function _injectDefaultValues(filePath) { let fileContent = fs.readFileSync(filePath, 'utf-8'); const valuePairs = _getValuePairsArray(); valuePairs.forEach((valuePair) => { fileContent = fileContent.replace(valuePair.str, valuePair.newStr); }); fs.outputFileSync(filePath, fileContent); } function _getValuePairsArray() { return [ { str: new RegExp('@import\ \"\.\.\/utilities', 'g'), //eslint-disable-line newStr: '@import "../../../../node_modules/@oracle/oraclejet/dist/scss/utilities', }, { str: new RegExp('.*\\$themeName.*'), newStr: `$themeName: ${THEMENAME_TOKEN} !default;`, }, { str: new RegExp('.*\\$imageDir.*'), newStr: `$imageDir: "../../../alta/${JET_VERSION_TOKEN}/${PLATFORM_TOKEN}/images/" !default;`, }, { str: new RegExp('.*\\$fontDir.*'), newStr: `$fontDir: "../../../alta/${JET_VERSION_TOKEN}/${PLATFORM_TOKEN}/fonts/" !default;`, }, { str: new RegExp('.*\\$commonImageDir.*'), newStr: `$commonImageDir: "../../../alta/${JET_VERSION_TOKEN}/common/images/" !default;`, }, ]; } } <file_sep>/generators/add-hybrid/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const childProcess = require('child_process'); const generators = require('yeoman-generator'); const fs = require('fs-extra'); const path = require('path'); const common = require('../../common'); const paths = require('../../util/paths'); const commonMessages = require('../../common/messages'); const commonHybrid = require('../../hybrid'); const cordovaHelper = require('../../hybrid/cordova'); const platformsHelper = require('../../hybrid/platforms'); const _configPaths = {}; /* * Generator for the add-hybrid step */ const OracleJetAddHybridGenerator = generators.Base.extend( { constructor: function() { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line this.option('platforms', { desc: 'Specify the platforms to be supported by the scaffolded hybrid app [android, ios, windows]', }); this.option('platform', { desc: 'Alias for --platforms if the user wishes to specify a single hybrid platform [android, ios, windows]' }); this.option('appid', { desc: 'Specify the app ID for scaffolded hybrid app' }); // Deprecated version this.option('appId', { desc: 'Deprecated. Use --appid instead.' }); this.option('appname', { desc: 'Specify the app name for scaffolded hybrid app' }); // Deprecated version this.option('appName', { desc: 'Deprecated. Use --appname instead.' }); }, initializing: function () { //eslint-disable-line const done = this.async(); _setConfigPaths(paths.getConfiguredPaths(this.destinationPath())); common.validateArgs(this) .then(_checkIfCordovaIsInstalled) .then(common.validateFlags) .then(_validateAppDirForAddHybrid) .then(() => { this.appDir = path.basename(this.destinationRoot()); commonHybrid.setupHybridEnv(this); done(); }) .catch((err) => { this.env.error(commonMessages.prefixError(err)); }); }, prompting: function () { //eslint-disable-line const done = this.async(); platformsHelper.getPlatforms(this) .then(() => { done(); }); }, writing: function() { //eslint-disable-line const done = this.async(); _createExtraSrcDirs(this) .then(cordovaHelper.create.bind(this)) .then(commonHybrid.copyHooks.bind(this)) .then(commonHybrid.copyResources.bind(this)) .then(_copyCordovaMocks.bind(this)) .then(commonHybrid.removeExtraCordovaFiles.bind(this)) .then(platformsHelper.addPlatforms.bind(this)) .then(commonHybrid.updateConfigXml.bind(this)) .then(() => { done(); }) .catch((err) => { if (err) { this.env.error(commonMessages.prefixError(err)); } }); }, end: function() { //eslint-disable-line this.log(commonMessages.appendJETPrefix('Add-hybrid finished.')); } }); function _checkIfCordovaIsInstalled(generator) { return new Promise((resolve, reject) => { childProcess.exec('cordova', (error) => { if (error) { reject('Cordova not installed. Please install by: "npm install -g cordova"'); } else { resolve(generator); } }); }); } function _setConfigPaths(configPathObj) { Object.keys(configPathObj).forEach((key) => { _configPaths[key] = configPathObj[key]; }); } function _validateAppDirForAddHybrid(generator) { return _validateSrcDirExists(generator) .then(_validateHybridDirDoesNotExist.bind(generator)); } function _createExtraSrcDirs(generator) { let srcHybridPath = _configPaths.sourceHybrid; let srcWebPath = _configPaths.sourceWeb; srcWebPath = generator.destinationPath(srcWebPath); srcHybridPath = generator.destinationPath(srcHybridPath); fs.ensureDirSync(srcHybridPath); fs.ensureDirSync(srcWebPath); return Promise.resolve(generator); } function _validateSrcDirExists(generator) { let errorMsg; const appSrcPath = _configPaths.source; try { fs.statSync(generator.destinationPath(appSrcPath)); return Promise.resolve(generator); } catch (err) { errorMsg = `Missing '${appSrcPath}' directory. ` + 'Invalid JET project structure.'; return Promise.reject(commonMessages.error(errorMsg, 'validateSrcDirExists')); } } function _validateHybridDirDoesNotExist(generator) { let stats; let errorMsg; try { const hybridPath = _configPaths.stagingHybrid; stats = fs.statSync(generator.destinationPath(hybridPath)); if (stats.isDirectory) { errorMsg = `The project already contains the '${hybridPath }' directory.`; return Promise.reject(commonMessages.error(errorMsg, 'validateHybridDirDoesNotExist')); } } catch (err) { // hybrid dir does not exist, OK to proceed } return Promise.resolve(generator); } function _copyCordovaMocks(generator) { const source = generator.templatePath('../../hybrid/templates/common/src/js/'); const srcHybridPath = _configPaths.sourceHybrid; const srcJsPath = _configPaths.sourceJavascript; const dest = generator.destinationPath(`./${srcHybridPath}/${srcJsPath}/`); return new Promise((resolve, reject) => { if (common.fsExistsSync(source)) { fs.copy(source, dest, (err) => { if (err) { reject(err); return; } resolve(generator); }); } else { reject('Missing file \'cordovaMocks.js\'.'); } }); } module.exports = OracleJetAddHybridGenerator; <file_sep>/RELEASENOTES.md ## Release Notes for generator-oraclejet ## ### 6.2.0 * No changes ### 5.2.0 * No changes ### 5.1.0 * No changes ### 5.0.0 * No changes ### 4.2.0 * No changes ### 4.1.0 * No changes ### 4.0.0 * Moved module into @oracle scope, changing the name to @oracle/generator-oraclejet * This module should no longer be installed directly. Use @oracle/ojet-cli instead for scaffolding JET apps. ### 3.2.0 * No changes ### 3.1.0 * No changes ### 3.0.0 * Replaced bower with npm * SASS tasks now run in CCA directories also * Added --destination=server-only option for web apps * Removed --destination=deviceOrEmulatorName option * Added ability to cutomize serve tasks such as watching additional files * Added gap://ready to inserted CSP meta tag for iOS 10 compatibility * Requires Node.js v4.0.0+ and npm v3.0.0+ * Known issue: grunt serve to iOS device requires developer profile ### 2.3.0 * Allow local files as scaffolding starting templates * Provide the ability to specify the Windows hybrid platform architecture * Better handling for determining which browser is launched when serving a hybrid app * Please use the latest version of yeoman as some earlier versions can cause issues with scaffolding ### 2.2.0 * Provide help page for generator <file_sep>/generators/hybrid/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const paths = require('../../util/paths'); const path = require('path'); const templateHandler = require('../../common/template/'); const common = require('../../common'); const commonHybrid = require('../../hybrid'); const commonComponent = require('../../common/component'); const commonMessages = require('../../common/messages'); const commonTest = require('../../common/test'); const cordovaHelper = require('../../hybrid/cordova'); const platformsHelper = require('../../hybrid/platforms'); /* * Generator for the create step * Mainly to: * 1) copy the template in * 2) perform cordova create * 3) perform cordova add */ const OracleJetHybridCreateGenerator = generators.Base.extend( { constructor: function () { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line this.argument( 'appDir', { type: String, required: false, optional: true, defaults: '.', desc: 'Application directory to contain the scaffold content' }); this.option('platforms', { desc: 'Specify the platforms to be supported by the scaffolded hybrid app [android, ios, windows]', }); this.option('platform', { desc: 'Alias for --platforms if the user wishes to specify a single hybrid platform [android, ios, windows]' }); this.option('template', { desc: 'Specify the starter template that is used to scaffold the app [blank, basic[:web|:hybrid], navbar[:web|:hybrid], navdrawer[:web|:hybrid], or <URL to zip file>' }); this.option('appid', { desc: 'Specify the app ID for scaffolded hybrid app', }); // Deprecated version this.option('appId', { desc: 'Deprecated. Use --appid instead.' }); this.option('appname', { desc: 'Specify the app name for scaffolded hybrid app' }); // Deprecated vrsion this.option('appName', { desc: 'Deprecated. Use --appname instead.' }); }, initializing: function () { //eslint-disable-line const done = this.async(); if (this.options.component) { this.appDir = this.options.component; } common.validateArgs(this) .then(common.validateFlags) .then(common.validateAppDirNotExistsOrIsEmpty) .then((validAppDir) => { this.appDir = path.basename(validAppDir); commonHybrid.setupHybridEnv(this); done(); }) .catch((err) => { console.error(`\x1b[31mError: ${commonMessages.prefixError(err)}\x1b[0m`); process.exit(1); }); }, prompting: function () { //eslint-disable-line const done = this.async(); platformsHelper.getPlatforms(this) .then(() => { done(); }); }, writing: function () { //eslint-disable-line const done = this.async(); _writeTemplate(this) .then(common.switchToAppDirectory.bind(this)) .then(common.writeCommonTemplates) .then(common.writeGitIgnore) .then(common.updatePackageJSON) .then(cordovaHelper.create) .then(commonHybrid.copyResources.bind(this)) .then(commonHybrid.removeExtraCordovaFiles.bind(this)) .then(platformsHelper.addPlatforms.bind(this)) .then(commonHybrid.updateConfigXml.bind(this)) .then(() => { done(); }) .catch((err) => { if (err) { this.log.error(err); process.exit(1); } }); }, end() { if (this.options.component) { this.log(`Your component ${this.options.component} project is scaffolded. Performing npm install may take a bit.`); } else { this.log(commonMessages.scaffoldComplete()); } if (!this.options.norestore) { this.composeWith('@oracle/oraclejet:restore-hybrid', { options: this.options }); } } }); module.exports = OracleJetHybridCreateGenerator; function _writeTemplate(generator) { return new Promise((resolve, reject) => { const appDir = generator.appDir; const appSrc = paths.getDefaultPaths().source; templateHandler.handleTemplate(generator, generator.destinationPath(`${appDir}/${appSrc}/`)) .then(commonComponent.writeComponentTemplate) .then(commonTest.writeTestTemplate) .then(() => { resolve(generator); }) .catch((err) => { reject(err); }); }); } <file_sep>/util/fetchZip.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const Admzip = require('adm-zip'); const request = require('request'); module.exports = function (url) { // fetches the zip file return new Promise((resolve, reject) => { const data = []; let dataLen = 0; request.get({ url, encoding: null }).on('error', (err) => { reject(err); }).on('data', (block) => { data.push(block); dataLen += block.length; }).on('end', (err) => { if (err) { reject(err); } const buf = new Buffer(dataLen); for (let i = 0, len = data.length, pos = 0; i < len; i += 1) { data[i].copy(buf, pos); pos += data[i].length; } try { const zip = new Admzip(buf); resolve(zip); } catch (e) { reject(e); } }); }); }; <file_sep>/generators/restore/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const fs = require('fs-extra'); const path = require('path'); const paths = require('../../util/paths'); const constants = require('../../util/constants'); /* * Compose with oraclejet:restore-web or oraclejet:restore-hybrid */ const OracleJetRestoreGenerator = generators.Base.extend( { constructor: function () { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line }, initializing: function () { //eslint-disable-line // if the project contains cordova's config.xml, consider it to be a hybrid; otherwise web const cordovaDir = paths.getConfiguredPaths(this.destinationPath()).stagingHybrid; this._hybrid = fs.existsSync(path.resolve(cordovaDir, constants.CORDOVA_CONFIG_XML)); }, end: function () { //eslint-disable-line const appType = constants.APP_TYPE; const restoreType = this._hybrid ? appType.HYBRID : appType.WEB; this.options.invokedByRestore = true; this.composeWith( `@oracle/oraclejet:restore-${restoreType}`, { options: this.options, arguments: this.arguments }); } }); module.exports = OracleJetRestoreGenerator; <file_sep>/README.md # @oracle/generator-oraclejet 6.2.0 ## About the generator This Yeoman generator for Oracle JET lets you quickly set up a project for use as a web application or hybrid mobile application for Android, iOS or Windows 10. This is an open source project maintained by Oracle Corp. ## Installation This module will be automatically installed as a dependency of the Oracle JET command-line interface [@oracle/ojet-cli](https://github.com/oracle/ojet-cli), and should not be installed directly. ## [Contributing](https://github.com/oracle/generator-oraclejet/tree/master/CONTRIBUTING.md) Oracle JET is an open source project. Pull Requests are currently not being accepted. See [CONTRIBUTING](https://github.com/oracle/generator-oraclejet/tree/master/CONTRIBUTING.md) for details. ## [License](https://github.com/oracle/generator-oraclejet/tree/master/LICENSE.md) Copyright (c) 2014, 2019 Oracle and/or its affiliates The Universal Permissive License (UPL), Version 1.0 <file_sep>/Gruntfile.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ module.exports = function (grunt) { grunt.initConfig({ }); // Load grunt tasks from NPM packages require("load-grunt-tasks")(grunt); // Merge sub configs var options = { config : { src : "build/generator.js" }, pkg: grunt.file.readJSON("package.json") } var configs = require('load-grunt-configs')(grunt, options); grunt.config.merge(configs); }; <file_sep>/common/restore.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const fs = require('fs-extra'); const path = require('path'); const common = require('./index'); const commonMessages = require('./messages'); const generatorJSON = require('../package.json'); const ORACLE_JET_CONFIG_FILE = 'oraclejetconfig.json'; module.exports = { writeOracleJetConfigFile: function _writeOracleJetConfigFile(context) { const generator = context.generator; const destinationRoot = generator.destinationRoot(); const configPath = path.resolve(destinationRoot, ORACLE_JET_CONFIG_FILE); return new Promise((resolve) => { generator.log('Writing:', ORACLE_JET_CONFIG_FILE); // need to place the oracletjetconfig.json at origDestRoot fs.stat(configPath, (err) => { const generatorVersion = _getOracleJetGeneratorVersion(generator); if (err) { generator.log(`${commonMessages.appendJETPrefix()}No config file. Writing the default config.`); fs.writeJSONSync(configPath, { generatorVersion }); } else { const configJson = fs.readJSONSync(configPath); configJson.generatorVersion = generatorVersion; fs.writeJSONSync(configPath, configJson); generator.log(`${commonMessages.appendJETPrefix() + ORACLE_JET_CONFIG_FILE} file exists. Checking config.`); } resolve(context); }); }); }, npmInstall: function _npmInstall(context) { return new Promise((resolve, reject) => { Promise.all([ common.gruntSpawnCommandPromise(context, 'npm', ['install'], 'Invoking npm install.') ]) .then(() => { // rejection will be handled by each promise which will // halt the generator resolve(context); }) .catch((err) => { reject(err); }); }); } }; /* * Gets the generator version */ function _getOracleJetGeneratorVersion() { // We intend to read the top level package.json for the generator-oraclejet module. // Note this path to package.json depends on the location of this file within the // module (common/restore.js) return generatorJSON.version; } <file_sep>/generators/add-sass/index.js /** Copyright (c) 2015, 2019, Oracle and/or its affiliates. The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; const generators = require('yeoman-generator'); const common = require('../../common'); const commonMessages = require('../../common/messages'); /* * Generator for the add-sass step */ const OracleJetAddSassGenerator = generators.Base.extend( { initializing: function () { //eslint-disable-line const done = this.async(); common.validateArgs(this) .then(common.validateFlags) .then(() => { done(); }) .catch((err) => { this.env.error(commonMessages.prefixError(err)); }); }, constructor: function() { //eslint-disable-line generators.Base.apply(this, arguments); //eslint-disable-line }, writing: function() { //eslint-disable-line const done = this.async(); _npmInstallNodeSass(this) .then(() => { done(); }) .catch((err) => { if (err) { this.env.error(commonMessages.prefixError(err)); } }); }, end: function() { //eslint-disable-line console.log(commonMessages.appendJETPrefix('add-sass finished.')); process.exit(0); } }); module.exports = OracleJetAddSassGenerator; function _npmInstallNodeSass(generator) { try { generator.npmInstall(['node-sass@4.7.2'], { saveDev: true }); return Promise.resolve(generator); } catch (err) { return Promise.reject(commonMessages.error(err, 'install node-sass')); } }
11676a80294a51764a2aeba40b59f7dc00d8ca4d
[ "JavaScript", "Markdown" ]
13
JavaScript
conceptslearningmachine-FEIN-85-1759293/generator-oraclejet
6dfa1f942aaa01d8ba682ef1c47439b4d95ca95a
a8a8ebc930863581e717196e094db3c5c420b7b7
refs/heads/master
<file_sep><?php if (($handle = fopen("BackOffice/BackEntreprise/Entreprise.csv","r"))) { while ($data = fgetcsv($handle, 1024, ';')) { include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; // <!-------------------------------------------------------> // <!-- Entreprise --> // <!-------------------------------------------------------> echo '<h1 class="titre_entreprise">L\'entreprise</h1> <section id="contenu"> <div class="presentation"> <h2 class="soustitre">Présentation</h2> <p id="texte_entreprise">'. $data[1] .'</p> </div> </section>'; } }else { echo "erreur de chargement"; } // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php $list = ["Decalage"]; $Destination = "img/"; if (($handle = fopen("Inauguration.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { echo "<pre>"; var_dump($_POST['formulaire'. 1]); echo "<pre>"; echo "<pre>"; var_dump($_FILES['formulaire'. 3 ]['name']); echo "<pre>"; echo "<pre>"; var_dump($_FILES['formulaire'. 3 ]['tmp_name']); echo "<pre>"; echo "<pre>"; var_dump($data); echo "<pre>"; array_push($list, $_POST["formulaire". 1]); array_push($list, $_POST["formulaire". 2]); if (strlen($_FILES['formulaire'. 3 ]['name']) > 0){ $Image = $_FILES['formulaire'. 3]; array_push($list, $Destination.$_FILES['formulaire'. 3]['name']); move_uploaded_file($Image["tmp_name"],"../../".$Destination.$_FILES['formulaire'. 3 ]['name']); echo "test1"; }else{ array_push($list, $data[3]); echo "test2"; } echo "<pre>"; var_dump($list); echo "<pre>"; } $fp = fopen('Inauguration.csv','w'); fprintf($fp, chr(0xEF).chr(0xBB).chr(0xbf)); fputcsv($fp,$list,';'); fclose($fp); } header("location:BackInauguration.php"); ?> <file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; echo "<div id='content'> <h1 class='Titre_conditions'>Conditions Général d'Utilisation</h1> <p id='texte_conditions'>En naviguant sur notre site, l’internaute reconnaît avoir pris connaissance et accepté nos conditions générales d’utilisation Données personnelles : Les données personnelles qui peuvent vous être demandées (exclusivement en vue de recevoir notre newsletter) sont vos nom prénom et adresse mails. Le traitement de ces données dont le responsable est <NAME> est en conformité avec le Règlement général de protection des données personnelles entré en vigueur le 25 Mai 2018. Vous pouvez faire valoir vos droits de consultation, de rectification et de suppression en le contactant à l’adresse suivante [e-mail] Nous nous engageons à ne pas revendre ni donner ces informations qui ne sont pas conservées dès lors que vous demandez à ne plus recevoir notre newsletter. Cookies : En vue d’améliorer notre site, nous utilisons Google Analytics qui est un outil « d'analyse d'audience Internet permettant aux propriétaires de sites Web et d'applications de mieux comprendre le comportement de leurs utilisateurs. Cet outil peut utiliser des cookies pour collecter des informations et générer des rapports sur les statistiques d'utilisation d'un site Web sans que les utilisateurs individuels soient identifiés personnellement par Google. Outre la génération de rapports sur les statistiques d'utilisation d'un site Web, Google Analytics permet également, en association avec certains des cookies publicitaires décrits ci-dessus, d'afficher des annonces plus pertinentes sur les sites Google (tels que la recherche Google) et sur le Web. » Nous utilisons également les cookies nécessaires à l’amélioration de votre navigation sur notre site tenant compte exclusivement de votre navigateur. Propriété intellectuelle : Le site web a été réalisé par notre webmaster, <NAME>. Il est la propriété de l’association et ne peut faire l’objet de reproduction. Photographies et contenu : Les photographies, vidéos, textes et illustrations publiés sur le site sont propriété de l’association ou ont fait l’objet de cession de droits. Ils ne peuvent faire l’objet d’aucune réutilisation.</p> </div>"; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; echo "<div id='content'> <h1 class='Titre_politique'>Politique de Confidentialité</h1> <p id='texte_politique'>A. Introduction : 1. La confidentialité des visiteurs de notre site Web est très importante pour nous et nous sommes engagé à le sauvegarder. Cette politique explique ce que nous faisons avec votre informations personnelles. 2. Consentement à notre utilisation des cookies conformément aux termes de cette politique lorsque vous visitez notre site Web pour la première fois, nous pouvons utiliser des cookies à chaque visite notre site Web. B. Crédit 1. Ce document a été créé à l'aide d'un modèle de SEQ Legal (seqlegal.com) et modifié par vpnMentor (www.vpnmentor.com) C. Comment nous recueillons vos données personnelles Les types d'informations personnelles suivants peuvent être collectés, stockés et utilisés: 1. Informations sur votre ordinateur, y compris votre adresse IP, vos coordonnées géographiques emplacement, type et version du navigateur et système d'exploitation 2. Informations sur vos visites et votre utilisation de ce site, y compris les source de référence, durée de la visite, pages vues et chemins de navigation du site Web. 3. Les informations que vous entrez lors de votre inscription sur notre site Web, telles que votre site e-mail. 4. Les informations que vous entrez lorsque vous créez un profil sur notre site Web. Pour Par exemple, votre nom, photos de profil, sexe, anniversaire, relation statut, intérêts et loisirs, détails de l'éducation et emploi détails. 5. Informations que vous entrez pour configurer votre abonnement à nos emails et / ou des lettres d'information. 6. Les informations générées lors de l'utilisation de notre site Web, y compris quand, à quelle fréquence et dans quelles circonstances vous l'utilisez. 7. Les informations relatives à tout ce que vous achetez, aux services que vous utilisez ou la transaction que vous effectuez sur notre site Web, qui comprend votre nom, adresse, numéro de téléphone, adresse e-mail et détails de carte de crédit. 8. Informations que vous publiez sur notre site Web dans l'intention de les publier c'est sur internet. 9. Toute autre information personnelle que vous nous envoyez. D. Utilisation des informations personnelles Les informations personnelles qui nous sont communiquées via notre site Web seront utilisées pour la aux fins spécifiées dans la présente politique ou sur les pages correspondantes du site Web. Nous pouvons Utilisez vos informations personnelles pour: 1. Administrer notre site Web et notre entreprise 2. Personnaliser notre site pour vous 3. Permettre votre utilisation des services disponibles sur notre site web 4. Vous envoyer les produits achetés via notre site Web 5. Fournir des services achetés via notre site Web 6. Vous envoyer des relevés, des factures et des rappels de paiement, et recueillir des paiements de votre part. 7. Vous envoyer des communications commerciales sur le marketing 8. Vous envoyer des notifications par courrier électronique que vous avez spécifiquement demandées. 9. Vous envoyer notre newsletter par e-mail si vous vous êtes inscrit (vous pouvez désinscrire à tout moment). 10.Envoi de communications marketing relatives à notre activité ou à la entreprises de tiers qui, à notre avis, pourraient vous intéresser. 11. Fournir à des tiers des informations statistiques sur nos utilisateurs. 12. Traitement des demandes de renseignements et des plaintes formulées par vous ou à votre sujet concernant notre site Web 13.En gardant notre site Web sécurisé et prévenir la fraude. 14.Vérifier le respect des conditions générales régissant l’utilisation de notre site Web. 15. Autres utilisations. Si vous soumettez des informations personnelles pour publication sur notre site Web, nous les publierons. et sinon, utilisez ces informations conformément à la licence que vous nous accordez. Vos paramètres de confidentialité peuvent être utilisés pour limiter la publication de vos informations sur notre site. site Web et peut être ajusté à l’aide des contrôles de confidentialité du site Web. Sans votre consentement, nous ne fournirons pas vos informations personnelles à tiers pour leur marketing direct ou celui de tout autre tiers. E. Divulgation d'informations personnelles Nous pouvons divulguer vos informations personnelles à l’un de nos employés, dirigeants, assureurs, conseillers professionnels, agents, fournisseurs ou sous-traitants dans la mesure du raisonnable. nécessaires aux fins énoncées dans la présente politique. Nous pouvons divulguer vos informations personnelles à tout membre de notre groupe de sociétés (c'est-à-dire nos filiales, notre société holding ultime et tous ses filiales) comme raisonnablement nécessaire aux fins énoncées dans la présente politique. Nous pouvons divulguer vos informations personnelles: 1. dans la mesure où nous sommes obligés de le faire par la loi; 2. dans le cadre de procédures judiciaires en cours ou à venir; 3. afin d’établir, d’exercer ou de défendre nos droits légaux (y compris en fournissant informations à des tiers à des fins de prévention de la fraude et de réduction des le risque de crédit); 4. à l'acheteur (ou l'acheteur potentiel) de toute entreprise ou actif que nous envisagent (ou envisagent) de vendre; et 5. à toute personne qui, selon nous, peut raisonnablement demander à un tribunal ou à une autre compétente pour la divulgation de ces informations personnelles lorsque, à notre avis, opinion raisonnable, ce tribunal ou cette autorité serait raisonnablement susceptible de ordonner la divulgation de ces renseignements personnels. Sauf indication contraire dans la présente politique, nous ne fournirons pas vos informations personnelles à des tiers. F. Transferts internationaux de données 1. Les informations que nous collectons peuvent être stockées, traitées et transférées entre l'un des pays dans lesquels nous opérons afin de nous permettre</p> </div>"; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php //Affiche les champs pour changer les elements d'inauguration // $j = 1; include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; echo ' <form action="Modifier.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">'; if (($handle = fopen("TeamBuilding.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { echo '<div id="evenement">'; echo "<label class='formulaire TEvenement'> Titre de l'évènement "; echo'<input type="text" name="formulaire'. 1 .'" class="formulaire" value="'.$data[1].'">'; echo '</label>'; echo "<label class='formulaire TEvenement'> Texte de l'évènement "; echo'<textarea name=" formulaire2" class="formulaire" rows="15" cols="70">'.$data[2].'</textarea>"'; echo '</label>'; echo '<img src="../../'.$data[3].'" id="inauguration">'; echo "<label class='formulaire'> Image de l'évènement"; echo '<input type="file" value="parcourir..." name= "formulaire'. 3 .'"">'; echo "</label>"; echo '<input type="submit" name="Modifier" value="Modifier"> </form> </div>'; // for ($i=1; $i < count($data); $i++) { // $ma_chaine = $data[$i]; // $trouve_moi = '.jpg'; //cherche l'extantion du fichier pour savoir si c'est une image // $position = strpos($ma_chaine, $trouve_moi); // if ($position === false){//si ce n'est pas une image mettre ce champ // echo '<label> Texte '; echo $j ; // echo'<input type="text" name="formulaire'.$j.'" class="formulaire" value="'.$data[$i].'">'; // echo '</label>'; // }else{//si c'est une image mettre ce champ // echo '<input type="file" value="parcourir..." name= "formulaire'.$j.'"">'; // } // $j++; // } } // echo '<form action="Ajouter.php" method="post" accept-charset="utf-8"> // <input type="submit" name="Ajouter Texte" value="Ajouter Texte"> // <input type="submit" name="Ajouter Image" value="Ajouter Image"> // </form>'; }else { echo "erreur de chargement"; } ?><file_sep><?php if (($handle = fopen("Entreprise.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; echo ' <form action="Modifier.php" method="post" accept-charset="utf-8">'; echo '<label> Contenue de la page' ; echo'<textarea name=" formulaire1" class="formulaire" rows="15" cols="70">'.$data[1].'</textarea>"'; echo '</label>'; } echo '<input type="submit" name="Modifier" value="Modifier"> </form>'; }else { echo "erreur de chargement"; } ?><file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; echo "<div> <h1 class='Titre_equipe'>L'équipe</h1> <p id='PEquipe'>Une équipe jeune et dynamique vous attent dans la création de vos projets.</p> <div> <div id='content'> <div class='galerie_carousel'> <div class='employee'> <img src='img/chan.jpg' class='photo'> <p id='text_identifiant'>Chin-Sekai - Li</p> <p id='text_identifiant'>directeur adjoint</p> </div> <div class='employee'> <img src='img/DRH.jpg' class='photo'> <p id='text_identifiant'>Reus - Berta</p> <p id='text_identifiant'>Chef Technique</p> </div> <div class='employee'> <img src='img/E=MC2.jpg' class='photo'> <p id='text_identifiant'>Einstein - Albert</p> <p id='text_identifiant' id='text_identifiant'>Ingénieur de Recherche</p> </div> <div class='employee'> <img src='img/lelouch.jpg' class='photo'> <p id='text_identifiant'>Goto - Sakai</p> <p id='text_identifiant'>Chef Organisateur</p> </div> <div class='employee'> <img src='img/girl.jpg' class='photo'> <p id='text_identifiant'>Beaujolais - Alexandra</p> <p id='text_identifiant'>Organisatrice adjointe</p> </div> <div class='employee'> <img src='img/mael.jpg' class='photo'> <p id='text_identifiant'>Laporte - Vincent</p> <p id='text_identifiant'>Commercial</p> </div> <div class='employee'> <img src='img/thierry.jpg' class='photo'> <p id='text_identifiant'>Lafont - Thierry</p> <p id='text_identifiant'>Commercial</p> </div> <div class='employee'> <img src='img/patron.jpg' class='photo'> <p id='text_identifiant'>Dupont - Benoit</p> <p id='text_identifiant'>Marketing</p> </div> <div class='employee'> <img src='img/grilr.jpg' class='photo'> <p id='text_identifiant'>Jalier - Camille</p> <p id='text_identifiant'>Marketing</p> </div> <div class='employee'> <img src='img/child.jpg' class='photo'> <p id='text_identifiant'>Baudouin - Juliette</p> <p id='text_identifiant'>Animatrice</p> </div> </div> </div> <script src='js/jquery-1.11.0.min.js'></script> <script src='js/jquery-migrate-1.2.1.min.js'></script> <script src='slick/slick.min.js'></script> <script src='js/carrousel.js'></script>"; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?> <file_sep><?php $list = ["Nom","Prenom","Adresse","Code Postal","Ville","Email","Telephone","Date de l'évènement","Objet","Adresse de l'évènement","Description"]; echo "<pre>"; var_dump($list); echo "<pre>"; $fp = fopen("BD.csv","w");// fprintf($fp, chr(0xEF).chr(0xBB).chr(0xbf)); fputcsv($fp,$list,";"); fclose($fp); header("location:Formulaire.php") ?><file_sep><?php // if ($_POST['prenom'] == false) { // $list = ['Nom' => $_POST['nom'], 'Email' => $_POST['mail'], 'Objet' => $_POST['objet'], 'Information' => $_POST['information']]; // } // else{ $list = ['Nom' => $_POST['nom'], 'Prenom' => $_POST['prenom'], 'Adresse' => $_POST['adresse'], 'Code' => $_POST['code'], 'Ville' => $_POST['ville'], 'Email' => $_POST['email'], 'Telephone' => $_POST['telephone'], 'Date' => $_POST['date'], 'Objet' => $_POST['objet'], 'AdresseEvenement' => $_POST['adresseEvenement'], 'Information' => $_POST['information']]; // } echo "<pre>"; var_dump($list); echo "<pre>"; $fp = fopen('BackOffice/Formulaire/BD.csv','a');// fprintf($fp, chr(0xEF).chr(0xBB).chr(0xbf)); fputcsv($fp,$list,";"); fclose($fp); header("location:Devis.php") ?><file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; // <!-------------------------------------------------------> // <!-- Contactez-Nous --> // <!-------------------------------------------------------> echo '<div id="formulaire"> <div id=Contactez> <form action="Insert.php" method="POST" id="contact"> <h1 class="Titre">Contactez Nous</h1> <input type="text" name="nom" id="nom_societe" class="champs" placeholder="Nom de votre société"/> <input type="email" name="mail" id="mail" class="champs" placeholder="Adresse email de contact"/> <input type="text" name="objet" id="objet" class="champs" placeholder="Objet"/> <textarea name="information" id="information" class="champs" placeholder="Taper votre demande" rows="15" cols="70"></textarea> <input type="submit" id="envoyer" value="Envoyer" /> </form> </div>'; // <!-------------------------------------------------------> // <!-- Devis --> // <!-------------------------------------------------------> echo '<div id="Devis"> <form action="Insert.php" method="POST" id="devis"> <h1 class="Titre">Devis</h1> <input type="text" name="entreprise" id="entreprise" class="champs" placeholder="Nom de votre Entreprise"/> <input type="text" name="nom" id="nom" class="champs" placeholder="Nom"/> <input type="text" name="prenom" id="prenom" class="champs" placeholder="Prénom"/> <input type="text" name="adresse" id="adresse" class="champs" placeholder="Adresse de la société"/> <input type="text" name="code" id="code" class="champs" placeholder="Code Postal"/> <input type="text" name="ville" id="ville" class="champs" placeholder="Ville"/> <input type="email" name="email" id="email" class="champs" placeholder="Email"/> <input type="text" name="telephone" id="telephone" class="champs" placeholder="Téléphone"/> <input type="text" name="date" id="date" class="champs" placeholder="Date de l\'évènement"/> <input type="text" name="objet" id="objet" class="champs" placeholder="Objet"/> <input type="text" name="adresseEvenement" id="adresseEvenement" class="champs" placeholder="Adresse de l\'évènement (Facultatif)"/> <textarea name="information" id="information" class="champs" placeholder="Spécifiez les détailles de votre évènement" rows="15" cols="70"></textarea> <input type="submit" id="envoyer" value="Envoyer"/> </form> </div> </div>'; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php $row=1; if (($handle = fopen("BD.csv","r"))) { while ($data = fgetcsv($handle, 1000, ",")) { $num = count($data); for ($i = 0; $i < $num; $i++) { echo $data[$i].' '; } echo "</br>"; $row++; }echo "</br>"; fclose($handle); } else { echo "erreur de chargement"; } ?> <file_sep><?php session_start(); $Identifiant = strtolower($_POST["username"]);//Entree formulaire nom d'utilisateur $Password = $_POST["<PASSWORD>"];// Entree du Formulaire Mot de passe if (($handle = fopen("Identifiant.csv","r"))) { while ($data = fgetcsv($handle, 1024, ';')) { // echo "<pre>"; // var_dump($data); // echo "</pre>"; if ($Identifiant === $data[1] && $Password === $data[2])//verification que l'identifiant et le mot de passe sont bon { $_SESSION['CO'] = 1;//initialise la session pour le bake office header("location:BackEntreprise/BackEntreprise.php"); // echo "reussite"; } else { header("location:index.php"); // echo "lose"; } } } ?><file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; // <!-------------------------------------------------------> // <!-- CARROUSEL --> // <!-------------------------------------------------------> echo '<div> <h1 class="titre_galerie">Galerie</h1> <div class="galerie_carousel"> <div> <img src="img/Toutou.jpg" alt="Toutou" class="Galerie"> </div> <div> <img src="img/Inauguration.jpg" alt="Inauguration" class="Galerie"> </div> <div> <img src="img/Lancement.PNG" alt="Lancement" class="Galerie"> </div> </div> </div> <script src="js/jquery-1.11.0.min.js"></script> <script src="js/jquery-migrate-1.2.1.min.js"></script> <script src="slick/slick.min.js"></script> <script src="js/carrousel.js"></script>'; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php $count =0; if (($handle = fopen("Equipe.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { $CSV[]=$data[0]; $count++; } }else { echo "erreur de chargement"; } include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; echo ' <form action="ModifierEntreprise_submit" method="get" accept-charset="utf-8">'; for ($i=0; $i < $count; $i++) { echo '<label> Texte '; echo $i+1 ; echo'<input type="text" name="formulaire'.$i.'" class="formulaire" value="'.$CSV[$i].'">'; echo '</label>'; } echo '<input type="submit" name="" value="modifier">'; echo '</form>'; ?><file_sep><?php if (($handle = fopen("Lancement.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; // <!-------------------------------------------------------> // <!-- PAGE --> // <!-------------------------------------------------------> echo '<div id="evenement"> <h1 class="Titre">Evenement</h1> <h2 class="TEvenement">'.$data[1].'</h2> <p class="PEvenement">'.$data[2].'</p> <img src="../../'.$data[3].'" id="lancement"> <a href="ModifierLancement.php" name="modifier"><input type="submit" name="modifier" value="modifier"></a> </div>'; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include '../BackFooter.php'; } }else { echo "erreur de chargement"; } ?><file_sep><!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <meta name="keywords" lang="fr" content="html,php,css"> <meta name="author" lang="fr" content="<NAME>"> <!-- IMPORT .CSS --> <link href="css/responsive.css" rel="stylesheet"> <!-- IMPORT FONTS --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <title> BackOffice </title> </head> <body> <bloc> <?php session_start(); if ($_SESSION['CO'] != 1){ header('Location:../index.php');//renvoie vers la page de connexion si la personne n'est pas identifier } ?><file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; // <!-------------------------------------------------------> // <!-- CARROUSEL --> // <!-------------------------------------------------------> echo "<img href='index.html' src='img/Logo.bmp' alt='Logo MotionDawn' id='logo_responsive'/> <div id='content'> <h1 id='titre_accueil'>Nos Réalisations !</h1> <div class='galerie_carousel'> <div> <img src='img/Toutou.jpg' alt='Toutou' class='Galerie'> </div> <div> <img src='img/Inauguration.jpg' alt='Inauguration' class='Galerie'> </div> <div> <img src='img/Lancement.PNG' alt='Lancement' class='Galerie'> </div> </div> <p class='Titre_logo'>Nos Partenaires</p> <div id='bloc_logo'> <img src='img/LogoGoogle.jpg' alt='logo_Google' class='logo'> <img src='img/logoSamsung.jpg' alt='Logo_Samsung' class='logo'> <img src='img/LogoApple.jpg' alt='Logo_Apple' class='logo'> </div> </div> <script src='js/jquery-1.11.0.min.js'></script> <script src='js/jquery-migrate-1.2.1.min.js'></script> <script src='slick/slick.min.js'></script> <script src='js/carrousel.js'></script>"; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php $list[] = "decalage"; $list[] = $_POST['formulaire1']; echo "<pre>"; var_dump($list); echo "<pre>"; $fp = fopen('Entreprise.csv','w'); fprintf($fp, chr(0xEF).chr(0xBB).chr(0xbf)); fputcsv($fp,$list,';'); fclose($fp); header("location:BackEntreprise.php"); ?><file_sep><?php if (($handle = fopen("Equipe.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; echo '<div> <h1>Equipe</h1> <p id="PEquipe">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis.</p> <div id="equipe"> <div class="employee"> <img src="img/chan.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/DRH.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/E=MC2.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/lelouch.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/girl.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/mael.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/thierry.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/patron.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/grilr.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> <div class="employee"> <img src="img/child.jpg" class="photo"> <p>Nom - Prenom</p> <p>role</p> </div> </div> </div>'; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include '../BackFooter.php'; } }else { echo "erreur de chargement"; } ?> <file_sep><?php $j = 1; include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; echo "<table>"; if (($handle = fopen("BD.csv","r"))) { while ($data = fgetcsv($handle, 1024, ";")) { $num = count($data); echo '<tr><td>Retour Formulmaire '; echo $j;echo "</td>"; for ($i = 0; $i < $num; $i++) { echo "<td>" . $data[$i] . "</td>"; } echo '</tr>'; $j++; } }else { echo "erreur de chargement"; } echo "</table>"; echo '<form action="supprimer.php" method="post" accept-charset="utf-8"> <input type="submit" name="supprimer" value="Tout supprimer"> </form>'; include '../BackFooter.php'; ?><file_sep><?php session_start(); ?> <div id="container8"> <!-- zone de connexion --> <form action="Verification.php" method="POST"> <h1>Connexion</h1> <label><b>Nom d'utilisateur</b></label> <input type="text" placeholder="Entrer le nom d'utilisateur" name="username" required> <label><b>Mot de passe</b></label> <input type="<PASSWORD>" placeholder="Entrer le mot de passe" name="password" required> <input type="submit" id='submit' value='Se connecter'> </form> </div><file_sep><?php echo "<pre>"; var_dump($_POST); echo "<pre>"; if ($_POST['Ajouter_Texte'] == "Ajouter Texte") { $list = ["ajoute"]; } else{ $list = ["Ajoute.jpg"]; } echo "<pre>"; var_dump($list); echo "<pre>"; $fp = fopen('Inauguration.csv','a');// fprintf($fp, chr(0xEF).chr(0xBB).chr(0xbf)); fputcsv($fp,$list,";"); fclose($fp); header("location:ModifierInauguration.php") ?><file_sep><?php include 'Head.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include 'nav.php'; echo "<form id='formulaire' action='Insert.php' method='POST' class='contactez'> <h1 class='Titre'>Contactez Nous</h1> <input type='text' name='nom' id='nom' class='zone' placeholder='Nom de votre société'/> <input type='email' name='mail' id='mail' class='zone' placeholder='Adresse email de contact'/> <input type='text' name='objet' id='objet' class='zone' placeholder='Objet'/> <textarea name='information' id='information' class='zone' placeholder='Taper votre demande' rows='15' cols='70'></textarea> <input type='submit' class='boutonEnvoyer' value='Envoyer' /> </form>"; // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include 'Footer.php'; ?><file_sep><?php if (($handle = fopen("Entreprise.csv","r"))) { while ($data = fgetcsv($handle, 1024, ';')) { include '../BackHead.php'; // <!-------------------------------------------------------> // <!-- MENU DE NAVIGATION --> // <!-------------------------------------------------------> include '../Backnav.php'; // <!-------------------------------------------------------> // <!-- Entreprise --> // <!-------------------------------------------------------> echo '<h1>Entreprise</h1> <section id="contenu"> <div class="titreEntreprise"> <h2>Présentation</h2> <p>'. $data[1] .'</p> </div> <a href="ModifierEntreprise.php" title=""><input type="submit" name="modifier" value="modifier"></a> </section>'; } }else { echo "erreur de chargement"; } // <!-------------------------------------------------------> // <!-- FOOTER --> // <!-------------------------------------------------------> include '../BackFooter.php'; ?>
06d8e6144fea2d1ed734aa9efb5583c5d54736cc
[ "PHP" ]
24
PHP
MuzardGeoffrey/MotionDawn
49a91f55b7e46687f5136a2c68574b887646988d
80adc44598972120cc8ee78169f041015ac90efd
refs/heads/master
<repo_name>vladL2C/exercism.io_hamming<file_sep>/hamming.rb def hamming(dna1,dna2) count = 0 dna1.each_with_index do |d1,i| if d1 != dna2[i] count += 1 end end return count end d1 = "GAGCCAB".split(//) d2 = "CATCGAC".split(//) hamming(d1,d2)
f4b7b48f08dae944dd102b1e14cce5e501b68a56
[ "Ruby" ]
1
Ruby
vladL2C/exercism.io_hamming
c56d78aa31c0e7645bc9553f3220a67b75ec9256
b12be82d2074a12a85a05cc81d00f641df649674
refs/heads/master
<file_sep>import React from 'react'; import Navbar from 'react-bootstrap/Navbar' import Nav from 'react-bootstrap/Nav' // import Form from 'react-bootstrap/Form' // import FormControl from 'react-bootstrap/FormControl' // import Button from 'react-bootstrap/Navbar' const Navigation = () => { return( <Navbar className="color-nav" variant="light"> <Navbar.Brand href="/">Nomad Beer Co</Navbar.Brand> <Nav className="mr-auto"> <Nav.Link href="/beers">Beers</Nav.Link> <Nav.Link href="/breweries">Breweries</Nav.Link> <Nav.Link href="/add-a-beer">Add a Beer</Nav.Link> </Nav> </Navbar> ) } export default Navigation <file_sep>export default function beerReducer(state = {beers: []}, action) { switch (action.type) { case 'FETCH_BEERS': return { beers: action.payload } case 'ADD_BEER': return {...state, beers: [...state.beers, action.payload]} default: return state; } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux' import { fetchBreweries } from './actions/fetchBreweries' import { fetchBeers } from './actions/fetchBeers' import BeerFinderForm from './components/BeerFinderForm' import BeersContainer from './containers/BeersContainer' import BreweriesContainer from './containers/BreweriesContainer' import BeerInput from './components/BeerInput' import BeerCard from './components/BeerCard' import BreweryCard from './components/BreweryCard' import Navigation from './components/Navigation' import { Route } from 'react-router-dom' import './App.css'; class App extends Component { componentDidMount(){ this.props.fetchBeers() this.props.fetchBreweries() } render () { return ( <div className="App"> <Navigation /> <Route exact path="/"> <BeerFinderForm /> </Route> <Route exact path="/beers"> <BeersContainer /> </Route> <Route exact path="/breweries"> <BreweriesContainer /> </Route> <Route exact path="/add-a-beer" render={(routerProps) => <BeerInput {...routerProps} breweries={this.props.breweries} allBeers={this.props.beers}/>}/> <Route exact path="/beers/:id" render={(routerProps) => <BeerCard {...routerProps} allBeers={this.props.beers}/>}/> <Route exact path="/breweries/:id" render={(routerProps) => <BreweryCard {...routerProps} breweries={this.props.breweries}/>}/> </div> ); } } const mapSTP = (state) => { return { beers: state.beers, breweries: state.breweries } } export default connect(mapSTP, { fetchBreweries, fetchBeers })(App) <file_sep>rails new NomadBeerCo --database=postgresql --api create-react-app NomadBeerCo-frontend //rails g resource style name:string rails g resource Brewery name:string city:string state:string image_url:string description:text rails g resource Beer brewery_id:integer name:string style:string rating:float description:text image_url:string thumbs_up:string rails db:create && rails db:migrate beer //belongs_to :style belongs_to :brewery brewery has_many :beers //style //has_many :beers HEADER: navbar with link to all home, beers, all breweries HOME PAGE: form with: -select dropdown for style of beer -input to enter your zip code and a style of beer to try -submit button to try something new -see all will display list of all beers within that style with links to card BEERS LINK: -display all beers -each beer links to beer card -select dropdown for style of beer -search by state BREWERIES LINK: -display all breweries -each brewery links to brewery card, lists beers with links to beer cards -filter by state Submit will display a beer card for a randomly selected beer of that style above a rating of 3.75 -will select one from random for you to try, button to see all -all beers component will display list of beers in that state with rating of 3 or higher in your state -like if you’ve tried it and liked it -thumbs down if you aren’t interested and take it off the list -add a beer with style, location, image, rating npm install npm install redux --save npm install react-redux --save npm install react-router-dom --save npm install redux-thunk --save npm install react-bootstrap bootstrap //index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers' import { BrowserRouter as Router, Route } from 'react-router-dom'; import App from './App'; import './index.css' const store = createStore(rootReducer, applyMiddleware(thunk)) <file_sep>import React, { Component } from 'react'; import BeerList from '../components/BeerList' import BeerSearch from '../components/BeerSearch' import { connect } from 'react-redux' class BeersContainer extends Component { state = { textInput: '' } handleSearchInput = (e) => { console.log(e.target.value) this.setState({ textInput: e.target.value }) } render() { const beerSearchList = this.props.beers.filter(beer => beer.name.includes(this.state.textInput)) return( <div> <BeerSearch handleSearchInput={this.handleSearchInput}/> <BeerList beers={beerSearchList} /> </div> ) } } const mapSTP = (state) => { return { beers: state.beers } } export default connect(mapSTP)(BeersContainer) <file_sep>import React, { Component } from 'react'; import BreweryList from '../components/BreweryList' import { connect } from 'react-redux' class BreweriesContainer extends Component { render() { return( <div> <BreweryList breweries={this.props.breweries}/> </div> ) } } const mapSTP = (state) => { return { breweries: state.breweries } } export default connect(mapSTP)(BreweriesContainer) <file_sep>class BeerSerializer def initialize(beer_obj) @beer_object = beer_obj end def to_serialized_json @beer_object.to_json({ include: {brewery: {except: [:created_at, :updated_at]}}, except: [:created_at, :updated_at] }) end end <file_sep>import React from 'react' import Modal from 'react-bootstrap/Modal' import Button from 'react-bootstrap/Button' import { useHistory } from 'react-router-dom' export default function BeerModal(props){ const [isOpen, setIsOpen] = React.useState(true); const history = useHistory() const hideModal = () => { setIsOpen(false); history.push(`/beers`) }; let beer = props.beer return ( <div> <Modal {...props} show={isOpen} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> <img src={beer.image_url} alt=""/>&nbsp;&nbsp;&nbsp; {beer.name} </Modal.Title> </Modal.Header> <Modal.Body> <p> {beer.style} - abv: {beer.abv} - rating: {beer.rating}<br/> <strong>{beer.brewery.name}</strong><br/> {beer.brewery.city}, {beer.brewery.state} </p> <p> {beer.description} </p> </Modal.Body> <Modal.Footer> <Button onClick={hideModal} >Close</Button> </Modal.Footer> </Modal> </div> ) } <file_sep>class BeersController < ApplicationController def index beers = Beer.all render json: BeerSerializer.new(beers).to_serialized_json end def show beer = Beer.find(params[:id]) render json: BeerSerializer.new(beer).to_serialized_json end def create beer = Beer.new(beer_params) if beer.save render json: BeerSerializer.new(beer).to_serialized_json else render json: {error: "Beer not created"} end end def update beer = Beer.find(params[:id]) beer.update(beer_params) render json: BeerSerializer.new(beer).to_serialized_json end def destroy beer = Beer.find(params[:id]) beer.destroy end private def beer_params params.require(:beer).permit(:brewery_id, :name, :style, :abv, :rating, :description, :thumbs_up, :image_url) end end <file_sep>import React from 'react' import Modal from 'react-bootstrap/Modal' import Button from 'react-bootstrap/Button' import { Link } from 'react-router-dom' import ListGroupItem from 'react-bootstrap/ListGroupItem' import { useHistory } from 'react-router-dom' export default function BreweryCard(props){ const [isOpen, setIsOpen] = React.useState(true); const history = useHistory() const hideModal = () => { setIsOpen(false); history.push(`/breweries`) }; let id = parseInt(props.match.params.id) let brewery = props.breweries.find(brewery => brewery.id === id ) if (brewery){ return ( <div> <Modal {...props} show={isOpen} onHide={hideModal} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"> <img src={brewery.image_url} alt="beer"/>&nbsp;&nbsp;&nbsp; {brewery.name} </Modal.Title> </Modal.Header> <Modal.Body> <p> {brewery.address}<br/> {brewery.city}, {brewery.state} {brewery.zip_code} </p> <ListGroupItem><strong>Beer Name :: Style :: Rating</strong></ListGroupItem> {brewery.beers.map(beer => <ListGroupItem key={beer.id}><Link to={`/beers/${beer.id}`}>{beer.name}</Link> :: {beer.style} :: {beer.rating}</ListGroupItem> )} </Modal.Body> <Modal.Footer> <Button onClick={hideModal} >Close</Button> </Modal.Footer> </Modal> </div> ) } else { return <div>loading...</div> } } <file_sep>class BrewerySerializer def initialize(brewery_obj) @brewery_object = brewery_obj end def to_serialized_json @brewery_object.to_json({ include: {beers: {except: [:created_at, :updated_at]}}, except: [:created_at, :updated_at] }) end end <file_sep>import React, { Component } from 'react'; import {connect} from 'react-redux' import { Link } from 'react-router-dom' import { updateThumbs } from '../actions/updateThumbs' import Card from 'react-bootstrap/Card' import ListGroupItem from 'react-bootstrap/ListGroupItem' import CardColumns from 'react-bootstrap/CardColumns' class BeerList extends Component { handleOnClick = (e) => { let beerId = parseInt(e.target.dataset.beerid) if (e.target.innerText === "like || "){ let beer = this.props.beers.filter(beer => beer.id === beerId)[0] beer.thumbs_up = "👍" console.log(beer.thumbs_up) this.props.updateThumbs(beer) } if (e.target.innerText === " || dislike"){ let beer = this.props.beers.filter(beer => beer.id === beerId)[0] beer.thumbs_up = "👎" this.props.updateThumbs(beer) } } render() { return( <div> <CardColumns className="beer-list-cards"> {this.props.beers.map(beer => <Card key={beer.id} border="dark"> <Card.Img className="beer-avatar" variant="top" src={`${beer.image_url}`} fluid/> <Card.Body> <Card.Title><Link to={`/beers/${beer.id}`}>{beer.name}</Link></Card.Title> <Card.Text> <ListGroupItem>{beer.style}</ListGroupItem> <ListGroupItem><Link to={`/breweries/${beer.brewery.id}`}>{beer.brewery.name}</Link></ListGroupItem> <ListGroupItem>Brewed in: {beer.brewery.city}, {beer.brewery.state}</ListGroupItem> <ListGroupItem>Stats: {beer.abv}% abv - rating of {beer.rating}</ListGroupItem> </Card.Text> </Card.Body> <Card.Footer> <small data-beerid={beer.id} className="text-muted" onClick={this.handleOnClick}>like || </small> {beer.thumbs_up} <small data-beerid={beer.id} className="text-muted" onClick={this.handleOnClick}> || dislike</small> </Card.Footer> </Card> )} </CardColumns> </div> ) } } export default connect(null, { updateThumbs })(BeerList) <file_sep>export const addBeer = (data) => { console.log('b') return (dispatch) => { console.log('c') fetch("http://localhost:3000/beers", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(data) }) .then(response => response.json()) .then(beer => { console.log('d') return dispatch({type: 'ADD_BEER', payload: beer}) }) console.log('e') } console.log('f') } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux' import { addBeer } from '../actions/addBeer' // import Col from 'react-bootstrap/Col' // import Row from 'react-bootstrap/Row' import Button from 'react-bootstrap/Button' import Form from 'react-bootstrap/Form' class BeerInput extends Component { state = { name: '', } handleOnChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } handleSubmit = (e) => { e.preventDefault() console.log('a') this.props.addBeer(this.state) console.log('g'); this.setState({ name: '', brewery_id: '', style: '', abv: '', rating: '', image_url: '', description: '' }) this.props.history.push('/beers') } render(){ return( <div> <Form onSubmit={this.handleSubmit} className="form-box"> <Form.Group className="mb-3"> <br/> <Form.Control type="text" name="name" placeholder="<NAME>" onChange={this.handleOnChange} value={this.state.name}/> <br/> <Form.Control value={this.props.brewery} as="select" name="brewery_id" onChange={this.handleOnChange}> <option>Select a Brewery</option> {this.props.breweries.map(brewery => <option value={brewery.id} key={brewery.id}>{brewery.name}</option>)} </Form.Control> <br/> <Form.Control value={this.props.beer} as="select" name="style" onChange={this.handleOnChange}> <option>Select a Style</option> {this.props.allBeers.map(beer => beer.style) .filter((value, index, self) => self.indexOf(value) === index).map(s => <option value={s} key={s}>{s}</option>)} </Form.Control> <br/> <Form.Control type="number" name="abv" placeholder="ABV" onChange={this.handleOnChange} value={this.state.abv}/> <br/> <Form.Control type="number" name="rating" placeholder="Rating (between 0.00 and 4.00)" onChange={this.handleOnChange} value={this.state.rating}/> <br/> <Form.Control type="text" name="image_url" placeholder="Image URL" onChange={this.handleOnChange} value={this.state.image_url}/> <br/> <Form.Control type="text" as="textarea" name="description" placeholder="Description" onChange={this.handleOnChange} value={this.state.description}/> <br/> <Button className="button" variant="primary" type="submit"> Add Beer </Button> </Form.Group> </Form> </div> ) } } export default connect(null, {addBeer})(BeerInput) <file_sep>export default function breweryReducer(state = {breweries: []}, action) { switch (action.type) { case 'FETCH_BREWERIES': return { breweries: action.payload } default: return state; } } <file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux' import BeerModal from './BeerModal' import Col from 'react-bootstrap/Col' import Row from 'react-bootstrap/Row' import Button from 'react-bootstrap/Button' import Form from 'react-bootstrap/Form' class BeerFinderForm extends Component { state = { style: '', st: '', beer: '', } handleOnChange = (e) => { this.setState({ [e.target.name]: e.target.value }) } handleOnSubmit = (e) => { e.preventDefault() let beerArray = this.props.beers.filter(beer => beer.style === this.state.style && beer.brewery.state === this.state.st) let randomBeer = random_item(beerArray) this.setState({ beer: randomBeer }) console.log(this.state.beer.name) console.log("a random beer", randomBeer.name) return( randomBeer ) } beerSelecterForm = () => { return ( <Form onSubmit={this.handleOnSubmit} className="form-box-finder"> <Form.Group> <Row> <Col> <Form.Control value={this.state.style} as="select" name="style" onChange={this.handleOnChange}> <option>Select a Style</option> {this.props.beers.map(beer => beer.style) .filter((value, index, self) => self.indexOf(value) === index).map(s => <option value={s} key={s}>{s}</option>)} </Form.Control> </Col> <Col> <Form.Control value={this.state.state} as="select" name="st" onChange={this.handleOnChange}> <option>Select a Location</option> {this.props.beers.map(beer => beer.brewery.state) .filter((value, index, self) => self.indexOf(value) === index).map(s => <option value={s} key={s}>{s}</option>)} </Form.Control> </Col> </Row> </Form.Group> <Button className="button" variant="primary" type="submit"> Cheers! </Button> </Form> ) } render() { return( <div> {this.state.beer !== '' ? <BeerModal beer={this.state.beer} /> : this.beerSelecterForm()} </div> ) } } const mapSTP = (state) => { return { beers: state.beers } } function random_item(items) { return items[Math.floor(Math.random()*items.length)] } export default connect(mapSTP)(BeerFinderForm) <file_sep> export default function beerReducer(state = { beers: [], breweries: [] }, action) { switch (action.type) { case 'FETCH_BEERS': return { ...state, beers: action.payload } case 'ADD_BEER': return {...state, beers: [...state.beers, action.payload]} case 'FETCH_BREWERIES': return { ...state, breweries: action.payload } case 'UPDATE_THUMBS': let beerToLike = state.beers.map(beer => { if (beer.id === action.payload.id) { return action.payload } else { return beer } }) return {...state, beers: beerToLike} default: return state; } } <file_sep>import React from 'react' import Card from 'react-bootstrap/Card' import ListGroup from 'react-bootstrap/ListGroup' import ListGroupItem from 'react-bootstrap/ListGroupItem' import { Link } from 'react-router-dom' export default function BeerCard(props){ console.log("beer card props", props.beer) let id = parseInt(props.match.params.id) let beer = props.allBeers.find(beer => beer.id === id ) console.log(beer); if (beer){ return ( <div> <Card style={{ width: '25rem' }} className='beercard'> <Card.Img variant="top" src={`${beer.image_url}`}/> <Card.Body> <Card.Title>{beer.name}</Card.Title> <Card.Text> {beer.description} </Card.Text> </Card.Body> <ListGroup className="list-group-flush"> <ListGroupItem>{beer.style}</ListGroupItem> <ListGroupItem><Link to={`/breweries/${beer.brewery.id}`}>{beer.brewery.name}</Link></ListGroupItem> <ListGroupItem>Brewed in: {beer.brewery.city}, {beer.brewery.state}</ListGroupItem> <ListGroupItem>Stats: {beer.abv}% abv - rating of {beer.rating}</ListGroupItem> </ListGroup> <Card.Footer> {(beer.thumbs_up !== "or") ? <medium>Your thoughts on this beer: {beer.thumbs_up}</medium> : <small>I'd put a link to "buy now" if it was allowed!</small> } </Card.Footer> </Card> </div> ) } else { return <div>why not</div> } }
6027bc00c9fe311a4c76313dcb87ea63eaedb84c
[ "JavaScript", "Text", "Ruby" ]
18
JavaScript
markcascardi/NomadBeerCo
02d33b7bd37c22df4e3312bb12169796c83b5d57
9da7f9471e465436a6e2b88011f4c54aa48be570
refs/heads/master
<file_sep> var all = document.getElementById('all'); var animals = document.getElementById('animals'); var bands = document.getElementById('bands'); var colors = document.getElementById('colors'); var fruits = document.getElementById('fruits'); filterElements('all'); all.addEventListener('click', function (event) { filterElements('all'); }); animals.addEventListener('click', function (event) { filterElements('animals'); }); bands.addEventListener('click', function (event) { filterElements('bands'); }); colors.addEventListener('click', function (event) { filterElements('colors'); }); fruits.addEventListener('click', function (event) { filterElements('fruits'); }); function filterElements (c) { var x = document.getElementsByClassName('filter-list'); for (var i = 0; i < x.length; i++) { removeClass(x[i], 'show'); if (x[i].className.indexOf(c) > -1) { x[i].classList.add('show'); } if (c === 'all') { x[i].classList.add('show'); } } } function removeClass (element, name) { if (element.className.indexOf('show') > -1) { element.classList.remove('show'); } }
6b0ac36f5e152f6a3019acf7f9628ed60f826bde
[ "JavaScript" ]
1
JavaScript
michaelvinci/random-code-tests
ad58709fa79baaf4c0f13474b4e8ca74133bbb32
b8672d8f2be4b5c1e5a4103bb0a9bfc438a0c1d7
refs/heads/master
<repo_name>DamonOehlman/pull-level-batch<file_sep>/test/all.js var test = require('tape'); var pull = require('pull-stream'); var batch = require('..'); var data = require('./data/simple'); test('a small max size ensures items are emitted one at a time', function(t) { t.plan(data.length); pull( pull.values(data), batch(1), pull.drain(function(batch) { t.equal(batch.length, 1); }) ); }); test('we should be able to collect multiple items with a slightly larger batch size', function(t) { t.plan(data.length >> 1); pull( pull.values(data), batch(20), pull.drain(function(batch) { t.equal(batch.length, 2); }) ); }); test('if the batch size is large enough all items should come through in a single hit', function(t) { t.plan(1); pull( pull.values(data), batch(7 * data.length), pull.drain(function(batch) { t.equal(batch.length, data.length); }) ); }); <file_sep>/index.js var looper = require('looper'); var Through = require('pull-core').Through; /** # pull-level-batch Gather upstream items with a valid `key` and `value` into optimal batches for writing with leveldb batch operations. ## Usage See the tests. **/ module.exports = function(maxSize, encoding) { var buffered = []; var currentSize = 0; var output = []; var ended = null; // set default max size to match default leveldb write buffer size maxSize = maxSize || (4 * 1024 * 1024); return function(read) { return function(abort, cb) { if (ended) { return cb(ended); } looper(function(next) { read(abort, function(end, data) { var itemSize; ended = ended || end; if (ended) { if (buffered.length || output.length) { return cb(null, buffered.splice(0).concat(output.splice(0))); } return cb(ended); } // calculate the size of the item itemSize = Buffer.byteLength(data.key + data.value, encoding); // if this item will push us over, extract a payload if (currentSize + itemSize > maxSize) { output = buffered.splice(0); currentSize = 0; } // add the new item to the buffer buffered.push(data); currentSize += itemSize; if (output.length) { return cb(null, output.splice(0)); } next(); }); }); }; }; }; <file_sep>/test/data/simple.js module.exports = [ { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' }, { key: 'hi', value: 'there' } ];
ea18776fcb157b90e12bccef3bd55fd3576f9ccb
[ "JavaScript" ]
3
JavaScript
DamonOehlman/pull-level-batch
087bea93680d61ff8d68458aeb1e20c75bf1bfc9
f9c18f7fad3047929dd650f68c96f4f5972f245b
refs/heads/main
<repo_name>agita-gut/Lesson-20-task<file_sep>/js/main.js console.log('------Task 1-----------'); console.log('The natural numbers are:'); for (let i = 1; i < 10; i++) { console.log(i); } console.log('------Task 2-----------'); console.log('Find the first 10 natural numbers:'); console.log('--------------------'); console.log('The natural numbers are:'); let sum = 0; for(i = 1; i <= 10; i++) { sum = sum + i; console.log(i); } console.log('Sum of first 10 natural numbers:' + sum); console.log('------Task 3-----------'); console.log('Input a number of terms:'); num1 = 9; console.log(num1); console.log('The natural numbers up to ' + num1 + ' terms are'); let sum1 = 0; for(i = 1; i <= num1; i++) { sum1 = sum1 + i; console.log(i); } console.log('Sum of the natural numbers:' + sum1); console.log('------Task 5-----------'); let PrimeNum =true; let num3 = 13; console.log('Input a number to check prime or not:' + num3); if (num3 === 1) { console.log('This is not prime number.'); } else if (num3 > 1) { for (let i = 2; i < num3; i++) { if (num3 % i == 0) { PrimeNum = false; break; } } if (PrimeNum) { console.log(`${num3} is a prime number`); } else { console.log(`${num3} is a not prime number`); } }
6db57410a37a76bc053b19ed333d4d0679f85964
[ "JavaScript" ]
1
JavaScript
agita-gut/Lesson-20-task
962483f2081d0745e4deaae99ae6dc8ba46b30b1
bbfc780efc1fde74db7754789e77b6cb86374112
refs/heads/master
<file_sep><?php namespace AgenterLab\FeatureChecker; use Illuminate\Support\Facades\Cache; // use Illuminate\Support\Facades\Config; use AgenterLab\FeatureChecker\Exceptions\SubscriptionException; use AgenterLab\FeatureChecker\Exceptions\FeatureNotFoundException; use Illuminate\Contracts\Cache\Repository; use Illuminate\Support\Facades\DB; class Saas { /** * @var \Illuminate\Contracts\Cache\Repository */ private Repository $repository; /** * @var \AgenterLab\FeatureChecker\Subscription */ private ?\AgenterLab\FeatureChecker\Subscription $subscription = null; /** * Create a new confide instance. * * @param string $storage * @return void */ public function __construct(string $storage) { $this->repository = Cache::store($storage); if ($this->repository instanceof \Illuminate\Cache\RedisStore) { $this->repository->getStore()->setPrefix(''); } } /** * Get repository * * @return \Illuminate\Contracts\Cache\Repository */ public function getRepository(): Repository { return $this->repository; } /** * Get subscription * * @return \AgenterLab\FeatureChecker\Subscription * @throws \AgenterLab\FeatureChecker\Exceptions\SubscriptionException */ public function subscription(int|string $id): Subscription { if (is_null($this->subscription)) { $this->subscription = $this->newInstance($id); } return $this->subscription; } /** * Get new subscription instance * * @return \AgenterLab\FeatureChecker\Subscription * @throws \AgenterLab\FeatureChecker\Exceptions\SubscriptionException */ public function newInstance(int|string $id): Subscription { $ttl = $this->repository->get('subscription_' . $id); if (!$ttl) { throw new SubscriptionException("Subscription not exists"); } return new Subscription($id, $ttl); } /** * Get feature * * @param int $id * @param string $name * @param int $ttl * @return null|array */ public function feature(int|string $id, string $name): null|array { return $this->repository->get($id . '_' . $name); } /** * delete * * @param int $id * @param array $features * @param bool $subscription */ public function delete(int|string $id, array $features, bool $subscription = false) { $values = array_map(function($name) use($id) { return $id . '_' . $name; }, $features); if ($subscription) { $values[] = 'subscription_' . $id; } $this->repository->deleteMultiple($values); return true; } /** * Sync * * @param int $id * @param int $ttl * @param array $features */ public function sync(int|string $id, int $ttl, array $features) { $values = ['subscription_' . $id => $ttl]; foreach($features as $feature) { $values[$id . '_' . $feature['name']] = [ 'd' => $feature['dtype'], 'v' => $feature['value'], 'u' => $feature['usage'] ?? 0 ]; } $this->repository->putMany($values , $ttl); } /** * Record usage * * @param int $id * @param string $name * @param int $newValue * @param int $ttl */ public function recordUsage(int|string $id, string $name, int $newValue, int $ttl) { $feature = $this->feature($id, $name); if (!$feature) { throw new FeatureNotFoundException; } if ($feature['d'] != 'numeric') { return; } $feature['u'] = (int)$feature['u'] + $newValue; $this->repository->set($id . '_' . $name, $feature, $ttl); } }<file_sep><?php return [ /* |-------------------------------------------------------------------------- | Cache |-------------------------------------------------------------------------- | | Manage IAM's cache configurations. It uses the driver defined in the | config/cache.php file. | */ 'storage' => env('SAAS_STORAGE', 'file'), 'token_name' => env('SAAS_TOKEN_NAME', '<PASSWORD>'), 'key' => env('SAAS_KEY', ''), 'request_restrict' => false, ];<file_sep><?php namespace AgenterLab\FeatureChecker; // use Illuminate\Support\Facades\Cache; // use Illuminate\Support\Facades\Config; // use AgenterLab\FeatureChecker\Exceptions\FeatureException; // use AgenterLab\FeatureChecker\Exceptions\SubscriptionException; interface SubscriptionContract { /** * Get end date */ public function getEndDate(): int; } <file_sep><?php namespace AgenterLab\FeatureChecker\Exceptions; class FeatureException extends SubscriptionException { private $feature; // Redefine the exception so message isn't optional public function __construct( string $feature, $value = '' ) { // some code // make sure everything is assigned properly parent::__construct('You are not allowed this action', 403); $this->feature = $feature; } }<file_sep><?php namespace AgenterLab\FeatureChecker; use AgenterLab\FeatureChecker\Exceptions\FeatureException; use AgenterLab\FeatureChecker\Exceptions\FeatureNotFoundException; use AgenterLab\FeatureChecker\Exceptions\SubscriptionExpiredException; class Subscription { /** * @var int */ private int $endDate; /** * @var int|string */ private int|string $id; /** * @var int */ private int $ttl; /** * @var array */ private array $aliases = []; /** * Create a new confide instance. * * @param int $id * @param int $endDate * @return void * @throws \AgenterLab\FeatureChecker\Exceptions\SubscriptionExpiredException */ public function __construct(int|string $id, int $endDate) { $this->id = $id; $this->endDate = $endDate; $this->setTTL(); } /** * Set ttl * * @throws \AgenterLab\FeatureChecker\Exceptions\SubscriptionExpiredException */ private function setTTL() { $this->ttl = $this->endDate - time(); if ($this->ttl <= 0) { throw new SubscriptionExpiredException; } } /** * Check Allow feature * * @param string $featureName * @param string|int|null $default * @throws \AgenterLab\FeatureChecker\Exceptions\FeatureException */ public function allow(string $featureName, string|int|null $dfValue = null) { if (!$this->can($featureName, $dfValue)) { throw new FeatureException($featureName); } } /** * Check feature * * @param string $featureName * @param string|int|null $default * @return bool */ public function can(string $featureName, string|int|null $dfValue = null): bool { $feature = app('saas')->feature($this->id, $this->keyName($featureName)); if (!$feature) { return (bool)$dfValue; } $method = 'validate' . ucfirst($feature['d']); return $this->$method($feature['v'], $feature['u'], $dfValue); } /** * Validate string */ private function validateString($value, $usage, $dfValue): bool { return $value === $dfValue; } /** * Validate numeric */ private function validateNumeric($value, $usage, $dfValue): bool { return (int)$value > (int)$usage; } /** * Validate options */ private function validateOptions($value, $usage, $dfValue): bool { return in_array($dfValue, explode(',', $value)); } /** * Record usage * * @param string $featureName * @param int $newValue * @throws \AgenterLab\FeatureChecker\Exceptions\FeatureNotFoundException */ public function recordUsage(string $featureName, int $newValue = 1) { app('saas')->recordUsage($this->id, $this->keyName($featureName), $newValue, $this->ttl); } private function keyName(string $name): string { return $this->aliases[$name] ?? $name; } /** * Set aliases * * @param array $aliases * @param bool $clear */ public function setAliases(array $aliases, bool $clear = false) { if ($clear) { $this->aliases = $aliases; } $this->aliases = array_merge($this->aliases, $aliases); } } <file_sep><?php namespace AgenterLab\FeatureChecker; use AgenterLab\FeatureChecker\Exceptions\SubscriptionException; class Request { /** * @var \AgenterLab\FeatureChecker\Subscription */ private ?\AgenterLab\FeatureChecker\Subscription $subscription = null; /** * Create a new confide instance. * * @param string $storage * @return void */ public function __construct(private string $key, private string $tokenName, private bool $restict) { } /** * Get repository * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Contracts\Cache\Repository */ public function validate() { $token = app('request')->headers->get($this->tokenName); if (empty($token)) { $token = app('request')->cookie($this->tokenName); } if (empty($token)) { return; } $parts = explode(':', $token); if (count($parts) != 2) { if (!$this->restict) { return; } throw new SubscriptionException("Subscription token invalid"); } $signature = $this->signature($parts[0]); if ($signature != $parts[1]) { if (!$this->restict) { return; } throw new SubscriptionException('Subscription signature failed'); } try { $this->subscription = app('saas')->newInstance($parts[0]); } catch (SubscriptionException $e) { if ($this->restict) { throw $e; } } } /** * Get subscription * * @return string */ public function signature(int|string $id): string { return hash_hmac('sha256', $id, $this->key); } /** * Get subscription * * @return \AgenterLab\FeatureChecker\Subscription * @throws \AgenterLab\FeatureChecker\Exceptions\SubscriptionException */ public function subscription(): Subscription { if (is_null($this->subscription)) { throw new SubscriptionException('Subscription empty'); } return $this->subscription; } }<file_sep><?php namespace AgenterLab\FeatureChecker\Exceptions; class SubscriptionExpiredException extends SubscriptionException { }<file_sep><?php namespace AgenterLab\FeatureChecker; use Closure; class SubscriptionMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { app('saas.request')->validate(); return $next($request); } } <file_sep>Install --- ``` composer require agenter-labs/illuminate-feature-checker ``` Enviornment ---- ``` SAAS_STORAGE_CACHE=redis,file SAAS_MODEL_SUBSCRIPTION=Subscription model class name SAAS_MODEL_FEATURE=Subscription feature model class name SAAS_KEY=Encryption key SAAS_TOKEN_NAME= Header or Cookie name ``` Setup ---- Register service provider ``` $app->register(AgenterLab\FeatureChecker\FeatureCheckerServiceProvider::class); ``` Register route middleware ``` $app->routeMiddleware([ 'subscription' => \AgenterLab\FeatureChecker\SubscriptionMiddleware::class ]); ``` Generate signature ``` app('saas.request')->signature(); ``` <file_sep><?php namespace AgenterLab\FeatureChecker\Exceptions; class SubscriptionException extends \RuntimeException { }<file_sep><?php $router->group(['middleware' => ['subscription']], function () use ($router) { $router->get('feature', function() { app('saas.request')->subscription()->allow('feature1', false); return "Feature"; }); }); <file_sep><?php namespace Tests\Unit; use Tests\TestCase; use AgenterLab\FeatureChecker\Exceptions\FeatureException; class RouteTest extends TestCase { public function testMiddleware() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '50' ] ]); $key = '1:' . app('saas.request')->signature(1); $this->get('feature', ['sub-tkn' => $key])->seeStatusCode(200); } public function testMiddlewareAllow() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature2', 'dtype' => 'numeric', 'value' => '50' ] ]); $key = '1:' . app('saas.request')->signature(1); $this->get('feature', ['sub-tkn' => $key])->seeStatusCode(500); } public function testMiddlewareRestrictConfig() { config([ 'saas.request_restrict' => true ]); app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '50' ] ]); $key = '2:' . app('saas.request')->signature(1); $this->get('feature', ['sub-tkn' => $key])->seeStatusCode(500); } }<file_sep><?php namespace Tests\Unit; use Tests\TestCase; use AgenterLab\FeatureChecker\Exceptions\FeatureException; use AgenterLab\FeatureChecker\Exceptions\SubscriptionExpiredException; class FeatureUsageTest extends TestCase { public function testSync() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '50' ] ]); $this->assertTrue(app('saas')->subscription(1)->can('feature1', true)); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature2', 'dtype' => 'numeric', 'value' => '50', 'usage' => '50' ] ]); $this->assertFalse(app('saas')->subscription(1)->can('feature2', true)); } public function testSyncExpired() { $this->expectException(SubscriptionExpiredException::class); app('saas')->getRepository()->clear(); app('saas')->sync(1, time() - 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '50' ] ]); $this->assertTrue(app('saas')->subscription(1)->can('feature1', true)); } public function testDefaultCan() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, []); $this->assertTrue(app('saas')->subscription(1)->can('feature-one', true)); $this->assertFalse(app('saas')->subscription(1)->can('feature-one', false)); } public function testDefaultAllowException() { app('saas')->getRepository()->clear(); $this->expectException(FeatureException::class); app('saas')->sync(1, time() + 35000, []); app('saas')->subscription(1)->allow('feature-one', false); } public function testCan() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, []); $this->assertTrue(app('saas')->subscription(1)->can('invoice', true)); } public function testFullyUsedCan() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'invoice', 'dtype' => 'numeric', 'value' => '50', 'usage' => '50' ] ]); $this->assertFalse(app('saas')->subscription(1)->can('invoice', true)); } public function testRecordUsage() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '2' ] ]); $this->assertTrue(app('saas')->subscription(1)->can('feature1', true)); app('saas')->subscription(1)->recordUsage('feature1'); $this->assertTrue(app('saas')->subscription(1)->can('feature1', true)); app('saas')->subscription(1)->recordUsage('feature1'); $this->assertFalse(app('saas')->subscription(1)->can('feature1', true)); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature2', 'dtype' => 'numeric', 'value' => '10' ] ]); app('saas')->subscription(1)->recordUsage('feature2', 10); $this->assertFalse(app('saas')->subscription(1)->can('feature2', true)); } public function testDelete() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '2' ] ]); $this->assertTrue(app('saas')->subscription(1)->can('feature1', false)); app('saas')->subscription(1)->recordUsage('feature1'); $this->assertTrue(app('saas')->delete(1, ['feature1'])); $this->assertFalse(app('saas')->subscription(1)->can('feature1', false)); // Restore app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'numeric', 'value' => '2' ] ]); $this->assertTrue(app('saas')->subscription(1)->can('feature1', false)); app('saas')->subscription(1)->recordUsage('feature1'); } public function testAliases() { app('saas')->getRepository()->clear(); app('saas')->sync(1, time() + 35000, [ [ 'name' => 'feature1', 'dtype' => 'string', 'value' => 'Y' ] ]); app('saas')->subscription(1)->setAliases(['alias1' => 'feature1']); $this->assertTrue(app('saas')->subscription(1)->can('alias1', 'Y')); } }<file_sep><?php namespace AgenterLab\FeatureChecker; use Illuminate\Support\ServiceProvider; class FeatureCheckerServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/../config/saas.php', 'saas'); $this->app->singleton('saas', function ($app) { return new Saas(config('saas.storage')); }); $this->app->singleton('saas.request', function ($app) { return new Request( config('saas.key'), config('saas.token_name'), config('saas.request_restrict') ); }); } /** * Boot the authentication services for the application. * * @return void */ public function boot() { // Here you may define how you wish users to be authenticated for your Lumen // application. The callback which receives the incoming request instance // should return either a User instance or null. You're free to obtain // the User instance via an API token or any other method necessary. } }
987951adfec53d8467b820f1637dd528a0755fd1
[ "Markdown", "PHP" ]
14
PHP
agenter-labs/illuminate-feature-checker
7b60ae53ca1726c7c7ac43e2fd62f2709419a975
494555dbb09c7f677803ed7b29e7e1adef85babf
refs/heads/main
<repo_name>Hayashi08/SD25<file_sep>/README.md # SD25 ## ソースコード管理手順 ### 作業前のルーティーン 1. GitBashを立ち上げる 1. cd /c/java_workspace/SD25 1. git pull ### コミット 1. git add . 1. git commit -m "コメント" ### プッシュ 1. git pull 1. git push ### プル 1. git pull <file_sep>/WEB-INF/src/action/employee/TopAction.java package action.employee; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; import dao.ShiftDAO; import bean.ShiftConfirmBean; public class TopAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ShiftDAO shiftDAO = new ShiftDAO(); ArrayList<ShiftConfirmBean> shiftConfirmBeans = shiftDAO.searchConfirm(); shiftDAO.close(); request.setAttribute("shiftConfirmBeans", shiftConfirmBeans); return "/view/employee/top.jsp"; } } <file_sep>/WEB-INF/src/action/situation/SetStateCleanAction.java package action.situation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.SituationDAO; import tool.Action; public class SetStateCleanAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String floor_id = request.getParameter("floor_id"); SituationDAO situationDAO = new SituationDAO(); situationDAO.setStateClean(floor_id); situationDAO.close(); action.situation.TopAction topAction = new action.situation.TopAction(); String url = topAction.execute(request, response); return url; } } <file_sep>/WEB-INF/src/action/login/ConfirmLogoutAction.java package action.login; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; public class ConfirmLogoutAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { return "/view/login/logout_confirm.jsp"; } } <file_sep>/WEB-INF/src/dao/UserDAO.java package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import bean.UserBean; import tool.DAO; public class UserDAO extends DAO { // コンストラクタ public UserDAO() throws Exception { // 親コンストラクタを呼び出し super(); } // userテーブルへインサート public boolean insert(String id, String pass, String name, String sex, String birth, String mail, String tel, String job, String credit, String rank) throws Exception { // ユーザーIDが重複してないか確認 if (checkUserId(id)) { // インサート失敗 return false; } // SQL文 String sql = "insert into user values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, curdate())"; // STATEMENTの作成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入 statement.setString(1, id); statement.setString(2, pass); statement.setString(3, name); statement.setString(4, sex); statement.setString(5, birth); statement.setString(6, mail); statement.setString(7, tel); statement.setString(8, job); statement.setString(9, credit); statement.setString(10, rank); // SQL文を実行 statement.executeUpdate(); // ちゃんと閉じる! statement.close(); // インサート成功 return true; } // ユーザーIDが存在するかどうかの判定 private boolean checkUserId(String user_id) throws Exception { boolean flag = false; String sql = "select * from user where user_id = ?"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, user_id); ResultSet rSet = statement.executeQuery(); if (rSet.next()) { flag = true; } statement.close(); return flag; } // 会員検索 public ArrayList<UserBean> search(String keyword) throws Exception { // Beanのリスト ArrayList<UserBean> userBeans = new ArrayList<UserBean>(); // SQL文 String sql = "select * from user where user_id like ?"; // STATEMENTの生成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入(ワイルドカード使用) statement.setString(1, "%" + keyword + "%"); // 検索結果を受け取る ResultSet rSet = statement.executeQuery(); // 検索結果をBeanのリストに格納 while (rSet.next()) { // Beanの生成 UserBean userBean = new UserBean(); // カラムの値をBeanに格納 userBean.setId(rSet.getString(1)); userBean.setPass(rSet.getString(2)); userBean.setName(rSet.getString(3)); userBean.setSex(rSet.getString(4)); userBean.setBirth(rSet.getString(5)); userBean.setMail(rSet.getString(6)); userBean.setTel(rSet.getString(7)); userBean.setJob(rSet.getString(8)); userBean.setCredit(rSet.getString(9)); userBean.setRank(rSet.getString(10)); userBean.setDate(rSet.getString(11)); // Beanをリストに追加 userBeans.add(userBean); } return userBeans; } // 会員詳細 public UserBean detail(String id) throws Exception { // Beanの生成 UserBean userBean = new UserBean(); // SQL文 String sql = "select * from user where user_id = ?"; // STATEMENTの生成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入 statement.setString(1, id); // 詳細情報取得 ResultSet rSet = statement.executeQuery(); // 詳細情報をBeanに格納 if (rSet.next()) { userBean.setId(rSet.getString(1)); userBean.setPass(rSet.getString(2)); userBean.setName(rSet.getString(3)); userBean.setSex(rSet.getString(4)); userBean.setBirth(rSet.getString(5)); userBean.setMail(rSet.getString(6)); userBean.setTel(rSet.getString(7)); userBean.setJob(rSet.getString(8)); userBean.setCredit(rSet.getString(9)); userBean.setRank(rSet.getString(10)); userBean.setDate(rSet.getString(11)); } // ちゃんと閉じる! statement.close(); return userBean; } // 会員更新処理 public boolean update(String id, String pass, String name, String sex, String birth, String mail, String tel, String job, String credit, String rank, String date) throws Exception { String sql = "update user set user_pass = ?, user_name = ?, user_sex = ?, user_birth = ?, user_mail = ?, user_tel = ?, user_job = ?, user_credit = ?, user_rank = ?, user_date = ?"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, pass); statement.setString(2, name); statement.setString(3, sex); statement.setString(4, birth); statement.setString(5, mail); statement.setString(6, tel); statement.setString(7, job); statement.setString(8, credit); statement.setString(9, rank); statement.setString(10, date); statement.executeUpdate(); // ちゃんと閉じる! statement.close(); return true; } // 会員削除処理 public void delete(String id) throws Exception { String sql = "delete from user where user_id = ?"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, id); statement.executeUpdate(); // ちゃんと閉じる! statement.close(); } } <file_sep>/WEB-INF/src/action/order_user/SelectAction.java package action.order_user; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; import dao.OrderUserDAO; import bean.OrderUserBean; public class SelectAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("id"); OrderUserDAO order_userDAO = new OrderUserDAO(); OrderUserBean order_userBean = order_userDAO.detail(id); order_userDAO.close(); request.setAttribute("order_userBean", order_userBean); return "/view/order_user/select.jsp"; } } <file_sep>/WEB-INF/src/tool/DAO.java package tool; import java.sql.Connection; import java.sql.DriverManager; public class DAO { // DB設定 private final String URL = "jdbc:mysql://localhost/masaru_db"; private final String USER = "root"; private final String PASSWORD = ""; private final String DRIVER = "com.mysql.jdbc.Driver"; protected Connection connection = null; // コンストラクタ //コネクションの接続 protected DAO() throws Exception { // JDBCドライバのロード Class.forName(DRIVER).newInstance(); // Connectionオブジェクトの作成 this.connection = DriverManager.getConnection(URL,USER,PASSWORD); } // コネクションの切断 public void close() throws Exception { this.connection.close(); } } <file_sep>/WEB-INF/src/action/book/FormSignupAction.java package action.book; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; public class FormSignupAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String floor_id = request.getParameter("floor_id"); String start = request.getParameter("end"); request.setAttribute("floor_id", floor_id); request.setAttribute("start", start); return "/view/situation/book_signup.jsp"; } } <file_sep>/WEB-INF/src/dao/AnalyseDAO.java package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import org.apache.jasper.tagplugins.jstl.core.If; import bean.OrderBean; import bean.TaskBean; import com.sun.xml.internal.ws.api.ha.StickyFeature; import tool.DAO; public class AnalyseDAO extends DAO { // コンストラクタ // 親コンストラクタを呼び出し public AnalyseDAO() throws Exception { super(); } // ジャンル別に全件検索 public ArrayList<String> menu_searchall(String genre)throws Exception { // Beanのリスト ArrayList<String> menulist = new ArrayList<String>(); // SQL文 String sql = "select menu_name from menu where menu_genre = ? order by menu_name asc"; // STATEMENTの生成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入(ワイルドカード使用) statement.setString(1, genre); // 検索結果を受け取る ResultSet rSet = statement.executeQuery(); // 検索結果をBeanのリストに格納 while (rSet.next()) { // Beanをリストに追加 menulist.add(rSet.getString(1)); } return menulist; } // メニュー別の売上分析 public ArrayList<String> analyse_menu( String xaxis , String yaxis , String date , String age , Boolean age_check , String sex , String time_lead , String time_last , Boolean timezone_check ,String dotw , Boolean dotw_check , String[] checked_menu , String datestr )throws Exception { System.out.println(""); System.out.println("-------ここからDAO-------"); System.out.println(""); String sql = "SELECT "; ArrayList<String> datas = new ArrayList<String>(); String birth_lead = ""; String birth_last = ""; int age_lead_int = -1; int age_last_int = -1; int birth_lead_int = -1; int birth_last_int = -1; String sex_condition = ""; int wildcard_cnt = 1; String yaxis_column = ""; String dotw_num = ""; if(yaxis.equals("sales")){ sql += "SUM(menu_price * menu_qty)";; } if(yaxis.equals("noo")){ sql += "SUM(menu_qty)"; } sql += " FROM sale_detail , menu , situation " + "where " + //saleテーブルとuserテーブルを結合 "sale_detail.situation_id = situation.situation_id and " + //saleテーブルとsituationテーブルを結合 "sale_detail.menu_id = menu.menu_id and "; if(!age_check){ //年齢層の絞り込み sql += "menu_age = ? and "; } if(!sex.equals("both")){//性別の絞り込み sql += "menu_sex = ? and "; } if(!timezone_check){//時間帯の絞り込み sql += "situation_start between ? and ? and "; } if(checked_menu != null){ sql += "menu_name in ("; for(int k = 0 ; k < checked_menu.length ; k++){ sql += "?"; if(k != checked_menu.length-1){ sql += ","; } } sql += ") and "; } //曜日の絞り込み if(!dotw_check){ if(dotw.equals("sun")){ dotw_num = "1"; } if(dotw.equals("mon")){ dotw_num = "2"; } if(dotw.equals("tue")){ dotw_num = "3"; } if(dotw.equals("wed")){ dotw_num = "4"; } if(dotw.equals("thu")){ dotw_num = "5"; } if(dotw.equals("fri")){ dotw_num = "6"; } if(dotw.equals("sat")){ dotw_num = "7"; } } if(!dotw_check){//曜日の絞り込み sql += "WEEKDAY(situation_date) IN (" + dotw_num + ") and "; } //日付の絞り込み if(!xaxis.equals("week")){ sql += "situation_date like ?"; } else{ sql += "situation_date between ? and ?"; } //年月日を取得 Date today = new Date(); Calendar cal = Calendar.getInstance();if(datestr.equals("")){ cal.setTime(today); } else{ String[] date_ar = datestr.split("-" , 0); cal.set(Calendar.YEAR,Integer.parseInt(date_ar[0])); cal.set(Calendar.MONTH,Integer.parseInt(date_ar[1])); cal.set(Calendar.DATE,Integer.parseInt(date_ar[2])); cal.add(Calendar.MONTH, -1); } int yy = cal.get(Calendar.YEAR); int mm = cal.get(Calendar.MONTH)+1; int dd = cal.get(Calendar.DATE); //性別の絞り込み if(sex.equals("male")){ sex = "男"; } if(sex.equals("female")){ sex = "女"; } int i = 0; if(xaxis.equals("year") || xaxis.equals("week")){ i = 10; } else if(xaxis.equals("month")){ i = 12; } else if(xaxis.equals("day")){ i = 7; } PreparedStatement statement = this.connection.prepareStatement(sql); // 未確定分を含まない設定 // if(xaxis.equals("year")){ // cal.add(Calendar.YEAR,-1); // } // if(xaxis.equals("month")){ // cal.add(Calendar.MONTH,-1); // } // if(xaxis.equals("week")){ // cal.add(Calendar.DATE,-1); // } // if(xaxis.equals("year")){ // cal.add(Calendar.DATE,-1); // } for(int j = 0 ; j < i ; j++){ System.out.println(""); System.out.println("-------ここからfor文-" + j + "周目------"); System.out.println(""); wildcard_cnt = 1; String sale_date_m = ""; String sale_date_d = ""; // STATEMENTの生成 statement = this.connection.prepareStatement(sql); //年齢の絞り込み if(!age_check){ statement.setString(wildcard_cnt, age); wildcard_cnt++; } //性別の絞り込み if(!sex.equals("both")){ statement.setString(wildcard_cnt, sex); wildcard_cnt++; } //時間帯の絞り込み if(!timezone_check){ statement.setString(wildcard_cnt, time_lead + ":00"); wildcard_cnt++; statement.setString(wildcard_cnt, time_last + ":00"); wildcard_cnt++; } //メニューの絞り込み if(checked_menu != null){ for(int k = 0 ; k < checked_menu.length ; k++){ statement.setString(wildcard_cnt,checked_menu[k]); wildcard_cnt++; } } //日付の絞り込み yy = cal.get(Calendar.YEAR); mm = cal.get(Calendar.MONTH)+1; dd = cal.get(Calendar.DATE); if(mm < 10){ sale_date_m = "0"; } sale_date_m += ""+mm; if(dd < 10){ sale_date_d = "0"; } sale_date_d += ""+dd; if(xaxis.equals("year")){ statement.setString(wildcard_cnt, yy + "%"); wildcard_cnt++; } if(xaxis.equals("month")){ statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "%"); wildcard_cnt++; } if(xaxis.equals("week")){ sale_date_d = ""; sale_date_m = ""; cal.add(Calendar.DATE,-7); yy = cal.get(Calendar.YEAR); mm = cal.get(Calendar.MONTH)+1; dd = cal.get(Calendar.DATE); if(mm < 10){ sale_date_m = "0"; } sale_date_m += ""+mm; if(dd < 10){ sale_date_d = "0"; } sale_date_d += ""+dd; statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "-" + sale_date_d + "%"); wildcard_cnt++; sale_date_d = ""; sale_date_m = ""; cal.add(Calendar.DATE,7); yy = cal.get(Calendar.YEAR); mm = cal.get(Calendar.MONTH)+1; dd = cal.get(Calendar.DATE); if(mm < 10){ sale_date_m = "0"; } sale_date_m += ""+mm; if(dd < 10){ sale_date_d = "0"; } sale_date_d += ""+dd; statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "-" + sale_date_d + "%"); wildcard_cnt++; } if(xaxis.equals("day")){ statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "-" + sale_date_d + "%"); wildcard_cnt++; } if(xaxis.equals("year")){ cal.add(Calendar.YEAR,-1); } if(xaxis.equals("month")){ cal.add(Calendar.MONTH,-1); } if(xaxis.equals("week")){ cal.add(Calendar.DATE,-7); } if(xaxis.equals("day")){ cal.add(Calendar.DATE,-1); } System.out.println(statement.toString()); // 検索結果を受け取る ResultSet rSet = statement.executeQuery(); rSet.next(); // リストに結果を追加 if(rSet.getString(1) == null){ datas.add("0"); } else{ datas.add(rSet.getString(1)); } } //リストを入れ替える ArrayList<String> datas_work = new ArrayList<String>(); for(int j = datas.size()-1 ; j >= 0 ; j--){ datas_work.add(datas.get(j)); } datas = datas_work; // ちゃんと閉じる! statement.close(); System.out.println(""); System.out.println("-------ここまでDAO-------"); System.out.println(""); return datas; } // 売上の分析 public ArrayList<String> analyse( String xaxis , String yaxis , String date , String age_lead , String age_last , Boolean age_check , String sex , String time_lead , String time_last , Boolean timezone_check ,String dotw , Boolean dotw_check , String datestr )throws Exception { System.out.println(""); System.out.println("-------ここからDAO-------"); System.out.println(""); String sql = "SELECT "; ArrayList<String> datas = new ArrayList<String>(); String birth_lead = ""; String birth_last = ""; int age_lead_int = -1; int age_last_int = -1; int birth_lead_int = -1; int birth_last_int = -1; String sex_condition = ""; int wildcard_cnt = 1; String yaxis_column = ""; String dotw_num = ""; if(yaxis.equals("sales")){ sql += "SUM(sale_total)";; } if(yaxis.equals("visitors")){ sql += "SUM(situation_qty)"; } sql += " FROM sale,user,situation " + "where " + //saleテーブルとuserテーブルを結合 "sale.user_id = user.user_id and " + //saleテーブルとsituationテーブルを結合 "sale.situation_id = situation.situation_id and "; if(!age_check){ //年齢層の絞り込み sql += "user_birth between ? and ? and "; } if(!sex.equals("both")){//性別の絞り込み sql += "user_sex = ? and "; } if(!timezone_check){//時間帯の絞り込み sql += "situation_start between ? and ? and "; } //曜日の絞り込み if(!dotw_check){ if(dotw.equals("sun")){ dotw_num = "1"; } if(dotw.equals("mon")){ dotw_num = "2"; } if(dotw.equals("tue")){ dotw_num = "3"; } if(dotw.equals("wed")){ dotw_num = "4"; } if(dotw.equals("thu")){ dotw_num = "5"; } if(dotw.equals("fri")){ dotw_num = "6"; } if(dotw.equals("sat")){ dotw_num = "7"; } } if(!dotw_check){//曜日の絞り込み sql += "WEEKDAY(situation_date) IN (" + dotw_num + ") and "; } //日付の絞り込み if(!xaxis.equals("week")){ sql += "situation_date like ?"; } else{ sql += "situation_date between ? and ?"; } //年月日を取得 Date today = new Date(); Calendar cal = Calendar.getInstance(); if(datestr.equals("")){ cal.setTime(today); } else{ String[] date_ar = datestr.split("-" , 0); cal.set(Calendar.YEAR,Integer.parseInt(date_ar[0])); cal.set(Calendar.MONTH,Integer.parseInt(date_ar[1])); cal.set(Calendar.DATE,Integer.parseInt(date_ar[2])); cal.add(Calendar.MONTH, -1); } System.out.print("date : " + cal.get(Calendar.YEAR) + "-"); System.out.print((cal.get(Calendar.MONTH)+1) + "-"); System.out.println(cal.get(Calendar.DATE)); int yy = cal.get(Calendar.YEAR); int mm = cal.get(Calendar.MONTH)+1; int dd = cal.get(Calendar.DATE); //年齢の絞り込み if(!age_check){ age_lead_int = Integer.parseInt(age_lead); age_last_int = Integer.parseInt(age_last); birth_lead_int = yy - age_lead_int; birth_last_int = yy - age_last_int-1; birth_lead = birth_lead_int + "-" + mm + "-" + dd + " 23:59:59"; birth_last = birth_last_int + "-" + mm + "-" + dd + " 00:00:00"; } //性別の絞り込み if(sex.equals("male")){ sex = "男"; } if(sex.equals("female")){ sex = "女"; } int i = 0; if(xaxis.equals("year") || xaxis.equals("week")){ i = 10; } else if(xaxis.equals("month")){ i = 12; } else if(xaxis.equals("day")){ i = 7; } PreparedStatement statement = this.connection.prepareStatement(sql); // 未確定分を含まない設定 // if(xaxis.equals("year")){ // cal.add(Calendar.YEAR,-1); // } // if(xaxis.equals("month")){ // cal.add(Calendar.MONTH,-1); // } // if(xaxis.equals("week")){ // cal.add(Calendar.DATE,-1); // } // if(xaxis.equals("year")){ // cal.add(Calendar.DATE,-1); // } for(int j = 0 ; j < i ; j++){ System.out.println(""); System.out.println("-------ここからfor文-" + j + "周目------"); System.out.println(""); wildcard_cnt = 1; String sale_date_m = ""; String sale_date_d = ""; // STATEMENTの生成 statement = this.connection.prepareStatement(sql); //年齢の絞り込み if(!age_check){ statement.setString(wildcard_cnt, birth_last); wildcard_cnt++; statement.setString(wildcard_cnt, birth_lead); wildcard_cnt++; } //性別の絞り込み if(!sex.equals("both")){ statement.setString(wildcard_cnt, sex); wildcard_cnt++; } //時間帯の絞り込み if(!timezone_check){ statement.setString(wildcard_cnt, time_lead + ":00"); wildcard_cnt++; statement.setString(wildcard_cnt, time_last + ":00"); wildcard_cnt++; } //日付の絞り込み yy = cal.get(Calendar.YEAR); mm = cal.get(Calendar.MONTH)+1; dd = cal.get(Calendar.DATE); if(mm < 10){ sale_date_m = "0"; } sale_date_m += ""+mm; if(dd < 10){ sale_date_d = "0"; } sale_date_d += ""+dd; if(xaxis.equals("year")){ statement.setString(wildcard_cnt, yy + "%"); wildcard_cnt++; } if(xaxis.equals("month")){ statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "%"); wildcard_cnt++; } if(xaxis.equals("week")){ sale_date_d = ""; sale_date_m = ""; cal.add(Calendar.DATE,-7); yy = cal.get(Calendar.YEAR); mm = cal.get(Calendar.MONTH)+1; dd = cal.get(Calendar.DATE); if(mm < 10){ sale_date_m = "0"; } sale_date_m += ""+mm; if(dd < 10){ sale_date_d = "0"; } sale_date_d += ""+dd; statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "-" + sale_date_d + "%"); wildcard_cnt++; sale_date_d = ""; sale_date_m = ""; cal.add(Calendar.DATE,7); yy = cal.get(Calendar.YEAR); mm = cal.get(Calendar.MONTH)+1; dd = cal.get(Calendar.DATE); if(mm < 10){ sale_date_m = "0"; } sale_date_m += ""+mm; if(dd < 10){ sale_date_d = "0"; } sale_date_d += ""+dd; statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "-" + sale_date_d + "%"); wildcard_cnt++; } if(xaxis.equals("day")){ statement.setString(wildcard_cnt, yy + "-" + sale_date_m + "-" + sale_date_d + "%"); wildcard_cnt++; } if(xaxis.equals("year")){ cal.add(Calendar.YEAR,-1); } if(xaxis.equals("month")){ cal.add(Calendar.MONTH,-1); } if(xaxis.equals("week")){ cal.add(Calendar.DATE,-7); } if(xaxis.equals("day")){ cal.add(Calendar.DATE,-1); } System.out.println(statement.toString()); // 検索結果を受け取る ResultSet rSet = statement.executeQuery(); rSet.next(); // リストに結果を追加 if(rSet.getString(1) == null){ datas.add("0"); } else{ datas.add(rSet.getString(1)); } } //リストを入れ替える ArrayList<String> datas_work = new ArrayList<String>(); for(int j = datas.size()-1 ; j >= 0 ; j--){ datas_work.add(datas.get(j)); } datas = datas_work; // ちゃんと閉じる! statement.close(); System.out.println(""); System.out.println("-------ここまでDAO-------"); System.out.println(""); return datas; } } <file_sep>/WEB-INF/src/bean/TopBean.java package bean; public class TopBean { private String floor_id = ""; private String situation_id = null; private String state = ""; public String getFloor_id() { return floor_id; } public void setFloor_id(String floor_id) { this.floor_id = floor_id; } public String getSituation_id() { return situation_id; } public void setSituation_id(String situation_id) { this.situation_id = situation_id; } public String getState() { return state; } public void setState(String state) { this.state = state; } } <file_sep>/WEB-INF/src/action/stock/ItemUpdateAction.java package action.stock; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; import dao.ItemDAO; public class ItemUpdateAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("id"); String name = request.getParameter("name"); String genre = request.getParameter("genre"); int max = Integer.parseInt(request.getParameter("max")); int min = Integer.parseInt(request.getParameter("min")); ItemDAO itemDAO = new ItemDAO(); boolean flag = itemDAO.update(id, name, genre, max, min); itemDAO.close(); if (flag) { return "/view/stock/item_update_complete.jsp"; } else { return "/view/stock/item_update_error.jsp"; } } } <file_sep>/WEB-INF/src/action/order/Miteikyou_TopAction.java package action.order; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.TaskBean; import dao.OrderDAO; import tool.Action; public class Miteikyou_TopAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // DAOの生成 OrderDAO orderDAO = new OrderDAO(); // DAOメソッドの実行 ArrayList<TaskBean> taskBeans = orderDAO.searchall_deployed(); // ちゃんと閉じる! orderDAO.close(); request.setAttribute("TaskBeans", taskBeans); return "/view/order/miteikyou_top.jsp"; } } <file_sep>/sql/sample_insert.sql set names utf8; use masaru_db; -- 会員 INSERT INTO user VALUES ('tanaka', 'renn', '田中蓮', '男', '1999-08-05', '<EMAIL>', '080-2222-0101', '学生', '4', '5', '2020-04-01'); INSERT INTO user VALUES ('yamaguti', 'kaede', '山口楓', '女', '1998-10-09', '<EMAIL>', '080-2222-0102', '学生', '5', '5', '2020-04-01'); INSERT INTO user VALUES ('ito', 'riko', '伊藤莉子', '女', '1995-01-03', '<EMAIL>', '080-2222-0103', '会社員', '3', '4', '2020-04-01'); INSERT INTO user VALUES ('yamasita', 'iori', '山下伊織', '男', '1980-12-24', '<EMAIL>', '080-2222-0104', '会社員', '4', '5', '2020-04-01'); INSERT INTO user VALUES ('nakazima', 'rio', '中島莉緒', '女', '1960-09-13', '<EMAIL>', '080-2222-0105', 'シニア', '2', '3', '2020-04-01'); INSERT INTO user VALUES ('isii', 'yuu', '石井悠', '男', '1997-10-05', '<EMAIL>', '080-2222-0106', '会社員', '1', '5', '2020-04-01'); INSERT INTO user VALUES ('ogawa', 'rio', '小川莉央', '女', '1992-06-25', '<EMAIL>', '080-2222-0107', '会社員', '2', '4', '2020-04-01'); INSERT INTO user VALUES ('maeda', 'asahi', '前田旭', '男', '1959-10-20', '<EMAIL>', '080-2222-0108', 'シニア', '1', '5', '2020-04-01'); INSERT INTO user VALUES ('okada', 'tumugi', '岡田紬希', '女', '2000-02-11', '<EMAIL>', '080-2222-0109', '学生', '1', '5', '2020-04-01'); INSERT INTO user VALUES ('hasegawa', 'nagi', '長谷川凪', '男', '2005-08-26', '<EMAIL>', '080-2222-0110', '学生', '1', '5', '2020-04-01'); INSERT INTO user VALUES ('huzita', 'sana', '藤田紗菜', '女', '1983-07-01', '<EMAIL>', '080-2222-0111', '会社員', '2', '4', '2020-04-01'); INSERT INTO user VALUES ('gotou', 'hinata', '後藤陽大', '男', '1998-04-03', '<EMAIL>', '080-2222-0112', '学生', '5', '5', '2020-04-01'); INSERT INTO user VALUES ('konndou', 'annna', '近藤杏奈', '女', '1955-03-03', '<EMAIL>', '080-2222-0113', 'シニア', '3', '5', '2020-04-01'); INSERT INTO user VALUES ('murakami', 'minato', '村上湊斗', '男', '1991-10-03', '<EMAIL>', '080-2222-0114', '会社員', '1', '2', '2020-04-01'); INSERT INTO user VALUES ('enndou', 'hana', '遠藤花', '女', '1978-12-11', '<EMAIL>', '080-2222-0115', '会社員', '5', '5', '2020-04-01'); INSERT INTO user VALUES ('aoki', 'souma', '青木蒼真', '男', '1981-11-07', '<EMAIL>', '080-2222-0116', '会社員', '2', '5', '2020-04-01'); INSERT INTO user VALUES ('sakamoto', 'rinn', '坂本凜', '女', '1992-01-03', '<EMAIL>', '080-2222-0117', '会社員', '1', '5', '2020-04-01'); INSERT INTO user VALUES ('saito', 'gaku', '斉藤岳', '男', '1977-01-23', '<EMAIL>', '080-2222-0118', '会社員', '4', '5', '2020-04-01'); INSERT INTO user VALUES ('hukuda', 'itika', '福田一華', '女', '1982-09-10', '<EMAIL>', '080-2222-0119', '会社員', '4', '4', '2020-04-01'); INSERT INTO user VALUES ('oota', 'riku', '太田陸', '男', '1990-03-22', '<EMAIL>', '080-2222-0120', '会社員', '1', '5', '2020-04-01'); -- 利用 INSERT INTO situation values (1, 'yamaguti', '101', '1', '2020-01-14' , '20:22:00' , '23:22:00' , '23:22:00' , '無'); INSERT INTO situation values (2, 'tanaka', '102', '2', '2020-01-15' , '15:46:00' , '18:46:00' , '18:46:00' , '無'); INSERT INTO situation values (3, 'yamaguti', '106', '3', '2020-01-15' , '12:11:00' , '15:11:00' , '15:11:00' , '無'); INSERT INTO situation values (4, 'ito', '110', '7', '2020-01-19' , '21:35:00' , '00:35:00' , '00:35:00' , '無'); INSERT INTO situation values (5, 'nakazima', '202', '5', '2020-02-01' , '10:57:00' , '13:57:00' , '11:57:00' , '無'); INSERT INTO situation values (6, 'isii', '208', '4', '2020-02-16' , '17:04:00' , '20:04:00' , '20:04:00' , '無'); INSERT INTO situation values (7, 'nakazima', '209', '9', '2020-02-19' , '11:01:00' , '14:01:00' , '14:01:00' , '無'); INSERT INTO situation values (8, 'ogawa', '303', '2', '2020-02-20' , '18:21:00' , '21:21:00' , '21:21:00' , '無'); INSERT INTO situation values (9, 'maeda', '307', '4', '2020-03-03' , '10:33:00' , '13:33:00' , '13:33:00' , '無'); INSERT INTO situation values (10, 'okada', '401', '2', '2020-03-11' , '13:10:00' , '16:10:00' , '16:10:00' , '無'); INSERT INTO situation values (11, 'hasegawa', '405', '6', '2020-03-15' , '14:41:00' , '17:41:00' , '19:41:00' , '無'); INSERT INTO situation values (12, 'huzita', '508', '5', '2020-03-20' , '16:47:00' , '19:47:00' , '19:47:00' , '無'); INSERT INTO situation values (13, 'gotou', '509', '10', '2020-04-02' , '12:39:00' , '15:39:00' , '15:39:00' , '無'); INSERT INTO situation values (14, 'konndou', '510', '8', '2020-04-28' , '11:12:00' , '14:12:00' , '14:12:00' , '無'); INSERT INTO situation values (15, 'murakami', '101', '5', '2020-04-29' , '19:00:00' , '22:00:00' , '22:00:00' , '無'); INSERT INTO situation values (16, 'enndou', '106', '2', '2020-05-06' , '15:28:00' , '18:28:00' , '18:28:00' , '無'); INSERT INTO situation values (17, 'aoki', '107', '1', '2020-05-08' , '14:38:00' , '17:38:00' , '17:38:00' , '無'); INSERT INTO situation values (18, 'sakamoto', '109', '12', '2020-05-17' , '10:06:00' , '13:06:00' , '13:06:00' , '無'); INSERT INTO situation values (19, 'saito', '204', '3', '2020-05-22' , '18:59:00' , '21:59:00' , '21:59:00' , '無'); INSERT INTO situation values (20, 'hukuda', '209', '8', '2020-06-07' , '17:24:00' , '20:24:00' , '20:24:00' , '無'); INSERT INTO situation values (21, 'oota', '307', '2', '2020-06-08' , '10:02:00' , '13:02:00' , '13:02:00' , '無'); INSERT INTO situation values (22, 'yamaguti', '310', '10', '2021-06-12' , '10:46:00' , '13:46:00' , '13:46:00' , '無'); INSERT INTO situation values (23, 'tanaka', '405', '3', '2020-06-12' , '13:31:00' , '16:31:00' , '16:31:00' , '無'); INSERT INTO situation values (24, 'yamaguti', '406', '2', '2020-06-21' , '16:22:00' , '19:22:00' , '19:22:00' , '無'); INSERT INTO situation values (25, 'ito', '407', '4', '2020-07-01' , '14:37:00' , '17:37:00' , '17:37:00' , '無'); INSERT INTO situation values (26, 'nakazima', '501', '4', '2020-07-05' , '11:55:00' , '14:55:00' , '14:55:00' , '無'); INSERT INTO situation values (27, 'isii', '504', '2', '2020-07-13' , '12:19:00' , '15:19:00' , '15:19:00' , '無'); INSERT INTO situation values (28, 'nakazima', '507', '3', '2020-07-18' , '14:25:00' , '17:25:00' , '17:25:00' , '無'); INSERT INTO situation values (29, 'ogawa', '508', '2', '2020-07-26' , '15:49:00' , '18:49:00' , '18:49:00' , '無'); INSERT INTO situation values (30, 'maeda', '101', '3', '2020-07-27' , '11:17:00' , '14:17:00' , '14:17:00' , '無'); INSERT INTO situation values (31, 'okada', '104', '3', '2020-08-09' , '20:41:00' , '23:41:00' , '23:41:00' , '無'); INSERT INTO situation values (32, 'hasegawa', '202', '2', '2020-08-10' , '10:39:00' , '13:39:00' , '13:39:00' , '無'); INSERT INTO situation values (33, 'huzita', '204', '3', '2020-08-20' , '17:21:00' , '20:21:00' , '20:21:00' , '無'); INSERT INTO situation values (34, 'gotou', '205', '3', '2020-09-03' , '18:05:00' , '21:05:00' , '21:05:00' , '無'); INSERT INTO situation values (35, 'konndou', '301', '1', '2020-09-16' , '11:28:00' , '14:28:00' , '14:28:00' , '無'); INSERT INTO situation values (36, 'murakami', '304', '1', '2020-09-22' , '14:43:00' , '17:43:00' , '17:43:00' , '無'); INSERT INTO situation values (37, 'enndou', '307', '1', '2020-10-04' , '16:31:00' , '19:31:00' , '19:31:00' , '無'); INSERT INTO situation values (38, 'aoki', '308', '2', '2020-10-15' , '10:25:00' , '13:25:00' , '13:25:00' , '無'); INSERT INTO situation values (39, 'sakamoto', '403', '2', '2020-10-27' , '20:50:00' , '23:50:00' , '23:50:00' , '無'); INSERT INTO situation values (40, 'saito', '404', '1', '2020-11-03' , '21:32:00' , '00:32:00' , '00:32:00' , '無'); INSERT INTO situation values (41, 'hukuda', '505', '3', '2020-11-23' , '18:29:00' , '21:29:00' , '21:29:00' , '無'); INSERT INTO situation values (42, 'oota', '508', '2', '2020-12-18' , '17:42:00' , '20:42:00' , '20:42:00' , '無'); -- 売上 INSERT INTO sale values (0 , 'yamaguti' , 1 , '3000' , '2020-01-14'); INSERT INTO sale values (0 , 'tanaka' , 2 , '6400' , '2020-01-15'); INSERT INTO sale values (0 , 'yamaguti' , 3 , '9000' , '2020-01-15'); INSERT INTO sale values (0 , 'ito' , 4 , '32400' , '2020-01-19'); INSERT INTO sale values (0 , 'nakazima' , 5 , '18000' , '2020-02-01'); INSERT INTO sale values (0 , 'isii' , 6 , '18000' , '2020-02-16'); INSERT INTO sale values (0 , 'nakazima' , 7 , '27000' , '2020-02-19'); INSERT INTO sale values (0 , 'ogawa' , 8 , '7200' , '2020-02-20'); INSERT INTO sale values (0 , 'maeda' , 9 , '12000' , '2020-03-03'); INSERT INTO sale values (0 , 'okada' , 10 , '6000' , '2020-03-11'); INSERT INTO sale values (0 , 'hasegawa' , 11 , '25200' , '2020-03-15'); INSERT INTO sale values (0 , 'huzita' , 12 , '22500' , '2020-03-20'); INSERT INTO sale values (0 , 'gotou' , 13 , '30000' , '2020-04-02'); INSERT INTO sale values (0 , 'konndou' , 14 , '24000' , '2020-04-28'); INSERT INTO sale values (0 , 'murakami' , 15 , '15000' , '2020-04-29'); INSERT INTO sale values (0 , 'enndou' , 16 , '6800' , '2020-05-06'); INSERT INTO sale values (0 , 'aoki' , 17 , '4200' , '2020-05-08'); INSERT INTO sale values (0 , 'sakamoto' , 18 , '43200' , '2020-05-17'); INSERT INTO sale values (0 , 'saito' , 19 , '13500' , '2020-05-22'); INSERT INTO sale values (0 , 'hukuda' , 20 , '36000' , '2020-06-07'); INSERT INTO sale values (0 , 'oota' , 21 , '6000' , '2020-06-08'); INSERT INTO sale values (0 , 'yamaguti' , 22 , '36000' , '2021-06-12'); INSERT INTO sale values (0 , 'tanaka' , 23 , '12600' , '2020-06-12'); INSERT INTO sale values (0 , 'yamaguti' , 24 , '9000' , '2020-06-21'); INSERT INTO sale values (0 , 'ito' , 25 , '12800' , '2020-07-01'); INSERT INTO sale values (0 , 'nakazima' , 26 , '14400' , '2020-07-05'); INSERT INTO sale values (0 , 'isii' , 27 , '6000' , '2020-07-13'); INSERT INTO sale values (0 , 'nakazima' , 28 , '13500' , '2020-07-18'); INSERT INTO sale values (0 , 'ogawa' , 29 , '9000' , '2020-07-26'); INSERT INTO sale values (0 , 'maeda' , 30 , '9000' , '2020-07-27'); INSERT INTO sale values (0 , 'okada' , 31 , '10800' , '2020-08-09'); INSERT INTO sale values (0 , 'hasegawa' , 32 , '6000' , '2020-08-10'); INSERT INTO sale values (0 , 'huzita' , 33 , '9000' , '2020-08-20'); INSERT INTO sale values (0 , 'gotou' , 34 , '9000' , '2020-09-03'); INSERT INTO sale values (0 , 'konndou' , 35 , '3000' , '2020-09-16'); INSERT INTO sale values (0 , 'murakami' , 36 , '3200' , '2020-09-22'); INSERT INTO sale values (0 , 'enndou' , 37 , '4500' , '2020-10-04'); INSERT INTO sale values (0 , 'aoki' , 38 , '6000' , '2020-10-15'); INSERT INTO sale values (0 , 'sakamoto' , 39 , '7200' , '2020-10-27'); INSERT INTO sale values (0 , 'saito' , 40 , '3600' , '2020-11-03'); INSERT INTO sale values (0 , 'hukuda' , 41 , '10800' , '2020-11-23'); INSERT INTO sale values (0 , 'oota' , 42 , '9000' , '2020-12-18'); -- 売上詳細 INSERT INTO sale_detail values (0,1,9,2,'女','20代'); INSERT INTO sale_detail values (0,1,8,2,'女','20代'); INSERT INTO sale_detail values (0,2,27,1,'男','20代'); INSERT INTO sale_detail values (0,3,9,2,'女','20代'); INSERT INTO sale_detail values (0,3,19,1,'男','20代'); INSERT INTO sale_detail values (0,4,1,1,'男','20代'); INSERT INTO sale_detail values (0,4,10,3,'男','20代'); INSERT INTO sale_detail values (0,4,13,1,'女','40代'); INSERT INTO sale_detail values (0,4,20,1,'女','30代'); INSERT INTO sale_detail values (0,5,10,1,'女','シニア'); INSERT INTO sale_detail values (0,5,22,2,'男','子ども'); INSERT INTO sale_detail values (0,5,12,1,'女','30代'); INSERT INTO sale_detail values (0,5,17,1,'男','30代'); INSERT INTO sale_detail values (0,5,9,2,'男','子ども'); INSERT INTO sale_detail values (0,6,2,1,'男','20代'); INSERT INTO sale_detail values (0,6,14,1,'男','30代'); INSERT INTO sale_detail values (0,6,3,1,'女','20代'); INSERT INTO sale_detail values (0,7,10,1,'女','シニア'); INSERT INTO sale_detail values (0,7,24,2,'女','子ども'); INSERT INTO sale_detail values (0,7,23,2,'男','子ども'); INSERT INTO sale_detail values (0,7,29,2,'女','30代'); INSERT INTO sale_detail values (0,7,26,1,'男','30代'); INSERT INTO sale_detail values (0,7,28,1,'男','10代'); INSERT INTO sale_detail values (0,8,15,2,'女','20代'); INSERT INTO sale_detail values (0,9,10,1,'男','シニア'); INSERT INTO sale_detail values (0,9,5,1,'男','シニア'); INSERT INTO sale_detail values (0,9,11,2,'女','シニア'); INSERT INTO sale_detail values (0,10,8,2,'女','10代'); INSERT INTO sale_detail values (0,11,25,1,'男','10代'); INSERT INTO sale_detail values (0,11,6,1,'男','10代'); INSERT INTO sale_detail values (0,11,17,2,'男','10代'); INSERT INTO sale_detail values (0,11,27,2,'男','10代'); INSERT INTO sale_detail values (0,12,7,1,'女','30代'); INSERT INTO sale_detail values (0,12,8,1,'女','30代'); INSERT INTO sale_detail values (0,12,9,1,'女','30代'); INSERT INTO sale_detail values (0,12,21,2,'女','30代'); INSERT INTO sale_detail values (0,13,27,2,'男','20代'); INSERT INTO sale_detail values (0,13,7,2,'男','20代'); INSERT INTO sale_detail values (0,13,8,2,'女','20代'); INSERT INTO sale_detail values (0,13,28,2,'女','20代'); INSERT INTO sale_detail values (0,13,18,2,'男','20代'); INSERT INTO sale_detail values (0,14,21,1,'女','20代'); INSERT INTO sale_detail values (0,14,1,2,'男','30代'); INSERT INTO sale_detail values (0,14,18,1,'男','40代'); INSERT INTO sale_detail values (0,14,18,2,'男','シニア'); INSERT INTO sale_detail values (0,14,12,1,'女','30代'); INSERT INTO sale_detail values (0,14,11,1,'女','40代'); INSERT INTO sale_detail values (0,15,26,2,'男','30代'); INSERT INTO sale_detail values (0,15,27,1,'男','20代'); INSERT INTO sale_detail values (0,15,4,2,'女','30代'); INSERT INTO sale_detail values (0,16,10,1,'女','40代'); INSERT INTO sale_detail values (0,16,13,1,'男','40代'); INSERT INTO sale_detail values (0,17,12,1,'男','40代'); INSERT INTO sale_detail values (0,18,23,2,'女','20代'); INSERT INTO sale_detail values (0,18,24,2,'女','20代'); INSERT INTO sale_detail values (0,18,8,2,'女','20代'); INSERT INTO sale_detail values (0,18,19,2,'女','20代'); INSERT INTO sale_detail values (0,28,27,1,'女','20代'); INSERT INTO sale_detail values (0,18,20,1,'女','20代'); INSERT INTO sale_detail values (0,19,14,2,'男','40代'); INSERT INTO sale_detail values (0,19,22,1,'女','40代'); INSERT INTO sale_detail values (0,20,6,2,'女','30代'); INSERT INTO sale_detail values (0,20,5,2,'男','30代'); INSERT INTO sale_detail values (0,20,13,2,'女','20代'); INSERT INTO sale_detail values (0,20,11,2,'男','20代'); INSERT INTO sale_detail values (0,21,21,1,'女','30代'); INSERT INTO sale_detail values (0,21,14,1,'男','30代'); INSERT INTO sale_detail values (0,22,14,2,'女','20代'); INSERT INTO sale_detail values (0,22,15,2,'女','20代'); INSERT INTO sale_detail values (0,22,9,2,'男','20代'); INSERT INTO sale_detail values (0,22,2,2,'男','20代'); INSERT INTO sale_detail values (0,22,24,1,'女','10代'); INSERT INTO sale_detail values (0,22,1,1,'男','10代'); INSERT INTO sale_detail values (0,23,3,1,'男','10代'); INSERT INTO sale_detail values (0,23,4,2,'女','10代'); INSERT INTO sale_detail values (0,24,23,2,'男','40代'); INSERT INTO sale_detail values (0,25,21,2,'女','20代'); INSERT INTO sale_detail values (0,25,22,2,'女','20代'); INSERT INTO sale_detail values (0,26,13,1,'女','シニア'); INSERT INTO sale_detail values (0,26,13,1,'男','シニア'); INSERT INTO sale_detail values (0,26,28,2,'男','子ども'); INSERT INTO sale_detail values (0,27,12,2,'男','20代'); INSERT INTO sale_detail values (0,27,13,2,'女','20代'); INSERT INTO sale_detail values (0,28,10,1,'女','シニア'); INSERT INTO sale_detail values (0,28,22,2,'女','10代'); INSERT INTO sale_detail values (0,29,25,2,'女','20代'); INSERT INTO sale_detail values (0,30,18,2,'男','シニア'); INSERT INTO sale_detail values (0,31,19,2,'女','10代'); INSERT INTO sale_detail values (0,31,28,1,'女','10代'); INSERT INTO sale_detail values (0,32,15,1,'男','10代'); INSERT INTO sale_detail values (0,32,16,1,'女','10代'); INSERT INTO sale_detail values (0,33,11,3,'女','30代'); INSERT INTO sale_detail values (0,34,9,2,'男','20代'); INSERT INTO sale_detail values (0,35,13,2,'女','シニア'); INSERT INTO sale_detail values (0,36,27,1,'男','30代'); INSERT INTO sale_detail values (0,36,12,1,'男','30代'); INSERT INTO sale_detail values (0,37,7,1,'女','40代'); INSERT INTO sale_detail values (0,38,5,1,'女','40代'); INSERT INTO sale_detail values (0,38,8,1,'男','30代'); INSERT INTO sale_detail values (0,39,4,2,'女','20代'); INSERT INTO sale_detail values (0,40,29,1,'女','40代'); INSERT INTO sale_detail values (0,41,15,1,'女','30代'); INSERT INTO sale_detail values (0,41,22,1,'男','30代'); INSERT INTO sale_detail values (0,41,19,1,'女','20代'); INSERT INTO sale_detail values (0,42,17,1,'男','30代'); INSERT INTO sale_detail values (0,42,15,1,'女','30代'); set names cp932; <file_sep>/WEB-INF/src/action/stock/ItemSearchAction.java package action.stock; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.ItemBean; import dao.ItemDAO; import tool.Action; public class ItemSearchAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String keyword = request.getParameter("keyword"); ItemDAO itemDAO = new ItemDAO(); ArrayList<ItemBean> itemBeans = itemDAO.search(keyword); itemDAO.close(); request.setAttribute("itemBeans", itemBeans); return "/view/stock/item_search.jsp"; } } <file_sep>/WEB-INF/src/bean/OrderBean.java package bean; public class OrderBean { // プロパティ private int menu_id = -1; private String menu_name = ""; private String menu_genre = ""; private int menu_price = -1; private String menu_create = ""; private String menu_update = ""; private String menu_des = ""; private String menu_allergy = ""; // ゲッター・セッター public int getMenu_id() { return menu_id; } public void setMenu_id(int menu_id) { this.menu_id = menu_id; } public String getMenu_name() { return menu_name; } public void setMenu_name(String menu_name) { this.menu_name = menu_name; } public String getMenu_genre() { return menu_genre; } public void setMenu_genre(String menu_genre) { this.menu_genre = menu_genre; } public int getMenu_price() { return menu_price; } public void setMenu_price(int menu_price) { this.menu_price = menu_price; } public String getMenu_create() { return menu_create; } public void setMenu_create(String menu_create) { this.menu_create = menu_create; } public String getMenu_update() { return menu_update; } public void setMenu_update(String menu_update) { this.menu_update = menu_update; } public String getMenu_des() { return menu_des; } public void setMenu_des(String menu_des) { this.menu_des = menu_des; } public String getMenu_allergy() { return menu_allergy; } public void setMenu_allergy(String menu_allergy) { this.menu_allergy = menu_allergy; } } <file_sep>/WEB-INF/src/dao/FloorDAO.java package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import tool.DAO; import bean.FloorBean; public class FloorDAO extends DAO { // コンストラクタ // 親コンストラクタを呼び出し public FloorDAO() throws Exception { super(); } // userテーブルへインサート public boolean insert(String id,Integer cap,String machine,String state) throws Exception { // ユーザーIDが重複してないか確認 if (checkFloorId(id)) { return false; } String sql = "insert into floor values ( ?, ?, ?, ?, 0)"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, id); statement.setInt(2, cap); statement.setString(3, machine); statement.setString(4, state); statement.executeUpdate(); // ちゃんと閉じる! statement.close(); return true; } // ユーザーIDが存在するかどうかの判定 private boolean checkFloorId(String floor_id) throws Exception { boolean flag = false; String sql = "select * from floor where floor_id like ?"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, floor_id); ResultSet rSet = statement.executeQuery(); if (rSet.next()) { flag = true; } // ちゃんと閉じる! statement.close(); return flag; } // フロア検索処理 public ArrayList<FloorBean> search(String keyword) throws Exception { // Beanのリスト ArrayList<FloorBean> floorBeans = new ArrayList<FloorBean>(); // SQL文 String sql = "select * from floor where floor_id like ?"; // STATEMENTの生成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入(ワイルドカード使用) statement.setString(1, "%" + keyword + "%"); // 検索結果を受け取る ResultSet rs = statement.executeQuery(); // 検索結果をBeanのリストに格納 while (rs.next()) { // Beanの生成 FloorBean floorBean = new FloorBean(); // カラムの値をBeanに格納 floorBean.setId(rs.getString(1)); floorBean.setCap(rs.getInt(2)); floorBean.setMachine(rs.getString(3)); floorBean.setState(rs.getString(4)); floorBean.setDevice(rs.getInt(5)); // Beanをリストに追加 floorBeans.add(floorBean); } // ちゃんと閉じる! statement.close(); return floorBeans; } // 部屋詳細 public FloorBean detail(String id) throws Exception { // Beanの生成 FloorBean floorBean = new FloorBean(); // SQL文 String sql = "select * from floor where floor_id = ?"; // STATEMENTの生成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入 statement.setString(1, id); // 詳細情報取得 ResultSet rs = statement.executeQuery(); // 詳細情報をBeanに格納 if (rs.next()) { floorBean.setId(rs.getString(1)); floorBean.setCap(rs.getInt(2)); floorBean.setMachine(rs.getString(3)); floorBean.setState(rs.getString(4)); floorBean.setDevice(rs.getInt(5)); } // ちゃんと閉じる! statement.close(); return floorBean; } // フロア更新処理 public boolean update(String id,Integer cap,String machine,String state) throws Exception { String sql = "update floor set floor_cap = ?, floor_machine = ?, floor_state = ? where floor_id = ? "; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setInt(1, cap); statement.setString(2, machine); statement.setString(3, state); statement.setString(4, id); statement.executeUpdate(); // ちゃんと閉じる! statement.close(); return true; } // フロア削除処理 public void delete(String id) throws Exception { String sql = "delete from floor where floor_id = ?"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, id); statement.executeUpdate(); // ちゃんと閉じる! statement.close(); } // フロアデバイス更新処理 public boolean updateOrderUser(String floor_id) throws Exception { //フロアIDが存在しない場合 if (!(checkFloorId(floor_id))) { return false; } FloorBean floorBean = new FloorBean(); String select_sql = "select floor_device from floor where floor_id = ?"; PreparedStatement select_sm = this.connection.prepareStatement(select_sql); select_sm.setString(1, floor_id); ResultSet rs = select_sm.executeQuery(); if (rs.next()) { floorBean.setDevice(rs.getInt(1)); } select_sm.close(); //フロアのデバイス登録状態 if (floorBean.getDevice() == 1) { return false; } String update_sql = "update floor set floor_device = 1 where floor_id = ? "; PreparedStatement update_sm = this.connection.prepareStatement(update_sql); update_sm.setString(1, floor_id); update_sm.executeUpdate(); update_sm.close(); return true; } } <file_sep>/WEB-INF/src/action/situation/TopAction.java package action.situation; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.TopBean; import dao.TopDAO; import tool.Action; public class TopAction extends Action{ @Override public String execute( HttpServletRequest request, HttpServletResponse response ) throws Exception{ String floor = "1"; if (request.getParameter("floor") != null) { floor = request.getParameter("floor"); } TopDAO topDAO = new TopDAO(); ArrayList<TopBean> topBeans = topDAO.getCurrent(floor); topDAO.close(); request.setAttribute("topBeans", topBeans); request.setAttribute("floor", Integer.parseInt(floor)); return "/view/situation/top.jsp"; } } <file_sep>/WEB-INF/src/action/stock/OrderingSearchAction.java package action.stock; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.OrderingBean; import dao.OrderingDAO; import tool.Action; public class OrderingSearchAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String keyword = request.getParameter("keyword"); OrderingDAO orderingDAO = new OrderingDAO(); ArrayList<OrderingBean> orderingBeans = orderingDAO.search(keyword); orderingDAO.close(); request.setAttribute("orderingBeans", orderingBeans); return "/view/stock/ordering_search.jsp"; } } <file_sep>/WEB-INF/src/FrontController.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.*; import tool.Action; public class FrontController extends HttpServlet { public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String class_name = request.getParameter("class_name"); // セッションチェック if (request.getSession(true).getAttribute("id") == null && !class_name.equals("login.LoginAction")) { response.sendRedirect("/SD25/"); } try { class_name = "action." + class_name; Action action = (Action)Class.forName(class_name).newInstance(); String url = action.execute(request, response); request.getRequestDispatcher(url).forward(request, response); } catch (Exception e) { e.printStackTrace(out); } } public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doPost(request, response); } } <file_sep>/WEB-INF/src/action/employee/ShiftSignupAction.java package action.employee; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; import dao.ShiftDAO; import bean.ShiftBean; public class ShiftSignupAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String employee_id = request.getParameter("employee_id"); String date = request.getParameter("date"); String start = request.getParameter("start_hh") + ":" + request.getParameter("start_mm"); String end = request.getParameter("end_hh") + ":" + request.getParameter("end_mm"); ShiftDAO shiftDAO = new ShiftDAO(); shiftDAO.insert(employee_id, date, start, end); ArrayList<ShiftBean> shiftBeans = shiftDAO.search(employee_id); shiftDAO.close(); request.setAttribute("shiftBeans", shiftBeans); return "/view/employee/shift_signup.jsp"; } } <file_sep>/WEB-INF/src/action/employee/SearchAction.java package action.employee; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.EmployeeBean; import dao.EmployeeDAO; import tool.Action; public class SearchAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String keyword = request.getParameter("keyword"); EmployeeDAO employeeDAO = new EmployeeDAO(); ArrayList<EmployeeBean> employeeBeans = employeeDAO.search(keyword); employeeDAO.close(); request.setAttribute("employeeBeans", employeeBeans); return "/view/employee/search.jsp"; } } <file_sep>/WEB-INF/src/bean/FloorBean.java package bean; public class FloorBean { // プロパティ private String id = ""; private int cap = 0; private String machine = ""; private String state = ""; private int device = 0; // ゲッター・セッター public String getId() { return id; } public void setId(String id) { this.id = id; } public int getCap() { return cap; } public void setCap(int cap) { this.cap = cap; } public String getMachine() { return machine; } public void setMachine(String machine) { this.machine = machine; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getDevice() { return device; } public void setDevice(int device) { this.device = device; } } <file_sep>/WEB-INF/src/action/stock/GenreSearchAction.java package action.stock; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.ItemBean; import dao.ItemDAO; import tool.Action; public class GenreSearchAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String genre = request.getParameter("genre"); if (genre != null) { ItemDAO itemDAO = new ItemDAO(); ArrayList<ItemBean> itemBeans = itemDAO.searchGenre(genre); itemDAO.close(); request.setAttribute("itemBeans", itemBeans); request.setAttribute("genre", genre); } return "/view/stock/genre_search.jsp"; } } <file_sep>/WEB-INF/src/bean/ShiftConfirmBean.java package bean; public class ShiftConfirmBean { // プロパティ private String id = ""; private String employee_id = ""; private String date = ""; private String start = ""; private String end = ""; private String name = ""; // ゲッターセッター public String getId() { return id; } public void setId(String id) { this.id = id; } public String getEmployee_id() { return employee_id; } public void setEmployee_id(String employee_id) { this.employee_id = employee_id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/WEB-INF/src/action/user/FormUpdateAction.java package action.user; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.UserBean; import tool.Action; import dao.UserDAO; public class FormUpdateAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // パラメータの取得 String id = request.getParameter("id"); // DAOの生成 UserDAO userDAO = new UserDAO(); // DAOメソッドの実行 UserBean userBean = userDAO.detail(id); // ちゃんと閉じる! userDAO.close(); // Beanのリスト(検索結果)をセット request.setAttribute("userBean", userBean); return "/view/user/edit.jsp"; } } <file_sep>/WEB-INF/src/action/stock/StockSignupConsumptionAction.java package action.stock; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import tool.Action; import dao.StockDAO; import bean.ItemBean; import bean.StockBean; import dao.ItemDAO; public class StockSignupConsumptionAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); String employee_id = (String) session.getAttribute("id"); String item_name = request.getParameter("item_name"); String genre = request.getParameter("genre"); String keyword = request.getParameter("keyword"); //System.out.println(request.getParameter("qty")); int qty = Integer.parseInt(request.getParameter("qty")); StockDAO stockDAO = new StockDAO(); stockDAO.insert_cons(employee_id, item_name, qty); ArrayList<StockBean> stockBeans = stockDAO.search(keyword); stockDAO.close(); ItemDAO itemDAO = new ItemDAO(); ArrayList<ItemBean> itemBeans = itemDAO.search(keyword); itemDAO.close(); request.setAttribute("stockBeans", stockBeans); request.setAttribute("itemBeans", itemBeans); request.setAttribute("keyword", keyword); return "/view/stock/stock_search.jsp"; } } <file_sep>/WEB-INF/src/dao/TopDAO.java package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import bean.TopBean; import tool.DAO; public class TopDAO extends DAO { public TopDAO() throws Exception { super(); } public ArrayList<TopBean> getCurrent(String floor) throws Exception { ArrayList<TopBean> topBeans = new ArrayList<TopBean>(); String sql = "select a.floor_id, b.situation_id, a.floor_state from floor a left join (select * from situation where situation_end is NULL) b on a.floor_id = b.floor_id where a.floor_id like ?"; PreparedStatement statement = this.connection.prepareStatement(sql); statement.setString(1, floor + "%"); ResultSet rSet = statement.executeQuery(); while (rSet.next()) { TopBean topBean = new TopBean(); topBean.setFloor_id(rSet.getString(1)); topBean.setSituation_id(rSet.getString(2)); topBean.setState(rSet.getString(3)); topBeans.add(topBean); } statement.close(); return topBeans; } } <file_sep>/WEB-INF/src/action/book/SignupAction.java package action.book; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.BookDAO; import sun.misc.Perf.GetPerfAction; import tool.Action; public class SignupAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String floor_id = request.getParameter("floor_id"); String user_id = request.getParameter("user_id"); int qty = Integer.parseInt(request.getParameter("qty")); String start = request.getParameter("start"); String end = request.getParameter("end"); String free = request.getParameter("free"); BookDAO bookDAO = new BookDAO(); bookDAO.insertToday(user_id, floor_id, qty, start, end, free); bookDAO.close(); return "/view/situation/book_signup_complete.jsp"; } } <file_sep>/WEB-INF/src/action/situation/DetailAction.java package action.situation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.FloorBean; import bean.SituationBean; import dao.FloorDAO; import dao.SituationDAO; import tool.Action; public class DetailAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getParameter("floor") != null) { TopAction topAction = new TopAction(); String url = topAction.execute(request, response); return url; } String floor_id = request.getParameter("id"); FloorDAO floorDAO = new FloorDAO(); FloorBean floorBean = floorDAO.detail(floor_id); floorDAO.close(); SituationDAO situationDAO = new SituationDAO(); SituationBean situationBean = situationDAO.getCurrentDetail(floor_id); situationDAO.close(); if (situationBean.getId() != 0) { request.setAttribute("situationBean", situationBean); return "/view/situation/detail.jsp"; } request.setAttribute("floorBean", floorBean); return "/view/situation/floor_detail.jsp"; } } <file_sep>/sql/stock_and_ordering.sql set names utf8; use masaru_db; -- stock -- E01 INSERT INTO stock VALUES (0,'E01',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 1 , (select item_max from item where item_id = 1)-5); INSERT INTO stock VALUES (0,'E01',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 2 , (select item_max from item where item_id = 2)/2); INSERT INTO stock VALUES (0,'E01',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 3 , (select item_max from item where item_id = 3)/3); INSERT INTO stock VALUES (0,'E01',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 4 , (select item_min from item where item_id = 4)-1); -- E02 INSERT INTO stock VALUES (0,'E02',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 5 , (select item_max from item where item_id = 5)-5); INSERT INTO stock VALUES (0,'E02',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 6 , (select item_max from item where item_id = 6)/2); INSERT INTO stock VALUES (0,'E02',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 7 , (select item_max from item where item_id = 7)/3); INSERT INTO stock VALUES (0,'E02',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 8 , (select item_min from item where item_id = 8)-1); -- E03 INSERT INTO stock VALUES (0,'E03',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 9 , (select item_max from item where item_id = 9)-5); INSERT INTO stock VALUES (0,'E03',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 10 , (select item_max from item where item_id = 10)/2); INSERT INTO stock VALUES (0,'E03',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 11 , (select item_max from item where item_id = 11)/3); INSERT INTO stock VALUES (0,'E03',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 12 , (select item_min from item where item_id = 12)-1); -- E04 INSERT INTO stock VALUES (0,'E04',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 13 , (select item_max from item where item_id = 13)-5); INSERT INTO stock VALUES (0,'E04',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 14 , (select item_max from item where item_id = 14)/2); INSERT INTO stock VALUES (0,'E04',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 15 , (select item_max from item where item_id = 15)/3); INSERT INTO stock VALUES (0,'E04',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 16 , (select item_min from item where item_id = 16)-1); -- E05 INSERT INTO stock VALUES (0,'E05',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 17 , (select item_max from item where item_id = 17)-5); INSERT INTO stock VALUES (0,'E05',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 18 , (select item_max from item where item_id = 18)/2); INSERT INTO stock VALUES (0,'E05',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 19 , (select item_max from item where item_id = 19)/3); INSERT INTO stock VALUES (0,'E05',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 20 , (select item_min from item where item_id = 20)-1); -- E06 INSERT INTO stock VALUES (0,'E06',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 21 , (select item_max from item where item_id = 21)-5); INSERT INTO stock VALUES (0,'E06',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 22 , (select item_max from item where item_id = 22)/2); INSERT INTO stock VALUES (0,'E06',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() ,23 , (select item_max from item where item_id = 23)/3); INSERT INTO stock VALUES (0,'E06',curdate()); INSERT INTO stock_detail VALUES (0 , LAST_INSERT_ID() , 24 , (select item_min from item where item_id = 24)-1); -- ordering -- E01 INSERT INTO ordering VALUES (0,'E01',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 1 , (select item_max from item where item_id = 1)-(select stock_detail_qty from stock_detail where stock_detail_id = 1) , '0'); INSERT INTO ordering VALUES (0,'E01',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 2 , (select item_max from item where item_id = 2)-(select stock_detail_qty from stock_detail where stock_detail_id = 2) , '0'); INSERT INTO ordering VALUES (0,'E01',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 3 , (select item_max from item where item_id = 3)-(select stock_detail_qty from stock_detail where stock_detail_id = 3) , '1'); INSERT INTO ordering VALUES (0,'E01',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 4 , (select item_max from item where item_id = 4)-(select stock_detail_qty from stock_detail where stock_detail_id = 4) , '0'); -- E02 INSERT INTO ordering VALUES (0,'E02',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 5 , (select item_max from item where item_id = 5)-(select stock_detail_qty from stock_detail where stock_detail_id = 5) , '0'); INSERT INTO ordering VALUES (0,'E02',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 6 , (select item_max from item where item_id = 6)-(select stock_detail_qty from stock_detail where stock_detail_id = 6) , '1'); INSERT INTO ordering VALUES (0,'E02',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 7 , (select item_max from item where item_id = 7)-(select stock_detail_qty from stock_detail where stock_detail_id = 7) , '0'); INSERT INTO ordering VALUES (0,'E02',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 8 , (select item_max from item where item_id = 8)-(select stock_detail_qty from stock_detail where stock_detail_id = 8) , '0'); -- E03 INSERT INTO ordering VALUES (0,'E03',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 9 , (select item_max from item where item_id = 9)-(select stock_detail_qty from stock_detail where stock_detail_id = 9) , '1'); INSERT INTO ordering VALUES (0,'E03',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 10 , (select item_max from item where item_id = 10)-(select stock_detail_qty from stock_detail where stock_detail_id = 10) , '0'); INSERT INTO ordering VALUES (0,'E03',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 11 , (select item_max from item where item_id = 11)-(select stock_detail_qty from stock_detail where stock_detail_id = 11) , '0'); INSERT INTO ordering VALUES (0,'E03',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 12 , (select item_max from item where item_id = 12)-(select stock_detail_qty from stock_detail where stock_detail_id = 12) , '1'); -- E04 INSERT INTO ordering VALUES (0,'E04',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 13 , (select item_max from item where item_id = 13)-(select stock_detail_qty from stock_detail where stock_detail_id = 13) , '0'); INSERT INTO ordering VALUES (0,'E04',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 14 , (select item_max from item where item_id = 14)-(select stock_detail_qty from stock_detail where stock_detail_id = 14) , '0'); INSERT INTO ordering VALUES (0,'E04',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 15 , (select item_max from item where item_id = 15)-(select stock_detail_qty from stock_detail where stock_detail_id = 15) , '1'); INSERT INTO ordering VALUES (0,'E04',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 16 , (select item_max from item where item_id = 16)-(select stock_detail_qty from stock_detail where stock_detail_id = 16) , '0'); -- E05 INSERT INTO ordering VALUES (0,'E05',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 17 , (select item_max from item where item_id = 17)-(select stock_detail_qty from stock_detail where stock_detail_id = 17) , '0'); INSERT INTO ordering VALUES (0,'E05',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 18 , (select item_max from item where item_id = 18)-(select stock_detail_qty from stock_detail where stock_detail_id = 18) , '1'); INSERT INTO ordering VALUES (0,'E05',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 19 , (select item_max from item where item_id = 19)-(select stock_detail_qty from stock_detail where stock_detail_id = 19) , '0'); INSERT INTO ordering VALUES (0,'E05',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 20 , (select item_max from item where item_id = 20)-(select stock_detail_qty from stock_detail where stock_detail_id = 20) , '0'); -- E06 INSERT INTO ordering VALUES (0,'E06',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 21 , (select item_max from item where item_id = 21)-(select stock_detail_qty from stock_detail where stock_detail_id = 21) , '1'); INSERT INTO ordering VALUES (0,'E06',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 22 , (select item_max from item where item_id = 22)-(select stock_detail_qty from stock_detail where stock_detail_id = 22) , '0'); INSERT INTO ordering VALUES (0,'E06',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 23 , (select item_max from item where item_id = 23)-(select stock_detail_qty from stock_detail where stock_detail_id = 23) , '0'); INSERT INTO ordering VALUES (0,'E06',curdate()); INSERT INTO ordering_detail VALUES (0 , LAST_INSERT_ID() , 24 , (select item_max from item where item_id = 24)-(select stock_detail_qty from stock_detail where stock_detail_id = 24) , '1'); set names cp932; <file_sep>/WEB-INF/src/dao/BookDAO.java package dao; import java.sql.PreparedStatement; import tool.DAO; public class BookDAO extends DAO { // コンストラクタ public BookDAO() throws Exception { // 親コンストラクタを呼び出し super(); } public void insertToday(String user_id, String floor_id, int qty, String start, String end, String free) throws Exception { // SQL文 String sql = "insert into book values ( 0, ?, ?, ?, curdate(), ?, ?, ?, now())"; // STATEMENTの作成 PreparedStatement statement = this.connection.prepareStatement(sql); // パラメータの挿入 statement.setString(1, user_id); statement.setString(2, floor_id); statement.setInt(3, qty); statement.setString(4, start); statement.setString(5, end); statement.setString(6, free); // SQL文を実行 statement.executeUpdate(); statement.close(); } } <file_sep>/WEB-INF/src/action/stock/StockSignupAction.java package action.stock; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import tool.Action; import dao.StockDAO; import bean.ItemBean; import dao.ItemDAO; public class StockSignupAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); String employee_id = (String) session.getAttribute("id"); String item_id = request.getParameter("item_id"); String genre = request.getParameter("genre"); StockDAO stockDAO = new StockDAO(); stockDAO.insert(employee_id, item_id); stockDAO.close(); ItemDAO itemDAO = new ItemDAO(); ArrayList<ItemBean> itemBeans = itemDAO.searchGenre(genre); itemDAO.close(); request.setAttribute("itemBeans", itemBeans); request.setAttribute("genre", genre); return "/view/stock/genre_search.jsp"; } } <file_sep>/sql/floor.sql set names utf8; use masaru_db; -- 利用 INSERT INTO situation values (43, 'yamaguti', '101', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (44, 'tanaka', '102', '1', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (45, 'ito', '105', '3', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (46, 'nakazima', '110', '10', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (47, 'isii', '203', '1', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (48, 'ogawa', '205', '4', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (49, 'okada', '206', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (50, 'hasegawa', '301', '3', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (51, 'huzita', '304', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (52, 'gotou', '308', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (53, 'konndou', '401', '1', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (54, 'murakami', '406', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (55, 'enndou', '407', '1', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (56, 'aoki', '408', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (57, 'sakamoto', '502', '3', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (58, 'saito', '503', '1', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (59, 'sakamoto', '508', '2', curdate(), '11:00:00' , '14:00:00' , null , '有'); INSERT INTO situation values (60, 'oota', '509', '8', curdate(), '11:00:00' , '14:00:00' , null , '有'); set names cp932; <file_sep>/sql/sample_insert2.sql set names utf8; use masaru_db; -- 22日 INSERT INTO shift VALUES ('0', 'E01', '2021-02-22', '09:00:00', '21:00:00'); INSERT INTO shift VALUES ('0', 'E03', '2021-02-22', '14:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A01', '2021-02-22', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A02', '2021-02-22', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A03', '2021-02-22', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A04', '2021-02-22', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A05', '2021-02-22', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A06', '2021-02-22', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A07', '2021-02-22', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A08', '2021-02-22', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A09', '2021-02-22', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A10', '2021-02-22', '13:00:00', '23:00:00'); -- 23日 INSERT INTO shift VALUES ('0', 'E02', '2021-02-23', '09:00:00', '21:00:00'); INSERT INTO shift VALUES ('0', 'E04', '2021-02-23', '14:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A11', '2021-02-23', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A12', '2021-02-23', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A13', '2021-02-23', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A14', '2021-02-23', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A15', '2021-02-23', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A16', '2021-02-23', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A17', '2021-02-23', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A18', '2021-02-23', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A19', '2021-02-23', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A20', '2021-02-23', '13:00:00', '23:00:00'); -- 24日 INSERT INTO shift VALUES ('0', 'E01', '2021-02-24', '09:00:00', '21:00:00'); INSERT INTO shift VALUES ('0', 'E05', '2021-02-24', '14:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A01', '2021-02-24', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A03', '2021-02-24', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A05', '2021-02-24', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A07', '2021-02-24', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A09', '2021-02-24', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A11', '2021-02-24', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A13', '2021-02-24', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A15', '2021-02-24', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A17', '2021-02-24', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A19', '2021-02-24', '13:00:00', '23:00:00'); -- 25日 INSERT INTO shift VALUES ('0', 'E02', '2021-02-25', '09:00:00', '21:00:00'); INSERT INTO shift VALUES ('0', 'E06', '2021-02-25', '14:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A02', '2021-02-25', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A04', '2021-02-25', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A06', '2021-02-25', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A08', '2021-02-25', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A10', '2021-02-25', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A12', '2021-02-25', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A14', '2021-02-25', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A16', '2021-02-25', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A18', '2021-02-25', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A20', '2021-02-25', '13:00:00', '23:00:00'); -- 26日 INSERT INTO shift VALUES ('0', 'E01', '2021-02-26', '09:00:00', '21:00:00'); INSERT INTO shift VALUES ('0', 'E02', '2021-02-26', '14:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A01', '2021-02-26', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A04', '2021-02-26', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A06', '2021-02-26', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A09', '2021-02-26', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A10', '2021-02-26', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A11', '2021-02-26', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A15', '2021-02-26', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A17', '2021-02-26', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A19', '2021-02-26', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A20', '2021-02-26', '13:00:00', '23:00:00'); -- 3/1 INSERT INTO shift VALUES ('0', 'E01', '2021-03-01', '09:00:00', '21:00:00'); INSERT INTO shift VALUES ('0', 'E03', '2021-03-01', '14:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A01', '2021-03-01', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A02', '2021-03-01', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A03', '2021-03-01', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A04', '2021-03-01', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A05', '2021-03-01', '10:00:00', '22:00:00'); INSERT INTO shift VALUES ('0', 'A06', '2021-03-01', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A07', '2021-03-01', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A08', '2021-03-01', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A09', '2021-03-01', '13:00:00', '23:00:00'); INSERT INTO shift VALUES ('0', 'A10', '2021-03-01', '13:00:00', '23:00:00'); set names cp932; <file_sep>/WEB-INF/src/action/employee/ShiftFormAction.java package action.employee; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import tool.Action; import dao.ShiftDAO; import bean.ShiftBean; public class ShiftFormAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); String employee_id = (String) session.getAttribute("id"); ShiftDAO shiftDAO = new ShiftDAO(); ArrayList<ShiftBean> shiftBeans = shiftDAO.search(employee_id); shiftDAO.close(); request.setAttribute("shiftBeans", shiftBeans); return "/view/employee/shift_signup.jsp"; } } <file_sep>/WEB-INF/src/action/user/SearchAction.java package action.user; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.UserBean; import dao.UserDAO; import tool.Action; public class SearchAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // パラメータの取得 String keyword = request.getParameter("keyword"); // DAOの生成 UserDAO userDAO = new UserDAO(); // DAOメソッドの実行 ArrayList<UserBean> userBeans = userDAO.search(keyword); // ちゃんと閉じる! userDAO.close(); // Beanのリスト(検索結果)をセット request.setAttribute("userBeans", userBeans); return "/view/user/search.jsp"; } } <file_sep>/sql/masaru_db.sql set names utf8; DROP DATABASE IF EXISTS masaru_db; create database masaru_db default character set = utf8; use masaru_db; CREATE TABLE user ( user_id VARCHAR(16) NOT NULL, user_pass VARCHAR(16) NOT NULL, user_name VARCHAR(24) NOT NULL, user_sex CHAR(1) NOT NULL, user_birth DATE NOT NULL, user_mail VARCHAR(32) DEFAULT '未入力', user_tel CHAR(13) NOT NULL, user_job VARCHAR(16) DEFAULT '未入力', user_credit CHAR(1) DEFAULT '5', user_rank CHAR(1) DEFAULT '1', user_date DATE NOT NULL, PRIMARY KEY (user_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE floor ( floor_id CHAR(3) NOT NULL, floor_cap TINYINT UNSIGNED NOT NULL, floor_machine CHAR(1) NOT NULL, floor_state CHAR(1) NOT NULL, floor_device BOOLEAN DEFAULT false, PRIMARY KEY (floor_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE situation ( situation_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id VARCHAR(16) NOT NULL, floor_id CHAR(3) NOT NULL, situation_qty TINYINT UNSIGNED NOT NULL, situation_date DATE NOT NULL, situation_start TIME NOT NULL, situation_end_schedule TIME NOT NULL, situation_end TIME, situation_free CHAR(1) NOT NULL DEFAULT '無', PRIMARY KEY (situation_id), FOREIGN KEY (user_id) REFERENCES user (user_id), FOREIGN KEY (floor_id) REFERENCES floor (floor_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE book ( book_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id VARCHAR(16) NOT NULL, floor_id CHAR(3) NOT NULL, book_qty TINYINT UNSIGNED NOT NULL, book_date DATE NOT NULL, book_start TIME NOT NULL, book_end TIME NOT NULL, book_free CHAR(1) NOT NULL DEFAULT '無', book_date_register DATETIME NOT NULL, PRIMARY KEY (book_id), FOREIGN KEY (user_id) REFERENCES user (user_id), FOREIGN KEY (floor_id) REFERENCES floor (floor_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE menu ( menu_id INT UNSIGNED NOT NULL AUTO_INCREMENT, menu_name VARCHAR(30) NOT NULL, menu_genre VARCHAR(20) NOT NULL, menu_price SMALLINT UNSIGNED NOT NULL, menu_create DATE NOT NULL, menu_update DATE NOT NULL, menu_des VARCHAR(500) DEFAULT 'なし', menu_allergy VARCHAR(100) DEFAULT 'なし', PRIMARY KEY (menu_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE task ( task_id INT UNSIGNED NOT NULL AUTO_INCREMENT, menu_id INT UNSIGNED NOT NULL, situation_id INT UNSIGNED NOT NULL, floor_id CHAR(3) NOT NULL, task_qty TINYINT UNSIGNED NOT NULL, task_time TIME NOT NULL, task_comp TIME, task_deploy TIME, PRIMARY KEY (task_id), FOREIGN KEY (menu_id) REFERENCES menu (menu_id), FOREIGN KEY (situation_id) REFERENCES situation (situation_id), FOREIGN KEY (floor_id) REFERENCES floor (floor_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE sale ( sale_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id VARCHAR(16) NOT NULL, situation_id INT UNSIGNED NOT NULL, sale_total MEDIUMINT UNSIGNED NOT NULL, sale_date DATE NOT NULL, PRIMARY KEY (sale_id), FOREIGN KEY (user_id) REFERENCES user (user_id), FOREIGN KEY (situation_id) REFERENCES situation (situation_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE sale_detail ( sale_detail_id INT UNSIGNED NOT NULL AUTO_INCREMENT, situation_id INT UNSIGNED NOT NULL, menu_id INT UNSIGNED NOT NULL, menu_qty TINYINT UNSIGNED NOT NULL, menu_sex CHAR(1), menu_age CHAR(3), PRIMARY KEY (sale_detail_id), FOREIGN KEY (situation_id) REFERENCES situation (situation_id), FOREIGN KEY (menu_id) REFERENCES menu (menu_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE employee ( employee_id CHAR(3) NOT NULL, employee_pass VARCHAR(16) NOT NULL, employee_name VARCHAR(24) NOT NULL, employee_position VARCHAR(12) NOT NULL, employee_mail VARCHAR(32) NOT NULL, employee_tel CHAR(13) NOT NULL, PRIMARY KEY (employee_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE shift ( shift_id INT UNSIGNED NOT NULL AUTO_INCREMENT, employee_id CHAR(3) NOT NULL, shift_date DATE NOT NULL, shift_start TIME NOT NULL, shift_end TIME NOT NULL, PRIMARY KEY (shift_id), FOREIGN KEY (employee_id) REFERENCES employee (employee_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE shift_confirm ( shift_confirm_id INT UNSIGNED NOT NULL AUTO_INCREMENT, employee_id CHAR(3) NOT NULL, shift_confirm_date DATE NOT NULL, shift_confirm_start TIME NOT NULL, shift_confirm_end TIME NOT NULL, PRIMARY KEY (shift_confirm_id), FOREIGN KEY (employee_id) REFERENCES employee (employee_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE item ( item_id INT UNSIGNED NOT NULL AUTO_INCREMENT, item_name VARCHAR(30) NOT NULL, item_genre VARCHAR(20) NOT NULL, item_max SMALLINT UNSIGNED NOT NULL, item_min SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (item_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE stock ( stock_id INT UNSIGNED NOT NULL AUTO_INCREMENT, employee_id CHAR(3) NOT NULL, stock_date DATE NOT NULL, PRIMARY KEY (stock_id), FOREIGN KEY (employee_id) REFERENCES employee (employee_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE stock_detail ( stock_detail_id INT UNSIGNED NOT NULL AUTO_INCREMENT, stock_id INT UNSIGNED NOT NULL, item_id INT UNSIGNED NOT NULL, stock_detail_qty SMALLINT NOT NULL, PRIMARY KEY (stock_detail_id), FOREIGN KEY (stock_id) REFERENCES stock (stock_id), FOREIGN KEY (item_id) REFERENCES item (item_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE ordering ( ordering_id INT UNSIGNED NOT NULL AUTO_INCREMENT, employee_id CHAR(3) NOT NULL, ordering_date DATE NOT NULL, PRIMARY KEY (ordering_id), FOREIGN KEY (employee_id) REFERENCES employee (employee_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE ordering_detail ( ordering_detail_id INT UNSIGNED NOT NULL AUTO_INCREMENT, ordering_id INT UNSIGNED NOT NULL, item_id INT UNSIGNED NOT NULL, ordering_detail_qty SMALLINT UNSIGNED NOT NULL, ordering_detail_state CHAR(1) DEFAULT '0', PRIMARY KEY (ordering_detail_id), FOREIGN KEY (ordering_id) REFERENCES ordering (ordering_id), FOREIGN KEY (item_id) REFERENCES item (item_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE news ( news_id INT UNSIGNED NOT NULL AUTO_INCREMENT, news_title VARCHAR(50) NOT NULL, news_content VARCHAR(1000) NOT NULL, news_schedule DATETIME NOT NULL, PRIMARY KEY (news_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE coupon ( coupon_id INT UNSIGNED NOT NULL AUTO_INCREMENT, coupon_title VARCHAR(50) NOT NULL, coupon_content VARCHAR(500) NOT NULL, coupon_genre VARCHAR(20) NOT NULL, coupon_discount CHAR(4) NOT NULL, coupon_start DATETIME NOT NULL, coupon_end DATETIME NOT NULL, PRIMARY KEY (coupon_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- インサート文 -- 従業員 INSERT INTO employee VALUES ('ore', 'sama', '俺様', 'アルバイト', '<EMAIL>', '080-1111-0001'); INSERT INTO employee VALUES ('E01', 'hal', 'HALマサル', '店長', '<EMAIL>', '080-1111-0002'); INSERT INTO employee VALUES ('E02', 'renn', '田中蓮', '副店長', '<EMAIL>', '080-1111-0003'); INSERT INTO employee VALUES ('E03', 'kaede', '山口楓', '社員', '<EMAIL>', '080-1111-0004'); INSERT INTO employee VALUES ('E04', 'ritu', '佐藤律', '社員', '<EMAIL>', '080-1111-0005'); INSERT INTO employee VALUES ('E05', 'tumugi', '鈴木紬', '社員', '<EMAIL>', '080-1111-0006'); INSERT INTO employee VALUES ('E06', 'sou', '高橋湊', '社員', '<EMAIL>', '080-1111-0007'); INSERT INTO employee VALUES ('A01', 'riko', '伊藤莉子', 'アルバイト', '<EMAIL>', '080-1111-0008'); INSERT INTO employee VALUES ('A02', 'haruto', '渡辺陽翔', 'アルバイト', '<EMAIL>', '080-1111-0009'); INSERT INTO employee VALUES ('A03', 'yuduki', '後藤結月', 'アルバイト', '<EMAIL>', '080-1111-0010'); INSERT INTO employee VALUES ('A04', 'aoi', '中村蒼', 'アルバイト', '<EMAIL>', '080-1111-0011'); INSERT INTO employee VALUES ('A05', 'mei', '小林芽依', 'アルバイト', '<EMAIL>', '080-1111-0012'); INSERT INTO employee VALUES ('A06', 'yuuma', '加藤悠真', 'アルバイト', '<EMAIL>', '080-1111-0013'); INSERT INTO employee VALUES ('A07', 'hinata', '吉田陽葵', 'アルバイト', '<EMAIL>', '080-1111-0014'); INSERT INTO employee VALUES ('A08', 'hiroto', '藤田大翔', 'アルバイト', '<EMAIL>', '080-1111-0015'); INSERT INTO employee VALUES ('A09', 'rinn', '佐々木凛', 'アルバイト', '<EMAIL>', '080-1111-0016'); INSERT INTO employee VALUES ('A10', 'souta', '松本蒼大', 'アルバイト', '<EMAIL>', '080-1111-0017'); INSERT INTO employee VALUES ('A11', 'aoi', '井上葵', 'アルバイト', '<EMAIL>', '080-1111-0018'); INSERT INTO employee VALUES ('A12', 'syuu', '木村柊', 'アルバイト', '<EMAIL>', '080-1111-0019'); INSERT INTO employee VALUES ('A13', 'yuina', '清水結菜', 'アルバイト', '<EMAIL>', '080-1111-0020'); INSERT INTO employee VALUES ('A14', 'ituki', '近藤樹', 'アルバイト', '<EMAIL>', '080-1111-0021'); INSERT INTO employee VALUES ('A15', 'iroha', '森彩葉', 'アルバイト', '<EMAIL>', '080-1111-0022'); INSERT INTO employee VALUES ('A16', 'dann', '池田暖', 'アルバイト', '<EMAIL>', '080-1111-0023'); INSERT INTO employee VALUES ('A17', 'mituki', '橋本美月', 'アルバイト', '<EMAIL>', '080-1111-0024'); INSERT INTO employee VALUES ('A18', 'yuuto', '阿部悠斗', 'アルバイト', '<EMAIL>', '080-1111-0025'); INSERT INTO employee VALUES ('A19', 'yua', '石川結愛', 'アルバイト', '<EMAIL>', '080-1111-0026'); INSERT INTO employee VALUES ('A20', 'takasi', '松田隆', 'アルバイト', '<EMAIL>', '080-1111-0027'); -- 会員 INSERT INTO user VALUES ('hirata', 'hirata', '<NAME>', '男', '1999-12-31', '<EMAIL>', '000-0000-0000', '学生', '1', '5', '2015-04-01'); -- フロア INSERT INTO floor VALUES ('101', 6, '良', '済', false); INSERT INTO floor VALUES ('102', 6, '良', '済', false); INSERT INTO floor VALUES ('103', 6, '良', '済', false); INSERT INTO floor VALUES ('104', 6, '可', '済', false); INSERT INTO floor VALUES ('105', 6, '可', '済', false); INSERT INTO floor VALUES ('106', 6, '良', '済', false); INSERT INTO floor VALUES ('107', 6, '良', '済', false); INSERT INTO floor VALUES ('108', 6, '良', '済', false); INSERT INTO floor VALUES ('109', 12, '良', '済', false); INSERT INTO floor VALUES ('110', 12, '良', '済', false); INSERT INTO floor VALUES ('201', 6, '良', '済', false); INSERT INTO floor VALUES ('202', 6, '不', '済', false); INSERT INTO floor VALUES ('203', 6, '良', '済', false); INSERT INTO floor VALUES ('204', 6, '良', '済', false); INSERT INTO floor VALUES ('205', 6, '可', '済', false); INSERT INTO floor VALUES ('206', 6, '良', '済', false); INSERT INTO floor VALUES ('207', 6, '良', '済', false); INSERT INTO floor VALUES ('208', 6, '良', '済', false); INSERT INTO floor VALUES ('209', 12, '可', '済', false); INSERT INTO floor VALUES ('210', 12, '良', '済', false); INSERT INTO floor VALUES ('301', 6, '良', '済', false); INSERT INTO floor VALUES ('302', 6, '可', '済', false); INSERT INTO floor VALUES ('303', 6, '良', '済', false); INSERT INTO floor VALUES ('304', 6, '良', '済', false); INSERT INTO floor VALUES ('305', 6, '良', '済', false); INSERT INTO floor VALUES ('306', 6, '良', '済', false); INSERT INTO floor VALUES ('307', 6, '良', '済', false); INSERT INTO floor VALUES ('308', 6, '可', '済', false); INSERT INTO floor VALUES ('309', 12, '良', '済', false); INSERT INTO floor VALUES ('310', 12, '不', '済', false); INSERT INTO floor VALUES ('401', 6, '良', '済', false); INSERT INTO floor VALUES ('402', 6, '良', '済', false); INSERT INTO floor VALUES ('403', 6, '可', '済', false); INSERT INTO floor VALUES ('404', 6, '良', '済', false); INSERT INTO floor VALUES ('405', 6, '良', '済', false); INSERT INTO floor VALUES ('406', 6, '良', '済', false); INSERT INTO floor VALUES ('407', 6, '可', '済', false); INSERT INTO floor VALUES ('408', 6, '良', '済', false); INSERT INTO floor VALUES ('409', 12, '良', '済', false); INSERT INTO floor VALUES ('410', 12, '良', '済', false); INSERT INTO floor VALUES ('501', 6, '良', '済', false); INSERT INTO floor VALUES ('502', 6, '良', '済', false); INSERT INTO floor VALUES ('503', 6, '可', '済', false); INSERT INTO floor VALUES ('504', 6, '良', '済', false); INSERT INTO floor VALUES ('505', 6, '良', '済', false); INSERT INTO floor VALUES ('506', 6, '良', '済', false); INSERT INTO floor VALUES ('507', 6, '可', '済', false); INSERT INTO floor VALUES ('508', 6, '良', '済', false); INSERT INTO floor VALUES ('509', 12, '良', '済', false); INSERT INTO floor VALUES ('510', 12, '良', '済', false); -- 在庫管理 INSERT INTO item VALUES (1, '米', '米・雑穀・シリアル', 20, 5); INSERT INTO item VALUES (2, 'コンフレーク', '米・雑穀・シリアル', 25, 5); INSERT INTO item VALUES (3, '中華麺', '麺類', 23, 7); INSERT INTO item VALUES (4, 'パスタ', '麺類', 24, 8); INSERT INTO item VALUES (5, 'キャベツ', '野菜', 25, 5); INSERT INTO item VALUES (6, 'ピーマン', '野菜', 20, 10); INSERT INTO item VALUES (7, '玉ねぎ', '野菜', 27, 9); INSERT INTO item VALUES (8, 'ニンジン', '野菜', 26, 4); INSERT INTO item VALUES (9, 'トマト', '野菜', 28, 10); INSERT INTO item VALUES (10, 'エビ', '水産物・水産加工品', 26, 5); INSERT INTO item VALUES (11, 'タコ', '水産物・水産加工品', 24, 8); INSERT INTO item VALUES (12, '卵', '卵・チーズ・乳製品', 30, 7); INSERT INTO item VALUES (13, 'チーズ', '卵・チーズ・乳製品', 25, 5); INSERT INTO item VALUES (14, 'リンゴ', '果物', 22, 7); INSERT INTO item VALUES (15, 'バナナ', '果物', 24, 6); INSERT INTO item VALUES (16, '塩', '調味料', 20, 8); INSERT INTO item VALUES (17, '砂糖', '調味料', 20, 6); INSERT INTO item VALUES (18, 'カルーア', 'リキュール', 25, 10); INSERT INTO item VALUES (19, 'ヒプノティック', 'リキュール', 20, 8); INSERT INTO item VALUES (20, 'メロンソーダ', 'ソフトドリンク', 28, 9); INSERT INTO item VALUES (21, 'ウーロン茶', 'ソフトドリンク', 26, 7); INSERT INTO item VALUES (22, 'オレンジジュース', 'ソフトドリンク', 29, 6); INSERT INTO item VALUES (23, 'リンゴジュース', 'ソフトドリンク', 30, 5); INSERT INTO item VALUES (24, 'カルピス', 'ソフトドリンク', 25, 5); -- メニュー INSERT INTO menu VALUES (1, 'オムライス', 'フード', 700, curdate(), curdate(), 'フワフワトロトロ', '卵,乳'); INSERT INTO menu VALUES (2, 'ハンバーグ', 'フード', 900, curdate(), curdate(), '外はカリカリ中はジューシー', '卵'); INSERT INTO menu VALUES (3, 'カレーライス', 'フード', 500, curdate(), curdate(), '子供も食べやすい辛さ', ''); INSERT INTO menu VALUES (4, 'カルボナーラ', 'フード', 600, curdate(), curdate(), 'ソースがとても美味しい', '乳,小麦'); INSERT INTO menu VALUES (5, '焼きそば', 'フード', 500, curdate(), curdate(), 'ソースが甘くておいしい', '小麦'); INSERT INTO menu VALUES (6, 'ざるそば', 'フード', 450, curdate(), curdate(), '麵が特注', 'そば'); INSERT INTO menu VALUES (7, 'ラーメン', 'フード', 550, curdate(), curdate(), '醬油ベース', '卵,小麦'); INSERT INTO menu VALUES (8, 'マルゲリータピザ', 'フード', 900, curdate(), curdate(), 'たっぷりチーズでとても美味しい', '乳,小麦'); INSERT INTO menu VALUES (9, 'メロンソーダ', 'ドリンク', 400, curdate(), curdate(), 'アイスが乗っている', '卵,乳'); INSERT INTO menu VALUES (10, 'ウーロン茶', 'ドリンク', 120, curdate(), curdate(), '子供でも飲みやすい', ''); INSERT INTO menu VALUES (11, 'オレンジジュース', 'ドリンク', 150, curdate(), curdate(), '大人にも子供にも人気', ''); INSERT INTO menu VALUES (12, 'リンゴジュース', 'ドリンク', 150, curdate(), curdate(), '甘味がとても強い', ''); INSERT INTO menu VALUES (13, 'カルピス', 'ドリンク', 170, curdate(), curdate(), '大人気', ''); INSERT INTO menu VALUES (14, '唐揚げ', 'サイドメニュー', 400, curdate(), curdate(), 'とてもジューシー', '卵,小麦'); INSERT INTO menu VALUES (15, 'フライドポテト', 'サイドメニュー', 300, curdate(), curdate(), '揚げたてでサクサク', '小麦'); INSERT INTO menu VALUES (16, 'エビフライ', 'サイドメニュー', 300, curdate(), curdate(), '揚げたてでサクサクプリプリ', 'えび'); INSERT INTO menu VALUES (17, 'チキンナゲット', 'サイドメニュー', 300, curdate(), curdate(), 'サクサクで食べやすい', '卵,小麦'); INSERT INTO menu VALUES (18, 'イカリング', 'サイドメニュー', 400, curdate(), curdate(), 'イカが新鮮', '卵,小麦'); INSERT INTO menu VALUES (19, 'チョコレートパフェ', 'デザート', 600, curdate(), curdate(), 'ホイップたっぷり', '卵,乳,小麦'); INSERT INTO menu VALUES (20, 'コーヒーゼリー', 'デザート', 450, curdate(), curdate(), 'クリームは甘く、ゼリーはほろ苦くておいしい', '乳'); INSERT INTO menu VALUES (21, 'スイートポテト', 'デザート', 350, curdate(), curdate(), '芋の甘さ引き立つ', '卵,乳'); INSERT INTO menu VALUES (22, 'プリン', 'デザート', 400, curdate(), curdate(), 'ホイップたっぷりでサクランボが乗っている', '卵,乳'); INSERT INTO menu VALUES (23, 'ポテトチップス', 'デザート', 200, curdate(), curdate(), 'サクサクで大人気', '卵,小麦'); INSERT INTO menu VALUES (24, 'ホットケーキ', 'デザート', 600, curdate(), curdate(), 'ホイップたっぷりでフワフワ', '卵,乳,小麦'); INSERT INTO menu VALUES (25, '海鮮丼', 'オススメ', 1500, curdate(), curdate(), 'とても豪華で数量限定', 'えび,かに'); INSERT INTO menu VALUES (26, '豚汁', 'オススメ', 500, curdate(), curdate(), '特性豚汁でおいしい', ''); INSERT INTO menu VALUES (27, 'ステーキ', 'オススメ', 2000, curdate(), curdate(), 'お肉がとても柔らかい', ''); INSERT INTO menu VALUES (28, '豪華パフェ', 'オススメ', 1500, curdate(), curdate(), 'たくさんお果物が乗っている', '卵,乳,小麦'); INSERT INTO menu VALUES (29, '特製シチュー', 'オススメ', 800, curdate(), curdate(), '子供から大人まで大人気', '卵,乳'); -- ビュー create view stock_control as select i.item_id,i.item_name,i.item_genre,i.item_max,i.item_min,sum(sd.stock_detail_qty) as stock_qty, sum(od.ordering_detail_qty) as ordering_qty,od.ordering_detail_state, o.ordering_date from item as i left join stock_detail as sd on sd.item_id = i.item_id left join ordering_detail as od on od.item_id = i.item_id and ordering_detail_state = '1' left join ordering as o on o.ordering_id = od.ordering_id and o.ordering_date = (select min(o.ordering_date) from ordering) group by i.item_id; create view stock_operation as select s.stock_id,i.item_name,i.item_genre,i.item_max,i.item_min,sd.stock_detail_qty,e.employee_name,s.stock_date from item as i inner join stock_detail as sd on i.item_id = sd.item_id inner join stock as s on s.stock_id = sd.stock_id inner join employee as e on e.employee_id = s.employee_id order by s.stock_id desc; create view ordering_operation as select o.ordering_id,i.item_name,i.item_genre,i.item_max,i.item_min,od.ordering_detail_qty,od.ordering_detail_state,e.employee_name,o.ordering_date from item as i inner join ordering_detail as od on i.item_id = od.item_id inner join ordering as o on o.ordering_id = od.ordering_id inner join employee as e on e.employee_id = o.employee_id order by o.ordering_id desc; set names cp932;<file_sep>/WEB-INF/src/action/floor/SignupAction.java package action.floor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; import dao.FloorDAO; public class SignupAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // パラメータの取得 String floor = request.getParameter("floor"); String floor_number = request.getParameter("floor_number"); int cap = Integer.parseInt(request.getParameter("cap")); String machine = request.getParameter("machine"); String state = request.getParameter("state"); String id = floor + floor_number; FloorDAO floorDAO = new FloorDAO(); boolean flag = floorDAO.insert(id, cap, machine, state); // ちゃんと閉じる! floorDAO.close(); if (flag) { return "/view/floor/signup_complete.jsp"; } else { return "/view/floor/signup_error.jsp"; } } } <file_sep>/WEB-INF/src/action/order/FormMenyuDetailAction.java package action.order; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.OrderBean; import dao.OrderDAO; import tool.Action; public class FormMenyuDetailAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // パラメータの取得 String id = request.getParameter("id"); // DAOの生成 OrderDAO orderDAO = new OrderDAO(); // DAOメソッドの実行 OrderBean orderBean = orderDAO.detail(id); // ちゃんと閉じる! orderDAO.close(); // Beanのリスト(検索結果)をセット request.setAttribute("orderBean", orderBean); return "/view/order/menyu_detail.jsp"; } } <file_sep>/WEB-INF/src/action/order/MenyuUpdateAction.java package action.order; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.OrderBean; import bean.UserBean; import dao.OrderDAO; import dao.UserDAO; import tool.Action; public class MenyuUpdateAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // パラメータの取得 String id = request.getParameter("id"); String name = request.getParameter("name"); String genre = request.getParameter("genre"); String price = request.getParameter("price"); String des = request.getParameter("des"); String allergy = request.getParameter("allergy"); // DAOの生成 OrderDAO orderDAO = new OrderDAO(); // DAOメソッドの実行 orderDAO.update(id,name,genre,price,des,allergy); // ちゃんと閉じる! orderDAO.close(); return "/view/order/menyu_update_complete.jsp"; } } <file_sep>/WEB-INF/src/action/floor/FormDelete_CompleteAction.java package action.floor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import tool.Action; public class FormDelete_CompleteAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { return "/view/floor/delete_complete.jsp"; } } <file_sep>/WEB-INF/src/action/situation/LiquidationAction.java package action.situation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.SituationDAO; import tool.Action; public class LiquidationAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String user_id = request.getParameter("user_id"); String id = request.getParameter("id"); int sale_total = Integer.parseInt(request.getParameter("sale_total")); String floor_id = request.getParameter("floor_id"); SituationDAO situationDAO = new SituationDAO(); situationDAO.finish(user_id, id, sale_total, floor_id); situationDAO.close(); return "/view/situation/liquidation_complete.jsp"; } } <file_sep>/WEB-INF/src/action/analyse/MenuAction.java package action.analyse; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.OrderBean; import dao.AnalyseDAO; import tool.Action; public class MenuAction extends Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { // パラメータの取得 String xaxis = request.getParameter("xaxis"); if(xaxis == null){//最初の読み込み xaxis = "month"; } String yaxis = request.getParameter("yaxis"); if(yaxis == null){//最初の読み込み yaxis = "sales"; } String date = request.getParameter("date"); if(date == null){ date = ""; } String age = ""; age = request.getParameter("age"); String age_check_str = request.getParameter("age_check"); boolean age_check = false; if(age == null){//最初の読み込み age_check = true; } if(age != null){//最初の読み込みでない場合 if(age_check_str != null){//booleanに変換 age_check = true; age = ""; } if(age.equals("")){//入力欄に空欄があり、チェックがされていない場合 age_check = true; age = ""; } } if(age == null){//最初の読み込み age = ""; } String sex = request.getParameter("sex"); if(sex == null){//最初の読み込み sex = "both"; } String time_lead = ""; time_lead = request.getParameter("time_lead"); String time_last = ""; time_last = request.getParameter("time_last"); int time_lead_int = 0; int time_last_int = 0; String timezone_check_str = request.getParameter("timezone_check"); boolean timezone_check = true; if(timezone_check_str == null){//最初の読み込み timezone_check = true; } if(time_lead != null){//最初の読み込みでない場合 if(timezone_check_str != null){ timezone_check = true; time_lead = ""; time_last = ""; } else{ timezone_check = false; } if(time_lead.equals("") || time_last.equals("")){//入力欄に空欄があり、チェックがされていない場合 timezone_check = true; time_lead = ""; time_last = ""; } if(!time_lead.equals("") && !time_last.equals("")){//入力欄両方に入力されている場合 String[] time_lead_split = time_lead.split(":", 0); String time_lead_work = ""; for(int i = 0 ; i < time_lead_split.length ; i++){ time_lead_work += time_lead_split[i]; } System.out.println(time_lead_work); String[] time_last_split = time_last.split(":", 0); String time_last_work = ""; for(int i = 0 ; i < time_last_split.length ; i++){ time_last_work += time_last_split[i]; } time_lead_int = Integer.parseInt(time_lead_work); time_last_int = Integer.parseInt(time_last_work); if(time_lead_int > time_last_int){//入力に矛盾がある場合 timezone_check = true; time_lead = ""; time_last = ""; } } } if(time_lead == null){//最初の読み込み time_lead = ""; } if(time_last == null){//最初の読み込み time_last = ""; } String dotw = request.getParameter("dotw"); String dotw_check_str = request.getParameter("dotw_check"); boolean dotw_check = true; if(dotw == null){//最初の読み込み dotw_check = true; } if(dotw != null){//最初の読み込みでない場合 if(dotw_check_str != null){ dotw_check = true; } else{ dotw_check = false; } if(dotw.equals("") || xaxis.equals("day")){//入力欄が空欄だった場合と、x軸がdayの場合 dotw_check = true; } } if(dotw == null){ dotw = ""; } String[] checked_menu = request.getParameterValues("menu_check"); System.out.println(""); System.out.println("------ここからservelet------"); System.out.println(""); System.out.println("xaxis : " + xaxis); System.out.println("yaxis : " + yaxis); System.out.println("date : " + date); System.out.println("age : " + age); System.out.println("age_check : " + age_check); System.out.println("sex : " + sex); System.out.println("time_lead : " + time_lead); System.out.println("time_last : " + time_last); System.out.println("timezone_check : " + timezone_check); System.out.println("dotw : " + dotw); System.out.println("dotw_check : " + dotw_check); if(checked_menu != null){ for(int i = 0 ; i < checked_menu.length ; i++){ System.out.println("checked_menu : " + checked_menu[i]); } } else{ System.out.println("checked_menu : null"); } request.setAttribute("xaxis", xaxis); request.setAttribute("yaxis", yaxis); request.setAttribute("date", date); request.setAttribute("age", age); request.setAttribute("age_check", age_check); request.setAttribute("sex", sex); request.setAttribute("time_lead", time_lead); request.setAttribute("time_last", time_last); request.setAttribute("timezone_check", timezone_check); request.setAttribute("dotw", dotw); request.setAttribute("dotw_check", dotw_check); // DAOの生成 AnalyseDAO analyseDAO = new AnalyseDAO(); // DAOメソッドの実行 ArrayList<String> datas = analyseDAO.analyse_menu(xaxis , yaxis , date , age , age_check , sex , time_lead , time_last , timezone_check , dotw , dotw_check , checked_menu, date ); for(int i = 0 ; i < datas.size() ; i++){ System.out.print(i + " : "); System.out.println(datas.get(i)); } request.setAttribute("datas", datas); request.setAttribute("checked_menu", checked_menu); // DAOメソッドの実行 ArrayList<String> menulist_reco = analyseDAO.menu_searchall("オススメ"); ArrayList<String> menulist_food = analyseDAO.menu_searchall("フード"); ArrayList<String> menulist_drink = analyseDAO.menu_searchall("ドリンク"); ArrayList<String> menulist_side = analyseDAO.menu_searchall("サイドメニュー"); ArrayList<String> menulist_dessert = analyseDAO.menu_searchall("デザート"); // ちゃんと閉じる! analyseDAO.close(); request.setAttribute("menulist_reco", menulist_reco); request.setAttribute("menulist_food", menulist_food); request.setAttribute("menulist_drink", menulist_drink); request.setAttribute("menulist_side", menulist_side); request.setAttribute("menulist_dessert", menulist_dessert); System.out.println(""); System.out.println("------ここまでservelet------"); System.out.println(""); return "/view/analyse/menu.jsp"; } } <file_sep>/WEB-INF/src/bean/OrderUserBean.java package bean; public class OrderUserBean { // プロパティ private String id = ""; private String name = ""; private String genre = ""; private int price = -1; private String create = ""; private String update = ""; private String des = ""; private String allergy = ""; private int qty = -1; private String deploy = ""; // ゲッター・セッター public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getCreate() { return create; } public void setCreate(String create) { this.create = create; } public String getUpdate() { return update; } public void setUpdate(String update) { this.update = update; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } public String getAllergy() { return allergy; } public void setAllergy(String allergy) { this.allergy = allergy; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public String getDeploy() { return deploy; } public void setDeploy(String deploy) { this.deploy = deploy; } }
30fb18bf082a3834dec12034916a685b0767a802
[ "Markdown", "Java", "SQL" ]
44
Markdown
Hayashi08/SD25
14122e5965171c1cdce10626bf127f0a2ccfb81e
3c78f96d3dd457670cbaddc7d22a70362baf1457
refs/heads/master
<file_sep>'use strict' const fs = require('fs') const _ = require('lodash') const uuidv4 = require('uuid/v4') module.exports = { dataSource: undefined, getCompiledTemplateFileName() { return this._getMappings().template.compiled }, getCoreTemplateFileName() { return this._getMappings().template.core }, getStackName() { return this._getMappings().stack }, getRoleName() { return this._getMappings().role }, getPolicyName() { return this._getMappings().policy }, getApiGatewayName() { return this._getMappings().apiGateway }, getLogGroupName(name) { name = name .replace(this.provider.getStage() || 'dev', '') .replace(this.provider.serverless.service.service, '') .replace(/^\-+/g, '') .trim() var logGroupName = this._getMappings(name).logGroup return logGroupName }, setFunctionNames(provider) { const self = this self.provider = provider if (self.provider) { _.forEach(self.provider.serverless.service.functions, (functionObj, functionName) => { if (!functionObj.events) { self.provider.serverless.service.functions[functionName].events = [] } const mappings = self._getMappings(functionName) self.provider.serverless.service.functions[functionName].name = mappings.lambda }) } }, _getMappings(lambdaName) { if (!this.dataSource) { this.dataSource = fs.readFileSync(this.provider.serverless.service.custom['serverless-aws-resource-names'].source, 'utf8').replace(new RegExp('\\$rand', 'g'), uuidv4()) } var data = this.dataSource.replace(new RegExp('\\$stage', 'g'), this.provider.getStage() || 'dev') data = data.replace(new RegExp('\\$region', 'g'), this.provider.getRegion()) data = data.replace(new RegExp('\\$service', 'g'), this.provider.serverless.service.service) data = data.replace(new RegExp('\\$lambda', 'g'), lambdaName) return JSON.parse(data) } } <file_sep>'use strict' const naming = require('./naming') const mergeIamTemplates = require('./mergeIamTemplates') class AWSNaming { constructor(serverless, options) { this.serverless = serverless this.options = options this.provider = serverless.getProvider('aws') this.hooks = { 'package:setupProviderConfiguration': this.cleanAndMergeIamTemplates.bind(this) } // Overwrite the AWS provider's naming module serverless.cli.log('Setting custom naming conventions...') Object.assign(this.provider.naming, naming) // Overwrite the function names serverless.cli.log('Setting custom function names...') naming.setFunctionNames(this.provider) } async cleanAndMergeIamTemplates() { this.provider.serverless.cli.log('Cleaning out broken policy and putting in consolidated') mergeIamTemplates.mergeIamTemplates(this.provider) } } module.exports = AWSNaming <file_sep># serverless-plugin-aws-resource-names [![serverless](http://public.serverless.com/badges/v3.svg)](http://www.serverless.com) Serverless plugin to enable custom AWS resource names ## Usage Install the plugin to your project: npm install serverless-aws-resource-names --save Add the plugin and its configuration to your serverless project: plugins: - serverless-aws-resource-names custom: serverless-aws-resource-names: source: mapping.json Create the `mapping.json` file in your project and modify the names to your hearts desire! { "template": { "compiled": "cloudformation-template-update-stack.json", "core": "cloudformation-template-create-stack.json" }, "stack": "$service-$stage", "role": { "Fn::Join": [ "-", [ "$service", "$stage", "$region", "lambdaRole" ] ] }, "policy": { "Fn::Join": [ "-", [ "$stage", "$service", "lambda" ] ] }, "apiGateway": "$stage-$service", "lambda": "$service-$stage-$lambda", "logGroup": "/aws/lambda/$service-$stage-$lambda" } ### Mapping Variable Reference - **$service** - Refers to the service attribute in your serverless.yml - **$stage** - Refers to the stage which you deploy to via serverless e.g. sls deploy **-s dev** - **$region** - Refers to the AWS region that you are deploying to. This is configured in your serverless.yml under the _provider.region_ attribute or by your AWS CLI configuration. - **$lambda** - Refers to the name of your lambda function, defined in your serverless.yml under the _functions_ attribute. - **$rand** - Globally replaces all instances with a random UUID.
240962b33a1cf0e4b9a462e84d9ad834777b8001
[ "JavaScript", "Markdown" ]
3
JavaScript
emilhdiaz/serverless-plugin-aws-resource-names
bd41dd166bdb0ee4a6952f9da109c43c73f981fd
2d3e98181e899d80f1bc8ddce700639bc8d83ca3
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CarDealerManager.Models { public class Car { public int Id { get; set; } [Required] [Display(Name = "Car Brand Name")] public string CarBrandName { get; set; } [Required] public string CarModel { get; set; } [Required] [MaxLength(4)] [MinLength(4)] [RegularExpression("^[0-9]*$", ErrorMessage = "Year Needs 4 numbers")] [Display(Name = "Year")] public string CarYear { get; set; } [Required] [Display(Name = "Fuel Type")] public FuelType Fuel { get; set; } [Required] [Display(Name = "Transmission Type")] public TransmissionType Transmission { get; set; } [Required] [Display(Name = "Color")] public string Color { get; set; } [Required] [Display(Name = "InStock")] public int InStock { get; set; } [ForeignKey("SupplierFK")] [Display(Name = "Supplier")] public Supplier supplier { get; set; } public int SupplierFK { get; set; } } public enum FuelType { Diesel, BioFuel, EthanolFuel, Electrical, Hybrid } public enum TransmissionType { Automatic, Manual, CVT, DCT, DSG, Tiptronic } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace CarDealerManager.Models { public class Supplier { public int Id { get; set; } [Required] [Display(Name = "Name of Supplier")] public string SupplierName { get; set; } [Required] [DataType(DataType.EmailAddress)] public string Email { get; set; } [DataType(DataType.PhoneNumber)] public int Phone { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CarDealerManager.Models { public class Customer { public int Id { get; set; } [Required] [Display(Name = "First Name")] public string FirstName { get; set; } [Required] [Display(Name = "Last Name")] public string LastName { get; set; } [Display(Name = "Full Name")] public string FullName { get { return FirstName + " " + LastName; } } [Required] [Display(Name = "Address")] public string Address { get; set; } [Required] [DataType(DataType.EmailAddress)] public string Email { get; set; } [DataType(DataType.PhoneNumber)] public int Phone { get; set; } } } <file_sep>using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CarDealerManager.Models { public class ErrorMessageHandler { public static string ISThereError { get; set; } public static string ErrorMessage { get; set; } public static string CustomErrorMessagePart1 { get; set; } public static string CustomErrorMessagePart2 { get; set; } } } <file_sep>Run below mentioned commands in Package Manage Console. 1) update-database CREDdb -context CarDealerManagerCREDContext 2) update-database CreateIdentitySchema -context CarDealerManagerIdentityContext<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using CarDealerManager.Models; namespace CarDealerManager.Data { public class CarDealerManagerCREDContext : DbContext { public CarDealerManagerCREDContext (DbContextOptions<CarDealerManagerCREDContext> options) : base(options) { } public DbSet<CarDealerManager.Models.Customer> Customer { get; set; } public DbSet<CarDealerManager.Models.Supplier> Supplier { get; set; } public DbSet<CarDealerManager.Models.Car> Car { get; set; } public DbSet<CarDealerManager.Models.Store> Store { get; set; } } } <file_sep>using System; using System.IO; using Microsoft.EntityFrameworkCore.Migrations; namespace CarDealerManager.Migrations.CarDealerManagerCRED { public partial class CREDdb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Customer", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FirstName = table.Column<string>(nullable: false), LastName = table.Column<string>(nullable: false), Address = table.Column<string>(nullable: false), Email = table.Column<string>(nullable: false), Phone = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Customer", x => x.Id); }); migrationBuilder.CreateTable( name: "Supplier", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), SupplierName = table.Column<string>(nullable: false), Email = table.Column<string>(nullable: false), Phone = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Supplier", x => x.Id); }); migrationBuilder.CreateTable( name: "Car", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CarBrandName = table.Column<string>(nullable: false), CarModel = table.Column<string>(nullable: false), CarYear = table.Column<string>(maxLength: 4, nullable: false), Fuel = table.Column<int>(nullable: false), Transmission = table.Column<int>(nullable: false), Color = table.Column<string>(nullable: false), InStock = table.Column<int>(nullable: false), SupplierFK = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Car", x => x.Id); table.ForeignKey( name: "FK_Car_Supplier_SupplierFK", column: x => x.SupplierFK, principalTable: "Supplier", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Store", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), DateOfPurchase = table.Column<DateTime>(nullable: false), WarrantyDuration = table.Column<int>(nullable: false), CarFK = table.Column<int>(nullable: false), CustomerFK = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Store", x => x.Id); table.ForeignKey( name: "FK_Store_Car_CarFK", column: x => x.CarFK, principalTable: "Car", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Store_Customer_CustomerFK", column: x => x.CustomerFK, principalTable: "Customer", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Car_SupplierFK", table: "Car", column: "SupplierFK"); migrationBuilder.CreateIndex( name: "IX_Store_CarFK", table: "Store", column: "CarFK"); migrationBuilder.CreateIndex( name: "IX_Store_CustomerFK", table: "Store", column: "CustomerFK"); var sqlFile = Path.Combine(".\\DatabaseScript", @"Data.sql"); migrationBuilder.Sql(File.ReadAllText(sqlFile)); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Store"); migrationBuilder.DropTable( name: "Car"); migrationBuilder.DropTable( name: "Customer"); migrationBuilder.DropTable( name: "Supplier"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CarDealerManager.Models { public class Store { public int Id { get; set; } [Required] [Display(Name = "Date Of Purchase")] public DateTime DateOfPurchase { get; set; } [Required] [Display(Name = "Warranty Duration (Number of Years)")] public int WarrantyDuration { get; set; } [ForeignKey("CarFK")] public Car car { get; set; } [Display(Name = "Car")] public int CarFK { get; set; } [ForeignKey("CustomerFK")] public Customer customer { get; set; } [Display(Name = "Customer")] public int CustomerFK { get; set; } } } <file_sep>using System; using CarDealerManager.Data; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; [assembly: HostingStartup(typeof(CarDealerManager.Areas.Identity.IdentityHostingStartup))] namespace CarDealerManager.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { services.AddDbContext<CarDealerManagerIdentityContext>(options => options.UseSqlServer( context.Configuration.GetConnectionString("CarDealerManagerIdentityContextConnection"))); services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<CarDealerManagerIdentityContext>(); }); } } }
fb5d50f3a301dfb1a186ee99fbe30f732779b428
[ "C#", "Text" ]
9
C#
amanbal/CarDealerManager
7ca0264b9bbbfe5a84391630591b86d374c71721
ba0a7133e6fcfc95aeefb339d2e5331e0214f87d
refs/heads/master
<repo_name>tectronics/body-builder<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project> <modelVersion>4.0.0</modelVersion> <groupId>org.agora.games.bodybuilder</groupId> <artifactId>BodyBuilder</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>Body Builder</name> <url>http://code.google.com/p/body-builder</url> <description></description> <scm> <connection></connection> <url></url> </scm> <dependencies> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <!-- Guice --> <dependency> <groupId>com.google.code.guice</groupId> <artifactId>guice</artifactId> <version>1.0</version> </dependency> <!-- JSON --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20070829</version> </dependency> </dependencies> <!--Cache --> <build> <finalName>FixtureBuilder</finalName> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.5</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> </configuration> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <phase>install</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <copy file="${project.build.directory}/${project.build.finalName}.jar" tofile="${install.dir}/${project.artifactId}.jar"/> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <reportSets> <reportSet> <reports> <report>dependencies</report> <report>project-team</report> <report>mailing-list</report> <report>cim</report> <report>issue-tracking</report> <report>license</report> <report>scm</report> <report>taglist</report> <report>pmd</report> </reports> </reportSet> </reportSets> </plugin> <plugin> <artifactId>maven-pmd-plugin</artifactId> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>taglist-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> </plugin> <plugin> <groupId>net.sf</groupId> <artifactId>stat-scm</artifactId> </plugin> <plugin> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <aggregate>true</aggregate> </configuration> </plugin> <plugin> <artifactId>maven-jxr-plugin</artifactId> <configuration> <aggregate>true</aggregate> </configuration> </plugin> </plugins> </reporting> </project> <file_sep>/src/main/java/org/agora/games/bodybuilder/geometry/Line.java package org.agora.games.bodybuilder.geometry; import svg.parser.Vertex; import java.awt.*; /** * @author : <NAME> <<EMAIL>> * Date: 12-01-11 * Time: 8:57 PM * CBC.ca All rights reserved. */ public class Line { public Vertex start; public Vertex end; public boolean selected; public Line(Vertex start, Vertex end) { this.start = start; this.end = end; } } <file_sep>/src/main/resources/log4j.properties log4j.rootLogger = DEBUG, stdout log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=FixtureBuilder.log log4j.appender.R.layout = org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern = %d{ISO8601} %-5p [%F:%L] : %m%n log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Threshold = DEBUG log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{ISO8601} %-5p [%F:%L] : %m%n log4j.logger.org.agora=debug,stdout <file_sep>/src/main/java/org/agora/games/bodybuilder/geometry/mcd/CompGeom/DecompPoly.java package org.agora.games.bodybuilder.geometry.mcd.CompGeom; import org.agora.games.bodybuilder.geometry.Line; import java.awt.Graphics; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List; final public class DecompPoly extends Anim2D { private PointList sp; // the polygon private int n; // number of vertices private SubDecomp subD; // the subproblems in n x r space private int reflexFirst; // for reflexIter private int reflexNext[]; private boolean reflexFlag[]; private ArrayList<PP> lines = new ArrayList<PP>(); final static int DELAY = 100; // time for animation public class PP implements Comparable<PP>{ public int start,end; public PP(int s, int e){ start = s; end = e; } public String toString(){ return " PP[" + start +", " + end + " ]"; } @Override public int compareTo(PP pp) { if(this.start < pp.start){ return -1; } else if(this.start == pp.start && this.end > pp.end){ return -1; } else { return 1; } } } public DecompPoly(){ } public DecompPoly(PointList pl) { sp = pl; n = sp.number(); } public void setPoints(PointList sp) { this.sp = sp; n = sp.number(); } public List<List<PP>> getPolygons(ArrayList<PP> pps){ List<List<PP>> polygons = new ArrayList<List<PP>>(); List<PP> notches = new ArrayList<PP>(); while (pps.size() > 0) { Collections.sort(pps); polygons.add(getPolygon(pps,notches)); } return polygons; } public List<PP> getPolygon(List<PP> pps, List<PP> notches){ List<PP> polygon = new ArrayList<PP>(); polygon.add(pps.get(0)); pps.remove(0); PP last = polygon.get(0); for (int i = 0; i < pps.size(); i++) { PP p = pps.get(i); if (last == null || p.start == last.end) { polygon.add(p); pps.remove(p); last = p; for (PP p1 : notches) { if (p1.start == p.end && p1.end == polygon.get(0).start) { //close polygon and return polygon.add(p1); notches.remove(p1); System.out.println("polygon found " + polygon); return polygon; } } i--; } else if (p.start != last.end) { notches.add(last); while (i < pps.size() - 1 && pps.get(i + 1).start != last.end) { i++; } } } polygon.add(new PP(polygon.get(polygon.size()-1).end,polygon.get(0).start)); System.out.println("polygon found: " + polygon); return polygon; } public void init() { initReflex(); subD = new SubDecomp(reflexFlag); initVisibility(); initSubproblems(); } public boolean reflex(int i) { return reflexFlag[i]; } private void initReflex() { reflexFlag = new boolean[n]; reflexNext = new int[n]; int wrap = 0; /* find reflex vertices */ reflexFlag[wrap] = true; // by convention for (int i = n-1; i > 0; i--) { reflexFlag[i] = Point.right(sp.p(i-1), sp.p(i), sp.p(wrap)); wrap = i; } reflexFirst = n; // for reflexIter for (int i = n-1; i >= 0; i--) { reflexNext[i] = reflexFirst; if (reflex(i)) { reflexFirst = i; } } } /* a cheap iterator through reflex vertices; each vertex knows the index of the next reflex vertex. */ public int reflexIter() { return reflexFirst; } public int reflexIter(int i) { // start w/ i or 1st reflex after... if (i <= 0) return reflexFirst; if (i > reflexNext.length) return reflexNext.length; return reflexNext[i-1]; } public int reflexNext(int i) { return reflexNext[i]; } public final static int INFINITY = 100000; public final static int BAD = 999990; public final static int NONE = 0; public boolean visible(int i, int j) { return subD.weight(i,j) < BAD; } public void initVisibility() { // initReflex() first if (animating()) animGraphics.setColor(Color.yellow); VisPoly vp = new VisPoly(sp); for (int i = reflexIter(); i < n; i = reflexNext(i)) { vp.build(i); while (!vp.empty()) { int j = vp.popVisible() % n; if (j < i) subD.setWeight(j, i, INFINITY); else subD.setWeight(i, j, INFINITY); if (animating()) animGraphics.drawLine(sp.p(i).x(), sp.p(i).y(), sp.p(j).x(), sp.p(j).y()); } } if (animating()) { animGraphics.setColor(Color.blue); try { Thread.sleep(DELAY); } catch(InterruptedException e) { } } } private void setAfter(int i) { // i reflex assert reflex(i); subD.setWeight(i, i+1, 0); if (visible(i,i+2)) subD.init(i, i+2, 0, i+1, i+1); } private void setBefore(int i) { // i reflex assert reflex(i); subD.setWeight(i-1, i, 0); if (visible(i-2, i)) subD.init(i-2, i, 0, i-1, i-1); } public void initSubproblems() { // initVisibility first int i; i = reflexIter(); if (i == 0) { setAfter(i); i = reflexNext(i); } if (i == 1) { subD.setWeight(0, 1, 0); setAfter(i); i = reflexNext(i); } while (i < n-2) { setBefore(i); setAfter(i); i = reflexNext(i); } if (i == n-2) { setBefore(i); subD.setWeight(i,i+1,0); i = reflexNext(i);} if (i == n-1) { setBefore(i); } } public void initPairs(int i, int k) { subD.init(i, k); } public int guard; public void recoverSolution(int i, int k) { int j; if (guard-- < 0) { System.out.println("Can't recover"+i+","+k); return;} if (k-i <= 1) return; PairDeque pair = subD.pairs(i,k); if (reflex(i)) { j = pair.bB(); recoverSolution(j, k); if (j-i > 1) { if (pair.aB() != pair.bB()) { PairDeque pd = subD.pairs(i, j); pd.restore(); while ((!pd.emptyB()) && pair.aB() != pd.aB()) pd.popB(); assert !pd.emptyB(); } recoverSolution(i, j); } } else { j = pair.aF(); recoverSolution(i, j); if (k-j > 1) { if (pair.aF() != pair.bF()) { PairDeque pd = subD.pairs(j, k); pd.restore(); while ((!pd.empty()) && pair.bF() != pd.bF()) pd.pop(); assert !pd.empty(); } recoverSolution(j, k); } } } public void typeA(int i, int j, int k) { /* i reflex; use jk */ // System.out.print("\nA "+i+","+j+","+k+":"); // assert(reflex(i), "non reflex i in typeA("+i+","+j+","+k+")"); // assert(k-i > 1, "too small in typeA("+i+","+j+","+k+")"); if (!visible(i,j)) return; int top = j; int w = subD.weight(i,j); if (k-j > 1) { if (!visible(j,k)) return; w += subD.weight(j, k) + 1; } if (j-i > 1) { // check if must use ij, too. PairDeque pair = subD.pairs(i, j); if (!Point.left(sp.p(k), sp.p(j), sp.p(pair.bB()))) { while (pair.more1B() && !Point.left(sp.p(k), sp.p(j), sp.p(pair.underbB()))) pair.popB(); if ((!pair.emptyB()) && !Point.right(sp.p(k), sp.p(i), sp.p(pair.aB()))) top = pair.aB(); else w++; // yes, need ij. top = j already } else w++; // yes, need ij. top = j already } update(i,k, w, top, j); } public void typeB(int i, int j, int k) { /* k reflex, i not. */ // System.out.print("\nB "+i+","+j+","+k+":"); if (!visible(j,k)) return; int top = j; int w = subD.weight(j,k); if (j-i > 1) { if (!visible(i,j)) return; w += subD.weight(i, j) + 1; } if (k-j > 1) { // check if must use jk, too. PairDeque pair = subD.pairs(j, k); if (!Point.right(sp.p(i), sp.p(j), sp.p(pair.aF()))) { while (pair.more1() && !Point.right(sp.p(i), sp.p(j), sp.p(pair.underaF()))) pair.pop(); if ((!pair.empty()) && !Point.left(sp.p(i), sp.p(k), sp.p(pair.bF()))) top = pair.bF(); else w++; // yes, use jk. top=j already } else w++; // yes, use jk. top=j already } update(i, k, w, j, top); } /* We have a new solution for subprob a,b with weight w, using i,j. If it is better than previous solutions, we update. We assume that a<b and i < j. */ public void update(int a, int b, int w, int i, int j) { // System.out.print("update("+a+","+b+" w:"+w+" "+i+","+j+")"); int ow = subD.weight(a,b); if (w <= ow) { PairDeque pair = subD.pairs(a, b); if (w < ow) { pair.flush(); subD.setWeight(a,b, w); } pair.pushNarrow(i, j); } } private void drawDiagonal(Graphics g, boolean label, int i, int k) { g.drawLine(sp.p(i).x(), sp.p(i).y(), sp.p(k).x(), sp.p(k).y()); if (label && (reflex(i) || reflex(k))) g.drawString(Integer.toString(subD.weight(i,k)), (sp.p(i).x()+sp.p(k).x())/2, (sp.p(i).y()+sp.p(k).y())/2); } private void drawHelper(Graphics g, boolean label, int i, int k) { int j; boolean ijreal = true, jkreal = true; if (k-i <= 1) return; PairDeque pair = subD.pairs(i,k); if (reflex(i)) { j = pair.bB(); ijreal = (pair.aB() == pair.bB()); } else { j = pair.aF(); jkreal = (pair.bF() == pair.aF()); } if (ijreal){ lines.add(new PP(i,j)); drawDiagonal(g, label, i, j); } else if (label) { g.setColor(Color.orange); drawDiagonal(g, label, i, j); g.setColor(Color.blue); } if (jkreal) { lines.add(new PP(j,k)); drawDiagonal(g, label, j, k); } else if (label) { g.setColor(Color.orange); drawDiagonal(g, label, j, k); g.setColor(Color.blue); } if (guard-- < 0) { System.out.println("Infinite Loop drawing"+i+","+k); return; } drawHelper(g, label, i, j); drawHelper(g, label, j, k); } public List<List<PP>> calculate(){ lines = new ArrayList<PP>(); init(); int i, k, n = sp.number(); for (int l = 3; l < n; l++) { for (i = this.reflexIter(); i + l < n; i = this.reflexNext(i)) if (this.visible(i, k = i + l)) { this.initPairs(i, k); if (this.reflex(k)) for (int j = i+1; j < k; j++) this.typeA(i, j, k); else { for (int j = this.reflexIter(i + 1); j < k-1; j = this.reflexNext(j)) this.typeA(i, j, k); this.typeA(i, k - 1, k); // do this, reflex or not. } } for (k = this.reflexIter(l); k < n; k = this.reflexNext(k)) if ((!this.reflex(i = k - l)) && this.visible(i, k)) { this.initPairs(i, k); this.typeB(i, i + 1, k); // do this, reflex or not. for (int j = this.reflexIter(i + 2); j < k; j = this.reflexNext(j)) this.typeB(i, j, k); } } this.guard = 3*n; this.recoverSolution(0, n - 1); doHelper(0, sp.number()-1 ); return getPolygons(lines); } private void doHelper( int i, int k) { int j; boolean ijreal = true, jkreal = true; if (k-i <= 1) return; PairDeque pair = subD.pairs(i,k); if (reflex(i)) { j = pair.bB(); ijreal = (pair.aB() == pair.bB()); } else { j = pair.aF(); jkreal = (pair.bF() == pair.aF()); } if (ijreal){ lines.add(new PP(i,j)); } if (jkreal) { lines.add(new PP(j,k)); } if (guard-- < 0) { System.out.println("Infinite Loop drawing"+i+","+k); return; } doHelper(i, j); doHelper(j, k); } public void getSolution(){ doHelper(0,sp.number()-1); } public void draw(Graphics g, boolean label) { sp.drawPolygon(g, sp.number()); if (animating()) { for (int i = reflexIter(); i < sp.number(); i = reflexNext(i)) sp.p(i).drawCirc(animGraphics, 5); } guard = 3*n; lines = new ArrayList(); drawDiagonal(g, label, 0, sp.number()-1); drawHelper(g, label, 0, sp.number()-1); Collections.sort(lines); System.out.println(lines); this.getPolygons(lines); } public String toString() { StringBuffer s = new StringBuffer(); s.append(sp.number()+": "+sp.toString()); return s.toString(); } } /* this class stores all subproblems for a decomposition by dynamic programming. It uses an indirect addressing into arrays that have all the reflex vertices first, so that I can allocate only O(nr) space. */ final class SubDecomp { private int wt[][]; private PairDeque pd[][]; private int rx[]; // indirect index so reflex come first SubDecomp(boolean [] reflex) { int n = reflex.length, r = 0; rx = new int[n]; for (int i = 0; i < n; i++) if (reflex[i]) rx[i] = r++; int j = r; for (int i = 0; i < n; i++) if (!reflex[i]) rx[i] = j++; wt = new int[n][]; pd = new PairDeque[n][]; for (int i = 0; i < r; i++) { wt[i] = new int[n]; for (j = 0; j < wt[i].length; j++) wt[i][j] = DecompPoly.BAD; pd[i] = new PairDeque[n]; } for (int i = r; i < n; i++) { wt[i] = new int[r]; for (j = 0; j < wt[i].length; j++) wt[i][j] = DecompPoly.BAD; pd[i] = new PairDeque[r]; } } public void setWeight(int i, int j, int w) { wt[rx[i]][rx[j]] = w; } public int weight(int i, int j) { return wt[rx[i]][rx[j]]; } public PairDeque pairs(int i, int j) { return pd[rx[i]][rx[j]]; } public PairDeque init(int i, int j) { return pd[rx[i]][rx[j]] = new PairDeque(); } public void init(int i, int j, int w, int a, int b) { setWeight(i,j,w); init(i,j).push(a,b); } } <file_sep>/src/main/java/org/agora/games/bodybuilder/Triangularizer.java package org.agora.games.bodybuilder; import org.agora.games.bodybuilder.geometry.FixtureDefinition; import svg.parser.Vertex; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author : <NAME> <<EMAIL>> * Date: 12-01-04 * Time: 12:25 AM * CBC.ca All rights reserved. */ public class Triangularizer { ArrayList<Vertex> vertexes; public Triangularizer(ArrayList<Vertex> v) { vertexes = v; } public FixtureDefinition calculate() { List<FixtureDefinition> result = new ArrayList<FixtureDefinition>(); //calculate the middle float sumX = sumX(vertexes); float sumY = sumY(vertexes); float centerX = sumX / vertexes.size(); float centerY = sumY / vertexes.size(); return new FixtureDefinition(new Vertex(centerX,centerY), vertexes, 1,1,1); } private float sumX(List<Vertex> vertexes) { float result = 0; for (Vertex v : vertexes) { result += v.x; } return result; } private float sumY(List<Vertex> vertexes) { float result = 0; for (Vertex v : vertexes) { result += v.y; } return result; } }
77c725f18458dad2b185a74d3f726ecc58c55698
[ "Java", "Maven POM", "INI" ]
5
Maven POM
tectronics/body-builder
2052b59a43cf1e5b2463011633741d4c36dadc52
878a009d17a6e22d86cf083abe08a8a2536795ea
refs/heads/master
<file_sep>import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; public class Initialisation { private Game game; @Given("^a game setter for initialisation$") public void create_game() throws Throwable { game = new Game(); } @When("^program starts for initialisation$") public void init_game() throws Throwable { game.Init(); } @Then("^a deck is created$") public void check_deck() throws Throwable { Assert.assertEquals(20, game.getDeck().size()); } } <file_sep>import java.util.List; public class Goblin extends Card { // ********** VARIABLES ********** // ********** CONSTRUCTORS ********** // ********** GETTERS ********** // ********** SETTERS ********** // ********** METHODS ********** public void ApplyPower(Game game, Player player) { //switch your hand with you opponent List<Card> buffer = game.getPlayer1().getHand(); game.getPlayer1().setHand(game.getPlayer2().getHand()); game.getPlayer2().setHand(buffer); } public Race getRace() { return Race.GOBLIN; } } <file_sep>public abstract class Card { // ********** VARIABLES ********** // ********** CONSTRUCTORS ********** // ********** GETTERS ********** // ********** SETTERS ********** // ********** METHODS ********** /** * Method to apply the power of the card * @param game : the current game * @param player : the player that owns the card */ public abstract void ApplyPower(Game game, Player player); /** * Method to get the Race of the card * @return the race of the card */ public abstract Race getRace(); } <file_sep>public class Korrigan extends Card { // ********** VARIABLES ********** // ********** CONSTRUCTORS ********** // ********** GETTERS ********** // ********** SETTERS ********** // ********** METHODS ********** public void ApplyPower(Game game, Player player) { //draw 2 random cards within your opponent hand game.getPlayer1().Draw(game.getPlayer2().getHand()); game.getPlayer1().Draw(game.getPlayer2().getHand()); } public Race getRace() { return Race.KORRIGAN; } } <file_sep>public class Gnome extends Card { // ********** VARIABLES ********** // ********** CONSTRUCTORS ********** // ********** GETTERS ********** // ********** SETTERS ********** // ********** METHODS ********** public void ApplyPower(Game game, Player player) { //draw 2 cards player.Draw(game.getDeck()); player.Draw(game.getDeck()); } public Race getRace() { return Race.GNOME; } } <file_sep>import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; public class Gameplay { private Game game; @Given("^A player$") public void init_game() throws Throwable { game = new Game(); game.Init(); } @And("^the deck is not empty$") public void check_deck() throws Throwable { Assert.assertFalse(game.DeckIsEmpty()); } @When("^it is his turn to draw a card$") public void draw_card() throws Throwable { game.getPlayer1().Draw(game.getDeck()); } @Then("^He can draw a card$") public void draw_card_sucess() throws Throwable { Assert.assertEquals(6, game.getPlayer1().getHand().size()); } @When("^it is his turn to play$") public void check_turn() throws Throwable { game.getPlayer1().Play(this.game); } @And("^he has drawn$") public void check_drawn() throws Throwable { Assert.assertEquals(19, game.getDeck().size()); } @Then("^he can play a card$") public void try_to_play() throws Throwable { Assert.assertEquals(7, game.getPlayer1().getHand().size()); } @When("^he add a card to kingdom$") public void played_card() throws Throwable { game.getPlayer1().AddCardToKingdom(game.getPlayer1().ChooseCardFromHand()); } @Then("^the card is added to his kingdom$") public void check_kingdom() throws Throwable { Assert.assertEquals(1, game.getPlayer1().getKingdom().size()); } // // @And("^the deck is not empty$") // public void deck_not_empty() throws Throwable { // Assert.assertEquals(game.DeckIsEmpty(), false); // } // // @When("^he draw a card from the deck$") // public void draw_from_deck() throws Throwable { // player.Draw(game.getDeck()); // } // // @Then("^this card is added to his hand$") // public void card_add_to_hand throws Throwable { // Assert.assertEquals(player.getHand().size(), hand.size()+1); // } // // @Given("^a player$") // public void a_player() throws Throwable { // //voir plus haut, je pense mÍme qu'il faille faire un stepdefs comme dans l'exemple prof // } // // @When("^he choose a card$") // public void choose_a_card() throws Throwable { // player.ChooseCardFromHand(); // } // // @Then("^ha can play this card$") // public void play_card() throws Throwable { // Assert.assertEquals(hand.size() - 1, player.getHand().size()); // } // // @Given("^a player$") // public void a_player throws Throwable { // //comme l'autre // } // // @When("^he has played a card$") // public void paly_a_card() throws Throwable { // // } // // @Then("^it triggered its effect$") // public void trigger_effect() throws Throwable { // // } // // @Given("^a Korrigan card$") // public void korrigan_card throws Throwable { // // } // // @When("^it is added to a kingdom's player from the hand$") // public void add_kingdom() throws Throwable { // // } // // @Then("^the player draw two cards in his opponent hand$") // public void korrigan_effect() throws Throwable { // // } // // @Given("^a Gnome Card$") // public void gnome_card() throws Throwable { // // } // // @When("^it is added to a kingdom's player from the hand$") // public void add_kingdom() throws Throwable { // // } // // @Then("^the player draw two card in the deck$") // public void gnome_effect() throws Throwable { // // } // // // // @Given("^an Elf card$") // public void elf_card() throws Throwable { // // } // // @When("^it is added to a kingdom's player from the hand$") // public void add_kingdom() throws Throwable { // // } // // @Then("^play the power of a card of the ennemy s kingdom$") // public void elf_effect() throws Throwable { // // } // // // // @Given("^a Dryad card$") // public void dryad_card() throws Throwable { // // } // // @When("^it is added to a kingdom's player from the hand$") // public void add_kingdom() throws Throwable { // // } // // @Then("^the player steal a card from the opponent s kingdom to add it to his$") // public void drayd_effect() throws Throwable { // // } // // // // @Given("^a Troll card$") // public void troll_card() throws Throwable { // // } // // @When("^it is added to a kingdom's player from the hand$") // public void add_kingdom() throws Throwable { // // } // // @Then("^the two kingdoms are swapped$") // public void troll_effect() throws Throwable { // // } // // @When("^both player's hand are empty$") // public void palyer_hand_empty() throws Throwable { // // } // // @And("^the deck is empty$") // public void deck_empty() throws Throwable{ // // } // // @Then("^the game is finished$") // public void game_end() throws Throwable { // // } // // @Given("^a Game checker$") // public void game_checker() throws Throwable { // // } // // @When("^both player's hand are empty$") // public void palyer_hand_empty() throws Throwable { // // } // // @And("^the deck is empty$") // public void deck_empty() throws Throwable{ // // } // // @Then("^his turn is passed$") // public void test() throws Throwable { // // } } <file_sep># Software Development Process Project This year, each Team will have to code a card game. Technic notes: the project will be coded in Java and the User Interface (UI) will be realize with the JavaFX library (using FXML for layout description and CSS for decoration) ## Rules ### Game Setup : Cards are shuffled. Each player draw 5 cards. ### How it works ? Each card represent an individual of a race. Each race have a specific power. When it's its turn, each player draws a card and plays a card from his/her hand in front of him/her. Then he/she applies the power of the card. The cards in front of a player compose his/her kingdom. Then it's the turn of the next player. ### End of the game The game continue even if the deck is empty until one of the players plays his/her last card. Then the other player play his/her last turn. So each players have played the same number of cards during the game. Each player receive 1 point for each individual within its kingdom. He/She also receive 3 extra point if he/she has almost one individual of each of the 6 races. ### Races - Korrigan : draw 2 random cards within your opponent hand - Gnome : draw 2 cards - Goblin: switch your hand with you opponent - Elf : copy and use the power of one of the card in front of you - Dryad : stole a card in front of your opponent and add it in front of you without activating its power. - Troll: swap the cards in front of you with the cards in front of your opponent Modifié le: dimanche 24 septembre 2017, 17:05<file_sep>import java.util.ArrayList; import java.util.List; public class Troll extends Card { // ********** VARIABLES ********** // ********** CONSTRUCTORS ********** // ********** GETTERS ********** // ********** SETTERS ********** // ********** METHODS ********** public void ApplyPower(Game game, Player player) { //swap the cards in front of you with the cards in front of your opponent List<Card> swap = game.getPlayer1().getKingdom(); // Store the kingdom of the 1st player in game.getPlayer1().setKingdom(game.getPlayer2().getKingdom()); game.getPlayer2().setKingdom(swap); } public Race getRace() { return Race.TROLL; } } <file_sep>import org.junit.Assert; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class TrollTest { private Troll troll; private boolean success; @Given("^my service exists$") public void my_service_exists() throws Throwable { } @When("^I call my service$") public void i_call_my_service() throws Throwable { troll = new Troll(); } @Then("^it should have been a success$") public void it_should_have_been_a_success() throws Throwable { Assert.assertTrue(troll.getRace() == Race.TROLL); } }
c5096f12f2f2f6cd5bd6ab58cd0d14d25ec7ed78
[ "Markdown", "Java" ]
9
Java
Yaskomega/SoftwareDevelopmentProcessCourse
aa20ba0043bab71c2354a4c6aa83b2472f761958
022384d3a6fa5148343880179a78887590a3dd3d
refs/heads/master
<repo_name>mustafabeshr/fourG.UI<file_sep>/fourG.Web/Data/Interfaces/IAppDbContext.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.Web.Data.Interfaces { public interface IAppDbContext { Task<int> ExecuteSqlCommandAsync(string sql, IEnumerable<SqlParameter> parameters); Task<DataTable> GetDataAsync(string sql, IEnumerable<SqlParameter> parameters); Task<int> ExecuteStoredProcAsync(string spName, IEnumerable<SqlParameter> parameters); } } <file_sep>/fourG.UI/Data/Repos/AppRoleRepo.cs using fourG.UI; using fourG.UI.Data.Entities; using fourG.UI.Data.Interfaces; using fourG.UI.Data.Utility; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Repo { public class AppRoleRepo { private readonly IAppDbContext _db; public AppRoleRepo(IAppDbContext db) { this._db = db; } public async Task<List<AppRole>> GetListAsync() { var sql = $"SELECT * FROM[dbo].[roles] ORDER BY role_id"; var resultData = await _db.GetDataAsync(sql, null); if (resultData == null) return null; var result = new List<AppRole>(); foreach (DataRow row in resultData.Rows) { var order = new AppConverter(_db).ToAppRole(row); result.Add(order); } return result; } public async Task<AppRole> GetSingleAsync(int id) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE role_id = @RowId "; parameters.Add(new SqlParameter("RowId", id)); } else { return null; } #endregion var sql = $"SELECT * FROM [dbo].[roles] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = new AppConverter(_db).ToAppRole(row); return order; } } } <file_sep>/fourG.UI/Data/Entities/SubcriberPackages.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Entities { public class SubscriberPackage { public int Id { get; set; } public string MobileNo { get; set; } public string PackageId { get; set; } public string PackageName { get; set; } public DateTime StartedOn { get; set; } public DateTime ExpiredOn { get; set; } public int Status { get; set; } } public class SubscriberPackageHistory : SubscriberPackage { public DateTime DeactivatedOn { get; set; } } } <file_sep>/fourG.UI/Data/Entities/AppOperator.cs using System; using System.Collections.Generic; using System.Text; namespace fourG.UI.Data.Entities { public class AppOperator { public string Id { get; set; } public string Name { get; set; } public AppRole Role { get; set; } public int Status { get; set; } public string Secret { get; set; } public string SecretKey { get; set; } public int Attempts { get; set; } public DateTime CreatedOn { get; set; } public DateTime StatusChangedOn { get; set; } public DateTime LastLoggedOn { get; set; } public DateTime LockedTo { get; set; } } } <file_sep>/fourG.UI/Data/Entities/Subcriber.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Entities { public class Subscriber { public int Id { get; set; } public string MobileNo { get; set; } public string IMSI { get; set; } public DateTime RegisteredOn { get; set; } public DateTime ExpiredOn { get; set; } public int Status { get; set; } public DateTime LastPackageOn { get; set; } public string LastPackageId { get; set; } public string LastPackageName { get; set; } public int AAAStatus { get; set; } public int HSSStatus { get; set; } } } <file_sep>/fourG.UI/Data/Repos/AppOperatorRepo.cs using fourG.UI; using fourG.UI.Data.Interfaces; using fourG.UI.Data.Utility; using Microsoft.AspNetCore.Http; using System; using System.Linq; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using fourG.UI.Data.Entities; using Microsoft.Extensions.Configuration; namespace fourG.UI.Data.Repo { public class AppOperatorRepo : IAppOperator { private readonly IAppDbContext _db; private readonly IConfiguration _configuration; public AppOperatorRepo(IAppDbContext db, IConfiguration configuration) { this._db = db; this._configuration = configuration; } public string GetLoggedOperatorId(HttpContext httpContext) { if (!httpContext.User.Identity.IsAuthenticated) return "-1"; Claim claim = httpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (claim == null) return "-1"; string currectOperatorId = claim.Value; //if (!int.TryParse(claim.Value, out currentUserId)) // return "-1"; return currectOperatorId; } public int GetLoggedOperatorRoleId(HttpContext httpContext) { if (!httpContext.User.Identity.IsAuthenticated) return -1; Claim claim = httpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role); if (claim == null) return -1; int currentRoleId = int.Parse(claim.Value); //if (!int.TryParse(claim.Value, out currentUserId)) // return "-1"; return currentRoleId; } public async Task<List<AppOperator>> GetListAsync(int status, int role) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (status >= 0) { where = $" WHERE status = @OpStatus "; parameters.Add(new SqlParameter("@OpStatus", status)); } if (role >= 0) { where += string.IsNullOrEmpty(where) ? $" WHERE op_role_id = @RoleId " : $" AND op_role_id = @RoleId "; parameters.Add(new SqlParameter("@RoleId", role)); } #endregion var sql = $"SELECT * FROM[dbo].[operators] {where} ORDER BY op_id"; var resultData = await _db.GetDataAsync(sql, null); if (resultData == null) return null; var result = new List<AppOperator>(); foreach (DataRow row in resultData.Rows) { var order = await new AppConverter(_db).ToAppOperator(row); result.Add(order); } return result; } public async Task<AppOperator> GetSingleAsync(string id) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (!string.IsNullOrEmpty(id)) { where = $" WHERE op_id = @RowId "; parameters.Add(new SqlParameter("RowId", id)); }else { return null; } #endregion var sql = $"SELECT * FROM [dbo].[operators] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = await new AppConverter(_db).ToAppOperator(row); return order; } public async Task<AppOperator> GetLoggedOperatorAsync(HttpContext httpContext) { var opId = GetLoggedOperatorId(httpContext); if (opId == "-1") return null; return await GetSingleAsync(opId); } public async Task<bool> IncreaseWrongPwdAttempts(string operatorId, int wrongAttempts = 0) { var maxWrongPasswordCount = _configuration.GetSection("SecurityRules:MaxWrongPasswordCount").Value ?? "3"; var maxLockedDurationHours = _configuration.GetSection("SecurityRules:MaxLockedDurationHours").Value ?? "2"; var where = " WHERE op_id = @OpId "; string sql = string.Empty; var parameters = new List<SqlParameter> { new SqlParameter("OpId", operatorId) }; if (wrongAttempts < int.Parse(maxWrongPasswordCount)) { sql = $"UPDATE [dbo].[operators] SET attempts = attempts + 1 {where} "; } else { parameters.Add(new SqlParameter("LockedToTime", DateTime.Now.AddHours(int.Parse(maxLockedDurationHours)))); sql = $"UPDATE [dbo].[operators] SET lockedOn = @LockedToTime {where} "; } var result = await _db.ExecuteSqlCommandAsync(sql, parameters); return result > 0; } public async Task<bool> PreSuccessLogin(string operatorId) { var where = " WHERE op_id = @OpId "; string sql = string.Empty; var parameters = new List<SqlParameter> { new SqlParameter("OpId", operatorId) }; parameters.Add(new SqlParameter("CurrentTime", DateTime.Now)); sql = $"UPDATE [dbo].[operators] SET lastLoggedOn = @CurrentTime, attempts=0 {where} "; var result = await _db.ExecuteSqlCommandAsync(sql, parameters); return result > 0; } public async Task LoginAsync(AppOperator user, string password) { } public IEnumerable<Claim> GetUserClaims(AppOperator user) { List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id)); claims.Add(new Claim(ClaimTypes.Name, user.Name)); claims.Add(new Claim(ClaimTypes.GivenName, user.Role.Id.ToString())); claims.Add(new Claim(ClaimTypes.Role, user.Role.Name)); claims.AddRange(this.GetUserRoleClaims(user)); return claims; } private IEnumerable<Claim> GetUserRoleClaims(AppOperator user) { List<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Role, user.Role.Name)); //claims.AddRange(this.GetUserPermissionClaims(role)); return claims; } public Task<bool> LoginAsync(string operatodId, string password, string secretKey) { throw new NotImplementedException(); } } } <file_sep>/fourG.UI/Data/Entities/LteOrder.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Entities { public class LteOrder { public int Id { get; set; } public string MobileNo { get; set; } public bool IsExist { get; set; } public int OrderType { get; set; } public DateTime ExpiredOn { get; set; } public int Postpaid { get; set; } public string IMSI { get; set; } public string IMSIPassword { get; set; } public string PackageId { get; set; } public string PackageName { get; set; } public string AlterPackageId { get; set; } public string AlterPackageName { get; set; } public int PackageValidity { get; set; } public string OfferId { get; set; } public int Status { get; set; } public int AAAStatus { get; set; } public int PRLStatus { get; set; } public int CRMStatus { get; set; } public int HSSStatus { get; set; } public string Channel { get; set; } public DateTime CreatedOn { get; set; } public DateTime ClosedOn { get; set; } public string Note { get; set; } } public class LteOrderHistory : LteOrder { } } <file_sep>/fourG.UI/Data/Entities/Product.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Entities { public class Product { public int Id { get; set; } public string FirstId { get; set; } public string SecondId { get; set; } public string Name { get; set; } public double Fee { get; set; } public double Size { get; set; } public int Validity { get; set; } public string PrepaidOfferId { get; set; } public string PostpaidOfferId { get; set; } } } <file_sep>/fourG.Web/Data/Entities/MessageSpool.cs using System; using System.Collections.Generic; using System.Text; namespace fourG.Web.Data.Entities { public class MessageSpool { public int Id { get; set; } public string MobileNo { get; set; } public string Message { get; set; } public string Shortcode { get; set; } public DateTime CreatedOn { get; set; } public int Status { get; set; } } public class MessageSpoolHistory { public int Id { get; set; } public string MobileNo { get; set; } public string Message { get; set; } public string Shortcode { get; set; } public DateTime CreatedOn { get; set; } public DateTime BackedupOn { get; set; } public int Status { get; set; } } } <file_sep>/fourG.Infra/Interfaces/IAppOperator.cs using fourG.Data; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace fourG.Infra.Interfaces { public interface IAppOperator { Task<List<AppOperator>> GetListAsync(int status, int role); Task<AppOperator> GetSingleAsync(string id); string GetLoggedOperatorId(HttpContext httpContext); int GetLoggedOperatorRoleId(HttpContext httpContext); Task<AppOperator> GetLoggedOperatorAsync(HttpContext httpContext); } } <file_sep>/fourG.Sms/frmSettings.cs using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace fourG.Sms { public partial class frmSettings : Form { private readonly IConfiguration configuration; private readonly SMSCReceiverSettings receiverSettings; private readonly SMSCSenderSettings senderSettings; public frmSettings(IConfiguration configuration) { InitializeComponent(); this.configuration = configuration; receiverSettings = new SMSCReceiverSettings(); senderSettings = new SMSCSenderSettings(); configuration.GetSection("SmscSettings:Receiver").Bind(receiverSettings); configuration.GetSection("SmscSettings:Sender").Bind(senderSettings); } private void frmSettings_Load(object sender, EventArgs e) { txtRecServer.Text = receiverSettings.Server; txtRecPort.Text = receiverSettings.Port; txtRecSysId.Text = receiverSettings.SystemId; txtRecPassword.Text = receiverSettings.<PASSWORD>; txtRecCount.Text = receiverSettings.Count; txtRecShortcode.Text = receiverSettings.Shortcode; txtSenServer.Text = senderSettings.Server; txtSenPort.Text = senderSettings.Port; txtSenSysId.Text = senderSettings.SystemId; txtSenPassword.Text = sender<PASSWORD>; txtSenCount.Text = senderSettings.Count; txtSenShortcode.Text = senderSettings.Shortcode; } } } <file_sep>/fourG.UI/Data/Entities/SubscriberExceedMaxValidity.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Entities { public class SubscriberExceedMaxValidity { public int Id { get; set; } public string MobileNo { get; set; } public string PackageId { get; set; } public string PackageName { get; set; } public int OperationType { get; set; } public DateTime CreatedOn { get; set; } } } <file_sep>/fourG.Web/Data/Repos/OperationLogRepo.cs using fourG.Web; using fourG.Web.Data.Entities; using fourG.Web.Data.Interfaces; using fourG.Web.Data.Utility; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace fourG.Web.Data.Repo { public class OperationLogRepo { private readonly IAppDbContext _db; public OperationLogRepo(IAppDbContext db) { this._db = db; } public async Task<List<OperationLog>> GetListAsync(int transId, string mobileNo) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (!string.IsNullOrEmpty(mobileNo)) { where = $" WHERE mobile_no = @MobileNo "; parameters.Add(new SqlParameter("MobileNo", mobileNo)); } if (transId > 0) { where += string.IsNullOrEmpty(where) ? $" WHERE trans_no = @TransNO " : $" AND trans_no = @TransNO "; parameters.Add(new SqlParameter("TransNO", transId)); } #endregion var sql = $"SELECT * FROM [dbo].[operation_log] {where} ORDER BY row_no"; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; var result = new List<OperationLog>(); foreach (DataRow row in resultData.Rows) { var order = new AppConverter(_db).ToOperationLog(row); result.Add(order); } return result; } public async Task<OperationLog> GetSingleAsync(int rowNo) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (rowNo > 0) { where = $" WHERE row_no = @RowNo "; parameters.Add(new SqlParameter("RowNo", rowNo)); } #endregion var sql = $"SELECT * FROM [dbo].[operation_log] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = new AppConverter(_db).ToOperationLog(row); return order; } } } <file_sep>/fourG.Sms/Program.cs using fourG.Infra; using fourG.Infra.Interfaces; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace fourG.Sms { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var host = Host.CreateDefaultBuilder() .ConfigureAppConfiguration((context, builder) => { // Add other configuration files... builder.AddJsonFile("appsettings.json", optional: true); }) .ConfigureServices((context, services) => { ConfigureServices(context.Configuration, services); }) .ConfigureLogging(logging => { // Add other loggers... }).Build(); using (var serviceScope = host.Services.CreateScope()) { var services = serviceScope.ServiceProvider; try { var mainForm = services.GetRequiredService<frmMain>(); Application.Run(mainForm); } catch (Exception ex) { } } } private static void ConfigureServices(IConfiguration configuration, IServiceCollection services) { services.AddSingleton<IAppDbContext, AppDbContext>(); services.AddScoped<frmMain>(); } } } <file_sep>/fourG.Web/Data/Repos/AppDbContext.cs using System.Data.SqlClient; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using fourG.Web.Data.Interfaces; namespace fourG.Web.Data.Repo { public class AppDbContext : IAppDbContext { public IConfiguration Configuration { get; } public AppDbContext(IConfiguration configuration) { Configuration = configuration; } private SqlConnection GetConnection(string connectionStringName) { var connString = Configuration.GetConnectionString(connectionStringName); return new SqlConnection(connString); } public async Task<int> ExecuteSqlCommandAsync(string sql, IEnumerable<SqlParameter> parameters) { using (var conn = GetConnection("AppDb")) { var cmd = GetCommand(sql, parameters); cmd.Connection = conn; if (conn.State != ConnectionState.Open) conn.Open(); return await cmd.ExecuteNonQueryAsync(); } } public async Task<int> ExecuteStoredProcAsync(string spName, IEnumerable<SqlParameter> parameters) { using (var conn = GetConnection("AppDb")) { var cmd = GetCommand(spName, parameters); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn; if (conn.State != ConnectionState.Open) conn.Open(); return await cmd.ExecuteNonQueryAsync(); } } public async Task<DataTable> GetDataAsync(string sql, IEnumerable<SqlParameter> parameters) { using (var conn = GetConnection("AppDb")) { var ds = new DataSet(); await Task.Run(() => { var cmd = GetCommand(sql, parameters); cmd.Connection = conn; if (conn.State != ConnectionState.Open) conn.Open(); var da = new SqlDataAdapter(cmd); da.Fill(ds); }); if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) { return null; } return ds.Tables[0]; } } private SqlCommand GetCommand(string sql, IEnumerable<SqlParameter> parameters) { var cmd = new SqlCommand(sql); if (parameters != null && parameters.Count() > 0) { foreach (var p in parameters) { cmd.Parameters.Add(p); } } return cmd; } } } <file_sep>/fourG.Infra/MessageSpoolRepo.cs using fourG.Data; using fourG.Infra.Interfaces; using fourG.Infra.Utility; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace fourG.Infra { public class MessageSpoolRepo { private readonly IAppDbContext _db; public MessageSpoolRepo(IAppDbContext db) { this._db = db; } public async Task<List<MessageSpool>> GetListAsync(int id, string mobileNo, int status, int count = 100) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE row_id = @RowId "; parameters.Add(new SqlParameter("@RowId", id)); } if (!string.IsNullOrEmpty(mobileNo)) { where += string.IsNullOrEmpty(where) ? $" WHERE mobile_no = @MobileNo " : $" AND mobile_no = @MobileNo "; parameters.Add(new SqlParameter("@MobileNo", mobileNo)); } if (status >= 0) { where += string.IsNullOrEmpty(where) ? $" WHERE status = @pStatus " : $" AND status = @pStatus "; parameters.Add(new SqlParameter("@pStatus", status)); } #endregion var sql = $"SELECT TOP {count} * FROM[dbo].[message_spool] {where} ORDER BY row_id"; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; var result = new List<MessageSpool>(); foreach (DataRow row in resultData.Rows) { var order = AppConverter.ToMessageSpool(row); result.Add(order); } return result; } public async Task<MessageSpool> GetSingleAsync(int id) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE row_id = @RowId "; parameters.Add(new SqlParameter("RowId", id)); } #endregion var sql = $"SELECT * FROM [dbo].[message_spool] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = AppConverter.ToMessageSpool(row); return order; } public async Task<int> Remove(int id) { var parameters = new List<SqlParameter>(); var idParameter = new SqlParameter(); idParameter.ParameterName = "@p_rowNo"; idParameter.SqlDbType = SqlDbType.Int; idParameter.Direction = ParameterDirection.Input; idParameter.Value = id; parameters.Add(idParameter); var resultParameter = new SqlParameter(); resultParameter.ParameterName = "@p_result"; resultParameter.SqlDbType = SqlDbType.Int; resultParameter.Direction = ParameterDirection.Output; parameters.Add(resultParameter); await _db.ExecuteStoredProcAsync("sp_MessageSpool_Remove", parameters); return Convert.ToInt32(resultParameter.Value); } } } <file_sep>/fourG.Infra/Utility/AppConverter.cs using fourG.Data; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace fourG.Infra.Utility { public class AppConverter { public static LteOrder ToLteOrder(DataRow row) { var order = new LteOrder(); order.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); order.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); order.IsExist = row["isexist"] == DBNull.Value ? false : Convert.ToBoolean(row["isexist"]); order.OrderType = row["order_type"] == DBNull.Value ? 0 : Convert.ToInt32(row["order_type"]); order.ExpiredOn = row["exp_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["exp_date"]); order.Postpaid = row["postpaid"] == DBNull.Value ? 0 : Convert.ToInt32(row["postpaid"]); order.IMSI = row["imsi"] == DBNull.Value ? string.Empty : Convert.ToString(row["imsi"]); order.IMSIPassword = row["imsi_pass"] == DBNull.Value ? string.Empty : Convert.ToString(row["imsi_pass"]); order.PackageId = row["pkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["pkg_id"]); order.AlterPackageId = row["alter_pkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["alter_pkg_id"]); order.PackageValidity = row["bkg_validity"] == DBNull.Value ? 0 : Convert.ToInt32(row["bkg_validity"]); order.OfferId = row["offer_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["offer_id"]); order.Status = row["STATUS"] == DBNull.Value ? 0 : Convert.ToInt32(row["STATUS"]); order.AAAStatus = row["AAA_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["AAA_status"]); order.PRLStatus = row["prl_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["prl_status"]); order.CRMStatus = row["crm_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["crm_status"]); order.HSSStatus = row["hss_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["hss_status"]); order.Channel = row["channel"] == DBNull.Value ? string.Empty : Convert.ToString(row["channel"]); order.CreatedOn = row["enter_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["enter_date"]); order.ClosedOn = row["close_time"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["close_time"]); order.Note = row["note"] == DBNull.Value ? string.Empty : Convert.ToString(row["note"]); return order; } public static LteOrderHistory ToLteOrderHistory(DataRow row) { var order = new LteOrderHistory(); order.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); order.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); order.IsExist = row["isexist"] == DBNull.Value ? false : Convert.ToBoolean(row["isexist"]); order.OrderType = row["order_type"] == DBNull.Value ? 0 : Convert.ToInt32(row["order_type"]); order.ExpiredOn = row["exp_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["exp_date"]); order.Postpaid = row["postpaid"] == DBNull.Value ? 0 : Convert.ToInt32(row["postpaid"]); order.IMSI = row["imsi"] == DBNull.Value ? string.Empty : Convert.ToString(row["imsi"]); order.IMSIPassword = row["imsi_pass"] == DBNull.Value ? string.Empty : Convert.ToString(row["imsi_pass"]); order.PackageId = row["pkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["pkg_id"]); order.AlterPackageId = row["alter_pkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["alter_pkg_id"]); order.PackageValidity = row["bkg_validity"] == DBNull.Value ? 0 : Convert.ToInt32(row["bkg_validity"]); order.OfferId = row["offer_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["offer_id"]); order.Status = row["STATUS"] == DBNull.Value ? 0 : Convert.ToInt32(row["STATUS"]); order.AAAStatus = row["AAA_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["AAA_status"]); order.PRLStatus = row["prl_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["prl_status"]); order.CRMStatus = row["crm_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["crm_status"]); order.HSSStatus = row["hss_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["hss_status"]); order.Channel = row["channel"] == DBNull.Value ? string.Empty : Convert.ToString(row["channel"]); order.CreatedOn = row["enter_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["enter_date"]); order.ClosedOn = row["close_time"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["close_time"]); order.Note = row["note"] == DBNull.Value ? string.Empty : Convert.ToString(row["note"]); return order; } public static MobileOffer ToMobileOffer(DataRow row) { var order = new MobileOffer(); order.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); order.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); order.OfferId = row["offer_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["offer_id"]); order.LastOperation = row["last_op"] == DBNull.Value ? 0 : Convert.ToInt32(row["last_op"]); order.OfferName = row["offer_name"] == DBNull.Value ? string.Empty : Convert.ToString(row["offer_name"]); order.CreatedOn = row["enter_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["enter_date"]); order.SubscribedOn = row["last_sub_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["last_sub_date"]); return order; } public static OperationLog ToOperationLog(DataRow row) { var result = new OperationLog(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.Result = row["result_msg"] == DBNull.Value ? string.Empty : Convert.ToString(row["result_msg"]); result.TransactionId = row["trans_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["trans_no"]); result.OperationCode = row["op_code"] == DBNull.Value ? string.Empty : Convert.ToString(row["op_code"]); result.CreatedOn = row["enter_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["enter_date"]); return result; } public static Product ToProduct(DataRow row) { var result = new Product(); result.Id = row["product_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["product_no"]); result.FirstId = row["product_id1"] == DBNull.Value ? string.Empty : Convert.ToString(row["product_id1"]); result.SecondId = row["product_id2"] == DBNull.Value ? string.Empty : Convert.ToString(row["product_id2"]); result.Name = row["product_name"] == DBNull.Value ? string.Empty : Convert.ToString(row["product_name"]); result.Fee = row["product_fee"] == DBNull.Value ? 0 : Convert.ToDouble(row["product_fee"]); result.Size = row["product_size"] == DBNull.Value ? 0 : Convert.ToDouble(row["product_size"]); result.Validity = row["product_validity"] == DBNull.Value ? 0 : Convert.ToInt32(row["product_validity"]); result.PrepaidOfferId = row["pre_offer_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["pre_offer_id"]); result.PostpaidOfferId = row["post_offer_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["post_offer_id"]); return result; } public static SubscriberExceedMaxValidity ToSubscriberExceedMaxValidity(DataRow row) { var result = new SubscriberExceedMaxValidity(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.PackageId = row["pkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["pkg_id"]); result.PackageName = "Unknown"; result.OperationType = row["op_type"] == DBNull.Value ? 0 : Convert.ToInt32(row["op_type"]); result.CreatedOn = row["enter_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["enter_date"]); return result; } public static Subscriber ToSubscriber(DataRow row) { var result = new Subscriber(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.IMSI = row["imsi"] == DBNull.Value ? string.Empty : Convert.ToString(row["imsi"]); result.RegisteredOn = row["reg_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["reg_date"]); result.ExpiredOn = row["exp_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["exp_date"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); result.LastPackageOn = row["last_bkg_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["last_bkg_date"]); result.LastPackageId = row["last_bkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["last_bkg_id"]); result.LastPackageName = "Unknown"; result.AAAStatus = row["aaa_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["aaa_status"]); result.HSSStatus = row["hss_status"] == DBNull.Value ? 0 : Convert.ToInt32(row["hss_status"]); return result; } public static SubscriberPackage ToSubscriberPackage(DataRow row) { var result = new SubscriberPackage(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.PackageId = row["bkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["bkg_id"]); result.PackageName = "N/A"; result.StartedOn = row["eff_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["eff_date"]); result.ExpiredOn = row["exp_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["exp_date"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); return result; } public static SubscriberPackageHistory ToSubscriberPackageHistory(DataRow row) { var result = new SubscriberPackageHistory(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.PackageId = row["bkg_id"] == DBNull.Value ? string.Empty : Convert.ToString(row["bkg_id"]); result.PackageName = "N/A"; result.StartedOn = row["eff_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["eff_date"]); result.ExpiredOn = row["exp_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["exp_date"]); result.DeactivatedOn = row["deactivate_date"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["deactivate_date"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); return result; } public static SMSReceiver ToSMSReceiver(DataRow row) { var result = new SMSReceiver(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.Message = row["message"] == DBNull.Value ? string.Empty : Convert.ToString(row["message"]); result.Shortcode = row["shortcode"] == DBNull.Value ? string.Empty : Convert.ToString(row["shortcode"]); result.CreatedOn = row["createdOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["createdOn"]); return result; } public static MessageSpool ToMessageSpool(DataRow row) { var result = new MessageSpool(); result.Id = row["row_id"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_id"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.Message = row["message"] == DBNull.Value ? string.Empty : Convert.ToString(row["message"]); result.Shortcode = row["shortcode"] == DBNull.Value ? string.Empty : Convert.ToString(row["shortcode"]); result.CreatedOn = row["createdOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["createdOn"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); return result; } public static MessageSpoolHistory ToMessageSpoolHistory(DataRow row) { var result = new MessageSpoolHistory(); result.Id = row["row_no"] == DBNull.Value ? 0 : Convert.ToInt32(row["row_no"]); result.MobileNo = row["mobile_no"] == DBNull.Value ? string.Empty : Convert.ToString(row["mobile_no"]); result.Message = row["message"] == DBNull.Value ? string.Empty : Convert.ToString(row["message"]); result.Shortcode = row["shortcode"] == DBNull.Value ? string.Empty : Convert.ToString(row["shortcode"]); result.CreatedOn = row["createdOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["createdOn"]); result.BackedupOn = row["backedOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["backedOn"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); return result; } public static AppRole ToAppRole(DataRow row) { var result = new AppRole(); result.Id = row["role_id"] == DBNull.Value ? 0 : Convert.ToInt32(row["role_id"]); result.Name = row["role_name"] == DBNull.Value ? string.Empty : Convert.ToString(row["role_name"]); result.CreatedOn = row["createdOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["createdOn"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); return result; } public static AppOperator ToAppOperator(DataRow row) { var result = new AppOperator(); result.Id = row["role_id"] == DBNull.Value ? 0 : Convert.ToInt32(row["role_id"]); result.Name = row["role_name"] == DBNull.Value ? string.Empty : Convert.ToString(row["role_name"]); result.Secret = row["op_pass"] == DBNull.Value ? string.Empty : Convert.ToString(row["op_pass"]); result.SecretKey = row["op_extra"] == DBNull.Value ? string.Empty : Convert.ToString(row["op_extra"]); result.Status = row["status"] == DBNull.Value ? 0 : Convert.ToInt32(row["status"]); result.Attempts = row["attempts"] == DBNull.Value ? 0 : Convert.ToInt32(row["attempts"]); result.CreatedOn = row["createdOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["createdOn"]); result.StatusChangedOn = row["statusChangedOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["statusChangedOn"]); result.LastLoggedOn = row["lastLoggedOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["lastLoggedOn"]); result.LockedTo = row["lockedOn"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(row["lockedOn"]); return result; } } } <file_sep>/fourG.Sms/SmscSettings.cs using System; using System.Collections.Generic; using System.Text; namespace fourG.Sms { public class SMSCReceiverSettings { public string Server { get; set; } public string Port { get; set; } public string SystemId { get; set; } public string Password { get; set; } public string Count { get; set; } public string Shortcode { get; set; } } public class SMSCSenderSettings { public string Server { get; set; } public string Port { get; set; } public string SystemId { get; set; } public string Password { get; set; } public string Count { get; set; } public string Shortcode { get; set; } } } <file_sep>/fourG.UI/Data/Dtos/LoginDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace fourG.UI.Data.Dtos { public class LoginDto { [Required(ErrorMessage = "يجب ادخال رمز المستخدم")] [StringLength(12, ErrorMessage ="اكبر طول لرمز المستخدم هو 12 حرف")] [MinLength(3, ErrorMessage ="رمز المستخدم اقل من المتوقع")] public string Id { get; set; } public string Name { get; set; } [Required(ErrorMessage = "يجب ادخال الرقم السري")] [StringLength(20, ErrorMessage = "اكبر طول للرقم السري هو 20 حرف")] [MinLength(6, ErrorMessage = "الرقم السري اقل من المتوقع")] public string Secret { get; set; } } } <file_sep>/fourG.Sms/frmMain.cs using fourG.Infra; using fourG.Infra.Interfaces; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace fourG.Sms { public partial class frmMain : Form { private int childFormNumber = 0; private readonly IConfiguration configuration; private readonly IAppDbContext _db; public frmMain(IConfiguration configuration, IAppDbContext db) { InitializeComponent(); this.configuration = configuration; this._db = db; } private void ShowNewForm(object sender, EventArgs e) { Form childForm = new Form(); childForm.MdiParent = this; childForm.Text = "Window " + childFormNumber++; childForm.Show(); } private async void ShowSettingsForm(object sender, EventArgs e) { if (IsFormAlreadyLoaded("frmSettings") == true) { return; } frmSettings frm = new frmSettings(configuration); frm.MdiParent = this; frm.Tag = "frmSettings"; frm.Text = "Settings"; frm.Show(); } private void ShowSMSCInterfaceForm(object sender, EventArgs e) { var frmTag = sender.ToString() == "Receiver" ? "frmSMSCInterfaceR" : "frmSMSCInterfaceS"; if (IsFormAlreadyLoaded(frmTag) == true) { return; } frmSMSCInterface frm = new frmSMSCInterface(configuration, sender.ToString(), sender.ToString().Substring(0,1), _db); frm.Tag = frmTag; frm.MdiParent = this; frm.Text = sender.ToString(); frm.Show(); } private void CloseAllForms(object sender, EventArgs e) { foreach (Form childForm in MdiChildren) { childForm.Close(); } } private void TailVertically(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileVertical); } private void TailHorizontally(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileHorizontal); } private bool IsFormAlreadyLoaded(string formToLoadName) { foreach (Form frmChild in this.MdiChildren) { if (frmChild.Tag.ToString() == formToLoadName) { frmChild.Activate(); return true; } } return false; } } } <file_sep>/fourG.Web/Data/Repos/SMSReceiverRepo.cs using fourG.Web; using fourG.Web.Data.Entities; using fourG.Web.Data.Interfaces; using fourG.Web.Data.Utility; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace fourG.Web.Data.Repo { public class SMSReceiverRepo { private readonly IAppDbContext _db; public SMSReceiverRepo(IAppDbContext db) { this._db = db; } public async Task<int> Create(SMSReceiver obj) { var parameters = new List<SqlParameter>(); var mobileNoParameter = new SqlParameter(); mobileNoParameter.ParameterName = "@p_mobile_no"; mobileNoParameter.SqlDbType = SqlDbType.VarChar; mobileNoParameter.Direction = ParameterDirection.Input; mobileNoParameter.Size = 50; mobileNoParameter.Value = obj.MobileNo; parameters.Add(mobileNoParameter); var messageParameter = new SqlParameter(); messageParameter.ParameterName = "@p_message"; messageParameter.SqlDbType = SqlDbType.NVarChar; messageParameter.Direction = ParameterDirection.Input; messageParameter.Size = 300; messageParameter.Value = obj.Message; parameters.Add(messageParameter); var shortcodeParameter = new SqlParameter(); shortcodeParameter.ParameterName = "@p_shortcode"; shortcodeParameter.SqlDbType = SqlDbType.VarChar; shortcodeParameter.Direction = ParameterDirection.Input; shortcodeParameter.Size = 50; shortcodeParameter.Value = obj.Shortcode; parameters.Add(shortcodeParameter); var resultParameter = new SqlParameter(); resultParameter.ParameterName = "@p_result"; resultParameter.SqlDbType = SqlDbType.Int; resultParameter.Direction = ParameterDirection.Output; parameters.Add(resultParameter); await _db.ExecuteStoredProcAsync("sp_smsReceiver_create", parameters); return Convert.ToInt32(resultParameter.Value); } public async Task<List<SMSReceiver>> GetListAsync(int id, string mobileNo) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE row_id = @RowId "; parameters.Add(new SqlParameter("RowId", id)); } if (!string.IsNullOrEmpty(mobileNo)) { where += string.IsNullOrEmpty(where) ? $" WHERE mobile_no = @MobileNo " : $" AND mobile_no = @MobileNo "; parameters.Add(new SqlParameter("MobileNo", mobileNo)); } #endregion var sql = $"SELECT * FROM [dbo].[sms_receiver] {where} ORDER BY row_id"; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; var result = new List<SMSReceiver>(); foreach (DataRow row in resultData.Rows) { var order = new AppConverter(_db).ToSMSReceiver(row); result.Add(order); } return result; } public async Task<SMSReceiver> GetSingleAsync(int id) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE row_id = @RowId "; parameters.Add(new SqlParameter("RowId", id)); } #endregion var sql = $"SELECT * FROM [dbo].[sms_receiver] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = new AppConverter(_db).ToSMSReceiver(row); return order; } } } <file_sep>/fourG.UI/Data/Entities/MobileOffer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Entities { public class MobileOffer { public int Id { get; set; } public string MobileNo { get; set; } public string OfferId { get; set; } public string OfferName { get; set; } public DateTime SubscribedOn { get; set; } public DateTime CreatedOn { get; set; } public int LastOperation { get; set; } } } <file_sep>/fourG.Data/OperationLog.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fourG.Data { public class OperationLog { public int Id { get; set; } public int TransactionId { get; set; } public string MobileNo { get; set; } public string OperationCode { get; set; } public string Result { get; set; } public DateTime CreatedOn { get; set; } } } <file_sep>/fourG.Infra/ProductRepo.cs using fourG.Data; using fourG.Infra.Interfaces; using fourG.Infra.Utility; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace fourG.Infra { public class ProductRepo { private readonly IAppDbContext _db; public ProductRepo(IAppDbContext db) { this._db = db; } public async Task<List<Product>> GetListAsync(int id, string firstId, string secondId) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE product_no = @ProductNo " ; parameters.Add(new SqlParameter("ProductNo", id)); } if (!string.IsNullOrEmpty(firstId)) { where += string.IsNullOrEmpty(where) ? $" WHERE product_id1 = @firstId " : $" AND product_id1 = @firstId "; parameters.Add(new SqlParameter("firstId", firstId)); } if (!string.IsNullOrEmpty(secondId)) { where += string.IsNullOrEmpty(where) ? $" WHERE product_id2 = @secondId " : $" AND product_id2 = @secondId "; parameters.Add(new SqlParameter("secondId", secondId)); } #endregion var sql = $"SELECT * FROM [dbo].[products] {where} ORDER BY product_no"; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; var result = new List<Product>(); foreach (DataRow row in resultData.Rows) { var order = AppConverter.ToProduct(row); result.Add(order); } return result; } public async Task<Product> GetSingleAsync(int id) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (id > 0) { where = $" WHERE product_no = @ProductNo "; parameters.Add(new SqlParameter("ProductNo", id)); } #endregion var sql = $"SELECT * FROM [dbo].[products] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = AppConverter.ToProduct(row); return order; } } } <file_sep>/fourG.UI/Data/Interfaces/IAppOperator.cs using fourG.UI; using fourG.UI.Data.Entities; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace fourG.UI.Data.Interfaces { public interface IAppOperator { Task<List<AppOperator>> GetListAsync(int status, int role); Task<AppOperator> GetSingleAsync(string id); string GetLoggedOperatorId(HttpContext httpContext); int GetLoggedOperatorRoleId(HttpContext httpContext); Task<AppOperator> GetLoggedOperatorAsync(HttpContext httpContext); Task<bool> IncreaseWrongPwdAttempts(string operatorId, int wrongAttempts); Task<bool> PreSuccessLogin(string operatorId); Task<bool> LoginAsync(string operatodId, string password, string secretKey); IEnumerable<Claim> GetUserClaims(AppOperator user); } } <file_sep>/fourG.UI/Data/Dtos/SubscriberSearchDto.cs using fourG.UI.Data.Entities; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace fourG.UI.Data.Dtos { public class SubscriberSearchDto { public SubscriberSearchDto() { Subscribers = new List<Subscriber>(); } [Required(ErrorMessage = "يجب ادخال رقم المشترك")] [StringLength(9, ErrorMessage ="اكبر طول رقم المشترك هو 9 حرف")] [MinLength(9, ErrorMessage ="رقم المشترك اقل من المتوقع")] [MaxLength(9, ErrorMessage = "رقم المشترك اكبر من المتوقع")] public string MobileNo { get; set; } public List<Subscriber> Subscribers { get; set; } } } <file_sep>/fourG.UI/Data/Utility/CustomAuthenticationStateProvider.cs using Blazored.SessionStorage; using fourG.UI.Data.Entities; using fourG.UI.Data.Interfaces; using Microsoft.AspNetCore.Components.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace fourG.UI.Data.Utility { public class CustomAuthenticationStateProvider : AuthenticationStateProvider { private readonly ISessionStorageService _sessionStorageService; private readonly IAppOperator _appOperator; public CustomAuthenticationStateProvider(ISessionStorageService sessionStorageService, IAppOperator appOperator) { this._sessionStorageService = sessionStorageService; this._appOperator = appOperator; } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var userId = await _sessionStorageService.GetItemAsStringAsync("OperatorId"); var currentOperator = await _appOperator.GetSingleAsync(userId); ClaimsIdentity identity; if (currentOperator != null) { identity = GetClaimsIdentity(currentOperator); } else { identity = new ClaimsIdentity(); } //var identity = new ClaimsIdentity(new[] //{ // new Claim(ClaimTypes.Name ,"mustafa"), //}, "apiAyth"); var user = new ClaimsPrincipal(identity); return await Task.FromResult(new AuthenticationState(user)); } public async Task MarkUserAsAuthenticated(AppOperator user) { await _sessionStorageService.SetItemAsStringAsync("OperatorId", user.Id); var identity = GetClaimsIdentity(user); var claimsPrincipal = new ClaimsPrincipal(identity); NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal))); } public async Task MarkUserAsLoggedOut() { await _sessionStorageService.RemoveItemAsync("OperatorId"); var identity = new ClaimsIdentity(); var user = new ClaimsPrincipal(identity); NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user))); } private ClaimsIdentity GetClaimsIdentity(AppOperator user) { var claimsIdentity = new ClaimsIdentity(); if (user.Id != null) { claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.Name), new Claim(ClaimTypes.Role, user.Role.Name), new Claim(ClaimTypes.GivenName, user.Role.Id.ToString()) }, "apiauth_type"); } return claimsIdentity; } } } <file_sep>/fourG.Infra/AppOperatorRepo.cs using fourG.Data; using fourG.Infra.Interfaces; using fourG.Infra.Utility; using Microsoft.AspNetCore.Http; using System; using System.Linq; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace fourG.Infra { public class AppOperatorRepo : IAppOperator { private readonly IAppDbContext _db; public AppOperatorRepo(IAppDbContext db) { this._db = db; } public string GetLoggedOperatorId(HttpContext httpContext) { if (!httpContext.User.Identity.IsAuthenticated) return "-1"; Claim claim = httpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (claim == null) return "-1"; string currectOperatorId = claim.Value; //if (!int.TryParse(claim.Value, out currentUserId)) // return "-1"; return currectOperatorId; } public int GetLoggedOperatorRoleId(HttpContext httpContext) { if (!httpContext.User.Identity.IsAuthenticated) return -1; Claim claim = httpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role); if (claim == null) return -1; int currentRoleId = int.Parse(claim.Value); //if (!int.TryParse(claim.Value, out currentUserId)) // return "-1"; return currentRoleId; } public async Task<List<AppOperator>> GetListAsync(int status, int role) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (status >= 0) { where = $" WHERE status = @OpStatus "; parameters.Add(new SqlParameter("@OpStatus", status)); } if (role >= 0) { where += string.IsNullOrEmpty(where) ? $" WHERE op_role_id = @RoleId " : $" AND op_role_id = @RoleId "; parameters.Add(new SqlParameter("@RoleId", role)); } #endregion var sql = $"SELECT * FROM[dbo].[operators] {where} ORDER BY op_id"; var resultData = await _db.GetDataAsync(sql, null); if (resultData == null) return null; var result = new List<AppOperator>(); foreach (DataRow row in resultData.Rows) { var order = AppConverter.ToAppOperator(row); result.Add(order); } return result; } public async Task<AppOperator> GetSingleAsync(string id) { var where = string.Empty; var parameters = new List<SqlParameter>(); #region Build Where Clause if (!string.IsNullOrEmpty(id)) { where = $" WHERE op_id = @RowId "; parameters.Add(new SqlParameter("RowId", id)); } #endregion var sql = $"SELECT * FROM [dbo].[operators] {where} "; var resultData = await _db.GetDataAsync(sql, parameters); if (resultData == null) return null; DataRow row = resultData.Rows[0]; var order = AppConverter.ToAppOperator(row); return order; } public async Task<AppOperator> GetLoggedOperatorAsync(HttpContext httpContext) { var opId = GetLoggedOperatorId(httpContext); if (opId == "-1") return null; return await GetSingleAsync(opId); } } } <file_sep>/fourG.Sms/frmSMSCInterface.cs using ArdanStudios.Common.SmppClient; using fourG.Data; using fourG.Infra; using fourG.Infra.Interfaces; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace fourG.Sms { public partial class frmSMSCInterface : Form { private readonly IConfiguration _configuration; private readonly string _interfaceType; private readonly IAppDbContext _db; private readonly SMSCReceiverSettings receiverSettings; private readonly SMSCSenderSettings senderSettings; private string SMSCShortcode; private string SMSCServer; private int SMSCPort; private string SMSCSystemId; private string SMSCPassword; private int SMSCInterfaceCount; private static Timer timer1; private bool isReadyToLoadMessagesFromDb = true; ESMEManager connectionManager; public frmSMSCInterface(IConfiguration configuration, string title, string interfaceType, IAppDbContext db) { InitializeComponent(); _configuration = configuration; this._interfaceType = interfaceType; this._db = db; receiverSettings = new SMSCReceiverSettings(); senderSettings = new SMSCSenderSettings(); configuration.GetSection("SmscSettings:Receiver").Bind(receiverSettings); configuration.GetSection("SmscSettings:Sender").Bind(senderSettings); lblTitle.Text = title; if (interfaceType == "R") { SMSCServer = receiverSettings.Server; SMSCPort = int.Parse(receiverSettings.Port); SMSCSystemId = receiverSettings.SystemId; SMSCPassword = receiverSettings.Password; SMSCInterfaceCount = int.Parse(receiverSettings.Count); SMSCShortcode = receiverSettings.Shortcode; btnStartSend.Visible = false; } if (interfaceType == "S") { SMSCServer = senderSettings.Server; SMSCPort = int.Parse(senderSettings.Port); SMSCSystemId = senderSettings.SystemId; SMSCPassword = senderSettings.Password; SMSCInterfaceCount = int.Parse(senderSettings.Count); SMSCShortcode = senderSettings.Shortcode; btnStartSend.Visible = true; } lvLOG .GetType() .GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) .SetValue(lvLOG, true, null); } private void PrepareLogListView() { lvLOG.View = View.Details; lvLOG.GridLines = true; lvLOG.FullRowSelect = true; //Add column header lvLOG.Columns.Add("Mobile", 200, HorizontalAlignment.Center); lvLOG.Columns.Add("Message", 800, HorizontalAlignment.Left); lvLOG.Columns.Add("Type", 50, HorizontalAlignment.Center); lvLOG.Columns.Add("Short Code", 150, HorizontalAlignment.Center); lvLOG.Columns.Add("Time", 240, HorizontalAlignment.Center); lvLOG.Columns.Add("Event", 140, HorizontalAlignment.Left); } private void button3_Click(object sender, EventArgs e) { connectionManager = new ESMEManager("SMS", SMSCShortcode, new ESMEManager.CONNECTION_EVENT_HANDLER(connectionEventHandler), new ESMEManager.RECEIVED_MESSAGE_HANDLER(receivedMessageHandler), new ESMEManager.RECEIVED_GENERICNACK_HANDLER(receivedGenricnackHandler), new ESMEManager.SUBMIT_MESSAGE_HANDLER(submitMessageHandler), new ESMEManager.QUERY_MESSAGE_HANDLER(queryMessageHandler), new ESMEManager.LOG_EVENT_HANDLER(logEventHandler), new ESMEManager.PDU_DETAILS_EVENT_HANDLER(pduDetailsEventHandler)); connectionManager.AddConnections(SMSCInterfaceCount, _interfaceType == "R" ? ConnectionModes.Receiver : ConnectionModes.Transmitter, SMSCServer, SMSCPort, SMSCSystemId, SMSCPassword, "R", DataCodings.Default); } private void submitMessageHandler(string logKey, int sequence, string messageId) { if (chShowlogs.Checked) { AddLog(logKey, "sequence=" + sequence.ToString() + "|messageId=" + messageId, "SMT", SMSCShortcode, "SubmitMessageHandler", Color.Gray); } } private void logEventHandler(LogEventNotificationTypes logEventNotificationType, string logKey, string shortLongCode, string message) { if (chShowlogs.Checked) { AddLog(logKey, "log Type=" + logEventNotificationType.ToString() + "|message=" + message , "LOG", shortLongCode, "LogEventHandler", Color.Gray); } } private Guid? pduDetailsEventHandler(string logKey, PduDirectionTypes pduDirectionType, Header pdu, List<PduPropertyDetail> details) { throw new NotImplementedException(); } private void queryMessageHandler(string logKey, int sequence, string messageId, DateTime finalDate, int messageState, long errorCode) { if (chShowlogs.Checked) { AddLog(logKey, "sequence=" + sequence.ToString() + "|messageId=" + messageId + "|finalDate=" + finalDate.ToString("yyyyMMddHmmss") + "|messageState=" + messageState.ToString() + "|errorCode=" + errorCode.ToString() , "QRY", SMSCShortcode, "QueryMessageHandler", Color.Gray); } } private void receivedGenricnackHandler(string logKey, int sequence) { if (chShowlogs.Checked) { AddLog(logKey, "sequence=" + sequence.ToString(), "NCK", SMSCShortcode, "ReceivedGenericNackHandler", Color.Gray); } } private async void receivedMessageHandler(string logKey, string serviceType, Ton sourceTon, Npi sourceNpi, string shortLongCode, DateTime dateReceived, string phoneNumber, DataCodings dataCoding, string message) { await AddLogAsync(phoneNumber, message, "IN", shortLongCode, "ReceivedMessageHandler", Color.Blue); if (!string.IsNullOrEmpty(message)) { var receivedSMS = new SMSReceiver { MobileNo = phoneNumber, Shortcode = shortLongCode, Message = message }; var result = await new SMSReceiverRepo(_db).Create(receivedSMS); } } private void connectionEventHandler(string logKey, ConnectionEventTypes connectionEventType, string message) { if (chShowlogs.Checked) { AddLog(logKey, connectionEventType.ToString() + " " + message, "CON", SMSCShortcode, "ConnectionEvent", Color.Gray); } } private void frmSMSCInterface_Load(object sender, EventArgs e) { PrepareLogListView(); } private void AddLog(string mobileno, string MessageValue, string TypeValue, string shortcode, string appEvent, Color forecolor) { //Add items in the listview string[] arr = new string[6]; ListViewItem itm; //Add first item arr[0] = mobileno; arr[1] = MessageValue; arr[2] = TypeValue; arr[3] = shortcode; arr[4] = DateTime.Now.ToString("ss:mm:H dd/MM/yyyy"); arr[5] = appEvent; itm = new ListViewItem(arr); itm.ForeColor = forecolor; itm.ImageIndex = 1; //lvLOG.Items.Add(itm); if (lvLOG.InvokeRequired) lvLOG.Invoke((MethodInvoker)delegate () { lvLOG.Items.Add(itm); lvLOG.EnsureVisible(lvLOG.Items.Count - 1); if (lvLOG.Items.Count > 90) { lvLOG.Items.Clear(); } }); } private async Task AddLogAsync(string mobileno, string MessageValue, string TypeValue, string shortcode, string appEvent, Color forecolor) { //Add items in the listview string[] arr = new string[6]; ListViewItem itm; //Add first item arr[0] = mobileno; arr[1] = MessageValue; arr[2] = TypeValue; arr[3] = shortcode; arr[4] = DateTime.Now.ToString("ss:mm:H dd/MM/yyyy"); arr[5] = appEvent; itm = new ListViewItem(arr); itm.ForeColor = forecolor; itm.ImageIndex = 1; //lvLOG.Items.Add(itm); await Task.Run(() => { if (lvLOG.InvokeRequired) lvLOG.Invoke((MethodInvoker)delegate () { lvLOG.Items.Add(itm); lvLOG.EnsureVisible(lvLOG.Items.Count - 1); if (lvLOG.Items.Count > 90) { lvLOG.Items.Clear(); } }); }); } private void btnClear_Click(object sender, EventArgs e) { lvLOG.Items.Clear(); } private void btnStartSend_Click(object sender, EventArgs e) { AddLogAsync("SYS", "Start send", "", "", "", Color.Purple); timer1 = new Timer(); timer1.Tick += (async (sender, e) => { await Task.Run(() => { if (isReadyToLoadMessagesFromDb) { SendGeneratedMessages(); } }); }); timer1.Interval = 5000; timer1.Start(); } private async void SendGeneratedMessages() { int sendResult = 0; isReadyToLoadMessagesFromDb = false; await AddLogAsync("SYS", "Try to load messages from database", "", "", "Load Messages", Color.Purple); var messages = await new MessageSpoolRepo(_db).GetListAsync(0, string.Empty, 0);// get messages from database if (messages != null && messages.Count > 0) { await AddLogAsync("SYS", $"Load {messages.Count} messages", "", "", "Load Messages", Color.Purple); foreach (var msg in messages) { if (lblSendTime.InvokeRequired) { Invoke((MethodInvoker)delegate () { var cnt = int.Parse(lblSendTime.Text); lblSendTime.Text = (++cnt).ToString(); }); } SubmitSm submitSm = null; SubmitSmResp submitSmResp = null; List<SubmitSm> submitSmList = null; List<SubmitSmResp> submitSmRespList = null; if (msg.Message.Length <= 70) { sendResult = connectionManager.SendMessage(msg.MobileNo, null, Ton.Unknown, Npi.Unknown, DataCodings.UCS2 , DataCodings.UCS2, msg.Message, out submitSm, out submitSmResp); } else { sendResult = connectionManager.SendMessageLarge(msg.MobileNo, null, Ton.Unknown, Npi.Unknown, DataCodings.UCS2 , DataCodings.UCS2, msg.Message, out submitSmList, out submitSmRespList); } AddLog(msg.MobileNo, msg.Message, "OUT", SMSCShortcode, (sendResult == 0 ? "Success" : "Fail"), (sendResult == 0 ? Color.Black : Color.Red)); if (sendResult == 0) { await new MessageSpoolRepo(_db).Remove(msg.Id); } } } else { AddLogAsync("SYS", "No pending messages", "", "", "", Color.Purple); } isReadyToLoadMessagesFromDb = true; } private void btnStopSend_Click(object sender, EventArgs e) { timer1.Stop(); isReadyToLoadMessagesFromDb = true; AddLogAsync("SYS", "Stop sending", "", "", "", Color.Purple); } } } <file_sep>/fourG.UI/Data/Utility/AppSecurity.cs using Microsoft.AspNetCore.Cryptography.KeyDerivation; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; namespace fourG.UI.Data.Utility { public static class Pbkdf2Hasher { public static string ComputeHash(string password, byte[] salt) { return Convert.ToBase64String( KeyDerivation.Pbkdf2( password: <PASSWORD>, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, numBytesRequested: 256 / 8 ) ); } public static byte[] GenerateRandomSalt() { byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(salt); return salt; } } public static class AppSecurity { public static string HowMuchLeftTime(DateTime futime) { string timemessage = string.Empty; double seconds = (futime - DateTime.Now).TotalSeconds; TimeSpan time = TimeSpan.FromSeconds(seconds); if (time.Hours > 0) { if (time.Hours > 2 && time.Hours < 11) { timemessage = time.Hours.ToString() + " ساعات "; } else if (time.Hours == 1) { timemessage = " ساعة "; } else if (time.Hours == 2) { timemessage = " ساعتين "; } else { timemessage = time.Hours.ToString() + " ساعة "; } } if (time.Minutes > 0) { if (time.Minutes > 2 && time.Minutes < 11) { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " و " + time.Minutes.ToString() + " دقائق "; } else { timemessage = time.Minutes.ToString() + " دقائق "; } } else if (time.Minutes == 1) { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " و دقيقة"; } else { timemessage = " دقيقة "; } } else if (time.Minutes == 2) { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " ودقيقتين "; } else { timemessage = " دقيقتين "; } } else { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " و " + time.Minutes.ToString() + " دقيقة "; } else { timemessage = time.Minutes.ToString() + " دقيقة "; } } } if (time.Seconds > 0) { if (time.Seconds > 2 && time.Seconds < 11) { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " و " + time.Seconds.ToString() + " ثواني "; } else { timemessage = time.Seconds.ToString() + " ثواني "; } } else if (time.Seconds == 1) { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " وثانية "; } else { timemessage = " ثانية "; } } else if (time.Seconds == 2) { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " وثانيتين "; } else { timemessage = " ثانيتين "; } } else { if (!string.IsNullOrEmpty(timemessage)) { timemessage += " و " + time.Seconds.ToString() + " ثانية "; } else { timemessage = time.Seconds.ToString() + " ثانية "; } } } return timemessage; } } }
b327f9f476e1b7cdb300df5123cb57697b99e9de
[ "C#" ]
30
C#
mustafabeshr/fourG.UI
bacc0f0c56588874d0a53640297b0fe7e3684fd6
0b4f357b154a8ef22269e4cdf0fc08c3c65e4f6d
refs/heads/master
<file_sep>/* This code is based off code by <NAME>, you can see the original at http://atulbhats.com/terminal */ /* However there are a lot of changes and cleanups to make this work with wordpress with dynamic commands */ /* Allowing you to hopefully use Wordpress as you feel like it and this should dynamically work with it */ /* TODO: Remove all traces of JQuery as it'd be one less dependency */ /* TODO: Theming? */ /* TODO: Setup posts to be a directory */ /* Maybe make this DOS themed? */ var $history = new Array(); var $startup = [ 'Starting SD-DOS...', '', 'This driver provided by Oak Technology. Inc..', 'OTI-91X ATAPI CD-ROM device driver, Rev D91XV352', '(C)Copyright Oak Technology Inc. 1987-1997', ' Device Name : MSCD0001', ' Transfer Mode : Programmed I/O', ' Number of drives : 1', '', 'MSCDEX Version 2.23', 'Copyright (C) Microsoft Corp. 1986-1993. All rights reserved.', ' Drive D: = Driver MSCD0001 unit 0', '', 'CPUidle for DOS V2.10 [Build 0077]', 'Copyright (C) by <NAME>, 1998.', '', 'DETECTING...', '[Processor]: Unknown Intel.', '[Power/Man]: APM V1.2 [Enabled].', '[Op/System]: SD-DOS V6.22 [Standard].', '[32-bit mode]: 32-bit VCPI interface.', '', 'DOSidle installed successfully.', '' ]; var $commands = [ {cmd: 'help', hidden: false, type: 'function', output: show_help, help: 'Lists all available commands'}, {cmd: 'cls', hidden: false, type: 'function', output: clear_screen, help: 'Clear the screen'}, {cmd: 'dir', hidden: false, type: 'print', output: '', help: 'Show directories or files in current directory'}, {cmd: 'date', hidden: false, type: 'function', output: show_date, help: 'Display the current date and time'}, {cmd: 'type', hidden: false, type: 'print', output: '', help: 'Display a given file'}, {cmd: 'xyzzy', hidden: true, type: 'print', output: 'Nothing happens', help: 'Nothing happens'} ]; function hidedefault() { $('.defaulttext').hide(); } function showdefault() { $('.defaulttext').show(); } function find_tab_completed_command(command) { if (!command) return command; /* Loop through the list of commands and find if there is enough information for a single match */ var results = []; for (var i = 0; i < $commands.length; i ++) { cmd = $commands[i]; if (cmd.cmd.startsWith(command) && cmd.hidden == false) { results.push(cmd.cmd); } } return {command: command, results: results}; } function clear_screen(parameters) { $line=0; $('.line').remove(); $('.commandline').remove(); return ''; } function print_parameters(parameters) { return parameters.join("&#09;"); } function show_help(parameters) { if (parameters.length == 0) { // Show all commands var print = ''; for (var i = 0; i < $commands.length; i ++) { cmd = $commands[i]; if (cmd.hidden == false) { print += cmd.cmd + "&#09;"; } } return print; } var help_command = parameters[0]; for (var i = 0; i < $commands.length; i ++) { cmd = $commands[i]; if (cmd.hidden == false && cmd.cmd == help_command) { return cmd.help; } } return "No help found for this command"; } function format_date(date) { var dayNames = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]; var dayIndex = date.getDay(); var day = date.getDate(); var month = date.getMonth(); var year = date.getFullYear(); return dayNames[dayIndex] + ' ' + day + '/' + month + '/' + year; } function show_date(parameters) { var date = new Date(); return "Current date is " + format_date(date); } function outputText(outputText) { $('#defaultline').before('<div class="line" id="line'+$line+'"></div>'); $('#line'+$line).html(outputText.replace(/ /g, '&nbsp;')); $('#commandcontainer').text(""); $('#actualinput').val(""); $line++; $('#actualinput').focus(); $(document).scrollTop($(document).height()); } function runcommand($command) { unnull(); $command = $command.toLowerCase(); $command2=$command; rehistory($command); $history[$z]=$command; $z++; $x=$z; // } $('#defaultline').before('<div class="commandline" id="commandline'+$line+'"><span class="defaulttext">C:\\></span>'+$command2+'</div>'); var given_commands = $command.split(" "); var command = given_commands[0]; var parameters = []; if (given_commands.length > 1) { parameters = given_commands.slice(1, given_commands.length); } var found_command = false; for (var i = 0; i < $commands.length; i ++) { cmd = $commands[i]; if (cmd.cmd == command) { found_command = true; // Found a matching command, lets action it. if (cmd.type == 'function') { var fn = cmd.output; $html = fn(parameters); } else if (cmd.type == 'print') { $html = cmd.output; } } } if (!found_command) { $html="\'"+$command+"\' Is not a known Command. But that might change the next time you are here. Use '<b>help</b>' for the list of available commands"; } outputText($html); } function unnull(){ for($i=0;$i<$history.length;$i++){ if($history[$i]=="" || $history[$i]==null || $history[$i]==undefined ){ for($j=$i;$j<$history.length;$j++){ $history[$j]=$history[$j+1]; } $z--; } } $z=$history.length; } function rehistory($cmd){ if($history.indexOf($cmd)>=0){ for($i=$history.indexOf($cmd);$i<$history.length;$i++){ $history[$i]=$history[$i+1]; } $z--; } } $(document).ready(function() { $('#introdiv').html(''); $line=0; $z=0; $x=0; $('#actualinput').focus(); hidedefault(); $('.cursor').css('color','rgb(238, 238, 238)'); setInterval(function(){ blinkcursor(); },560); function blinkcursor(){ $bg=$('.cursor').css('color'); if($bg=='rgb(238, 238, 238)'){ $('.cursor').css('color','transparent'); } else $('.cursor').css('color','rgb(238, 238, 238)'); } var interval = setInterval(function(){ updateIntro(); }, 560); function updateIntro() { if ($line >= $startup.length) { clearInterval(interval); showdefault(); return; } outputText($startup[$line]+"<br/>"); } $(document).bind('keyup', function(e) { $existing=$('#commandcontainer').text(); if(e.which==38){ if($x>0){ $('#actualinput').val($history[$x-1]); $('#commandcontainer').text($history[$x-1]); $x--; if($x<0) $x=0; } if($x<0){ return false; } } else if(e.which==40){ if($x>=0){ $('#commandcontainer').text($history[$x+1]); $('#actualinput').val($history[$x+1]); $x++; } if($x>$z){ return false; } } if(e.which==13){ runcommand($existing); $('#actualinput').focus(); } else{ $type=true; } }); $(document).bind('keydown', function(e) { var existing = $('#commandcontainer').text(); var code = e.keyCode || e.which; if (code == '9') { var results = find_tab_completed_command(existing); if (results.results.length > 1) { $('#defaultline').before('<div class="commandline" id="commandline'+$line+'"><span class="defaulttext">C:\\></span>'+results.command+'</div>'); outputText(results.results.join("&#09;")); } else { $('#actualinput').val(results.command); if (results.results.length == 1) { $('#actualinput').val(results.results[0]); } } return false; } }); $('#actualinput').keyup(function(e){ if(e.which==8){ $exist=$('#commandcontainer').text(); /*delete pressed */ e.preventDefault(); /*alert('del');*/ $c=$exist.length-1; $('#commandcontainer').text($exist.slice(0,$c)); } else{ /*alert("pressed : "+e.which);*/ $('#commandcontainer').text($(this).val()); } }); $('body').click(function(){ $('body').scrollTop($(window).height()); }); $(document).on("tap", function(e) { $('#actualinput').focus(); }); $(document).keydown(function(e) { $('#actualinput').focus(); }); });<file_sep># terminal-wordpress-theme CLI Terminal Theme for Wordpress There is still so much to do here in regards to this. However https://thispageisblank.net/ shows off what this can do. <file_sep><!DOCTYPE HTML> <html lang="en"> <head> <title><?php echo get_bloginfo( 'name' ); ?></title> <meta charset="utf-8"> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="<?php echo get_bloginfo( 'name' ); ?>" /> <meta property="og:description" content="<?php echo get_bloginfo( 'description' ); ?>" /> <meta property="og:url" content="https://thispageisblank.net/" /> <meta property="og:keywords" content="Code, Command Line, Projects" /> <meta property="og:site_name" content="This Page is Blank" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="keywords" content="Code, Command Line, Projects"> <meta name="description" content="<?php echo get_bloginfo( 'description' ); ?>"> <meta property="og:image" content="favicon.ico" /> <meta name="robots" content="index,follow"> <link href='https://fonts.googleapis.com/css?family=VT323' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> /* Turn this into proper ajax requests */ var pages = []; <?php $pages = get_pages(); foreach ($pages as $key => $page) { ?> pages[<?php echo $key; ?>] = {command: "<?php echo $page->post_name; ?>", title: "<?php echo $page->post_title; ?>", page: "<?php echo $page->post_content; ?>"}; <?php } ?> </script> <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/terminal.js"></script> <link rel='stylesheet' href='<?php bloginfo('template_directory'); ?>/style.css' type='text/css' media='all' /> <script> $(document).on('click','#defaultline', function() { $('#actualinput').focus(); }); $(document).on('tap','#defaultline', function() { $('#actualinput').focus(); }); </script> <?php wp_head(); ?> </head> <body> <noscript> <div class="line">It looks like javascript has been disabled on your browser. This website runs on javascript for user experience. Please enable it and refresh the website.</div><br> </noscript> <div id="introdiv"> <span id="commandcontainer">There have been issues with the scripts required. Please refresh the browser to try again.</span> </div> <div id="commands"> <div id="defaultline"> <span class="defaulttext">C:\></span><span id="commandcontainer"></span><span class="cursor">_</span><input type="text" id="actualinput"> </div> </div> </body> </html>
7f6bcdccbb7fc0c7d107d36933fc9846b27ee882
[ "JavaScript", "PHP", "Markdown" ]
3
JavaScript
shockdesign/terminal-wordpress-theme
424a27ebb54535134cb2f6c83953b7344e0357eb
9521a9a85afe6fb8e981530b421028f48f267a03
refs/heads/master
<file_sep>""" __author__ = "<NAME>" This is a Disney trivia game. """ # The basic outline of the game is from a Youtube video # https://www.youtube.com/watch?v=l90vKQMDHPU&t=741s print("Hello! Welcome to this Disney Trivia Game!") print("Test your knowledge about all things Disney!") print(10 ** 2) # Instructions for the player. print("INSTRUCTIONS") print("Please enter all your answers in lowercase letters when necessary.") print("Enter your answers using numbers when necessary.") print("Have fun!") print("*******************************************************************") # Only works if the answer is lowercase. # This won't go away until the user inputs y. question = input("Do you want to play? [Y/N] ") while question == "n": print("Wrong answer. Try again") question = input("Do you want to play? [Y/N] ") if question == "y": print("Let's begin!") def win(): """ This is a message for the player at the end of the game based on if they answered all the questions correctly. :return: """ if q1 == "f" and answer == 1955 and answer2 == 28: print("Congratulations! You answered all of the questions correctly!") else: print("You did not get all the questions correct. :( ") print("Just keep swimming and you'll get it next time!") # Part of tis code is from https://www.101computing.net/number-only/ def q2(question): """ This is the second question of the game. :return: """ while True: try: q2 = int(input("2. What year did Disneyland open? ")) except ValueError: print("Not an integer. Try again.") else: return q2 # Part of this code is from https://www.101computing.net/number-only/ def q3(question): """ This is the third question of the game. :return: """ while True: try: q3 = int(input("3. What is Space Mountain's top speed? ")) except ValueError: print("Not an integer. Try again.") else: return q3 q1 = input("1. <NAME> and the Seven Dwarves was Walt Disney's " "favorite movie. [T/F] ") if q1 == "t": print("No, the correct answer is Dumbo.") if q1 == "f": print("Correct! Walt Disney's favorite movie was Dumbo.") answer = q2("2. What year did Disneyland open?") if answer == 1955: print("Hot dog!") else: print("Sorry, the correct answer is 1955.") answer2 = q3("3. What is Space Mountain's top speed?") if answer2 == 28: print("Hakuna matata!") else: print("No, the correct answer is 28mph.") # This is where the player's message comes up win() # This prints the number of smiley faces the user inputs. # It also prints a sad face if the user inputs zero. questions_correct = int(input("How many questions did you get correct? ")) for row in range(questions_correct): print(":)" + " ", end=" ") if questions_correct == 0: print(":(")
8b9b44c266151b3e392da94e80eb4684810cd1a8
[ "Python" ]
1
Python
stephaniefwagley/integration-project
eb31a3257e23905a0b2f4927e5556366de4e0259
575b2102900f77e7e14e63b658678701ae2bcf94
refs/heads/master
<file_sep># syncmer A synchronized web based timer, that can be shared via a link. View Live Version: [Click here](https://pavittarx.github.io/syncmer) ## Developer Docs ![module description](docs/infographic.jpg) ### utils.js > getTime() It returns current local time of a given timezone. Type: JSON Object > getLocalTime() It returns local time for current location. It does not use local system time for accuracy purposes. Type: JSON Object > getParams() It returns parameters encoded in URL. It is used to generate an already created timer. > convertU2Js() It converts Unix timestamp to Javascript Timestamp. > convertJs2U() It converts Javascript timestamp to Unix Timestamp. --- ### timer.js #### **Module: Timer** > DATA Object ```js timer.data = { days: 0, hours: 0, minutes: 0, seconds: 0, values: { difference: 0, current: 0, percentage: 100 } ``` The data object holds the values for given time. These values change with context of operation. The sub object `values` holds * difference - It is number of seconds left for timer to expire. * current - It contains current Unix timestamp. * percentage - The percentage of timer is left since last reload. > create() It is the driver module for creating a timer. > clock() It is the driver module for generating a timer. The timer is regenerated each time the page is reloaded. It does not affect the timer, the timer expires when it is supposed to. #### **Module: Helper** > helper.create.validate() It validates values being input by the user while creating a timer. > helper.create.getTimestampDifference() It gets difference in Timestamp when the timer expires. The timestamp is a UNIX Timestamp > helper.clock.calcDifference() It returns difference between current time & when the timer expires. The difference is a UNIX timestamp. > helper.clock.generate() It generates and returns a timer object from given timestamp (UNIX) difference. > helper.clock.update() It updates the timer object every second. > helper.clock.inject() It injects the values from timer object into the application UI. > helper.clock.push() It pushes the timer values to [timer.data](###_timer.js ) object. > helper.clock.convert() It converts time values to 00, 01, 02 format. <file_sep>### Errors > UI Fix * Loading Animation * Timer Expiry Link Fix > Message When timer Expires ## Features * New Timer Link (below clock) * Desktop Notifications Fix * auto start clock once the timer is created * Fix Expiry Link & Main Link for Github Pages * Fix Loading Gif<file_sep>/* A Global Variabale used for displaying messages*/ let message = document.getElementById('timer-message'); /* Driver Module - It runds the code */ async function renderView() { let params = getParams(); let create = document.getElementById('timer-create'); let clock = document.getElementById('timer-clock'); if (Object.values(params).length == 0) { create.style.display = "block"; } else { if (params.stamp == undefined || params.tz == undefined) { create.className = "displayOn"; } else if (isNaN(params.stamp) || !isNaN(params.tz) || params.stamp < (await getTime(params.tz)).unixtime) { message.className = "displayOn"; message.innerHTML = '<div> Your timer has been expired or is broken, please create a new one. </div><br/> <a class="button" style="padding-top:0;" href="/syncmer"> Create New Timer </a> '; } else { clock.className = "displayOn"; timer.clock(params); } } } renderView(); function copy() { let link = document.querySelector('#timer-link > input'); link.value = window.location.href; link.select(); link.setSelectionRange(0, 9999); document.execCommand("copy"); alert('The shareable link has been successfully copied. \n Share Now!'); }<file_sep>/* let canvas = document.getElementById('background-canvas'); canvas.width = window.innerWidth - 10; canvas.height = 500; let ctx = canvas.getContext('2d'); ctx.font = "36px Literata, sans-serif"; ctx.fillStyle = '#001534'; */ navigator.serviceWorker.register('sw.js'); function showNotification() { Notification.requestPermission(function(result) { if (result === 'granted') { navigator.serviceWorker.ready.then(function(registration) { registration.showNotification('Vibration Sample', { body: 'Buzz! Buzz!', icon: '../images/touch/chrome-touch-icon-192x192.png', vibrate: [200, 100, 200, 100, 200, 100, 200], tag: 'vibration-sample' }); }); } }); }<file_sep>// todo: Error & Messages needs to be displayed in the UI view let timer = { data: { days: 0, hours: 0, minutes: 0, seconds: 0, values: { difference: 0, current: 0, percentage: 100 } }, create: async function (event) { event.preventDefault(); let formData = document.querySelectorAll("#timer-form > input"); for (let i in formData) { if (formData[i].value == '') { formData[i].value = 0; } } this.data.days = parseInt(formData[0].value); this.data.hours = parseInt(formData[1].value); this.data.minutes = parseInt(formData[2].value); this.data.seconds = parseInt(formData[3].value); if (helpers.create.validate()) { // displays loader let create = document.getElementById('timer-create'); create.style.backgroundColor = "inherit"; create.style.maxWidth = "none"; create.innerHTML = '<img src="./docs/loading.gif" style="max-width:' + create.clientWidth + ';" />'; let currentTime = await getLocalTime(); let stamp = currentTime.unixtime; console.log('Stamp', stamp); let timezone = currentTime.timezone; // adjusts timeStamp to ending time stamp += parseInt(await helpers.create.getTimestampDifference(this.data)); window.location = '?stamp=' + stamp + "&tz=" + timezone; } else { console.log('Error with Timer parameters.') } }, clock: async function (params) { console.log(params); let difference = await helpers.clock.calcDifference(params); let data = await helpers.clock.generate(difference); helpers.clock.inject(data); helpers.clock.update(data); helpers.clock.push(this.data, data); console.log('this.data -->', this.data); } } let helpers = { create: { validate: function () { let data = timer.data; let validation = true; if (isNaN(data.days) || data.days < 0 || data.days > 366) validation = false; if (isNaN(data.hours) || data.hours < 0 || data.hours > 23) validation = false; if (isNaN(data.minutes) || data.minutes < 0 || data.minutes > 59) validation = false; if (isNaN(data.seconds) || data.seconds < 0 || data.seconds > 59) validation = false; if (!validation) { message.classList = "displayOn"; message.innerText = "The timer values are incorrect. Please make sure timer values don't exceed 365 days, 23 hours, 59 minutes, 59 seconds."; } return validation; }, getTimestampDifference: function (data) { return ((24 * 60 * 60 * data.days) + (60 * 60 * data.hours) + (60 * data.minutes) + (data.seconds)); } }, clock: { calcDifference: async function (params) { if (params.tz == "" || params.tz == undefined) return "Timezone not provided or incorrect"; else { let time = { current: parseInt((await getTime(params.tz)).unixtime), future: parseInt(params.stamp) } if (time.future > time.current) { return (time.future - time.current); } else { return "Your timer has expired..."; } } }, // injects clock values inject: function (data) { let ele = document.querySelectorAll('#timer-clock > span'); ele[0].textContent = helpers.clock.convert(data.hours); ele[1].textContent = helpers.clock.convert(data.minutes); ele[2].textContent = helpers.clock.convert(data.seconds); if (data.days > 0) { document.getElementById('clock-days').innerText = data.days + ' DAYS'; } }, // generates the clock generate: async function (difference) { const days = 24 * 60 * 60; const hours = 60 * 60; const minutes = 60; console.log(difference); let hms = difference % days; let ms = hms % hours; let data = { days: difference / days, hours: hms / hours, minutes: ms / minutes, seconds: ms % minutes } for (let key in data) { data[key] = parseInt(data[key]); } console.log(data); return data; }, // updates clock every second update: function (data) { let id = setInterval(async () => { if (data.seconds > 0) data.seconds--; else if (data.minutes > 0) { data.minutes--; data.seconds = 59; } else if (data.hours > 0) { data.hours--; data.minutes = 59; data.seconds = 59; } else if (data.days > 0) { data.days--; data.hours = 23; data.minutes = 59; data.seconds = 59; } else { data = { days: 0, hours: 0, minutes: 0, seconds: 0 } message.className = "displayOn"; message.innerText = "Your timer has expired."; clearInterval(id); } this.inject(data); }, 1000, data, this.inject) }, push: function (timerData, data) { timerData.days = data.days; timerData.hours = data.hours; timerData.minutes = data.minutes; timerData.seconds = data.seconds; }, convert: function (num) { if (num < 10) return '0' + num; else return num; } } }
86bd94b7737f8e107e3b5dc64c8dabee784ff0e3
[ "Markdown", "JavaScript" ]
5
Markdown
pavittarx/syncmer
59a2dbf61eb14693e41f55ba177a1eafa0203b03
d82f2bbfd234961249407c2079fdb46a3c305153
refs/heads/master
<repo_name>Jaffar3600/Spring-Web-MVC-Employee-Validation<file_sep>/employee-demo/src/main/java/com/cg/app/employee/dao/EmployeeDao.java package com.cg.app.employee.dao; import pojo.Employee; public interface EmployeeDao { Employee createNewAccount(Employee employee); }<file_sep>/employee-demo/src/main/java/com/cg/app/employee/controller/EmployeeController.java package com.cg.app.employee.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import com.cg.app.employee.service.EmployeeService; import com.cg.app.employee.validator.EmployeeValidator; import pojo.Employee; @Controller @RequestMapping("/employee") @SessionAttributes("employee") public class EmployeeController { @Autowired private EmployeeValidator validator; @Autowired EmployeeService service; @RequestMapping(value = "/save", method = RequestMethod.GET) public String askDetails(Map<String, Employee> map) { map.put("employee", new Employee()); return "input"; } /* * @RequestMapping("/save") public String save(@RequestParam("empId") int empId, * * @RequestParam("empName") String empName, * * @RequestParam("salary") double salary, Model model) { Employee employee = new * Employee(empId, empName, salary); model.addAttribute(employee); return * "display"; } */ @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(@ModelAttribute("employee") Employee employee, BindingResult result) { validator.validate(employee, result); if (result.hasErrors()) { return "input"; } service.createNewAccount(employee); return "redirect:afterSave"; } @RequestMapping(value = "/afterSave", method = RequestMethod.GET) public String save(SessionStatus status) { status.setComplete(); return "display"; } } <file_sep>/README.md # Spring-Web-MVC-Employee-Validation <file_sep>/employee-demo/src/main/java/com/cg/app/employee/dao/EmployeeDaoImpl.java package com.cg.app.employee.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import pojo.Employee; @Repository public class EmployeeDaoImpl implements EmployeeDao { @Autowired JdbcTemplate jdbctemplate; @Override public Employee createNewAccount(Employee employee) { jdbctemplate.update("INSERT into employee_db values(?,?,?)" ,new Object[] { employee.getEmpId(),employee.getEmpName(),employee.getSalary() }); return null; } } <file_sep>/employee-demo/src/main/java/com/cg/app/employee/service/EmployeeServiceImpl.java package com.cg.app.employee.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.app.employee.dao.EmployeeDao; import pojo.Employee; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired EmployeeDao dao; public void createNewAccount(Employee employee) { dao.createNewAccount(employee); } }
b83d29b668e8acf0a164308e374b133bdde9a3db
[ "Markdown", "Java" ]
5
Java
Jaffar3600/Spring-Web-MVC-Employee-Validation
75d380cb4a2548bc99364940452e134304c95b42
c3a37ce77451a3a2a0bbb52b83a776bdb1c89970
refs/heads/master
<repo_name>jamesformica/junior-dev-community-site-ddd-2019<file_sep>/js/app.js window.addEventListener('load', function() { console.log('💜 all systems are go!') window.setInterval(() => this.document.getElementById("parrot").append("Hello"), 2000) this.document.querySelector(".jd_footer").addEventListener("click", function(){ window.alert("Thanks for clicking, you're awesome!"); }) this.document.getElementById('click-me-pls').addEventListener("click", function() { document.body.classList.add('dog') setTimeout(function() { document.body.classList.remove('dog') }, 2000) }) // MOAR JAVASCRIPT })
d68146e79e08a0f67c77f3e704c72fb44db47df3
[ "JavaScript" ]
1
JavaScript
jamesformica/junior-dev-community-site-ddd-2019
28eb41fd0bc45615cde11639c9eb7dd19beb4a3d
c595373da191b6de19228a2d5341206e56af60b7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace cSharp___DrawLines { public partial class frmDrawLines : Form { Pen myPen = new Pen(Brushes.Black, 1); Graphics g = null; int xCenter, yCenter; int xStart, yStart; int xEnd, yEnd; int numOfLines, angle, angleOrig, length, increment = 0; private void frmDrawLines_Resize(object sender, EventArgs e) { frmDrawLines_Load(null, null); btnGO_Click(null, null); } private void frmDrawLines_Load(object sender, EventArgs e) { this.DoubleBuffered = true; xCenter = pnlCanvas.Width / 2; yCenter = pnlCanvas.Height / 2; xStart = xCenter; yStart = yCenter; xEnd = xCenter; yEnd = yCenter; } public frmDrawLines() { InitializeComponent(); } private void btnGO_Click(object sender, EventArgs e) { numOfLines = int.Parse(txtNumOfLines.Text); angle = int.Parse(txtAngle.Text); angleOrig = angle; length = int.Parse(txtLength.Text); increment = int.Parse(txtIncrement.Text); xStart = xCenter; yStart = yCenter; pnlCanvas.Refresh(); } private void pnlCanvas_Paint(object sender, PaintEventArgs e) { xCenter = pnlCanvas.Width / 2; yCenter = pnlCanvas.Height / 2; if (numOfLines > 0) { g = e.Graphics; for (int k = 0; k < numOfLines; k++) { drawLine(); } } } private void drawLine() { xEnd = (int)xStart + Convert.ToInt32(Math.Cos(deg2rad(angle)) * length); yEnd = (int)yStart + Convert.ToInt32(Math.Sin(deg2rad(angle)) * length); g.DrawLine(myPen, xStart, yStart, xEnd, yEnd); angle += angleOrig; length += increment; xStart = xEnd; yStart = yEnd; } private double deg2rad(double degrees) { double radians = (Math.PI / 180) * degrees; return (radians); } } }
6987a0445e7f1eee982f382db2823745564add0f
[ "C#" ]
1
C#
fischettijw/cSharp---DrawLines
d6fd81d73be69d3142abdf99eaa2f72d7da0465e
69bbcea0cde04f5dbfdd016f7cbb7b4b78400308
refs/heads/master
<repo_name>ahao1995/arbitrader<file_sep>/src/test/java/com/r307/arbitrader/service/model/ActivePositionTest.java package com.r307.arbitrader.service.model; import com.fasterxml.jackson.databind.ObjectMapper; import com.r307.arbitrader.ExchangeBuilder; import org.junit.Before; import org.junit.Test; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.mockito.MockitoAnnotations; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.charset.Charset; import java.util.UUID; import static com.r307.arbitrader.DecimalConstants.USD_SCALE; import static org.junit.Assert.assertEquals; public class ActivePositionTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CurrencyPair currencyPair = CurrencyPair.BTC_USD; private BigDecimal exitTarget = new BigDecimal(0.003); private Exchange longExchange = null; private Exchange shortExchange = null; private BigDecimal longVolume = new BigDecimal(1000.00); private BigDecimal shortVolume = new BigDecimal(1000.00); private BigDecimal longLimitPrice = new BigDecimal(5000.00); private BigDecimal shortLimitPrice = new BigDecimal(5000.00); private ActivePosition activePosition; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); longExchange = new ExchangeBuilder("Long", CurrencyPair.BTC_USD) .withTradeService() .withOrderBook(100, 100) .withBalance(Currency.USD, new BigDecimal(100.00).setScale(USD_SCALE, RoundingMode.HALF_EVEN)) .build(); shortExchange = new ExchangeBuilder("Short", CurrencyPair.BTC_USD) .withBalance(Currency.USD, new BigDecimal(500.00).setScale(USD_SCALE, RoundingMode.HALF_EVEN)) .build(); } @Test public void testSerialization() throws IOException{ activePosition = new ActivePosition(); activePosition.setCurrencyPair(currencyPair); activePosition.setExitTarget(exitTarget); activePosition.getLongTrade().setOrderId(UUID.randomUUID().toString()); activePosition.getLongTrade().setExchange(longExchange); activePosition.getLongTrade().setVolume(longVolume); activePosition.getLongTrade().setEntry(longLimitPrice); activePosition.getShortTrade().setOrderId(UUID.randomUUID().toString()); activePosition.getShortTrade().setExchange(shortExchange); activePosition.getShortTrade().setVolume(shortVolume); activePosition.getShortTrade().setEntry(shortLimitPrice); String json = OBJECT_MAPPER.writeValueAsString(activePosition); ActivePosition deserialized = OBJECT_MAPPER.readValue(json.getBytes(Charset.forName("utf-8")), ActivePosition.class); assertEquals(activePosition, deserialized); } }
3c38d17782b658732a0a17f0467f15e94f6845a2
[ "Java" ]
1
Java
ahao1995/arbitrader
d219f7398dd0de6a52874a1b539d5f1441e5bc69
3c0c59920919beda3809a25b5de2d8fffa665054
refs/heads/master
<file_sep># DeepLearning-DistractedDriver My solution to the, 'Distracted Driver' contest on Kaggle. Dependencies: python (>=3.2) python3-numpy python3-pandas Keras==1.2.2. Theano==0.9.0 HYPOTHESIS: Color plays only a minor role in determining if a driver is distracted or not. Consequently I am converting the images to grey scale, thus reducing the input dimensionality by a factor of three. The reduction of dimensionality is relected in reduced model complexity: I have reduced the width of the network by a facor of two, i.e., reducing the number of filters and the number of nodes in the dense layer. I have no idea if this is appropriate. The proof will be in the pudding... Results: 1. First few punts seem promising. Currently, I managed position 32 on the leaderboard (albeit retrospectively). <file_sep>#!/usr/bin/python3 ''' An attempt to solve the 'Distracted Driver' problem from kaggle. I encountered this problem whilst studying for the fast AI course (see: http://www.fast.ai/). Some of the code below is lifted from that course. HYPOTHESIS: Color plays only a minor role in determining if a driver is distracted or not. Consequently I am converting the images to grey scale, thus reducing the input dimensionality by a factor of three. The reduction of dimensionality is relected in reduced model complexity: I have reduced the width of the network by a facor of two, i.e., reducing the number of filters and the number of nodes in the dense layer. I have no idea if this is appropriate. The proof will be in the pudding... Written by <NAME>, Aug 2017, ''' from theano.sandbox import cuda import os, numpy as np, pandas as pd import keras from keras.utils.np_utils import to_categorical from keras.models import Sequential from keras.layers.core import Flatten, Dense, Dropout from keras.layers.convolutional import Convolution2D, ZeroPadding2D, MaxPooling2D from keras.layers.normalization import BatchNormalization from keras.optimizers import SGD, RMSprop from keras.metrics import categorical_crossentropy, categorical_accuracy from keras.preprocessing import image from keras.layers.advanced_activations import PReLU from keras.callbacks import ModelCheckpoint, CSVLogger class VggGrey(object): ''' This class builds a slimmed version of the VGG16 model (see: https://arxiv.org/abs/1409.1556), intended for use with greyscale images. ''' def __init__(self, p=0.5): ''' :param p: Dropout parameter. ''' self.model = Sequential() self.BuildModel() self.path = ('/home/martin/Documents/Python/DeepLearning/' '/DistractedDriver/Data/current/') self.batch_size = 64 self.p = p def BuildModelLeak(self): ''' The slimmed VGG architecture with parametric ReLU. ''' model = self.model act = keras.layers.advanced_activations.PReLU() model.add(ZeroPadding2D((1,1), input_shape=(1,224,224))) model.add(Convolution2D(32, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(32, 3, 3)) model.add(PReLU()) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(64, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3)) model.add(PReLU()) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3)) model.add(PReLU()) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3)) model.add(PReLU()) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3)) model.add(PReLU()) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3)) model.add(PReLU()) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(Flatten()) model.add(Dense(2056, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.25)) model.add(Dense(2056, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) def BuildModel(self): ''' The slimmed VGG architecture. ''' model = self.model model.add(ZeroPadding2D((1,1), input_shape=(1,224,224))) model.add(Convolution2D(32, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(32, 3, 3, activation='relu')) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(64, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3, activation='relu')) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(128, 3, 3, activation='relu')) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(ZeroPadding2D((1,1))) model.add(Convolution2D(256, 3, 3, activation='relu')) model.add(MaxPooling2D((2,2), strides=(2,2))) model.add(Flatten()) model.add(Dense(2056, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.25)) model.add(Dense(2056, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) def get_batches(self, path, gen = image.ImageDataGenerator(), batch_size = 64, class_mode = 'categorical', target_size = (224,224), shuffle=True): ''' Create batches of grey scale images. ''' return gen.flow_from_directory( path, target_size=target_size, class_mode = class_mode, batch_size = batch_size, color_mode = "grayscale", shuffle = shuffle ) def get_classes(self, path): ''' Determine data labels. ''' batches = self.get_batches(path+'train', batch_size=1) Vbatches = self.get_batches(path+'valid', batch_size=1) Tbatches = self.get_batches(path+'test', batch_size=1) return (Vbatches.classes, batches.classes, to_categorical(Vbatches.classes), to_categorical(batches.classes), Vbatches.filenames, batches.filenames, Tbatches.filenames) def do_clip(arr, mx): return np.clip(arr, (1-mx)/9, mx) def prepSubmission(): model = VggGrey() batch_size=64 batches = model.get_batches(model.path+'train', batch_size=batch_size) test_batches = model.get_batches(model.path+'test', batch_size=batch_size, shuffle=False) DeepGrey = keras.models.load_model('lr0001.h5') predictions = DeepGrey.predict_generator(test_batches,val_samples=79726) predictions = do_clip(predictions,0.93) file_names = test_batches.filenames classes = sorted(batches.class_indices, key=batches.class_indices.get) submission = pd.DataFrame(predictions, columns=classes) submission.insert(0, 'img', [a[5:] for a in test_batches.filenames]) submission.head() submission.to_csv('sub2.csv', index=False) def main(): batch_size = 64 model = VggGrey() batches = model.get_batches(model.path+'train', batch_size=batch_size) val_batches = model.get_batches(model.path+'valid', batch_size=batch_size*2, shuffle=False) (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filenames) = model.get_classes(model.path) DeepGrey = model.model for rate in [1e-3, 1e-4, 1e-5, 1e-6]: if rate > 1e-3: model.load_weights(fname) fname = 'lr' + str(rate).replace('.','') + '.h5' checkpointer = ModelCheckpoint( filepath=fname, verbose=1, save_best_only=True ) CSVlogging = CSVLogger( 'epochs.log', separator=',', append = True) DeepGrey.compile( RMSprop(lr=rate), loss='categorical_crossentropy', metrics=['accuracy'] ) DeepGrey.fit_generator( batches, samples_per_epoch=batches.n, nb_epoch=50, validation_data=val_batches, nb_val_samples=val_batches.n, callbacks=[checkpointer, CSVlogging] ) # Cherry pick a model and submit. # prepSubmission() if __name__ == '__main__': main()
d6a8f2501a0163d08e98e96d64f995397f881dbb
[ "Markdown", "Python" ]
2
Markdown
martinritchie/DeepLearning-DistractedDriver
7cec5f820bae446c617a2363a195ec0980b64df1
6d228fa0f762779a94602a6fb492ffbffdf29a37
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; class ThreadFilters extends Filter { public function user($value) { $this->builder->where('user_id', $value); } }
9558672bdeaaa0393e0479c76eba57c0b06280d9
[ "PHP" ]
1
PHP
guifelix/ForumApp
1b3ab6ed4fe3cd6236b8797f29394760cf203962
9ac8f0b736e264cabb3e9d7b34deceaf3995f675
refs/heads/master
<repo_name>naodeng/django_test<file_sep>/README.md # let-s-django django学习项目 <file_sep>/static/js/filter.js (function (w) { var filter = { init: function (data, selectedListData) { Date.prototype.format = function (format) { var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": this.getHours(), //hour "m+": this.getMinutes(), //minute "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds() //millisecond } if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; }; this.getDoms(); this.renderSelect(data, selectedListData); this.renderInput(selectedListData); this.initShowMore(data); this.initDatePickData(selectedListData); this.bindEvent(); }, getDoms: function () { this.doms = { $filterMenu: $('#filter .widget-menu'), $showmorebtn: $('.showmore-btn'), $filterAvanced: $('.filter-advanced'), $showmoreIconUp: $('.showmore-icon-up'), $showmoreIconDown: $('.showmore-icon-down'), $viewType: $('input[name="view_type"]'), $perPageInput: $('input[name="per_page"]'), $queryBtn: $('#filters_form_open .query-btn'), $form: $('#filters_form_open') }; }, // 鑾峰彇select2涓嬫媺妗嗛€変腑鐨刬d鏁扮粍 getSelectedIds: function (data) { var selectedList = []; for (var i = 0; i < data.length; i++) { if (data[i].id) { selectedList.push(data[i].id); } } return selectedList; }, // 鑾峰彇鏈懆 鍛ㄤ竴鑷冲懆鏃ョ殑鏃堕棿 getWeekRange: function () { var now = new Date(); var nowTime = now.getTime(); var day = now.getDay(); var oneDayLong = 24 * 60 * 60 * 1000; var MondayTime = nowTime - (day - 1) * oneDayLong; var SundayTime = nowTime + (7 - day) * oneDayLong; var monday = new Date(MondayTime); var sunday = new Date(SundayTime); var weekRange = { start: monday.format('yyyy-MM-dd'), end: sunday.format('yyyy-MM-dd') }; return weekRange; }, // 鑾峰彇骞存湀鏃ュ€� getDateVal: function (momentTime) { var timeArr = momentTime.split('-'); var year = parseInt(timeArr[0], 10); var month = parseInt(timeArr[1], 10); var day = parseInt(timeArr[2], 10); return { year: year, month: month, day: day }; }, // 璁剧疆鎻愪氦寮€濮嬫棩鏈� setSubmitStartDate: function (dateObj) { $('input[name = "start_year"]').val(dateObj.year); $('input[name = "start_month"]').val(dateObj.month); $('input[name = "start_day"]').val(dateObj.day); }, // 璁剧疆鎻愪氦缁撴潫鏃ユ湡 setSubmitEndDate: function (dateObj) { $('input[name = "end_year"]').val(dateObj.year); $('input[name = "end_month"]').val(dateObj.month); $('input[name = "end_day"]').val(dateObj.day); }, // 璁剧疆鏇存柊寮€濮嬫棩鏈� setUpdateStartDate: function (dateObj) { $('input[name = "last_updated_start_year"]').val(dateObj.year); $('input[name = "last_updated_start_month"]').val(dateObj.month); $('input[name = "last_updated_start_day"]').val(dateObj.day); }, // 璁剧疆鏇存柊缁撴潫鏃ユ湡 setUpdateEndDate: function (dateObj) { $('input[name = "last_updated_end_year"]').val(dateObj.year); $('input[name = "last_end_start_month"]').val(dateObj.month); $('input[name = "last_end_start_day"]').val(dateObj.day); }, // 鍒濆鍖栨棩鍘嗘暟鎹� initDatePickData: function (selectedListData) { var submitStartDateObj = {}; var submitEndDateObj = {}; var lastUpdatedStartDateObj = {}; var lastUpdatedEndDateObj = {}; var submitStartDate = ''; var submitStartYear = selectedListData['start_year']; var submitStartMonth = selectedListData['start_month']; var submitStartDay = selectedListData['start_day']; var submitEndDate = ''; var submitEndYear = selectedListData['end_year']; var submitEndMonth = selectedListData['end_month']; var submitEndDay = selectedListData['end_day']; var lastUpdatedStartDate = ''; var lastUpdatedStartYear = selectedListData['last_updated_start_year']; var lastUpdatedStartMonth = selectedListData['last_updated_start_month']; var lastUpdatedStartDay = selectedListData['last_updated_start_day']; var lastUpdatedEndDate = ''; var lastUpdatedEndYear = selectedListData['last_updated_end_year']; var lastUpdatedEndMonth = selectedListData['last_end_start_month']; var lastUpdatedEndDay = selectedListData['last_end_start_day']; if (submitStartYear && submitStartMonth && submitStartDay) { submitStartDateObj = { year: submitStartYear, month: submitStartMonth, day: submitStartDay }; submitStartDate = new Date(submitStartYear, submitStartMonth - 1, submitStartDay).format('yyyy-MM-dd'); } if (submitEndYear && submitEndMonth && submitEndDay) { submitEndDateObj = { year: submitEndYear, month: submitEndMonth, day: submitEndDay }; submitEndDate = new Date(submitEndYear, submitEndMonth - 1, submitEndDay).format('yyyy-MM-dd'); } if (lastUpdatedStartYear && lastUpdatedStartMonth && lastUpdatedStartDay) { lastUpdatedStartDateObj = { year: lastUpdatedStartYear, month: lastUpdatedStartMonth, day: lastUpdatedStartDay }; lastUpdatedStartDate = new Date(lastUpdatedStartYear, lastUpdatedStartMonth - 1, lastUpdatedStartDay).format('yyyy-MM-dd'); } if (lastUpdatedEndYear && lastUpdatedEndMonth && lastUpdatedEndDay) { lastUpdatedEndDateObj = { year: lastUpdatedEndYear, month: lastUpdatedEndMonth, day: lastUpdatedEndDay }; lastUpdatedEndDate = new Date(lastUpdatedEndYear, lastUpdatedEndMonth - 1, lastUpdatedEndDay).format('yyyy-MM-dd'); } this.setSubmitStartDate(submitStartDateObj); this.setSubmitEndDate(submitEndDateObj); this.setUpdateStartDate(lastUpdatedStartDateObj); this.setUpdateEndDate(lastUpdatedEndDateObj); this.initDatePick({ submitStartDate: submitStartDate, submitEndDate: submitEndDate, lastUpdatedStartDate: lastUpdatedStartDate, lastUpdatedEndDate: lastUpdatedEndDate }); }, // 鍒濆鍖栭〉闈㈡棩鍘嗘帶浠� initDatePick: function (data) { var that = this; var $dateTimePickIconLeft = null; var $dateTimePickIconRight = null; var submitStartDate = data.submitStartDate; var submitEndDate = data.submitEndDate; var lastUpdatedStartDate = data.lastUpdatedStartDate; var lastUpdatedEndDate = data.lastUpdatedEndDate; $(".submit-start-datetime, .submit-end-datetime, .update-start-datetime, .update-end-datetime").datetimepicker({ format: 'yyyy-mm-dd', minView: "month", autoclose: true, todayBtn: true, clearBtn: true }); $(".submit-start-datetime").val(submitStartDate) .on('changeDate', function (e) { //鑾峰彇浜嬩欢瀵硅薄 var e = e || window.event; //榧犳爣鐐瑰嚮鐨勭洰鏍囦綅缃� var target = e.target || e.srcElement; var dateObj = { year: '', month: '', day: '', }; if (target.value) { var momentTime = target.value; dateObj = that.getDateVal(momentTime); } that.setSubmitStartDate(dateObj); }); $(".submit-end-datetime").val(submitEndDate) .on('changeDate', function (e) { //鑾峰彇浜嬩欢瀵硅薄 var e = e || window.event; //榧犳爣鐐瑰嚮鐨勭洰鏍囦綅缃� var target = e.target || e.srcElement; var dateObj = { year: '', month: '', day: '', }; if (target.value) { var momentTime = target.value; var dateObj = that.getDateVal(momentTime); } that.setSubmitEndDate(dateObj); }); $(".update-start-datetime").val(lastUpdatedStartDate) .on('changeDate', function (e) { //鑾峰彇浜嬩欢瀵硅薄 var e = e || window.event; //榧犳爣鐐瑰嚮鐨勭洰鏍囦綅缃� var target = e.target || e.srcElement; var dateObj = { year: '', month: '', day: '', }; if (target.value) { var momentTime = target.value; var dateObj = that.getDateVal(momentTime); } that.setUpdateStartDate(dateObj); }); $(".update-end-datetime").val(lastUpdatedEndDate) .on('changeDate', function (e) { //鑾峰彇浜嬩欢瀵硅薄 var e = e || window.event; //榧犳爣鐐瑰嚮鐨勭洰鏍囦綅缃� var target = e.target || e.srcElement; var dateObj = { year: '', month: '', day: '', }; if (target.value) { var momentTime = target.value; var dateObj = that.getDateVal(momentTime); } that.setUpdateEndDate(dateObj); }); $dateTimePickIconLeft = $('.datetimepicker .icon-arrow-left'); $dateTimePickIconRight = $('.datetimepicker .icon-arrow-right'); $dateTimePickIconLeft.addClass('fa fa-arrow-left'); $dateTimePickIconRight.addClass('fa fa-arrow-right'); }, // 鍒濆鍖栧睍绀烘洿澶氭寜閽姸鎬侊紝浠ュ強楂樼骇閫夋嫨鍣ㄦ姌鍙犵姸鎬� initShowMore: function (data) { var isShowAdvanced = data['view_type']; if (isShowAdvanced == 'advanced') { this.showAdvanced(); } else if (isShowAdvanced == 'simple') { this.hideAdvanced(); } }, // 鏄剧ず楂樼骇绛涢€� showAdvanced: function () { var doms = this.doms; var $filterAvanced = doms.$filterAvanced; var $showmoreIconUp = doms.$showmoreIconUp; var $showmoreIconDown = doms.$showmoreIconDown; var $viewType = doms.$viewType; $filterAvanced.slideDown('slow'); $showmoreIconUp.show(); $showmoreIconDown.hide(); $viewType.val('advanced'); }, // 闅愯棌楂樼骇绛涢€� hideAdvanced: function () { var doms = this.doms; var $filterAvanced = doms.$filterAvanced; var $showmoreIconUp = doms.$showmoreIconUp; var $showmoreIconDown = doms.$showmoreIconDown; var $viewType = doms.$viewType; $filterAvanced.slideUp('slow'); $showmoreIconUp.hide(); $showmoreIconDown.show(); $viewType.val('simple'); }, // select2妯℃澘 template: function (data, container) { return data.text; }, // 鍒濆鍖栭〉闈nput妗嗗€� renderInput: function (data) { var $perPageInput = this.doms.$perPageInput; var value = data.per_page; $perPageInput.val(value); }, // 娓叉煋椤甸潰鎵€鏈変笅鎷夋 renderSelect: function (data, selectedListData) { var selectArr = []; for (var key in data) { selectArr = data[key]; this.renderOptions(key, selectArr, selectedListData); } }, // 鏍规嵁鍚庡彴鏁版嵁娓叉煋涓嬫媺妗嗛€夐」 renderOptions: function (key, selectArr, selectedListData) { var that = this; var selectTpl = ''; var optionsArr = []; var $select = $('#' + key); var selectName = $select.data('name'); var $input = $('input[name="' + selectName + '"]'); var initSelData = selectedListData ? selectedListData[selectName] : []; if (selectName && $select) { if (initSelData && initSelData.length == 0) { $input.val(0); } else { $input.val(initSelData); } for (var i = 0; i < selectArr.length; i++) { var optionObj = selectArr[i]; var id = optionObj.id; var name = optionObj.name; var optionTpl = '<option value="' + id + '">' + name + '</option>'; optionsArr.push(optionTpl); } selectTpl = optionsArr.join(''); $select.append(selectTpl).select2({ multiple: true, theme: "bootstrap", allowClear: true, placeholder: "璇烽€夋嫨", templateSelection: that.template, }); $select.val(initSelData).trigger('change'); $select.on("change", function (e) { var ele = e.currentTarget; var $ele = $(ele); var sel2data = $ele.select2("data"); var selectedList = that.getSelectedIds(sel2data); var $curInput = $('.data-' + ele.id); if (selectedList.length == 0) { $curInput.val(0); } else { $curInput.val(selectedList); } }); } }, bindEvent: function () { var that = this; var doms = this.doms; // 涓嬫媺妗嗘姌鍙� doms.$filterMenu.on('click', function (e) { var $this = $(this); if ($this.hasClass('open')) { $(this).removeClass('open'); } else { $(this).addClass('open'); } }); // 灞曠ず鏇村 doms.$showmorebtn.on('click', function (e) { if (doms.$filterAvanced.is(':visible')) { that.hideAdvanced(); } else { that.showAdvanced(); } }); // 鏌ヨ doms.$queryBtn.on('click', function (e) { doms.$form.submit(); }); } }; var defaultData = {}; var defaultSelectedData = {}; var data = window.flitervaluejson || defaultData; var selectedListData = window.tempflitervaluejson || defaultSelectedData; filter.init(data, selectedListData); window.filter = filter; })(window);
553682429aaf7229519bf820123b2d56f579c7aa
[ "Markdown", "JavaScript" ]
2
Markdown
naodeng/django_test
9c83b3d04067fea4bb008e977c2a20ee68d52fed
800c81f3666a9e6a19e6bc068dac82b2f8e8f00a
refs/heads/main
<repo_name>techne-tembusu/techweek-2020<file_sep>/sketch.js const particles = [[], [], []]; const colors = ["27,30,57", "95,134,141", "229,83,76"] const nums = 80; const noiseScale = 800; function windowResized() { resizeCanvas(windowWidth, windowHeight); background(0,0,0); } function setup() { createCanvas(windowWidth, windowHeight); background(0,0,0); for (let i = 0; i < particles.length; i++) for (let j = 0; j < nums; j++) particles[i][j] = new Particle(random(0, width),random(0,height)); } function draw(){ noStroke(); smooth(); for (let i = 0; i < nums; i++) { var radius = map(i,0,nums,1,2); var alpha = map(i,0,nums,0,1); for (let j = 0; j < 3; j++) { fill(`rgba(${colors[j]}, ${alpha})`); particles[j][i].draw(radius); } } } class Particle { constructor(x, y) { this.dir = createVector(0, 0); this.vel = createVector(0, 0); this.pos = createVector(x, y); this.speed = 0.4; } draw(r) { this.move(); this.display(r); this.checkEdge(); } move() { var angle = noise(this.pos.x/noiseScale, this.pos.y/noiseScale)*TWO_PI*noiseScale; this.dir.x = cos(angle); this.dir.y = sin(angle); this.vel = this.dir.copy(); this.vel.mult(this.speed); this.pos.add(this.vel); } checkEdge() { if (this.pos.x > width || this.pos.x < 0 || this.pos.y > height || this.pos.y < 0) { this.pos.x = random(50, width); this.pos.y = random(50, height); } } display(r) { ellipse(this.pos.x, this.pos.y, r, r); if (this.speed > 0.1) this.speed *= 0.999; } }
e130a54207ea212738d42b30944173526fa3a512
[ "JavaScript" ]
1
JavaScript
techne-tembusu/techweek-2020
0deb9c5aa00aefec03c65c1a0766f5364579753a
d910578c5af5121e0fd01db50f316399483a60ff
refs/heads/master
<file_sep>$(document).ready(function() { $('#accordion').find('.accordion-toggle').click(function() { $(this).next().slideToggle('fast'); $('.accordion-content').not($(this).next()).slideUp('slow'); }); $('#accordion').find('.accordion-sub_toggle').click(function() { $(this).next().slideToggle('fast'); // $('.accordion-content').not($(this).next()).slideUp('slow'); }); const $menu_inquirer = $('.inquirer_container'); $(document).mouseup((e) => { if ( !$menu_inquirer.is(e.target) && // if the target of the click isn't the container... $menu_inquirer.has(e.target).length === 0 ) { // ... nor a descendant of the container $menu_inquirer.removeClass('active'); } //hide/show avatar menu when clicked the avatar $('.inquirer').on('click', function() { $('.inquirer').toggleClass('active'); $menu_inquirer.toggleClass('active'); console.log('click'); }); }); const $menu_avatar = $('.avatar__content'); $(document).mouseup((e) => { if ( !$menu_avatar.is(e.target) && // if the target of the click isn't the container... $menu_avatar.has(e.target).length === 0 ) { // ... nor a descendant of the container $menu_avatar.removeClass('active'); } //hide/show avatar menu when clicked the avatar $('.header__avatar').on('click', function() { $('.header__avatar').toggleClass('active'); $menu_avatar.toggleClass('active'); }); }); $('#bell').on('click', function() { $.ajax({ url: 'data/fetch_bell.php', type: 'POST', processData: false, success: function(data) { $('#bell_count').remove(); $('#bell__content').show(); $('#bell__links').html(data); }, error: function() {} }); }); $('#envelope').on('click', function() { $.ajax({ url: 'data/fetch_inq.php', type: 'POST', processData: false, success: function(data) { $('#envelope_count').remove(); $('#envelope__content').show(); $('#envelope__links').html(data); }, error: function() {} }); }); $('body').click(function(e) { if (e.target.id != 'bell') { $('#bell__content').hide(); } if (e.target.id != 'envelope') { $('#envelope__content').hide(); } }); $('#appoint_list').DataTable({ aaSorting: [], responsive: true, pageLength: 5, lengthChange: false, language: { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [ { targets: [ 5, 6 ], orderable: false }, { responsivePriority: 1, targets: 0 }, { responsivePriority: 2, targets: 5 } ], initComplete: function() { this.api().columns([ 5 ]).every(function() { var column = this; var select = $( '<select class="status_dd"><option value="" disabled selected>Status</option><option value="">All</option></select>' ) .appendTo($(column.header()).empty()) .on('change', function() { var val = $.fn.dataTable.util.escapeRegex($(this).val()); column.search(val ? '^' + val + '$' : '', true, false).draw(); }); column.data().unique().sort().each(function(d, j) { select.append('<option value="' + d + '">' + d + '</option>'); }); }); } }); $('#closeappoint').click(function() { console.log('click'); modal__appoint.style.display = 'none'; window.location.replace('appoint-list.php'); }); }); <file_sep><?php session_start(); require_once 'config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/service.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/b-1.5.6/b-print-1.5.6/r-2.2.2/datatables.min.css" /> </head> <body> <?php include 'header.php'; ?> <main> <div class="grid-container"> <aside class="sidebar"> <div class="navi-container"> <h3>Our Services</h3> <nav class="navi"> <?php $sql_fetchCategory = "SELECT * FROM categories"; $stmt_fetchCategory = $connect->prepare($sql_fetchCategory); $stmt_fetchCategory->execute(); $rows_fetchCategory = $stmt_fetchCategory->fetchAll(); foreach ($rows_fetchCategory as $fetchCategory) { $category = $fetchCategory['category']; ?> <li id="<?php echo $category ?>"><a href="?<?php echo $category ?>"><?php echo $category ?></a></li> <?php } ?> </nav> </div> </aside> <section class="section-service"> <!-- <h1>Services</h1> --> <div class="service-container" id="service_contain"> <!-- <div class="service-box"> <div class="service-box-img"> <img src="images/smile.jpeg" alt=""> </div> <div class="service-box-info"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Amet, voluptates! </div> </div> --> </div> <div class="button_container"> <button class="button">Make an appointment now</button> </div> </section> </div> </main> <section class="section-footer"> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </section> <?php $sql_first_category = "SELECT * FROM service ORDER BY id ASC LIMIT 1"; $stmt_first_category = $connect->prepare($sql_first_category); $stmt_first_category->execute(); $rows_first_category = $stmt_first_category->fetch(PDO::FETCH_ASSOC); $first_category = $rows_first_category['category']; ?> <!-- script js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/main.js"></script> <!-- <script src="js/testimonial.js"></script> --> <!-- <script src="js/simple-lightbox.min.js"></script> --> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/b-1.5.6/b-print-1.5.6/r-2.2.2/datatables.min.js"></script> <script> </script> <script> $(document).ready(function() { function load_page_details(category) { $.ajax({ url: "controllers/fetchService.php", method: "POST", data: { category: category }, success: function(data) { $('#service_contain').html(data); } }) } var categorySelected = "<?php echo $first_category ?>"; load_page_details(categorySelected); $('.navi li:nth-child(1)').addClass('current_service'); $('.navi li').click(function(e) { e.preventDefault(); const service_boxes = $(this).attr("id"); $('.navi li').removeClass('current_service'); $(this).addClass('current_service'); load_page_details(service_boxes); }) }) </script> </body> </html><file_sep><?php require_once 'controllers/authController.php'; if (empty($_SESSION['ogliadmin'])) { echo "<script>window.location.replace('sign-in.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><NAME> | ADMIN</title> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/w/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Appointment List</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <table class="list__tbl display dt-responsive nowrap " id="appoint_list"> <thead> <tr> <th>Appoint ID</th> <th>Service</th> <th>Dentist</th> <th>Date</th> <th>Time</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_apoint = "SELECT * FROM appointment WHERE appointmentDate >= CURRENT_DATE ORDER BY timestamp ASC"; $stmnt_appoint = $connect->prepare($sql_apoint); $stmnt_appoint->execute(['clientID' => $idd]); $rows_appoint = $stmnt_appoint->fetchAll(PDO::FETCH_ASSOC); foreach ($rows_appoint as $rows) { $date = new DateTime($rows['appointmentDate']); $start = new DateTime($rows['start']); $end = new DateTime($rows['end']); $dentistID = $rows['doctorID']; $sql_nameDentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_nameDentist = $connect->prepare($sql_nameDentist); $stmt_nameDentist->execute(['did' => $dentistID]); $row_nameDentist = $stmt_nameDentist->fetch(PDO::FETCH_ASSOC); $salut = $row_nameDentist['Salutation']; $firstName = $row_nameDentist['firstName']; $middleName = $row_nameDentist['middleName']; $lastName = $row_nameDentist['lastName']; $dentistName = $salut . " " . $firstName . " " . $middleName . " " . $lastName; ?> <tr> <td><?php echo $rows['appointID'] ?></td> <td><?php echo $rows['service'] ?></td> <td><?php echo $dentistName ?></td> <td><?php echo date_format($date, 'd M Y') ?></td> <td><?php echo date_format($start, 'g:i a') . "-" . date_format($end, 'g:i a') ?></td> <td><?php echo $rows['status'] ?> </td> <td><a href="?viewID=<?php echo $rows['appointID'] ?>"><i class="fas fa-eye eye"></i></a></td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- MODAL --> <div id="modal__appoint" class="modal"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="closeappoint">&times;</span> <?php $aid = $_GET['viewID']; $sql_info = "SELECT * FROM appointment WHERE appointID = :aid"; $stmt_info = $connect->prepare($sql_info); $stmt_info->execute(['aid' => $aid]); $row_info = $stmt_info->fetch(PDO::FETCH_ASSOC); $date_info = new DateTime($row_info['appointmentDate']); $start_info = new DateTime($row_info['start']); $end_info = new DateTime($row_info['end']); $patient_id = $row_info['clientID']; $dentist_id = $row_info['doctorID']; $sql_patient = "SELECT * FROM client WHERE clientID = :pid"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['pid' => $patient_id]); $row_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $fn = $row_patient['firstName']; $mn = $row_patient['middleName']; $ln = $row_patient['lastName']; $fullname = $fn . " " . $mn . " " . $ln; $sql_dentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(['did' => $dentist_id]); $row_dentist = $stmt_dentist->fetch(PDO::FETCH_ASSOC); $salut = $row_dentist['Salutation']; $dfn = $row_dentist['firstName']; $dmn = $row_dentist['middleName']; $dln = $row_dentist['lastName']; $dfullname = $salut . " " . $dfn . " " . $dmn . " " . $dln; $schedTime = date_format($start_info, 'g:i a') . "-" . date_format($end_info, 'g:i a'); $schedDate = date_format($date_info, 'd M Y'); ?> <span class="modal_header-title"><?php echo $fullname ?>'s Appointment Info</span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="modal-view-body_container"> <div class="view__info"> <div class="patient_info_content"> <div class="patient_textbox"> <span>Appointment Id:</span> <span><?php echo $row_info['appointID'] ?></span> </div> <div class="patient_textbox"> <span>Patient Id:</span> <span><?php echo $patient_id ?></span> </div> <div class="patient_textbox"> <span>Last Name:</span> <span><?php echo $ln ?></span> </div> <div class="patient_textbox"> <span>First Name:</span> <span><?php echo $fn ?></span> </div> <div class="patient_textbox"> <span>Dentist:</span> <span><?php echo $dfullname ?></span> </div> <div class="patient_textbox"> <span>Service:</span> <span><?php echo $row_info['service'] ?></span> </div> <div class="patient_textbox"> <span>Scheduled Date:</span> <span><?php echo $schedDate ?></span> </div> <div class="patient_textbox"> <span>Scheduled Time:</span> <span><?php echo $schedTime ?></span> </div> </div> <div class="appoint_info_content"> <div class="prediag_header"> <h3>Pre-diagnostic image</h3> </div> <div class="prediag_img_container"> <img src="../<?php echo $row_info['prediag_img'] ?>" alt=""> </div> </div> </div> <?php if ($row_info['status'] == 'Pending') { ?> <?php } else { ?> <div class="remarks"> <span>Remarks</span> <textarea class="remark-box" name="remark"><?php echo $row_info['remarks'] ?></textarea> </div> <?php } ?> <div class="button-container"> <?php if ($row_info['status'] == 'Pending') { ?> <a href="?cancelID=<?php echo $aid ?>" class="button btn-cancel">Cancel Appointment</a> <input type="submit" name="approve" class="button" value="Approve Appointment" onclick="return confirm('Approved patient\'s appointment?')"> <?php } else if ($row_info['status'] == 'Done' || $row_info['status'] == 'Cancelled') { ?> <span></span> <?php } else { ?> <a href="?cancelID=<?php echo $aid ?>" class="button btn-cancel">Cancel Appointment</a> <input type="submit" name="done" class="button btn-done" value="Done Appointment" onclick="return confirm('Is the patient already done to his/her appointment?')"> <!-- <input type="submit" name="resched" class="button" value="Resched Appointment" onclick="return confirm('Finish the appointment and reschedule for new appointment?')"> --> <a href="patient.php?patient=<?php echo $patient_id ?>&&set=<?php echo $patient_id ?>" class="button">Resched Appointment</a> <?php } ?> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> <!-- MODAL --> <div id="modal__cancel" class="modal"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header cancel-header"> <span class="close" id="closecancel">&times;</span> <?php $aid = $_GET['cancelID']; $sql_infoCancel = "SELECT * FROM appointment WHERE appointID = :aid"; $stmt_infoCancel = $connect->prepare($sql_infoCancel); $stmt_infoCancel->execute(['aid' => $aid]); $row_infoCancel = $stmt_infoCancel->fetch(PDO::FETCH_ASSOC); $date_infoCancel = new DateTime($row_infoCancel['appointmentDate']); $start_infoCancel = new DateTime($row_infoCancel['start']); $end_infoCancel = new DateTime($row_infoCancel['end']); $service_infoCancel = $row_infoCancel['service']; $patient_id = $row_infoCancel['clientID']; $dentist_id = $row_infoCancel['doctorID']; $sql_patient = "SELECT * FROM client WHERE clientID = :pid"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['pid' => $patient_id]); $row_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $fn = $row_patient['firstName']; $mn = $row_patient['middleName']; $ln = $row_patient['lastName']; $fullname = $fn . " " . $mn . " " . $ln; $sql_dentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(['did' => $dentist_id]); $row_dentist = $stmt_dentist->fetch(PDO::FETCH_ASSOC); $salut = $row_dentist['Salutation']; $dfn = $row_dentist['firstName']; $dmn = $row_dentist['middleName']; $dln = $row_dentist['lastName']; $dfullname = $salut . " " . $dfn . " " . $dmn . " " . $dln; $schedTime = date_format($start_info, 'g:i a') . "-" . date_format($end_info, 'g:i a'); $schedDate = date_format($date_info, 'd M Y'); ?> <span class="modal_header-title">Are you sure you want to cancel <?php echo $fullname ?>'s Appointment?</span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="modal-view-body_container"> <table style="border-collapse:collapse; width:80%" width="100%"> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Appoint ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left"><?php echo $aid ?></td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Service</th> <td style="font-size:14px; padding:8px; text-align:left" align="left"><?php echo $service_infoCancel ?></td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Dentist</th> <td style="font-size:14px; padding:8px; text-align:left" align="left"><?php echo $dfullname ?></td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Date</th> <td style="font-size:14px; padding:8px; text-align:left" align="left"><?php echo $schedDate ?></td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Time</th> <td style="font-size:14px; padding:8px; text-align:left" align="left"><?php echo $schedTime ?></td> </tr> </table> <div class="remarks"> <h3>Please specify your reason of cancelation</h3> <textarea name="reason" class="remark-box"></textarea> </div> <input type="submit" name="cancel" class="button btn-cancel" value="Cancel Appointment"> </div> </form> </div> <div class="modal-footer cancel-header"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/script.js"></script> <script src="js/shortscript.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/w/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> </body> </html> <?php if (isset($_GET['viewID'])) { echo "<script>var modal__appoint= document.getElementById('modal__appoint')</script>"; echo "<script> modal__appoint.style.display='block'</script>"; $_SESSION['viewID'] = $_GET['viewID']; $appointID = $_GET['viewID']; $sql_patient_appoint = "SELECT * FROM appointment WHERE appointID = :appointID"; $stmt_patient_appoint = $connect->prepare($sql_patient_appoint); $stmt_patient_appoint->execute(['appointID' => $appointID]); $row_patient_appoint = $stmt_patient_appoint->fetch(PDO::FETCH_ASSOC); $patient_id = $row_patient_appoint['clientID']; $dentist_id = $row_patient_appoint['doctorID']; $date_info = new DateTime($row_patient_appoint['appointmentDate']); $start_info = new DateTime($row_patient_appoint['start']); $end_info = new DateTime($row_patient_appoint['end']); $sql_patient = "SELECT * FROM client WHERE clientID = :pid"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['pid' => $patient_id]); $row_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $email = $row_patient['email']; $fn = $row_patient['firstName']; $mn = $row_patient['middleName']; $ln = $row_patient['lastName']; $name = $fn . " " . $mn . " " . $ln; $sql_dentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(['did' => $dentist_id]); $row_dentist = $stmt_dentist->fetch(PDO::FETCH_ASSOC); $salut = $row_dentist['Salutation']; $dfn = $row_dentist['firstName']; $dmn = $row_dentist['middleName']; $dln = $row_dentist['lastName']; $dfullname = $salut . " " . $dfn . " " . $dmn . " " . $dln; $_SESSION['patientID'] = $patient_id; $_SESSION['email'] = $email; $_SESSION['name'] = $name; $_SESSION['dentist_name'] = $dfullname; $_SESSION['date'] = $date_info; $_SESSION['start'] = $start_info; $_SESSION['end'] = $end_info; exit(); } if (isset($_GET['cancelID'])) { echo "<script>const modal__cancel= document.querySelector('#modal__cancel')</script>"; echo "<script> modal__cancel.classList.add('modal_show')</script>"; } ?><file_sep><?php // require 'config/control.php'; function verifyUser($token) { global $connect; $sql_token = "SELECT * FROM client WHERE token= :token LIMIT 1"; $result = $connect->prepare($sql_token); $result->execute(['token' => $token]); $rows = $result->fetch(PDO::FETCH_ASSOC); if ($rows > 0) { $verified_1 = 1; $status = 'Verified'; $token_clear = ''; $update = "UPDATE client SET verified = :verified, status= :status, token= :token_clear WHERE token= :token"; $stmt_update = $connect->prepare($update); $stmt_update->execute(['verified' => $verified_1, 'status' => $status, 'token_clear' => $token_clear, 'token' => $token]); if ($stmt_update) { // $_SESSION['id'] = $rows['clientID']; // $_SESSION['username'] = $rows['userName']; $_SESSION['verified'] = 1; header('location: member.php'); exit(); } } } function verifyAppoint($token) { global $connect; $sql_token = "SELECT * FROM appointment WHERE token= :token LIMIT 1"; $result = $connect->prepare($sql_token); $result->execute(['token' => $token]); $rows = $result->fetch(PDO::FETCH_ASSOC); if ($rows > 0) { $verified_1 = 1; $status = 'Approved'; $token_clear = ''; $update = "UPDATE appointment SET verified = :verified, status= :status, token= :token_clear WHERE token= :token"; $stmt_update = $connect->prepare($update); $stmt_update->execute(['verified' => $verified_1, 'status' => $status, 'token_clear' => $token_clear, 'token' => $token]); if ($stmt_update) { $_SESSION['id'] = $rows['clientID']; $_SESSION['username'] = $rows['userName']; $_SESSION['verified'] = 1; header('location: myappoint.php'); exit(); } } } <file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script> $(document).ready(function(){ $("#dentist_table").DataTable({ responsive:true, pageLength : 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs:[ { targets: [5], orderable: false } ] }); tinymce.init({ selector: '#bio', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <!-- <div class="main-header"> <div class="main-header__heading">Hello User</div> <div class="main-header__updates">Recent Items</div> </div> --> <div class="main-header"> <div class="main-header__heading">Dentist</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1 appointment__card"> <div class="appoint_table"> <div class="header__sort"> <div class="add"> <button class="button patient_set" onclick="document.getElementById('modal__add').style.display='block'"><i class="fas fa-user-plus icon-m"></i><span>&nbsp;Add New Dentist</span></button> </div> </div> <table class="list__tbl display dt-responsive nowrap" id="dentist_table"> <thead> <tr> <th>Dentist ID</th> <th>Name</th> <th>Email</th> <th>Contact</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_dentist = "SELECT * FROM dentist"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(); $rows_dentist = $stmt_dentist->fetchAll(); foreach($rows_dentist as $row_dentist){ $did = $row_dentist['doctorID']; $email = $row_dentist['email']; $contact = $row_dentist['contact']; $status = $row_dentist['status']; $salut = $row_dentist['Salutation']; $dfn = $row_dentist['firstName']; $dmn = $row_dentist['middleName']; $dln = $row_dentist['lastName']; $dfullname = $salut." ".$dfn." ".$dmn." ".$dln; ?> <tr> <td><?php echo $did?></td> <td><?php echo $dfullname?></td> <td><?php echo $email?></td> <td><?php echo $contact?></td> <td><?php echo $status?></td> <td> <div class="icon_container"> <a href="?viewID=<?php echo $row_dentist['doctorID']?>"><i class="fas fa-eye eye"></i></a>&nbsp; <a href="?editID=<?php echo $row_dentist['doctorID']?>"><i class="fas fa-edit edit"></i></a>&nbsp; <a href="?deleteID=<?php echo $row_dentist['doctorID']?>" onclick="javascript:confirmationDelete(this);return false;"><i class="fas fa-trash bin"></i></a> </div> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- MODAL --> <div id="modal__view" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $dentist_id = $_GET['viewID']; $sql_eachDentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_eachDentist = $connect->prepare($sql_eachDentist); $stmt_eachDentist->execute(['did'=>$dentist_id]); $row_eachDentist = $stmt_eachDentist->fetch(PDO::FETCH_ASSOC); $salut = $row_eachDentist['Salutation']; $dfn = $row_eachDentist['firstName']; $dmn = $row_eachDentist['middleName']; $dln = $row_eachDentist['lastName']; $dfullname = $salut." ".$dfn." ".$dmn." ".$dln; ?> <span class="close" id="close">&times;</span> <span class="modal_header-title"><?php echo $dfullname?>'s Information</span> </div> <div class="modal-body view_body"> <div class="dentist-add_container"> <div class="dentist-image"> <div class="dentist-img_container"> <img src="<?php echo $row_eachDentist['image']?>" alt=""> </div> </div> <div class="dentist-info"> <div class="dentist-info_content"> <div class="dentist-info_name"> <div class="patient_textbox"> <span>Dentist Id:</span> <span class="dentistIdContainer"><?php echo $row_eachDentist['doctorID']?></span> </div> <div class="patient_textbox"> <span>Name:</span> <span id="name"><?php echo $dfullname?></span> </div> <div class="patient_textbox"> <span>Email:</span> <span id="email"><?php echo $row_eachDentist['email']?></span> </div> <div class="patient_textbox"> <span>Contact Number:</span> <span id="contact"><?php echo $row_eachDentist['contact']?></span> </div> <div class="years_content"> <label for="yrs">Years of experience:</label> <span id="yrs"><?php echo $row_eachDentist['experience']?></span> <label for="yrs">Year Start:</label> <span id="yrs"><?php echo $row_eachDentist['yearStart']?></span> </div> </div> </div> </div> <div class="dentist-bio"> <div class="bio_textarea"> <h5>Bio</h5> <textarea name="bio" id="" disabled> <?php echo $row_eachDentist['bio']?></textarea> </div> </div> <div class="dentist-schedule"> <?php $time_did = $_GET['viewID']; $sql_timeView = "SELECT * FROM schedule WHERE doctorID = :time_did"; $stmt_timeView = $connect->prepare($sql_timeView); $stmt_timeView->execute(['time_did'=>$time_did]); $row_timeView = $stmt_timeView->fetch(PDO::FETCH_ASSOC); $start = $row_timeView['starttime']; $starttime = date('g:i a',strtotime($start)); $end = $row_timeView['endtime']; $endtime = date('g:i a',strtotime($end)); $breakstart = $row_timeView['breakstart']; $breakIn = date('g:i a',strtotime($breakstart)); $breakend = $row_timeView['breakend']; $breakOut = date('g:i a',strtotime($breakend)); ?> <div class="sched_container"> <span class="modal_header-title">Select schedule time</span> <div class="dentist-sched_start"> <?php $sql_dayCheck = "SELECT * FROM schedule WHERE doctorID = :did"; $stmt_dayCheck = $connect->prepare($sql_dayCheck); $stmt_dayCheck->execute(['did'=>$dentist_id]); $row_dayCheck = $stmt_dayCheck->fetch(PDO::FETCH_ASSOC); $days = explode(',',$row_dayCheck['day']); ?> <span><input type="checkbox" name="day[]" value="Mon" <?php if(in_array("Mon", $days)) echo "checked=\"checked\""; ?> disabled>Mon</span> <span><input type="checkbox" name="day[]" value="Tue" <?php if(in_array("Tue", $days)) echo "checked=\"checked\""; ?> disabled>Tue</span> <span><input type="checkbox" name="day[]" value="Wed" <?php if(in_array("Wed", $days)) echo "checked=\"checked\""; ?> disabled>Wed</span> <span><input type="checkbox" name="day[]" value="Thu" <?php if(in_array("Thu", $days)) echo "checked=\"checked\""; ?> disabled>Thu</span> <span><input type="checkbox" name="day[]" value="Fri" <?php if(in_array("Fri", $days)) echo "checked=\"checked\""; ?> disabled>Fri</span> <span><input type="checkbox" name="day[]" value="Sat" <?php if(in_array("Sat", $days)) echo "checked=\"checked\""; ?> disabled>Sat</span> <span><input type="checkbox" name="day[]" value="Sun" <?php if(in_array("Sun", $days)) echo "checked=\"checked\""; ?> disabled>Sun</span> </div> <div class="dentist-sched_start"> <select name="start" id=""> <option value="" selected disabled><?php echo $starttime?></option> </select> <span>to</span> <select name="end" id=""> <option value="" selected disabled><?php echo $endtime?></option> </select> </div> </div> <div class="sched_container"> <span class="modal_header-title">Break time schedule</span> <div class="dentist-sched_start"> <select name="breakstart" id=""> <option value="" selected disabled><?php echo $breakIn?></option> </select> <span>to</span> <select name="breakend" id=""> <option value="" selected disabled><?php echo $breakOut?></option> </select> </div> </div> </div> </div> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!--END VIEW MODAL --> <!-- ADD MODAL --> <div id="modal__add" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close_add" onclick="document.getElementById('modal__add').style.display='none'">&times;</span> <h2>Add New Dentist</h2> </div> <div class="modal-body view_body"> <form action="" method="POST" id="dentist__add__form" class="dentist-update__form" enctype="multipart/form-data"> <div class="dentist-add_container"> <div class="dentist-image"> <div class="dentist-img_container"> <img src="../image/icons/doctor.png" alt="" id="img_add"> <label for="dentist_img" class="file-btn-label">Select Image</label> <input type="file" name="file_add" class="file-btn" id="dentist_img" onchange="addimg(event)" size="60"> </div> </div> <div class="dentist-info"> <div class="dentist-info_content"> <div class="dentist-info_name"> <select name="salut" id=""> <option value="Dr.">Dr.</option> <option value="Dra.">Dra.</option> </select> <input type="text" name="fname" placeholder="First Name"> <input type="text" name="mname" placeholder="Middle Name"> <input type="text" name="lname" placeholder="Last Name"> <input type="email" name="email" placeholder="Email"> <input type="text" name="contact" placeholder="Contact"> <div class="years_content edit_years_content"> <input type="text" name="exp" placeholder="Experience"> <input type="text" name="yrStart" placeholder="Year Start"> </div> </div> </div> </div> <div class="dentist-bio"> <div class="bio_textarea"> <h3>Bio</h3> <textarea name="bio" id=""></textarea> </div> </div> <div class="dentist-schedule"> <div class="sched_container"> <h3>Select schedule time</h3> <div class="dentist-sched_start"> <span><input type="checkbox" name="day[]" value="Mon">Mon</span> <span><input type="checkbox" name="day[]" value="Tue">Tue</span> <span><input type="checkbox" name="day[]" value="Wed">Wed</span> <span><input type="checkbox" name="day[]" value="Thu">Thu</span> <span><input type="checkbox" name="day[]" value="Fri">Fri</span> <span><input type="checkbox" name="day[]" value="Sat">Sat</span> <span><input type="checkbox" name="day[]" value="Sun">Sun</span> </div> <div class="dentist-sched_start"> <select name="start" id=""> <option value="" disabled selected>00:00</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> <span>to</span> <select name="end" id=""> <option value="" disabled selected>00:00</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> </div> </div> <div class="sched_container"> <h3>Break time schedule</h3> <div class="dentist-sched_start"> <select name="breakstart" id=""> <option value="" disabled selected>00:00</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> <span>to</span> <select name="breakend" id=""> <option value="" disabled selected>00:00</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> </div> </div> </div> </div> <input type="submit" class="button add_btn" name="add_dentist" id="add_dentist" value="Add Dentist"> </form> </div> <div class="modal-footer"> <h6>Del<NAME>-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- EDIT MODAL --> <div id="modal__edit" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $dentist_id = $_GET['editID']; $sql_eachDentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_eachDentist = $connect->prepare($sql_eachDentist); $stmt_eachDentist->execute(['did'=>$dentist_id]); $row_eachDentist = $stmt_eachDentist->fetch(PDO::FETCH_ASSOC); $salut = $row_eachDentist['Salutation']; $dfn = $row_eachDentist['firstName']; $dmn = $row_eachDentist['middleName']; $dln = $row_eachDentist['lastName']; $dfullname = $salut." ".$dfn." ".$dmn." ".$dln; ?> <span class="close" id="edit_close">&times;</span> <span class="module_header-title">Update <?php echo $dfullname?>'s Information</span> </div> <div class="modal-body view_body"> <form action="" method="POST" id="dentist__form" class="dentist-update__form" enctype="multipart/form-data"> <div class="dentist-add_container"> <div class="dentist-image"> <div class="dentist-img_container"> <?php if($row_eachDentist['image'] == NULL){ ?> <img src="../image/icons/doctor.png" alt=""> <?php }else{?> <img src="<?php echo $row_eachDentist['image'] ?>" alt="" id="img_toUpdate"> <?php }?> <label for="dentist_imge" class="file-btn-label">Select Image</label> <input type="file" name="file_update" class="file-btn" id="dentist_imge" onchange="updateImg(event)"> </div> </div> <div class="dentist-info"> <div class="dentist-info_content"> <div class="dentist-info_name"> <span class="dentistIdContainer"><b>Doctor's ID:</b><?php echo $row_eachDentist['doctorID']?></span> <select name="salut" id=""> <option value="<?php echo $salut?>" selected><?php echo $salut?></option> <option value="" disabled>----</option> <option value="Dr.">Dr.</option> <option value="Dra.">Dra.</option> </select> <input type="text" name="fname" value="<?php echo $dfn?>"> <input type="text" name="mname" value="<?php echo $dmn?>"> <input type="text" name="lname" value="<?php echo $dln?>"> <input type="email" name="email" value="<?php echo $row_eachDentist['email']?>"> <input type="text" name="contact" value="<?php echo $row_eachDentist['contact']?>"> <div class="years_content edit_years_content"> <input type="text" name="exp" value="<?php echo $row_eachDentist['experience']?>"> <input type="text" name="yrStart" value="<?php echo $row_eachDentist['yearStart']?>"> </div> </div> </div> </div> <div class="dentist-bio"> <div class="bio_textarea"> <span class="module_header-title">Bio</span> <textarea name="bio" id="bio"><?php echo $row_eachDentist['bio']?></textarea> </div> </div> <div class="dentist-schedule"> <?php // $dentist_id = $_GET['editID']; $sql_timeSlot = "SELECT * FROM schedule WHERE doctorID = :did"; $stmt_timeSlot = $connect->prepare($sql_timeSlot); $stmt_timeSlot->execute(['did'=>$dentist_id]); $row_timeSlot = $stmt_timeSlot->fetch(PDO::FETCH_ASSOC); $start_TS = new DateTime($row_timeSlot['starttime']); $startTo_TS = $start_TS->format('g:i a'); $end_TS = new DateTime($row_timeSlot['endtime']); $endTo_TS = $end_TS->format('g:i a'); $breakin_TS = new DateTime($row_timeSlot['breakstart']); $breakinTo_TS = $breakin_TS->format('g:i a'); $breakout_TS = new DateTime($row_timeSlot['breakend']); $breakoutTo_TS = $breakout_TS->format('g:i a'); ?> <div class="sched_container"> <span class="module_header-title">Select schedule time</span> <div class="dentist-sched_start"> <?php $sql_dayCheck = "SELECT * FROM schedule WHERE doctorID = :did"; $stmt_dayCheck = $connect->prepare($sql_dayCheck); $stmt_dayCheck->execute(['did'=>$dentist_id]); $row_dayCheck = $stmt_dayCheck->fetch(PDO::FETCH_ASSOC); $days = explode(',',$row_dayCheck['day']); ?> <span><input type="checkbox" name="day[]" value="Mon" <?php if(in_array("Mon", $days)) echo "checked=\"checked\""; ?>>Mon</span> <span><input type="checkbox" name="day[]" value="Tue" <?php if(in_array("Tue", $days)) echo "checked=\"checked\""; ?>>Tue</span> <span><input type="checkbox" name="day[]" value="Wed" <?php if(in_array("Wed", $days)) echo "checked=\"checked\""; ?>>Wed</span> <span><input type="checkbox" name="day[]" value="Thu" <?php if(in_array("Thu", $days)) echo "checked=\"checked\""; ?>>Thu</span> <span><input type="checkbox" name="day[]" value="Fri" <?php if(in_array("Fri", $days)) echo "checked=\"checked\""; ?>>Fri</span> <span><input type="checkbox" name="day[]" value="Sat" <?php if(in_array("Sat", $days)) echo "checked=\"checked\""; ?>>Sat</span> <span><input type="checkbox" name="day[]" value="Sun" <?php if(in_array("Sun", $days)) echo "checked=\"checked\""; ?>>Sun</span> </div> <div class="dentist-sched_start"> <select name="start" id=""> <option value="<?php echo $startTo_TS?>" selected><?php echo $startTo_TS?></option> <option value="" disabled>----</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> <span>to</span> <select name="end" id=""> <option value="<?php echo $endTo_TS?>" selected><?php echo $endTo_TS?></option> <option value="" disabled>----</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> </div> </div> <div class="sched_container"> <span class="module_header-title">Break time schedule</span> <div class="dentist-sched_start"> <select name="breakstart" id=""> <option value="<?php echo $breakinTo_TS?>" selected><?php echo $breakinTo_TS?></option> <option value="" disabled>----</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> <span>to</span> <select name="breakend" id=""> <option value="<?php echo $breakoutTo_TS?>" selected><?php echo $breakoutTo_TS?></option> <option value="" disabled>----</option> <option value="9:00 am" >9:00 am</option> <option value="10:00 am" >10:00 am</option> <option value="11:00 am" >11:00 am</option> <option value="12:00 pm" >12:00 pm</option> <option value="1:00 pm" >1:00 pm</option> <option value="2:00 pm" >2:00 pm</option> <option value="3:00 pm" >3:00 pm</option> <option value="4:00 pm" >4:00 pm</option> <option value="5:00 pm" >5:00 pm</option> <option value="6:00 pm" >6:00 pm</option> <option value="7:00 pm" >7:00 pm</option> <option value="8:00 pm" >8:00 pm</option> <option value="9:00 pm" >9:00 pm</option> <option value="10:00 pm" >10:00 pm</option> </select> </div> </div> </div> <input type="submit" class="button" name="update_dentist" id="update_dentist" value="Update"> </div> </form> </div> <div class="modal-footer"> <h6><NAME>-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- END EDIT MODAL --> </main> </div> <script> // view selected image var addimg = function(event) { var output = document.getElementById('img_add'); output.src = URL.createObjectURL(event.target.files[0]); }; var updateImg = function(event) { var output = document.getElementById('img_toUpdate'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> </div> </body> </html> <?php if(isset($_GET['viewID'])){ echo "<script>var view_modal= document.getElementById('modal__view')</script>"; echo "<script> view_modal.style.display='block'</script>"; } if(isset($_GET['editID'])){ $editid = $_GET['editID']; $_SESSION['dentistEditID'] = $editid; echo "<script>var edit_modal= document.getElementById('modal__edit')</script>"; echo "<script> edit_modal.style.display='block'</script>"; }; //add dentist if(isset($_POST['add_dentist'])){ $salut = $_POST['salut']; $fname = $_POST['fname']; $mname = $_POST['mname']; $lname = $_POST['lname']; $email = $_POST['email']; $contact = $_POST['contact']; $exp = $_POST['exp']; $bio = $_POST['bio']; $yr = $_POST['yrStart']; @$days = $_POST['day']; @$day = implode(',',$days); $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $shuffled = str_shuffle($str); $generatedID = $yr."-".substr($shuffled,0,8); $did = $generatedID; $start = $_POST['start']; $starttime = new DateTime($start); $starttotime = $starttime->format('H:i'); $end = $_POST['end']; $endtime = new DateTime($end); $endtotime = $endtime->format('H:i'); $breakstart = $_POST['breakstart']; $breaktostart = new DateTime($breakstart); $breakIn = $breaktostart->format('H:i'); $breakend = $_POST['breakend']; $breaktoend = new DateTime($breakend); $breakOut = $breaktoend->format('H:i'); $status = 'Active'; if(empty($fname) || empty($lname) || empty($email) || empty($contact) || empty($exp)){ echo "<script>alert('Invalid Email')</script>"; }else if(!filter_var($email,FILTER_VALIDATE_EMAIL)){ echo "<script>alert('Invalid Email')</script>"; }else if(empty($start) || empty($end) || empty($breakstart) || empty($breakend)){ echo "<script>alert('Invalid schedule time')</script>"; }else if(empty($day)){ echo "<script>alert('Invalid schedule day(s)')</script>"; }else if($start == $end || $breakstart == $breakend){ echo "<script>alert('Start and end must not be the same')</script>"; }else if($start == $end && $breakstart == $breakend){ echo "<script>alert('Start and end must not be the same')</script>"; }else if($start == $breakstart || $end == $breakend){ echo "<script>alert('Start and start of break or end and end of break must not be the same')</script>"; }else if($start == $breakstart && $end == $breakend){ echo "<script>alert('Start and start of break or end and end of break must not be the same')</script>"; }else{ // $target_dir = "../image/profile_dentist/"; // $target_file = $target_dir . basename($_FILES["file_add"]["name"]); $target_file = basename($_FILES["file_add"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); $check = getimagesize($_FILES["file_add"]["tmp_name"]); if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif"){ echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed.')</script>"; $uploadOk = 0; }else if($uploadOk == 0){ echo "<script>alert('Sorry, your file was not uploaded.')</script>"; }else{ $sql_add_dentist = "INSERT INTO dentist(doctorID,Salutation,firstName,middleName,lastName,email,contact,experience,yearStart,image,bio,status) VALUES(:did,:salut,:fn,:mn,:ln,:email,:contact,:exp,:yrStart,:img,:bio,:status)"; $smt_add_dentist = $connect->prepare($sql_add_dentist); $smt_add_dentist->execute(['did'=>$did,'salut'=>$salut,'fn'=>$fname,'mn'=>$mname,'ln'=>$lname,'email'=>$email,'contact'=>$contact,'exp'=>$exp,'yrStart'=>$yr,'img'=>$target_file,'bio'=>$bio,'status'=>$status]); $sql_add_sched = "INSERT INTO schedule(doctorID,day,starttime,endtime,breakstart,breakend) VALUES(:did,:day,:start,:end,:brkstrt,:brkend)"; $smt_add_sched = $connect->prepare($sql_add_sched); $smt_add_sched->execute(['did'=>$did,'day'=>$day,'start'=>$starttotime,'end'=>$endtotime,'brkstrt'=>$breakIn,'brkend'=>$breakOut]); if (move_uploaded_file($_FILES["file_add"]["tmp_name"], $target_file)) { echo "<script>alert('Added Successfully');window.location.replace('dentist.php')</script>"; exit(); } else { echo "Sorry, there was an error uploading your file."; } } } }; //update dentist if(isset($_POST['update_dentist'])){ $did = $_SESSION['dentistEditID']; $salut = $_POST['salut']; $fname = $_POST['fname']; $mname = $_POST['mname']; $lname = $_POST['lname']; $email = $_POST['email']; $contact = $_POST['contact']; $exp = $_POST['exp']; $bio = $_POST['bio']; $days = $_POST['day']; $day = implode(',',$days); $start = $_POST['start']; $starttime = new DateTime($start); $starttotime = $starttime->format('H:i'); $end = $_POST['end']; $endtime = new DateTime($end); $endtotime = $endtime->format('H:i'); $breakstart = $_POST['breakstart']; $breaktostart = new DateTime($breakstart); $breakIn = $breaktostart->format('H:i'); $breakend = $_POST['breakend']; $breaktoend = new DateTime($breakend); $breakOut = $breaktoend->format('H:i'); // $target_dir = "../image/profile_dentist/"; // $target_file = $target_dir . basename($_FILES["file_update"]["name"]); $target_file = basename($_FILES["file_update"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); $check = getimagesize($_FILES["file_update"]["tmp_name"]); if(empty($fname) || empty($lname) || empty($email) || empty($contact) || empty($exp)){ echo "<span class='form__error'>Fill in all fields!</span>"; $errorEmpty = true; }else if(!filter_var($email,FILTER_VALIDATE_EMAIL)){ echo "<span class='form__error'>Write a valid e-mail address!</span>"; $errorEmail = true; }else if($start == $end || $breakstart == $breakend){ echo "<script>alert('Start and end must not be the same')</script>"; }else if($start == $end && $breakstart == $breakend){ echo "<script>alert('Start and end must not be the same')</script>"; }else if($start == $breakstart || $end == $breakend){ echo "<script>alert('Start and start of break or end and end of break must not be the same')</script>"; }else if($start == $breakstart && $end == $breakend){ echo "<script>alert('Start and start of break or end and end of break must not be the same')</script>"; }else{ $check_img = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_img = $connect->prepare($check_img); $stmt_img->execute(['did'=>$did]); $row_img = $stmt_img->fetch(PDO::FETCH_ASSOC); $curImg = $row_img['image']; $sql_update_sched = "UPDATE schedule SET day = :day, starttime =:start, endtime = :end, breakstart = :breakstart, breakend = :breakend WHERE doctorID = :did"; $smt_update_sched = $connect->prepare($sql_update_sched); $smt_update_sched->execute(['day'=>$day,'start'=>$starttotime,'end'=>$endtotime,'breakstart'=>$breakIn,'breakend'=>$breakOut,'did'=>$did]); if(empty($_FILES["file_update"]["tmp_name"])){ $sql_update_dentist = "UPDATE dentist SET Salutation =:salut, firstName = :fn, middleName = :mn, lastName = :ln, email = :email, contact = :contact, experience = :exp, image = :curimg, bio = :bio WHERE doctorID = :did"; $smt_update_dentist = $connect->prepare($sql_update_dentist); $smt_update_dentist->execute(['salut'=>$salut,'fn'=>$fname,'mn'=>$mname,'ln'=>$lname,'email'=>$email,'contact'=>$contact,'exp'=>$exp,'curimg'=>$curImg,'bio'=>$bio,'did'=>$did]); echo "<script>alert('Updated Successfully');window.location.replace('dentist.php')</script>"; exit(); }else if(move_uploaded_file($_FILES["file_update"]["tmp_name"],$target_file)){ $sql_update_dentist = "UPDATE dentist SET Salutation =:salut, firstName = :fn, middleName = :mn, lastName = :ln, email = :email, contact = :contact, experience = :exp, image = :newimg, bio = :bio WHERE doctorID = :did"; $smt_update_dentist = $connect->prepare($sql_update_dentist); $smt_update_dentist->execute(['salut'=>$salut,'fn'=>$fname,'mn'=>$mname,'ln'=>$lname,'email'=>$email,'contact'=>$contact,'exp'=>$exp,'newimg'=>$target_file,'bio'=>$bio,'did'=>$did]); echo "<script>alert('Updated Successfully');window.location.replace('dentist.php')</script>"; exit(); } } } if(isset($_GET['deleteID'])){ $did = $_GET['deleteID']; $sql_delete_dentist = "DELETE FROM dentist WHERE doctorID = :did"; $stmt_delete_dentist = $connect->prepare($sql_delete_dentist); $stmt_delete_dentist->execute(['did'=>$did]); $sql_delete_sched = "DELETE FROM schedule WHERE doctorID = :did"; $stmt_delete_sched = $connect->prepare($sql_delete_sched); $stmt_delete_sched->execute(['did'=>$did]); echo "<script>alert('Deleted Successfully'); window.location.replace('dentist.php')</script>"; } ?> <script> const close = $('#close'); // When the user clicks on <span> (x), close the modal close.on('click', function() { view_modal.style.display = "none"; window.location.replace('dentist.php'); }); const edit_close = $('#edit_close'); // When the user clicks on <span> (x), close the modal edit_close.on('click', function() { edit_modal.style.display = "none"; window.location.replace('dentist.php'); }); //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Confirmation for DELETE function confirmationDelete(anchor) { var conf = confirm('Are you sure want to delete this service?'); if(conf) window.location=anchor.attr("href"); }; </script> <file_sep><?php session_start(); if (empty($_SESSION['ogliadmin'])) { echo "<script>window.location.replace('sign-in.php')</script>"; } include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><NAME> | Appointment Record</title> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" type="text/css" href="DataTables/DataTables-1.10.20/css/jquery.dataTables.min.css" /> <link rel="stylesheet" type="text/css" href="DataTables/Buttons-1.6.0/css/buttons.dataTables.min.css" /> <link rel="stylesheet" type="text/css" href="DataTables/Responsive-2.2.3/css/responsive.dataTables.min.css" /> <link rel="stylesheet" type="text/css" href="DataTables/RowGroup-1.1.1/css/rowGroup.dataTables.min.css" /> </head> <style> .dt-print-table, .dt-print-table thead, .dt-print-table th, .dt-print-table tr { border: 0 none !important; } .dt-print-table h1 { font-size: 22px !important; margin: 10px 0; letter-spacing: 2px; } .dt-print-table h3 { font-size: 14px; margin: 10px 0; letter-spacing: 2px; } .dt-print-table .header-print { display: flex; justify-content: space-around; align-items: center; margin: 35px 0; } .dt-print-table .header-print .header-print-logo img { width: 150px !important; height: 150px !important; } @media print { html, body { height: auto; } .dt-print-table, .dt-print-table thead, .dt-print-table th, .dt-print-table tr { border: 0 none !important; color: #000; } .dt-print-table h1 { font-size: 28px !important; margin: 15px 0; letter-spacing: 2px; } .dt-print-table h3 { margin: 15px 0; letter-spacing: 2px; } .dt-print-table .header-print { display: flex; justify-content: space-around; align-items: center; } .dt-print-table .header-print .header-print-logo img { width: 150px !important; height: 150px !important; } } </style> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Appointment Records</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <div class="table appoint_table"> <table class="list__tbl display dt-responsive nowrap dt-print-table" id="appoint-list"> <thead> <tr> <th>Appoint ID</th> <th>Patient Name</th> <th>Service</th> <th>Dentist</th> <th>Date</th> <th>Time</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $pend = 'Pending'; $app = 'Approved'; $sql_apoint = "SELECT * FROM appointment WHERE status NOT IN(:pending,:approved) ORDER BY timestamp DESC"; $stmnt_appoint = $connect->prepare($sql_apoint); $stmnt_appoint->execute(['pending' => $pend, 'approved' => $app]); $rows_appoint = $stmnt_appoint->fetchAll(PDO::FETCH_ASSOC); foreach ($rows_appoint as $rows) { $date = new DateTime($rows['appointmentDate']); $start = new DateTime($rows['start']); $end = new DateTime($rows['end']); $pid = $rows['clientID']; $did = $rows['doctorID']; $sql_patient = "SELECT * FROM client WHERE clientID = :pid"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['pid' => $pid]); $row_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $fn = $row_patient['firstName']; $mn = $row_patient['middleName']; $ln = $row_patient['lastName']; $name = $fn . " " . $mn . " " . $ln; $sql_dentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(['did' => $did]); $row_dentist = $stmt_dentist->fetch(PDO::FETCH_ASSOC); $salut = $row_dentist['Salutation']; $fn = $row_dentist['firstName']; $mn = $row_dentist['middleName']; $ln = $row_dentist['lastName']; $dentistName = $salut . "" . $fn . "&nbsp;" . $mn . "&nbsp;" . $ln; ?> <tr> <td><?php echo $rows['appointID'] ?></td> <td><?php echo $name ?></td> <td><?php echo $rows['service'] ?></td> <td><?php echo $dentistName ?></td> <td><?php echo date_format($date, 'd M Y') ?></td> <td><?php echo date_format($start, 'g:i a') . "-" . date_format($end, 'g:i a') ?></td> <td> <?php echo $rows['status']; ?> </td> <td><a href="?viewID=<?php echo $rows['appointID'] ?>"><i class="fas fa-eye eye"></i></a></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- MODAL --> <div id="modal__view" class="modal view"> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close">&times;</span> <span class="modal_header-title">Patient's Appointment Info</span> </div> <div class="modal-body view_body"> <div class="modal-view-body_container"> <div class="view__info"> <div class="patient_info_content"> <?php $aid = $_GET['viewID']; $sql_info = "SELECT * FROM appointment WHERE appointID = :aid"; $stmt_info = $connect->prepare($sql_info); $stmt_info->execute(['aid' => $aid]); $row_info = $stmt_info->fetch(PDO::FETCH_ASSOC); $date_info = new DateTime($row_info['appointmentDate']); $start_info = new DateTime($row_info['start']); $end_info = new DateTime($row_info['end']); $patient_id = $row_info['clientID']; $dentist_id = $row_info['doctorID']; $sql_patient = "SELECT * FROM client WHERE clientID = :pid"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['pid' => $patient_id]); $row_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $fn = $row_patient['firstName']; $mn = $row_patient['middleName']; $ln = $row_patient['lastName']; $fullname = $fn . " " . $mn . " " . $ln; $sql_dentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(['did' => $dentist_id]); $row_dentist = $stmt_dentist->fetch(PDO::FETCH_ASSOC); $salut = $row_dentist['Salutation']; $dfn = $row_dentist['firstName']; $dmn = $row_dentist['middleName']; $dln = $row_dentist['lastName']; $dfullname = $salut . " " . $dfn . " " . $dmn . " " . $dln; ?> <div class="patient_textbox"> <span>Appointment Id:</span> <span><?php echo $row_info['appointID'] ?></span> </div> <div class="patient_textbox"> <span>Patient's ID:</span> <span><?php echo $row_info['clientID'] ?></span> </div> <div class="patient_textbox"> <span>Patient's name:</span> <span><?php echo $fullname ?></span> </div> <div class="patient_textbox"> <span>Dentist:</span> <span><?php echo $dfullname ?></span> </div> <div class="patient_textbox"> <span>Service:</span> <span><?php echo $row_info['service'] ?></span> </div> <div class="patient_textbox"> <span>Schedule Date:</span> <span><?php echo date_format($date_info, 'd M Y') ?></span> </div> <div class="patient_textbox"> <span>Schedule Time:</span> <span><?php echo date_format($start_info, 'g:i a') . "-" . date_format($end_info, 'g:i a') ?></span> </div> </div> </div> </div> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> </main> </div> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/script.js"></script> <script type="text/javascript" src="DataTables/DataTables-1.10.20/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="DataTables/Buttons-1.6.0/js/dataTables.buttons.min.js"></script> <script type="text/javascript" src="DataTables/Buttons-1.6.0/js/buttons.print.js"></script> <script type="text/javascript" src="DataTables/Responsive-2.2.3/js/dataTables.responsive.min.js"></script> <script type="text/javascript" src="DataTables/RowGroup-1.1.1/js/dataTables.rowGroup.min.js"></script> <script> $(document).ready(function() { $("#appoint-list").DataTable({ responsive: true, pageLength: 5, "aaSorting": [], "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [6, 7], orderable: false, }, { responsivePriority: 1, targets: 0 }, { responsivePriority: 2, targets: 6 } ], initComplete: function() { this.api().columns([6]).every(function() { var column = this; var select = $('<select class="status_dd" id="status_dis"><option value="" disabled selected>Status</option><option value="">All</option></select>') .appendTo($(column.header()).empty()) .on('change', function() { // var status_ok = $('#status_dis').find(":selected").html(); // console.log(status_ok); var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search(val ? '^' + val + '$' : '', true, false) .draw(); }); column.data().unique().sort().each(function(d) { select.append('<option value="' + d + '" id="status_okok">' + d + '</option>') }); }); }, dom: 'Bfrtip', buttons: [{ extend: 'print', text: '<i class="fas fa-print"></i>', title: function() { return $('#status_dis').find(":selected").text() + " Appointments"; }, titleAttr: 'Print', exportOptions: { columns: [0, 1, 2, 3, 4, 5, 6] }, repeatingHead: { logo: '', logoPosition: '', logoStyle: 'width:150px;height:150px;object-fit:cover;border-radius:50%;position:absolute;right:0;top:0;z-index-1;', title: '<div class="header-print"><div class="header-print-info"><h1>Dela Paz-Oglimen Dental Care Clinic \'08</h1><h3>2nd Flr. <NAME>,<h3> Km. 30 Brgy. Burol,</h3><h3> <NAME>,</h3><h3>Dasmariñas, Cavite Cavite City 4114</h3><h3>+(63) 925 759 7983</h3>' + "" + '</div><div class="header-print-logo"><img src="../image/dpom_logo.png"></div></div>' } }] }); }) </script> </body> </html> <?php if (isset($_GET['viewID'])) { echo "<script>var view_modal= document.getElementById('modal__view')</script>"; echo "<script> view_modal.style.display='block'</script>"; $_SESSION['viewID'] = $_GET['viewID']; } ?> <script> const close = $('#close'); // When the user clicks on <span> (x), close the modal close.on('click', function() { view_modal.style.display = "none"; window.location.replace('appoint-history.php'); }); const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); function confirmationLogout(anchor) { var conf = confirm('Are you sure want to SIGN OUT?'); if (conf) window.location = anchor.attr("href"); } </script><file_sep><?php require '../../config/control.php'; $column ?><file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CMS | Testimonials</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script> $(document).ready(function() { $("input:checkbox").on("change", function() { var val = $(this).val(); var apply = $(this).is(':checked') ? 1 : 0; $.ajax({ type: "POST", url: "check.php", data: { val: val, apply: apply } }); }); $("#testimonial_list").DataTable({ responsive: true, pageLength: 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [3], orderable: false }] }); $(document).ready(function() { $("#appoint-list").DataTable({ pageLength: 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [7], orderable: false }] }); }) }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Content Management/ Testimonials</div> </div> <div id="result"></div> <div class="main-cards appoint__cards"> <div class="card card-1 appointment__card"> <div class=" appoint_table"> <div class="header__sort"> <div class="add"> <button class="button patient_set" onclick="document.getElementById('modal__add').style.display='block'"><i class="fas fa-bullhorn icon-m"></i><span>&nbsp;Add new testimonials</span></button> </div> </div> <div class="header__sort"> </div> <table class="list__tbl display dt-responsive" id="testimonial_list"> <thead> <tr> <th>ID</th> <th>NAME</th> <th>TESTIMONIAL</th> <th>ACTION</th> </tr> </thead> <tbody> <?php $sql_testi = "SELECT * FROM cms_testi"; $stmt_testi = $connect->prepare($sql_testi); $stmt_testi->execute(); $rows_testi = $stmt_testi->fetchAll(); foreach ($rows_testi as $testi) { $testi_id = $testi['id']; $sql_testiChecked = "SELECT * FROM cms_testi WHERE id = :id"; $stmt_testiChecked = $connect->prepare($sql_testiChecked); $stmt_testiChecked->execute(['id' => $testi_id]); $row_testiChecked = $stmt_testiChecked->fetch(PDO::FETCH_ASSOC); $switch = $row_testiChecked['switch']; ?> <tr> <td><?php echo $testi['id'] ?></td> <td><?php echo $testi['name'] ?></td> <td><?php echo $testi['testimonials'] ?></td> <td> <label class="switch"> <input type="checkbox" class="check_box" name="testi_id[]" value="<?php echo $testi['id'] ?>" id="toggle" <?php if (($testi['switch']) == '1') echo "checked='checked'"; ?>> <span class="slider round"></span> </label> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </main> </div> </body> </html> <script> //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); </script><file_sep><?php session_start(); require_once 'config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/modal.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> <link rel="stylesheet" href="css/about.css"> </head> <body> <?php include 'header.php'; ?> <div class="page-container"> <main> <section class="section-about" id="about"> <?php $sql_aboutUs = "SELECT * FROM cms_about"; $stmt_aboutUs = $connect->prepare($sql_aboutUs); $stmt_aboutUs->execute(); $row_aboutUs = $stmt_aboutUs->fetch(PDO::FETCH_ASSOC); $text = $row_aboutUs['text']; $banner = $row_aboutUs['img']; ?> <div class="about-info"> <h1>ABOUT US</h1> <h3>Dela Paz-Oglimen Dental Care Clinic</h3> <p><?php echo $text ?></p> </div> <div class="about-banner"> <a href="<?php echo (empty($banner)) ? 'image/smile3.jpeg' : 'image/' . $banner ?>"><img src="<?php echo (empty($banner)) ? 'image/smile3.jpeg' : 'image/' . $banner ?>" alt=""></a> </div> </section> <section class="section-team" id="ourTeam"> <div class="team-container"> <h1>Meet Our Dentist</h1> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Incidunt eaque voluptatum earum. Nisi in, </p> <div class="main-cards"> <?php $sql_dentists = "SELECT * FROM dentist"; $stmt_dentists = $connect->prepare($sql_dentists); $stmt_dentists->execute(); $rows_dentists = $stmt_dentists->fetchALl(); foreach ($rows_dentists as $dentists) { $salut = $dentists['Salutation']; $fn = $dentists['firstName']; $ln = $dentists['lastName']; $dentistsName = $salut . " " . $fn . " " . $ln; $profile = $dentists['image']; $bio = $dentists['bio']; ?> <div class="card-dentist middle"> <div class="image-container front"> <img src="<?php echo (empty($profile)) ? 'image/profile_dentist/smile2.jpeg' : 'image/' . $profile ?>" alt=""> </div> <div class="back"> <div class="back-content middle"> <h2><?php echo $dentistsName ?></h2> <p><?php echo $bio ?></p> <div class="social-media"> <span><i class="fab fa-facebook-f fb"></i></span> <span><i class="fab fa-twitter tw"></i></span> <span><i class="fab fa-instagram ig"></i></span> </div> </div> </div> </div> <?php } ?> </div> </div> </section> <section class="testimonials" id="testimonials"> <h1>What they say about us</h1> <div class="testimonial-slider"> <?php $sql_first_testimonials = "SELECT * FROM cms_testi WHERE switch = 1 ORDER BY id DESC LIMIT 1"; $stmt_first_testimonials = $connect->prepare($sql_first_testimonials); $stmt_first_testimonials->execute(); $rows_first_testimonials = $stmt_first_testimonials->fetch(PDO::FETCH_ASSOC); ?> <div class="testimonial-slide current"> <blockquote> <p> <?php echo $rows_first_testimonials['testimonials'] ?> </p> <h3><?php echo $rows_first_testimonials['name'] ?></h3> </blockquote> </div> <?php $sql_testimonials = "SELECT * FROM cms_testi WHERE switch = 1 AND id NOT IN (SELECT MAX(id) FROM cms_testi) ORDER BY id ASC"; $stmt_testimonials = $connect->prepare($sql_testimonials); $stmt_testimonials->execute(); $rows_testimonials = $stmt_testimonials->fetchAll(); foreach ($rows_testimonials as $testimonials) { ?> <div class="testimonial-slide"> <blockquote> <p> <?php echo $testimonials['testimonials']; ?> </p> <h3><?php echo $testimonials['name']; ?></h3> </blockquote> </div> <?php } ?> </div> <div class="slider-buttons testimonial-slider--buttons"> <button id="prev"><i class="fas fa-arrow-left"></i></button> <button id="next"><i class="fas fa-arrow-right"></i></button> </div> <?php if (isset($_SESSION['id'])) { ?> <div class="feedback"> <button id="feedback_btn">Give us some feed back</button> </div> <?php } else { } ?> </section> </main> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </div> <!-- modal --> <div id="modal_feedback" class="modal"> <!-- Modal content --> <div class="modal-content modal-content-small"> <div class="modal-header"> <span class="close" id="feedback_close">&times;</span> <h2>Give us some feedback</h2> </div> <form action="" method="POST"> <div class="modal-body "> <div class="rate-container"> <h3>Please rate us!</h3> <div class="rate"> <input type="radio" id="star5" name="rate5" value="5" /> <label for="star5" title="text">5 stars</label> <input type="radio" id="star4" name="rate4" value="4" /> <label for="star4" title="text">4 stars</label> <input type="radio" id="star3" name="rate3" value="3" /> <label for="star3" title="text">3 stars</label> <input type="radio" id="star2" name="rate2" value="2" /> <label for="star2" title="text">2 stars</label> <input type="radio" id="star1" name="rate1" value="1" /> <label for="star1" title="text">1 star</label> </div> </div> <div class="comment"> <h2>Write a review</h2> <textarea name="comment" class="comment_area" id="" cols="30" rows="10"></textarea> </div> <div class="btn-container"> <input type="submit" class="button" name="testify" value="Submit"> </div> </div> </form> </div> </div> <!-- script js --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/main.js"></script> <script src="js/testimonial.js"></script> <script src="js/simple-lightbox.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script> $(function() { var lightbox = $('.about-banner a').simpleLightbox(); }); </script> </body> </html> <?php if (isset($_POST['testify'])) { $patientID = $_SESSION['id']; $testimonial = $_POST['comment']; $sql_getPatientInfo = "SELECT * FROM client WHERE clientID = :id"; $stmt_getPatientInfo = $connect->prepare($sql_getPatientInfo); $stmt_getPatientInfo->execute(['id' => $patientID]); $row_getPatientInfo = $stmt_getPatientInfo->fetch(PDO::FETCH_ASSOC); $patient_id = $row_getPatientInfo['clientID']; $fname = $row_getPatientInfo['firstName']; $lname = $row_getPatientInfo['lastName']; $name = $fname . " " . $lname; $sql_comment = "INSERT INTO cms_testi (name,testimonials) VALUES (:name,:testimonial)"; $stmt_comment = $connect->prepare($sql_comment); $stmt_comment->execute(['name' => $name, 'testimonial' => $testimonial]); echo "<script>alert('Submit Successfully');window.location.replace('about.php#testimonials')</script>"; } ?><file_sep> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendarView'); var now = new Date();//today's date var today = now.setDate(now.getDate());//current date + 1 day var calendar_view = new FullCalendar.Calendar(calendarEl, { height: 400, plugins: [ 'interaction', 'dayGrid', 'timeGrid','moment','momentTimezone'], header: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridDay' }, defaultView: 'dayGridMonth', validRange: { start: today }, dateClick: function(info,date) { document.getElementById('strDate').value = info.dateStr; }, selectable: false, editable: false, navLinks: true, eventLimit: true, // allow "more" link when too many events eventSources:[ './data/client_each_event.php', { url: '../events/event_holiday.php', rendering: 'background' }, ], eventOverlap:false, slotEventOverlap: false }); calendar_view.render(); }); <file_sep><?php include '../../config/control.php'; $sql_updateBell = "UPDATE appointment SET view = 1 WHERE view=0"; $stmt_updateBell = $connect->prepare($sql_updateBell); $stmt_updateBell->execute(); $sql_bellContent = "SELECT * FROM appointment ORDER BY timestamp DESC LIMIT 5"; $stmt_bellContent = $connect->prepare($sql_bellContent); $stmt_bellContent->execute(); $response = ''; while ($rowss = $stmt_bellContent->fetch(PDO::FETCH_ASSOC)) { $timestamp = new DateTime($rowss['timestamp']); $time_sent = date_format($timestamp, 'd-m-Y g:i a'); $pid = $rowss["clientID"]; $sql_patient = "SELECT * FROM client WHERE clientID = :pid"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['pid' => $pid]); $row_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $fn = $row_patient['firstName']; $mn = $row_patient['middleName']; $ln = $row_patient['lastName']; $full = $ln . " " . $fn . " " . $mn; $response .= '<li class="bell__links__list"> <a href="appoint-list.php?viewID=' . $rowss['appointID'] . '" class="bell__list"> <div class="bell__list__container"> <span class="list__header">' . $full . '</span> </div> <div class="bell__info__container"> <span class="list__info">' . $rowss["service"] . '</span> <span class="list__time"><em>' . $time_sent . '</em></span> </div> </a> </li>'; } if (!empty($response)) { print $response; } <file_sep><?php session_start(); if (empty($_SESSION['ogliadmin'])) { echo "<script>window.location.replace('sign-in.php')</script>"; } include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><NAME> | ADMIN</title> <link rel="stylesheet" href="../css/style.css"> <link href='../fullcalendar/core/main.min.css' rel='stylesheet' /> <link href='../fullcalendar/daygrid/main.min.css' rel='stylesheet' /> <link href='../fullcalendar/timegrid/main.min.css' rel='stylesheet' /> <link href='../fullcalendar/list/main.min.css' rel='stylesheet' /> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-overview"> <a href="" class="overview-card"> <div class="overviewcard"> <?php $sql_count_total = "SELECT * FROM client"; $stmt_count_total = $connect->prepare($sql_count_total); $stmt_count_total->execute(); $rows_count_total = $stmt_count_total->fetchAll(PDO::FETCH_ASSOC); $rows_total = count($rows_count_total); $sql_count_new = "SELECT * FROM client WHERE CURRENT_DATE <= DATE_ADD(DATE(date), INTERVAL 15 DAY) ORDER BY date ASC"; $stmt_count_new = $connect->prepare($sql_count_new); $stmt_count_new->execute(); $rows_count_new = $stmt_count_new->fetchAll(PDO::FETCH_ASSOC); $rows_count = count($rows_count_new); ?> <div class="overviewcard__icon"><span><i class="fas fa-user card-icon green"></i></span></div> <div class="overviewcard__info"> <div class="overviewcard__info__contain"> <span class="text">Total&nbsp;Clients:</span><span class="number"><?php echo $rows_total ?></span> </div> <div class="overviewcard__info__contain"> <span class="text">New&nbsp;Clients:</span><span class="number"> <?php echo $rows_count ?></span> </div> </div> </div> </a> <a href="appoint-list.php" class="overview-card"> <div class="overviewcard"> <?php $verified = 1; $sql_cnt_appoint = "SELECT * FROM appointment"; $stmt_cnt_appoint = $connect->prepare($sql_cnt_appoint); $stmt_cnt_appoint->execute(['verified' => $verified]); $rows_cnt_appoint = $stmt_cnt_appoint->fetchAll(PDO::FETCH_ASSOC); $rows_appoint = count($rows_cnt_appoint); ?> <div class="overviewcard__icon"><span><i class="fas fa-calendar-check card-icon green"></i></span></div> <div class="overviewcard__info"> <div class="overviewcard__info__contain"> <span class="text">Appointments: </span><span class="number"><?php echo $rows_appoint ?></span> </div> </div> </div> </a> <a href="message.php"> <div class="overviewcard"> <?php $sql_messages = $connect->prepare("SELECT * FROM inquiry"); $sql_messages->execute(); $row_cnt_messages = $sql_messages->fetchAll(); $count_messages = count($row_cnt_messages); ?> <div class="overviewcard__icon"><span><i class="fa fa-envelope card-icon green"></i></span></div> <div class="overviewcard__info"> <div class="overviewcard__info__contain"> <span class="text">Messages:</span><span class="number"><?php echo $count_messages ?></span> </div> </div> </div> </a> </div> <div class="main-cards"> <div class="card card-1"> <div id="calendar" class="calendar"></div> </div> <div class="card card-3"><canvas id="myChart"></canvas></div> <div class="card card-4"><canvas id="cancelled_chart"></canvas></div> </div> </main> </div> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="js/script.js"></script> <script src="js/chart.js"></script> <script src='../fullcalendar/core/main.min.js'></script> <script src='../fullcalendar/daygrid/main.min.js'></script> <script src='../fullcalendar/timegrid/main.min.js'></script> <script src='../fullcalendar/interaction/main.min.js'></script> <script src='../fullcalendar/list/main.min.js'></script> <script src='../fullcalendar/moment/main.min.js'></script> <script src='../fullcalendar/moment-timezone/main.min.js'></script> <script src="../js/moment.min.js"></script> <script src="js/calendar-script.js"></script> <script src="../chart/chartjs/dist/Chart.js"></script> <script> const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); function confirmationLogout(anchor) { var conf = confirm('Are you sure want to SIGN OUT?'); if (conf) window.location = anchor.attr("href"); } </script> </body> </html><file_sep>$(document).ready(function() { $('#doctor').on('change', function() { var doctorID = $('#doctor').val(); var date = $('#strDate').val(); $select = $('#starttime'); $.ajax({ url: 'time.php', type: 'POST', data: { doctorID: doctorID, date: date }, dataType: 'JSON', success: function(data) { $select.html(''); //iterate over the data and append a select option $select.append('<option value="" selected disabled>Please Select Time</option>'); console.log(data.optionTime); console.log(data.time); // const hide_time = data.optionTime; // const hide_time2 = hide_time[0]; // const hide_the_time = hide_time2.option; // console.log(hide_the_time); // for (i = 0; i < data.optionTime.length; i++) { // var optTime = data.optionTime[i]; // var new_object = $.extend({}, optTime); // console.log(new_object); // } $.each(data.optionTime, function(key, value) { const hide_time = value.option; $.each(data.time, function(key, value) { // console.log(value.starts); const startTheTime = value.starts; // $.each(data.optionTime, function(key, value) { // const hide_time = value.option; // for (i = 0; i < hide_time.length; i++) { // const hideTheTime = hide_time[i].startoftime; // console.log(hideTheTime); // } // }); if (jQuery.inArray(startTheTime, hide_time) !== -1) { $('#starttime').append( '<option disabled value=' + startTheTime + '>' + startTheTime + '</option>' ); } else { $('#starttime').append('<option value=' + startTheTime + '>' + startTheTime + '</option>'); } // console.log(startTheTime); }); var found = {}; $('#starttime option').each(function() { var $this = $(this); if (found[$this.attr('value')] && $this.prop('disabled') == false) { $this.remove(); // found[$this.attr('value')] = true; } else { // $this.remove(); found[$this.attr('value')] = true; } }); }); } }); }); $('#strDate').change(function() { var strDate = $('#strDate').val(); $.ajax({ url: 'doctor-sched.php', type: 'POST', dataType: 'json', data: { strDate: strDate }, success: function(response) { $selectDentist = $('#doctor'); $selectDentist.html(''); //iterate over the data and append a select option $selectDentist.append('<option value="" selected disabled>Please Select Dentist</option>'); $.each(response.doctor, function(key, value) { $('#doctor').append('<option value=' + value.doctorID + '>' + value.doctorName + '</option>'); }); } }); }); }); $("#strDate").datepicker({ minDate: 0, showAnim: 'fadeIn', dateFormat: 'yy-mm-dd' }); <file_sep> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendarSet'); var now = new Date();//today's date var today = now.setDate(now.getDate()); var calendar = new FullCalendar.Calendar(calendarEl, { height:400, plugins: [ 'interaction', 'dayGrid', 'timeGrid','moment','momentTimezone'], header: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridDay' }, defaultView: 'dayGridMonth', validRange: { start: today }, dateClick: function(info,jsEvent, view) { document.getElementById('strDate').value = info.dateStr; var strDate = document.getElementById('strDate').value; $.ajax({ url: "./../doctor-sched.php", type: 'POST', dataType: "json", data: {strDate:strDate}, success: function(response){ $select = $('#dentist'); $select.html(''); //iterate over the data and append a select option $select.append('<option value="" selected disabled>Please select dentist</option>'); $.each(response.doctor,function(key,value){ $("#dentist").append( "<option value=" +value.doctorID + ">"+value.doctorName+"</option>" ); }); } }) }, selectable: false, editable: false, navLinks: true, eventLimit: true, // allow "more" link when too many events eventSources:[ '../events/event.php', '../events/event_pending.php', { url: '../events/event_holiday.php', rendering: 'background' }, ], eventOverlap:false, slotEventOverlap: false }); calendar.render(); }); <file_sep>const closeModal = () => { const cancel_modal = document.querySelector('#cancel_modal'); const view_modal = document.querySelector('#view_modal'); const close_cancel_modal = document.querySelector('#close_cancel_modal'); const no_cancel_modal = document.querySelector('#no_button'); const close_view_modal = document.querySelector('#close_view_modal'); const resched_modal = document.querySelector('#resched_modal'); const close_reched_modal = document.querySelector('#close_resched_modal'); close_cancel_modal.addEventListener('click', () => { cancel_modal.classList.remove('modal_show'); window.location.replace('account.php'); }); no_cancel_modal.addEventListener('click', () => { cancel_modal.classList.remove('modal_show'); window.location.replace('account.php'); }); close_view_modal.addEventListener('click', () => { view_modal.classList.remove('modal_show'); window.location.replace('account.php'); }); close_reched_modal.addEventListener('click', () => { resched_modal.classList.remove('modal_show'); console.log('click'); window.location.replace('account.php'); }); }; closeModal(); const accountModal = () => { const edit_account_btn = document.querySelector('#edit_account_btn'); const account_modal = document.querySelector('#account_modal'); const close_account_modal = document.querySelector('#close_account_modal'); edit_account_btn.addEventListener('click', () => { account_modal.classList.add('modal_show'); }); close_account_modal.addEventListener('click', () => { account_modal.classList.remove('modal_show'); }); }; accountModal(); //preview image js vanilla const profileImage = () => { const imageInput = document.querySelector('#account_profile_file'); const account_img = document.querySelector('#account_img'); const reader = new FileReader(); reader.onload = (e) => { account_img.src = e.target.result; }; imageInput.addEventListener('change', (e) => { const f = e.target.files[0]; reader.readAsDataURL(f); }); }; profileImage(); <file_sep><?php $host ="localhost"; $user ="root"; $password =""; $dbname = "cera"; //SET DSN $dsn= 'mysql:host='. $host . ';dbname='.$dbname; //CREATE PDO Instance $connect = new PDO($dsn,$user,$password); $connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); ?><file_sep><?php if (isset($_GET['cancel'])) { $id = $_GET['cancel']; echo "<script>const cancel_modal = document.getElementById('cancel_modal')</script>"; echo "<script> cancel_modal.classList.add('modal_show')</script>"; }; if (isset($_GET['view'])) { $id = $_GET['view']; echo "<script>const view_modal = document.getElementById('view_modal')</script>"; echo "<script> view_modal.classList.add('modal_show')</script>"; }; if (isset($_GET['appointID'])) { $id = $_GET['appointID']; echo "<script>const resched_modal = document.getElementById('resched_modal')</script>"; echo "<script> resched_modal.classList.add('modal_show')</script>"; }; <file_sep><?php require_once 'controllers/authController.php'; if (empty($_SESSION['ogliadmin'])) { echo "<script>window.location.replace('sign-in.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><NAME> | ADMIN</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="../js/moment.min.js"></script> <script> $(document).ready(function() { $(".patient_list").DataTable({ responsive: true, pageLength: 5, "aaSorting": [], "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [4], orderable: false }, { responsivePriority: 1, targets: 0 }, { responsivePriority: 2, targets: 4 }] }); }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Patient List</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <div class=" appoint_table"> <!-- <div class="header__sort"> <div class="add"> <button class="button patient_set" onclick="document.getElementById('modal__add').style.display='block'"><i class="fas fa-calendar-check check"></i>&nbsp;Set&nbsp;an&nbsp;appointment</button> </div> </div> --> <table class="list__tbl display dt-responsive nowrap patient_list" id="patient-list"> <thead> <tr> <th>Patient ID</th> <th>Last Name</th> <th>First Name</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_patients = $connect->prepare("SELECT * FROM client ORDER BY date DESC"); $sql_patients->execute(); $rows_patients = $sql_patients->fetchAll(); foreach ($rows_patients as $patient) { ?> <tr> <td><?php echo $patient['clientID'] ?></td> <td><?php echo $patient['lastName'] ?></td> <td><?php echo $patient['firstName'] ?></td> <td><?php echo $patient['status'] ?></td> <td> <a href="patient.php?patient=<?php echo $patient['clientID'] ?>"><i class="fas fa-eye eye"></i></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </body> </html> <?php if (isset($_GET['patient'])) { $_SESSION['patient'] = $_GET['patient']; } ?> <script> const close = $('#close'); // When the user clicks on <span> (x), close the modal close.on('click', function() { view_modal.style.display = "none"; window.location.replace('appoint-list.php'); }); const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); function confirmationLogout(anchor) { var conf = confirm('Are you sure want to SIGN OUT?'); if (conf) window.location = anchor.attr("href"); } function confirmation(ask) { var conf = confirm(ask); if (conf) { } return false; }; </script><file_sep>window.addEventListener('load', () => { const loader = document.querySelector('.loader'); loader.classList.add('loader-finish'); }); const navSlide = () => { const burger = document.querySelector('.burger'); const nav = document.querySelector('.nav-links'); const navLinks = document.querySelectorAll('.nav-links li'); //toggle nav burger.addEventListener('click', () => { nav.classList.toggle('nav-active'); //animate links navLinks.forEach((link, index) => { if (link.style.animation) { link.style.animation = ''; } else { link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`; } }); //burger animation burger.classList.toggle('toggle'); }); }; navSlide(); const scrollFixed = () => { window.addEventListener('scroll', () => { const nav = document.querySelector('.nav'); if (window.scrollY > 10) { nav.classList.add('fixed'); console.log(window.scrollY); } else { nav.classList.remove('fixed'); } }); }; scrollFixed(); const avatar = () => { const avatar = document.querySelector('#userAvatar'); const avatarMenu = document.querySelector('#avatarMenu'); avatar.addEventListener('click', () => { avatarMenu.classList.toggle('user-menu-active'); }); }; avatar(); <file_sep><?php session_start(); include '../config/control.php'; $cid = $_SESSION['id']; $status = 'Cancelled'; $query = $connect->prepare("SELECT * FROM appointment WHERE clientID=:clientID AND status != :status"); $query->execute(['clientID'=>$cid,'status'=>$status]); $json_array = array(); while($rows=$query->fetch(PDO::FETCH_ASSOC)){ $docID = $rows['doctorID']; $verify = $rows['verified']; $query4 = $connect->prepare("SELECT * FROM dentist WHERE doctorID = ?"); $query4->execute([$docID]); while($rows4=$query4->fetch(PDO::FETCH_ASSOC)){ $docName = $rows4['Salutation']." ".$rows4['firstName']." ".$rows4['lastName']; if($verify == false){ $json_array[] = array( 'doctorID' => $rows["doctorID"], 'title' => $rows["service"]." - ".$docName, 'start' => $rows["appointmentDate"]." ".$rows["start"], 'end' => $rows["appointmentDate"]." ".$rows["end"], 'color' => '#f22613' ); }else if($verify == true){ $json_array[] = array( 'doctorID' => $rows["doctorID"], 'title' => $rows["service"]." - ".$docName, 'start' => $rows["appointmentDate"]." ".$rows["start"], 'end' => $rows["appointmentDate"]." ".$rows["end"], 'color' => '#013243' ); } } } echo json_encode($json_array); ?><file_sep><?php // session_start(); require_once 'controllers/authController.php'; // include 'config/control.php'; // include 'controllers/verify.php'; // if (isset($_GET['token'])) { // $token = $_GET['token']; // verifyUser($token); // } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dela Paz-Oglimen</title> <link rel="shortcut icon" type="image/x-icon" href="image/dpom_icon.ico"> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> </head> <body> <?php include 'header.php'; ?> <div class="page-container"> <main> <?php $sql_bg = "SELECT * FROM cms_home"; $stmt_bg = $connect->prepare($sql_bg); $stmt_bg->execute(); $rows = $stmt_bg->fetch(); ?> <style> .banner { background: linear-gradient(rgb(246, 249, 250, 1), rgba(0, 0, 0, 0.5)), url('image/<?php echo $rows['bg'] ?>') no-repeat; background-size: cover; background-position: center; background-attachment: fixed; } </style> <div class="banner"> <div class="banner-text"> <h1>Dela Paz-Oglimen Dental Care Clinic</h1> <h3><?php echo $rows['text'] ?></h3> <a href="index.php#services"><button>Learn more</button></a> </div> </div> <section class="section-1" id="services"> <h1>Our Services</h1> <div class="main-cards"> <?php $sql_categories = "SELECT * FROM categories LIMIT 4"; $stmt_categories = $connect->prepare($sql_categories); $stmt_categories->execute(); $rows_categories = $stmt_categories->fetchAll(); foreach ($rows_categories as $row_categ) { ?> <div class="card-service card-thumbnail"> <div class="card-img"><i class="fas fa-tooth"></i></div> <div class="card-img-title"> <h3><?php echo $row_categ['category'] ?></h3> </div> <div class="card-img-info"> <p><?php echo strip_tags($row_categ['description']) ?></p> </div> </div> <?php } ?> </div> </section> <section class="section-2"> <div class="section-2_card about"> <div class="section-2_card-about_content"> <h1><span class="title-highlight">Dela Paz-Oglimen</span> Dental Care Clinic</h1> <h3>Lorem ipsum dolor sit amet consectetur adipisicing elit.</h3> <?php $sql_about = "SELECT * FROM cms_about"; $stmt_about = $connect->prepare($sql_about); $stmt_about->execute(); $rows_about = $stmt_about->fetch(PDO::FETCH_ASSOC); $string = strip_tags($rows_about['text']); if (strlen($string) > 500) { // truncate string $stringCut = substr($string, 0, 500); $endPoint = strrpos($stringCut, ' '); //if the string doesn't contain any space then it will cut without word basis. $string = $endPoint ? substr($stringCut, 0, $endPoint) : substr($stringCut, 0); $string .= '...'; } ?> <p><?php echo $string ?></p> <a href="about.php#about"><button class="btn">Read More</button></a> </div> </div> <div class="section-2_card schedule"> <div class="section-2_card-sched_content"> <div class="sched-header"> <i class="far fa-clock clock"></i> <div class="sched-header_title"> <h1>Opening Hours</h1> <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Repellat, temporibus!</p> </div> </div> <div class="sched-info"> <div class="sched-info_day"> <h3>Monday - Friday</h3> <span>9:00 am - 10:00 pm</span> </div> <div class="sched-info_day"> <h3>Saturday</h3> <span>9:00 am - 10:00 pm</span> </div> <div class="sched-info_day"> <h3>Sunday</h3> <span>9:00 am - 10:00 pm</span> </div> </div> </div> </div> </section> <section class="section-3" id="testimony"> <h1>What they say about us</h1> <div class="testimonial-slider"> <?php $sql_first_testimonials = "SELECT * FROM cms_testi ORDER BY id DESC LIMIT 1"; $stmt_first_testimonials = $connect->prepare($sql_first_testimonials); $stmt_first_testimonials->execute(); $rows_first_testimonials = $stmt_first_testimonials->fetch(PDO::FETCH_ASSOC); ?> <div class="testimonial-slide current"> <blockquote> <p> <?php echo $rows_first_testimonials['testimonials'] ?> </p> <h3><?php echo $rows_first_testimonials['name'] ?></h3> </blockquote> </div> <?php $sql_testimonials = "SELECT * FROM cms_testi WHERE id NOT IN (SELECT MAX(id) FROM cms_testi) ORDER BY id ASC"; $stmt_testimonials = $connect->prepare($sql_testimonials); $stmt_testimonials->execute(); $rows_testimonials = $stmt_testimonials->fetchAll(); foreach ($rows_testimonials as $testimonials) { ?> <div class="testimonial-slide"> <blockquote> <p> <?php echo $testimonials['testimonials']; ?> </p> <h3><?php echo $testimonials['name']; ?></h3> </blockquote> </div> <?php } ?> </div> <div class="slider-buttons testimonial-slider--buttons"> <button id="prev"><i class="fas fa-arrow-left"></i></button> <button id="next"><i class="fas fa-arrow-right"></i></button> </div> </section> <section class="section-4"> <h1>Meet our Dentist</h1> <div class="main-cards card-container"> <?php $sql_dentist = "SELECT * FROM dentist LIMIT 4"; $stmt_dentist = $connect->prepare($sql_dentist); $stmt_dentist->execute(); $rows_dentist = $stmt_dentist->fetchAll(); foreach ($rows_dentist as $dentist) { $salut = $dentist['Salutation']; $fn = $dentist['firstName']; $ln = $dentist['lastName']; $dentist_name = $salut . " " . $fn . " " . $ln; ?> <div class="card-dentist middle"> <div class="image-container front"> <?php if (empty($dentist['image'])) { ?> <img src="image/smile.jpeg" alt=""> <?php } else { ?> <img src="image/<?php echo $dentist['image'] ?>" alt=""> <?php } ?> </div> <div class="back"> <div class="back-content middle"> <h2><?php echo $dentist_name ?></h2> <p><?php echo $dentist['bio'] ?></p> <div class="social-media"> <span><i class="fab fa-facebook-f fb"></i></span> <span><i class="fab fa-twitter tw"></i></span> <span><i class="fab fa-instagram ig"></i></span> </div> </div> </div> </div> <?php } ?> </div> <a href="about.php#ourTeam"><button class="sec-3_btn btn ">Learn more about our dentist</button></a> </section> <section class="section-5"> <div class="gallery"> <?php $sql_gallery = "SELECT * FROM cms_gallery LIMIT 5"; $stmt_gallery = $connect->prepare($sql_gallery); $stmt_gallery->execute(); $rows_gallery = $stmt_gallery->fetchAll(); foreach ($rows_gallery as $gallery) { ?> <a href="image/<?php echo $gallery['image'] ?>" class="big"> <img src="image/<?php echo $gallery['image'] ?>" alt=""> </a> <?php } ?> <!-- <a href="images/smile5.jpeg" class="big"> <img src="images/smile5.jpeg" alt=""> </a> <a href="images/smile.jpeg" class="big"> <img src="images/smile.jpeg" alt=""> </a> <a href="images/smile4.jpeg" class="big"> <img src="images/smile4.jpeg" alt=""> </a> <a href="images/smile3.jpeg" class="big"> <img src="images/smile3.jpeg" alt=""> </a> <a href="images/smile2.jpeg" class="big"> <img src="images/smile2.jpeg" alt=""> </a> --> </div> <a href="gallery.php"><button class="sec-3_btn btn ">Load more</button></a> </section> <section class="section-6" id="contact"> <h1>How can we help?</h1> <h3>Send us a message</h3> <div class="contact-container"> <div class="contact-map"> <div class="map"> <iframe class="g_map" id="gmap_canvas" src="https://maps.google.com/maps?q=%202nd%20Flr.%20Waltermart%20Mall%2C%20Km.%2030%20Brgy.%20Burol%2C%20Emilio%20Aguinaldo%20Hwy%2C%20Dasmari%C3%B1as%2C%20Cavite%20Cavite%20City%204114&t=&z=17&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="yes" marginheight="0" marginwidth="0"></iframe> <div class="gtext"> <span>Google Maps Generator by </span> <a href="https://www.embedgooglemap.net"> <span>embedgooglemap.net</span> </a> </div> </div> <div class="address"> <?php $sql_cms_homeAddress = "SELECT * FROM cms_contact"; $stmt_cms_homeAddress = $connect->prepare($sql_cms_homeAddress); $stmt_cms_homeAddress->execute(); $row_address = $stmt_cms_homeAddress->fetch(PDO::FETCH_ASSOC); ?> <p><?php echo $row_address['address'] ?></p> <span> +(63) <?php echo $row_address['contact'] ?></span> </div> </div> <div class="contact-form"> <form action="" method="POST"> <?php if (count($errors) > 0) { ?> <div class="form__error"> <?php foreach ($errors as $error) { ?> <li style="list-style:none"><?php echo $error ?></li> <?php } ?> </div> <?php } ?> <input type="text" name="fname" placeholder="First name"> <input type="text" name="lname" placeholder="Last name"> <input type="email" name="email" placeholder="E-Mail"> <textarea name="message" id="" placeholder="Message"></textarea> <input type="submit" name="send" class="contact-btn" value="SEND"> </form> </div> </div> </section> </main> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </div> <!-- script js --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/main.js"></script> <script src="js/testimonial.js"></script> <script src="js/simple-lightbox.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script> $(function() { var lightbox = $('.gallery a').simpleLightbox(); }); </script> </body> </html><file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CMS | Contacts</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script> tinymce.init({ selector: '#address', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Content Management / Contact</div> </div> <form action="" method="POST"> <?php $sql_address = "SELECT * FROM cms_contact"; $stmt_address = $connect->prepare($sql_address); $stmt_address->execute(); $row_address = $stmt_address->fetch(PDO::FETCH_ASSOC); ?> <div class="sections contact" id="contact"> <h1>Address Location</h1> <form method="POST"> <textarea name="address" class="address_text mytextarea" id="address"><?php echo $row_address['address'] ?></textarea> <h4>Contact Number</h4> <div class="contactNumber"> <span>+(63) </span><input type="text" name="phone" value="<?php echo $row_address['contact'] ?>"> </div> <input type="submit" class="button" name="save_address" value="save address"> </form> </div> </form> </main> </div> </body> </html> <?php if (isset($_POST['save_address'])) { $location = $_POST['address']; $phone = $_POST['phone']; if (empty($location) || empty($phone)) { echo "<script>alert('Contact Information must not be empty');window.location.replace('cms-contact.php')</script>"; } else { $sql_updateContactInfo = "UPDATE cms_contact SET address = :address, contact = :contact"; $stmt_updateContactInfo = $connect->prepare($sql_updateContactInfo); $stmt_updateContactInfo->execute(['address' => $location, 'contact' => $phone]); if ($stmt_updateContactInfo) { echo "<script>alert('Update information successfully');window.location.replace('cms-contact.php')</script>"; } else { echo "<script>alert('Something went wrong. Please try again');window.location.replace('cms-contact.php')</script>"; } } } ?> <script> //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); </script><file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script> $(document).ready(function(){ $("#service_table").DataTable({ responsive: true, pageLength : 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs:[ { targets: [3], orderable: false } ] }); }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Services</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <div class="appoint_table"> <div class="header__sort"> <div class="add"> <button class="button left" onclick="document.getElementById('modal__add').style.display='block'"><i class="fas fa-tooth icon-s"></i><span class="add-span">&nbsp;Add&nbsp;New&nbsp;Service</span></button> </div> <div class="add"> <a href="service-category.php"><button class="button right"><span class="add-span">&nbsp;Service&nbsp;Category</span></button></a> </div> </div> <table class="list__tbl display dt-responsive nowrap" id="service_table"> <thead> <tr> <th>Service ID</th> <th>Category</th> <th>Service Title</th> <th>Duration</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_service = "SELECT * FROM service"; $stmt_service = $connect->prepare($sql_service); $stmt_service->execute(); $rows_service = $stmt_service->fetchAll(); foreach($rows_service as $row_service){ $service_id = $row_service['id']; $hour = $row_service['hour']; $min = $row_service['min']; $duration = "+".$hour." "."hour"." ".$min." "."min"; ?> <tr> <td><?php echo $service_id?></td> <td><?php echo $row_service['category']?></td> <td><?php echo $row_service['title']?></td> <td><?php echo substr($duration,1)?></td> <td> <div class="icon_container"> <a href="?editID=<?php echo $service_id?>"><i class="fas fa-edit edit"></i></a>&nbsp; <a href="?deleteID=<?php echo $service_id?>" onclick="javascript:confirmDelete(this);return false;"><i class="fas fa-trash bin"></i></a> </div> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- MODAL --> <!-- ADD MODAL --> <div id="modal__add" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close_add" onclick="document.getElementById('modal__add').style.display='none'">&times;</span> <span class="modal_header-title">Add New Service</span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="modal-view-body_container"> <div class="patient_textbox"> <span>Categories:</span> <span> <select name="category" id="category"> <option selected disabled>Select Category</option> <?php $sql_categorySelection = "SELECT * FROM categories"; $stmt_categorySelection = $connect->prepare($sql_categorySelection); $stmt_categorySelection->execute(); $row_categorySelection = $stmt_categorySelection->fetchAll(); foreach($row_categorySelection as $row_categories){ ?> <option value="<?php echo $row_categories['category']?>"><?php echo $row_categories['category']?></option> <?php } ?> </select> </span> </div> <div class="title_content"> <div class="patient_textbox"> <span>Service Title:</span> <span><input type="text" name="title" id="title" placeholder="Title"></span> </div> </div> <div class="labelService"> <span>Hour(s)</span> <span>Minute(s)</span> </div> <div class="labelService"> <select name="hour" id="hour"> <option value="00">00</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <select name="min" id="min"> <option value="00">00</option> <option value="15">15</option> <option value="30">30</option> <option value="45">45</option> </select> </div> <input type="submit" class="button" name="add_service" id="add_service" value="Add Service"> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- EDIT MODAL --> <div id="modal__edit" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $service_id = $_GET['editID']; $sql_eachService = "SELECT * FROM service WHERE id = :id"; $stmt_eachService = $connect->prepare($sql_eachService); $stmt_eachService->execute(['id'=>$service_id]); $row_eachService = $stmt_eachService->fetch(PDO::FETCH_ASSOC); $title = $row_eachService['title']; $hour = $row_eachService['hour']; $min = $row_eachService['min']; // $duration = "+".$hour." "."hour"." ".$min." "."min"; ?> <span class="close" id="edit_close">&times;</span> <span class="modal_header-title">Update <?php echo $title?></span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="modal-view-body_container"> <div class="patient_textbox"> <span>Categories:</span> <span> <select name="category" id="category"> <option value="<?php echo $row_catrow_eachServiceegories['category']?>" selected><?php echo $row_eachService['category']?></option> <option disabled>--------------</option> <?php $sql_categorySelection = "SELECT * FROM categories"; $stmt_categorySelection = $connect->prepare($sql_categorySelection); $stmt_categorySelection->execute(); $row_categorySelection = $stmt_categorySelection->fetchAll(); foreach($row_categorySelection as $row_categories){ ?> <option value="<?php echo $row_categories['category']?>"><?php echo $row_categories['category']?></option> <?php } ?> </select> </span> </div> <div class="title_content"> <div class="patient_textbox"> <span for="title">Service Title:</span> <span><input type="text" name="title" id="title" value="<?php echo $title?>"></span> </div> </div> <div class="labelService"> <span>Hour(s)</span> <span>Minute(s)</span> </div> <div class="labelService"> <select name="hour" id="hour"> <option value="<?php echo $hour?>" selected><?php echo $hour?></option> <option value="" disabled>----------</option> <option value="00">00</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <select name="min" id="min"> <option value="<?php echo $min?>" selected><?php echo $min?></option> <option value="" disabled>----------</option> <option value="00">00</option> <option value="15">15</option> <option value="30">30</option> <option value="45">45</option> </select> </div> <input type="submit" class="button btn_service" name="edit_service" id="edit_service" value="Update Service"> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- END EDIT MODAL --> </main> </div> </body> </html> <?php if(isset($_GET['editID'])){ $editid = $_GET['editID']; $_SESSION['dentistEditID'] = $editid; echo "<script>var edit_modal= document.getElementById('modal__edit')</script>"; echo "<script> edit_modal.style.display='block'</script>"; }; if(isset($_POST['add_service'])){ $category = $_POST['category']; $title = $_POST['title']; $hour = $_POST['hour']; $min = $_POST['min']; $sql_serv= "SELECT * FROM service WHERE title = :title"; $stmt_serv = $connect->prepare($sql_serv); $stmt_serv->execute(['title'=>$title]); $rows_serv = $stmt_serv->fetch(PDO::FETCH_ASSOC); if(empty($title) || empty($category)){ echo "<script>alert('Please fill up the title');window.location.replace('service.php')</script>"; }else if($hour == "00" && $min == "00"){ echo "<script>alert('Invalid duration. Please specify the correct hour(s) and min(s).');window.location.replace('service.php')</script>"; }else if($rows_serv > 1){ echo "<script>alert('Service title already exist');window.location.replace('service.php')</script>"; }else{ $query_addServiceInfo = "INSERT INTO service (title,category,hour,min) VALUE(:title,:category,:hour,:min)"; $stmt_addServiceInfo = $connect->prepare($query_addServiceInfo); $stmt_addServiceInfo->execute(['title'=>$title,'category'=>$category,'hour'=>$hour,'min'=>$min]); echo "<script>alert('Successfully added a new service!');window.location.replace('service.php')</script>"; } } if(isset($_POST['edit_service'])){ $id = $_GET['editID']; $category = $_POST['category']; $title = $_POST['title']; $hour = $_POST['hour']; $min = $_POST['min']; if(empty($title)){ echo "<script>alert('Please fill up the title');window.location.replace('service.php')</script>"; }else if($hour == "00" && $min == "00"){ echo "<script>alert('Invalid duration. Please specify the correct hour(s) and min(s).');window.location.replace('service.php')</script>"; }else{ $query_updateServiceInfo = "UPDATE service SET title = :title, category = :category, hour =:hour, min =:min WHERE id =:id"; $stmt_updateServiceInfo = $connect->prepare($query_updateServiceInfo); $stmt_updateServiceInfo->execute(['title'=>$title,'category'=>$category,'hour'=>$hour,'min'=>$min,'id'=>$id]); echo "<script>alert('Successfully updated service!');window.location.replace('service.php')</script>"; } } if(isset($_GET['deleteID'])){ $serviceId = $_GET['deleteID']; $sql_deleteService = "DELETE FROM service WHERE id = :id"; $stmt_deleteService = $connect->prepare($sql_deleteService); $stmt_deleteService->execute(['id'=>$serviceId]); echo "<script>alert('Service deleted');window.location.replace('service.php')</script>"; } ?> <script> const edit_close = $('#edit_close'); // When the user clicks on <span> (x), close the modal edit_close.on('click', function() { edit_modal.style.display = "none"; window.location.replace('service.php'); }); //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Confirmation for DELETE function confirmDelete(anchor) { var conf = confirm('Are you sure want to delete this service?'); if(conf) window.location=anchor.attr("href"); }; </script> <file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CMS | Services</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script> tinymce.init({ selector: '.mytextarea', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Content Management / Service</div> </div> <div class="overviewcard header-title"> <span>Category list</span> </div> <div class="category-overview"> <?php $sql_categoryCard = "SELECT * FROM categories"; $stmt_categoryCard = $connect->prepare($sql_categoryCard); $stmt_categoryCard->execute(); $rows_categoryCard = $stmt_categoryCard->fetchAll(); foreach ($rows_categoryCard as $categoryCard) { ?> <div class="card category-card"> <div class="category-container"> <div class="category-logo"> <div class="logo-container"> <img src="<?php echo $categoryCard['img'] ?>" alt=""> </div> </div> <div class="category-title"> <div class="textbox category_textbox"> <span><?php echo $categoryCard['category'] ?></span> </div> </div> <div class="category-description textbox"> <span style="font-size:12px"><?php echo $categoryCard['description'] ?></span> </div> </div> <div class="content-overlay"> <div class="category-button"> <a href="?categoryID=<?php echo $categoryCard['category_id'] ?>"><button class="button">Update</button></a> </div> </div> </div> <?php } ?> </div> </form> <div class="overviewcard header-title"> <span>Service list</span> </div> <div class="main-cards service_cards"> <?php $sql_serviceCard = "SELECT * FROM service"; $stmt_serviceCard = $connect->prepare($sql_serviceCard); $stmt_serviceCard->execute(); $rows_serviceCard = $stmt_serviceCard->fetchAll(); foreach ($rows_serviceCard as $serviceCard) { ?> <div class="card service-card"> <div class="service-content"> <div class="service-img"> <div class="image-content"> <img src="<?php echo $serviceCard['image'] ?>" alt=""> </div> </div> <div class="service-title"> <div class="textbox category_textbox"> <span><?php echo $serviceCard['title'] ?></span> </div> </div> <div class="service-descrption"> <p><?php echo $serviceCard['description'] ?></p> </div> </div> <div class="service-overlay"> <div class="category-button"> <a href="?serviceID=<?php echo $serviceCard['id'] ?>"><button class="button">Update</button></a> </div> </div> </div> <?php } ?> </div> </main> </div> <!-- MODALS --> <div id="modal__updateCategory" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $category_id = $_GET['categoryID']; $sql_categoryModal = "SELECT * FROM categories WHERE category_id = :id"; $stmt_categoryModal = $connect->prepare($sql_categoryModal); $stmt_categoryModal->execute(['id' => $category_id]); $row_categoryModal = $stmt_categoryModal->fetch(PDO::FETCH_ASSOC); ?> <span class="close" id="close_category">&times;</span> <h2><?php echo $row_categoryModal['category'] ?></h2> </div> <div class="modal-body view_body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="modal-view-body_container"> <div class="categoryModal_img-container"> <div class="categoryModal_img-content"> <img src="<?php echo $row_categoryModal['img'] ?>" alt="" id="categoryImg"> </div> <div class="categoryModal_img-overlay"> <label for="category_img-btn" class="file-btn-label about-label"> <span>Select&nbsp;image</span> <input type="file" name="categoryImg" class="file-btn" id="category_img-btn" onchange="categoryImgUpdate(event)" size="60"> </label> </div> </div> <div class="message-reply_container"><textarea name="text" class="mytextarea"><?php echo $row_categoryModal['description'] ?></textarea></div> <div class="categoryModal_button"> <input type="submit" name="categoryCMSUpdate" class="button" value="update"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> <!-- Service modal --> <div id="modal__updateService" class="modal"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $service_id = $_GET['serviceID']; $sql_serviceModal = "SELECT * FROM service WHERE id = :id"; $stmt_serviceModal = $connect->prepare($sql_serviceModal); $stmt_serviceModal->execute(['id' => $service_id]); $row_serviceModal = $stmt_serviceModal->fetch(PDO::FETCH_ASSOC); ?> <span class="close" id="close_service">&times;</span> <h2><?php echo $row_serviceModal['title'] ?></h2> </div> <div class="modal-body view_body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="modal-view-body_container"> <div class="categoryModal_img-container"> <div class="categoryModal_img-content"> <img src="../image/service/checkup.jpg" alt="" id="serviceImg"> </div> <div class="categoryModal_img-overlay"> <label for="services_img-btn" class="file-btn-label about-label">Select Image <input type="file" name="serviceImg" class="file-btn" id="services_img-btn" onchange="updateServiceImg(event)" size="60"> </label> </div> </div> <div class="message-reply_container"><textarea name="servicetext" class="mytextarea"><?php echo $row_serviceModal['description'] ?></textarea></div> <div class="categoryModal_button"> <input type="submit" name="serviceCMSUpdate" class="button" value="update"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> </body> </html> <?php if (isset($_GET['categoryID'])) { echo "<script>var updateCategory_modal= document.getElementById('modal__updateCategory')</script>"; echo "<script> updateCategory_modal.style.display='block'</script>"; }; if (isset($_GET['serviceID'])) { echo "<script>var updateService_modal= document.getElementById('modal__updateService')</script>"; echo "<script> updateService_modal.style.display='block'</script>"; }; if (isset($_POST['categoryCMSUpdate'])) { $category_id = $_GET['categoryID']; $categorytext = $_POST['text']; // $categoryimg = $_POST['categoryImg']; $target_dir = "../image/icons/"; $uploadOk = 1; $target_categoryImg = $target_dir . substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 3) . basename($_FILES["categoryImg"]["name"]); $imgFileType = strtolower(pathinfo($target_categoryimg, PATHINFO_EXTENSION)); $checkImg = getimagesize($_FILES["categoryImg"]["tmp_name"]); $check_about = "SELECT * FROM categories"; $stmt_about = $connect->prepare($check_about); $stmt_about->execute(); $row_about = $stmt_about->fetch(PDO::FETCH_ASSOC); $curimg = $row_about['img']; if (empty($_FILES["categoryImg"]["tmp_name"])) { $sql_update_about = "UPDATE categories SET img = :img, description = :txt WHERE category_id = :id"; $smt_update_about = $connect->prepare($sql_update_about); $smt_update_about->execute(['img' => $curimg, 'txt' => $categorytext, 'id' => $category_id]); echo "<script>alert('Updated Successfully');window.location.replace('cms-service.php')</script>"; exit(); } else if (move_uploaded_file($_FILES["categoryImg"]["tmp_name"], $target_categoryImg)) { $sql_update_about = "UPDATE categories SET img = :img, description = :txt WHERE category_id = :id"; $smt_update_about = $connect->prepare($sql_update_about); $smt_update_about->execute(['img' => $target_categoryImg, 'txt' => $categorytext, 'id' => $category_id]); echo "<script>alert('Updated Successfully');window.location.replace('cms-service.php')</script>"; exit(); } }; if (isset($_POST['serviceCMSUpdate'])) { $service_id = $_GET['serviceID']; $servicetext = $_POST['servicetext']; // $categoryimg = $_POST['categoryImg']; $target_dir = "../image/service/"; $uploadOk = 1; $target_serviceImg = $target_dir . substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 5) . basename($_FILES["serviceImg"]["name"]); $imgFileType = strtolower(pathinfo($target_serviceImg, PATHINFO_EXTENSION)); $checkImg = getimagesize($_FILES["serviceImg"]["tmp_name"]); $check_serviceTable = "SELECT * FROM service"; $stmt_serviceTable = $connect->prepare($check_serviceTable); $stmt_serviceTable->execute(); $row_serviceTable = $stmt_serviceTable->fetch(PDO::FETCH_ASSOC); $oldimg = $row_serviceTable['image']; if (empty($_FILES["serviceImg"]["tmp_name"])) { $sql_update_service = "UPDATE service SET image = :img, description = :txt WHERE id = :id"; $smt_update_service = $connect->prepare($sql_update_service); $smt_update_service->execute(['img' => $oldimg, 'txt' => $servicetext, 'id' => $service_id]); echo "<script>alert('Updated Successfully');window.location.replace('cms-service.php')</script>"; exit(); } else if (move_uploaded_file($_FILES["serviceImg"]["tmp_name"], $target_serviceImg)) { $sql_update_service = "UPDATE service SET image = :img, description = :txt WHERE id = :id"; $smt_update_service = $connect->prepare($sql_update_service); $smt_update_service->execute(['img' => $target_serviceImg, 'txt' => $servicetext, 'id' => $service_id]); echo "<script>alert('Updated Successfully');window.location.replace('cms-service.php')</script>"; exit(); } }; ?> <script> var categoryImgUpdate = function(event) { var output = document.getElementById('categoryImg'); output.src = URL.createObjectURL(event.target.files[0]); }; var updateServiceImg = function(event) { var output = document.getElementById('serviceImg'); output.src = URL.createObjectURL(event.target.files[0]); }; const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); const categoryModal_close = $('#close_category'); // When the user clicks on <span> (x), close the modal categoryModal_close.on('click', function() { updateCategory_modal.style.display = "none"; window.location.replace('cms-service.php'); }); const serviceModal_close = $('#close_service'); // When the user clicks on <span> (x), close the modal serviceModal_close.on('click', function() { updateService_modal.style.display = "none"; window.location.replace('cms-service.php'); }); </script><file_sep><?php session_start(); include '../config/control.php'; foreach ($_FILES['images']['name'] as $i => $value) { $facilities = "Facilities"; $image_name = $_FILES['images']['tmp_name'][$i]; $folder = "../image/gallery/"; $image_path = $folder . $_FILES['images']['name'][$i]; move_uploaded_file($image_name, $image_path); $sql_insertImage = "INSERT INTO cms_gallery (image,category) VALUES (:path,:facilities)"; $stmt_insertImage = $connect->prepare($sql_insertImage); $stmt_insertImage->execute(['path' => $image_path, 'facilities' => $facilities]); } echo "image uploaded successfully"; echo "<script>window.location.replace('cms-gallery.php')</script>"; <file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CMS | Gallery</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script> $(document).ready(function() { $("#image").on('change', function() { var filename = $(this).val(); $(".custome-file-label").html(filename); }); $("#image_upload").submit(function(e) { e.preventDefault(); $.ajax({ url: 'upload.php', method: 'post', processData: false, contentType: false, cache: false, data: new FormData(this), success: function(response) { $("#result").html(response); } }) }); $("#serviceimages").on('change', function() { var filename = $(this).val(); $(".custome-file-label2").html(filename); }); $("#imageService_upload").submit(function(e) { e.preventDefault(); $.ajax({ url: 'gallery-service.upload.php', method: 'post', processData: false, contentType: false, cache: false, data: new FormData(this), success: function(response) { $("#resultService").html(response); } }) }); }); </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Gallery</div> </div> <section> <h1>Facilities</h1> <form action="" method="POST" enctype="multipart/form-data" id="image_upload"> <div class="overviewcard upload-container"> <h5 id="result"></h5> <div class="upload-input_content"> <input type="file" id="image" name="images[]" class="galleryFile" multiple> <label for="image" class="btn-1 custome-file-label">Select&nbsp;Image</label> </div> <div class="upload-button_content"> <input class="button btn-upload" type="submit" name="upload" value="Upload"> </div> </div> </form> <div class="category-overview"> <?php $facilities = "Facilities"; $sql_fetchImage = "SELECT * FROM cms_gallery WHERE category =:facilities"; $stmt_fetchImage = $connect->prepare($sql_fetchImage); $stmt_fetchImage->execute(['facilities' => $facilities]); $rows_fetchImage = $stmt_fetchImage->fetchAll(); foreach ($rows_fetchImage as $fetchImage) { ?> <div class="card gallery-card"> <div class="gallery-content"> <div class="gallery_container"> <div class="logo-container gallery_images"> <img src="<?php echo $fetchImage['image'] ?>" alt=""> </div> </div> <div class="gallery-overlay"> <a href="?galleryID=<?php echo $fetchImage['gallery_id'] ?>" onclick="return confirm('Delete this image?')"><span class="gallery-x">&times;</span></a> <form action="" method="POST"> <?php $galleryID = $fetchImage['gallery_id']; ?> <div class="gallery_overlay_content"> <input type="hidden" name="id" value="<?php echo $galleryID ?>"> <input type="text" name="title" value="<?php echo $fetchImage['title'] ?>"> <textarea name="description" id="" cols="30" rows="5"><?php echo $fetchImage['description'] ?></textarea> <input type="submit" name="save_label" class="button" value="Save"> </div> </form> </div> </div> </div> <?php } ?> </div> </section> <section> <h1>Services</h1> <form action="" method="POST" enctype="multipart/form-data" id="imageService_upload"> <div class="overviewcard upload-container"> <h5 id="resultService"></h5> <div class="upload-input_content"> <input type="file" id="serviceimages" name="serviceimages[]" class="galleryFile" multiple> <label for="serviceimages" class="btn-1 custome-file-label2">Select&nbsp;Image</label> </div> <div class="upload-button_content"> <input class="button btn-upload" type="submit" name="gallery_service" value="Upload"> </div> </div> </form> <div class="category-overview"> <?php $service = "Services"; $sql_fetchGalleryService = "SELECT * FROM cms_gallery WHERE category = :service"; $stmt_fetchGalleryService = $connect->prepare($sql_fetchGalleryService); $stmt_fetchGalleryService->execute(['service' => $service]); $rows_fetchGalleryService = $stmt_fetchGalleryService->fetchAll(); foreach ($rows_fetchGalleryService as $fetchGalleryService) { ?> <div class="card gallery-card"> <div class="gallery-content"> <div class="gallery_container"> <div class="logo-container gallery_images"> <img src="<?php echo $fetchGalleryService['image'] ?>" alt=""> </div> </div> <div class="gallery-overlay"> <a href="?galleryID=<?php echo $fetchGalleryService['gallery_id'] ?>" onclick="return confirm('Delete this image?')"><span class="gallery-x">&times;</span></a> <form action="" method="POST"> <?php $galleryID = $fetchGalleryService['gallery_id']; ?> <div class="gallery_overlay_content"> <input type="hidden" name="id" value="<?php echo $galleryID ?>"> <input type="text" name="title" value="<?php echo $fetchGalleryService['title'] ?>"> <textarea name="description" id="" cols="30" rows="5"><?php echo $fetchGalleryService['description'] ?></textarea> <input type="submit" name="save_labell" class="button" value="Save"> </div> </form> </div> </div> </div> <?php } ?> </div> </section> </main> </div> </body> </html> <?php if (isset($_GET['galleryID'])) { $id = $_GET['galleryID']; $sql_path = "SELECT * FROM cms_gallery WHERE gallery_id = :id"; $stmt_path = $connect->prepare($sql_path); $stmt_path->execute(['id' => $id]); $row_path = $stmt_path->fetch(PDO::FETCH_ASSOC); $path = $row_path['image']; if (!unlink($path)) { echo "<script>alert('You have an error.');window.location.replace('cms-gallery.php')</script>"; } else { $sql_deleteImg = "DELETE FROM cms_gallery WHERE gallery_id = :id"; $stmt_deleteImg = $connect->prepare($sql_deleteImg); $stmt_deleteImg->execute(['id' => $id]); echo "<script>alert('Image has been successfully deleted.');window.location.replace('cms-gallery.php')</script>"; } } if (isset($_POST['save_label'])) { $id = $_POST['id']; $title = $_POST['title']; $descript = $_POST['description']; $sql_galleryLabel = "UPDATE cms_gallery SET title = :title, description = :descript WHERE gallery_id = :id"; $stmt_galleryLabel = $connect->prepare($sql_galleryLabel); $stmt_galleryLabel->execute(['title' => $title, 'descript' => $descript, 'id' => $id]); echo "<script>alert('Data updated');window.location.replace('cms-gallery.php')</script>"; } if (isset($_POST['save_labell'])) { $id = $_POST['id']; $title = $_POST['title']; $descript = $_POST['description']; $sql_galleryLabel = "UPDATE cms_gallery SET title = :title, description = :descript WHERE gallery_id = :id"; $stmt_galleryLabel = $connect->prepare($sql_galleryLabel); $stmt_galleryLabel->execute(['title' => $title, 'descript' => $descript, 'id' => $id]); echo "<script>alert('Data updated');window.location.replace('cms-gallery.php')</script>"; } ?> <script> const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); </script><file_sep><?php DEFINE('HOST','localhost'); DEFINE('USER','root'); DEFINE('PASSWORD_DB',''); DEFINE('DB','oglimen_db'); DEFINE ('EMAIL','<EMAIL>'); DEFINE ('PASSWORD','<PASSWORD>');<file_sep><?php require 'define.php'; //SET DSN $dsn= 'mysql:host='. HOST . ';dbname='.DB; //CREATE PDO Instance $connect = new PDO($dsn,USER,PASSWORD_DB); // $connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ?><file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CMS | AboutUs</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script> tinymce.init({ selector: '#mytextarea', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">About us</div> </div> <div class="about-content"> <form action="" method="POST" enctype="multipart/form-data"> <div class="overviewcard about-overviewcards"> <?php $sql_about = "SELECT * FROM cms_about"; $stmt_about = $connect->prepare($sql_about); $stmt_about->execute(); $row_about = $stmt_about->fetch(PDO::FETCH_ASSOC); ?> <div class="img_card"> <div class="img-about"> <div class="img_content"> <img src="<?php echo $row_about['img'] ?>" alt="" id="img_toUpdate"> </div> <div class="about-overlay"> <label for="side_img-btn" class="file-btn-label about-label">Select Image <input type="file" name="img_update" class="file-btn" id="side_img-btn" onchange="updateSideImg(event)" size="60"> </label> </div> </div> </div> <div class="about_card"> <div class="text-about"><textarea name="about" id="mytextarea"><?php echo $row_about['text'] ?></textarea></div> </div> </div> <div class="overviewcard about-button_container"> <input type="submit" name="update" class="button" value="Update"> </div> </form> </div> <div class="sections" id="openhour"> <div class="store_schedule_container"> <div class="store_header"> <span>Day</span> <span>Hours</span> <span></span> </div> <div class="store_content"> <?php $sql_store = "SELECT * FROM openhour_tbl"; $stmt_store = $connect->prepare($sql_store); $stmt_store->execute(); $rows_store = $stmt_store->fetchAll(); foreach ($rows_store as $store) { $start = new DateTime($store['start']); $startFormat = $start->format('g:i a'); $end = new DateTime($store['end']); $endFormat = $end->format('g:i a'); $openhours = $startFormat . " - " . $endFormat; ?> <div class="sched_content_info"> <div class="sched_info"> <div class="days_container"><span><?php echo $store['day'] ?></span></div> <div class="time_container"><?php echo $openhours ?></div> </div> <div class="edit_sched"><a href="?edit_store=<?php echo $store['id'] ?>"><i class="fas fa-edit"></i></a></div> </div> <?php } ?> </div> </div> </div> <!-- modal --> <div id="modal_storeSched" class="modal"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="store_close">&times;</span> <h2>Update Store Schedule</h2> </div> <form action="" method="POST"> <div class="modal-body modal_body_store"> <div class="store_content"> <div class="sched_info_title"> <span>Day(s)</span> <span>Start</span> <span>End</span> </div> <?php $id = $_GET['edit_store']; $sql_editStore = "SELECT * FROM openhour_tbl WHERE id = :id"; $stmt_editStore = $connect->prepare($sql_editStore); $stmt_editStore->execute(['id' => $id]); $row_editStore = $stmt_editStore->fetch(PDO::FETCH_ASSOC); $day = $row_editStore['day']; $start = new DateTime($row_editStore['start']); $startFormat = $start->format('g:i a'); $end = new DateTime($row_editStore['end']); $endFormat = $end->format('g:i a'); ?> <div class="sched_content_info"> <div class="days_container"><input type="text" name="day" value="<?php echo $day ?>"></div> <div class="time_container"> <select name="start" id=""> <option value="<?php echo $startFormat ?>" selected><?php echo $startFormat ?></option> <option disabled>--------------</option> <option value="9:00 am">9:00 am</option> <option value="10:00 am">10:00 am</option> <option value="11:00 am">11:00 am</option> <option value="12:00 pm">12:00 pm</option> <option value="1:00 pm">1:00 pm</option> <option value="2:00 pm">2:00 pm</option> <option value="3:00 pm">3:00 pm</option> <option value="4:00 pm">4:00 pm</option> <option value="5:00 pm">5:00 pm</option> <option value="6:00 pm">6:00 pm</option> <option value="7:00 pm">7:00 pm</option> <option value="8:00 pm">8:00 pm</option> <option value="9:00 pm">9:00 pm</option> <option value="10:00 pm">10:00 pm</option> </select></div> <div class="time_container"> <select name="end" id=""> <option value="<?php echo $endFormat ?>" selected><?php echo $endFormat ?></option> <option disabled>--------------</option> <option value="9:00 am">9:00 am</option> <option value="10:00 am">10:00 am</option> <option value="11:00 am">11:00 am</option> <option value="12:00 pm">12:00 pm</option> <option value="1:00 pm">1:00 pm</option> <option value="2:00 pm">2:00 pm</option> <option value="3:00 pm">3:00 pm</option> <option value="4:00 pm">4:00 pm</option> <option value="5:00 pm">5:00 pm</option> <option value="6:00 pm">6:00 pm</option> <option value="7:00 pm">7:00 pm</option> <option value="8:00 pm">8:00 pm</option> <option value="9:00 pm">9:00 pm</option> <option value="10:00 pm">10:00 pm</option> </select></div> </div> <div class="edit_sched"><input type="submit" name="edit_openhour" value="UPDATE"></div> </div> </div> </form> </div> </div> </main> </div> <script> var updateSideImg = function(event) { var output = document.getElementById('img_toUpdate'); output.src = URL.createObjectURL(event.target.files[0]); }; const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); const storeSched = () => { const store_edit = document.querySelector('#store_edit'); const store_editModal = document.querySelector('#modal_storeSched'); const store_close = document.querySelector('#store_close'); store_close.addEventListener('click', () => { store_editModal.classList.remove('modal_show'); window.location.replace('cms-about.php#openhour'); }); }; storeSched(); </script> </body> </html> <?php if (isset($_POST['update'])) { $text = $_POST['about']; $img = $_POST['img_update']; $target_dir = "../image/"; $uploadOk = 1; $target_img = $target_dir . substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 3) . basename($_FILES["img_update"]["name"]); $imgFileType = strtolower(pathinfo($target_img, PATHINFO_EXTENSION)); $checkImg = getimagesize($_FILES["img_update"]["tmp_name"]); $check_about = "SELECT * FROM cms_about"; $stmt_about = $connect->prepare($check_about); $stmt_about->execute(); $row_about = $stmt_about->fetch(PDO::FETCH_ASSOC); $curimg = $row_about['img']; if (empty($_FILES["img_update"]["tmp_name"])) { $sql_update_about = "UPDATE cms_about SET text = :txt, img = :img"; $smt_update_about = $connect->prepare($sql_update_about); $smt_update_about->execute(['txt' => $text, 'img' => $curimg]); echo "<script>alert('Updated Successfully');window.location.replace('cms-about.php')</script>"; exit(); } else if (move_uploaded_file($_FILES["img_update"]["tmp_name"], $target_img)) { $sql_update_about = "UPDATE cms_about SET text = :txt, img = :img"; $smt_update_about = $connect->prepare($sql_update_about); $smt_update_about->execute(['txt' => $text, 'img' => $target_img]); echo "<script>alert('Updated Successfully');window.location.replace('cms-about.php')</script>"; exit(); } } if (isset($_GET['edit_store'])) { echo "<script>const store_editModal = document.getElementById('modal_storeSched');</script>"; echo "<script>store_editModal.classList.add('modal_show');</script>"; } if (isset($_POST['edit_openhour'])) { $id = $_GET['edit_store']; $day = $_POST['day']; $start = $_POST['start']; $starttime = new DateTime($start); $starttotime = $starttime->format('H:i'); $end = $_POST['end']; $endtime = new DateTime($end); $endtotime = $endtime->format('H:i'); $sql_updateStore = "UPDATE openhour_tbl SET day = :day, start = :start, end = :end WHERE id = :id"; $stmt_updateStore = $connect->prepare($sql_updateStore); $stmt_updateStore->execute(['day' => $day, 'start' => $starttotime, 'end' => $endtotime, 'id' => $id]); echo "<script>alert('Update successfully');window.location.replace('cms-about.php#openhour')</script>"; } ?><file_sep> <?php // session_start(); require 'config/control.php'; require_once 'emailController.php'; // require_once 'smsController.php'; date_default_timezone_set('Asia/Manila'); // Appointment $date = ""; $doctor = ""; $dentist_name = ""; $service = ""; $titleService = ""; $start = ""; $checked = ""; $errors = array(); if (isset($_POST['submit'])) { if (empty($_SESSION['id'])) { echo "<script>alert('Please Sign in to Continue');window.location.replace('member.php')</script>"; } else if (!$_SESSION['verified']) { echo "<script>alert('Please Verify your confirmation email to Continue');window.location.replace('index.php')</script>"; } else { $timestamp = date('Y-m-d H:i:s'); $clientID = $_SESSION['id']; $email_appoint = $_SESSION['email']; @$date = $_POST['date']; @$doctor = $_POST['doctor']; @$start = $_POST['start']; $cancel_status = 'Cancelled'; //get client id $sql_getID = "SELECT * FROM client WHERE clientID = :pid"; $stmt_getID = $connect->prepare($sql_getID); $stmt_getID->execute(['pid' => $clientID]); $row_getID = $stmt_getID->fetch(PDO::FETCH_ASSOC); $patient_id = $row_getID['clientID']; $contact = $row_getID['contact']; $clientFirstName = $row_getID['firstName']; $clientLastName = $row_getID['lastName']; $clientName = $clientLastName . ", " . $clientFirstName; //get dentist name $sql_getDentist = "SELECT Salutation,firstName,middleName,lastName FROM dentist WHERE doctorID = :docID"; $stmt_getDentist = $connect->prepare($sql_getDentist); $stmt_getDentist->execute(['docID' => $doctor]); $row_getDentist = $stmt_getDentist->fetch(PDO::FETCH_ASSOC); $dentist_name = $row_getDentist['Salutation'] . " " . $row_getDentist['firstName'] . " " . $row_getDentist['middleName'] . " " . $row_getDentist['lastName']; //explode service with option of 2 values @$service = $_POST['service']; $service_explode = explode('|', $service); $titleService = $service_explode[0]; $startto = $start; $starttime = new DateTime($startto); $starttotime = $starttime->format('H:i'); //$endtime = strtotime($startto)+ 60* 60; //adding 1hour --3600 secs is 1 hour-- @$endtime = new DateTime($startto . $service_explode[1]); //adding duration based on the selected duration $endtotime = $endtime->format('H:i:'); //format date and time to string for email html $dateAppoint = new DateTime($date); $dateAppointFormat = $dateAppoint->format('d M Y'); $timeStartFormat = $starttime->format('g:i a'); $timeEndFormat = $endtime->format('g:i a'); $timeAppoint = $timeStartFormat . " - " . $timeEndFormat; //checking for availability $check = $connect->prepare("SELECT * FROM appointment WHERE appointmentDate = :date AND doctorID = :doctor AND status != :status"); $check->execute(['date' => $date, 'doctor' => $doctor, 'status' => $cancel_status]); $rowTimeCheck = $check->fetch(PDO::FETCH_ASSOC); $starttimeCheck = $rowTimeCheck['start']; $endtimeCheck = $rowTimeCheck['end']; $check2 = $connect->prepare("SELECT count(*) FROM appointment WHERE clientID = :clientID AND appointmentDate= :date AND status != :cancel_status"); $check2->execute(['clientID' => $clientID, 'date' => $date, 'cancel_status' => $cancel_status]); $rowCheck2 = $check2->fetchColumn(); //check holiday $check3 = "SELECT * FROM events"; $stmt_check3 = $connect->prepare($check3); $stmt_check3->execute(); $rowCheck3 = $stmt_check3->fetch(PDO::FETCH_ASSOC); $holiday = $rowCheck3['allDay']; $holiday_title = $rowCheck3['holiday']; $appointDateTime = new DateTime($date); $appointDateTimeFormatted = $appointDateTime->format('Y-m-d'); $checkDate = new DateTime(); // $checkDateFormat = $checkDate->modify('+1 day'); $checkDateFormatted = $checkDate->format('Y-m-d'); if (empty($date) || empty($doctor) || empty($start) || empty($service)) { // echo "<script>alert('Please fill all fields to continue making an appointment');window.location.replace('appoint.php')</script>"; array_push($errors, "Please fill all fields to continue making an appointment"); } else if ($checkDateFormatted >= $appointDateTimeFormatted) { // echo "<script>alert('Invalid Date. Please choose day of your appointment atleast one day from today');window.location.replace('appoint.php')</script>"; array_push($errors, "Invalid Date. Please choose day of your appointment atleast one day from today"); } else if ($date == $holiday) { echo "<script>alert('This day is " . $holiday_title . " is not available. Please select another date');window.location.replace('appoint.php')</script>"; } else if ($rowCheck2 > 0) { // echo "<script>alert('You already booked an appointment on this day " . $date . "');window.location.replace('appointment.php')</script>"; array_push($errors, "You already booked an appointment on this day"); } else if ($starttimeCheck > $starttotime && $endtimeCheck < $endtotime) { #-> Check time is in between start and end time // echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('appoint.php')</script>"; array_push($errors, "Time Slot is unavailable. Please click the day of the calendar to view the current time slot available."); } else if (($starttimeCheck > $starttotime && $starttimeCheck < $endtotime) || ($endtimeCheck > $starttotime && $endtimeCheck < $endtotime)) { #-> Check start or end time is in between start and end time // echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('appoint.php')</script>"; array_push($errors, "Time Slot is unavailable. Please click the day of the calendar to view the current time slot available."); } else if ($starttimeCheck == $starttotime || $endtimeCheck == $endtotime) { #-> Check start or end time is at the border of start and end time // echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('appoint.php')</script>"; array_push($errors, "Time Slot is unavailable. Please click the day of the calendar to view the current time slot available."); } else if ($starttotime > $starttimeCheck && $endtotime < $endtimeCheck) { #-> start and end time is in between the check start and end time. // echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('appoint.php')</script>"; array_push($errors, "Time Slot is unavailable. Please click the day of the calendar to view the current time slot available."); } else if (!isset($_POST['terms'])) { // echo "<script>alert('Please read the terms and conditions and checked');window.location.replace('appoint.php')</script>"; array_push($errors, "Please read the terms and conditions and checked"); } else { if (count($errors) == 0) { $appointID = bin2hex(random_bytes('4')); // $token_appoint = bin2hex(random_bytes(50)); $status = 'Pending'; $view = 0; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Thank You!</h1> <p style="text-align:justify" align="justify">Thank you for making an appointment</p> </div> <div class="one-col" style="padding:2%"> <table style="border-collapse:collapse; width:100%" width="100%"> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Appoint ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $appointID . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">My ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $clientID . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Dentist</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $dentist_name . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Date</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $dateAppointFormat . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Time</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $timeAppoint . '</td> </tr> </table> </div> </div> </body> </html>'; // $textMsg = 'Good day'; $verified = 1; $image_name = $_FILES['preDiag_file']['tmp_name']; $folder = "image/pre_diag/"; $image_path = $folder . $_FILES['preDiag_file']['name']; move_uploaded_file($image_name, $image_path); $sql = "INSERT INTO appointment (appointID,clientID,doctorID,appointmentDate,start,end,service,status,prediag_img,verified,view,timestamp) value (:appointID,:clientID,:doctor,:date,:starttotime,:endtotime,:service,:status,:prediag,:verified,:view,:ts)"; $stmt_insert_appoint = $connect->prepare($sql); $stmt_insert_appoint->execute(['appointID' => $appointID, 'clientID' => $clientID, 'doctor' => $doctor, 'date' => $date, 'starttotime' => $starttotime, 'endtotime' => $endtotime, 'service' => $service_explode[0], 'status' => $status, 'prediag' => $image_path, 'verified' => $verified, 'view' => $view, 'ts' => $timestamp]); sendVerificationEmail($email_appoint, $body); // $result = itexmo($contact, $textMsg, "TR-ROBBI193582_6X9BF"); // if ($result == "") { // echo "iTexMo: No response from server!!!"; // } else if ($result == 0) { // echo "Message Sent!"; // } else { // echo "Error Num " . $result . " was encountered!"; // } echo "<script>window.location.replace('account.php')</script>"; } } } } if (isset($_POST['cancelYes'])) { $appointID = $_GET['cancel']; $status = 'Cancelled'; $reason = $_POST['reason']; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Good day </h1> <p style="text-align:justify" align="justify">Your appointment has been cancelled</p> </div> <div class="one-col" style="padding:2%"> <h4 style="letter-spacing:1%">Reason of cancellation</h4> <p style="text-align:justify" align="justify">' . $reason . '</p> </div> </div> </body> </html>'; $sql_checkResched = "SELECT appointmentDate,clientID FROM appointment WHERE appointID = :appointID"; $stmt_checkResched = $connect->prepare($sql_checkResched); $stmt_checkResched->execute(['appointID' => $appointID]); $row_checkResched = $stmt_checkResched->fetch(PDO::FETCH_ASSOC); $clientID = $row_checkResched['clientID']; $appointDate = $row_checkResched['appointmentDate']; $appointDateTime = new DateTime($appointDate); $appointDateTimeFormatted = $appointDateTime->format('Y-m-d'); $cancelDate = new DateTime(); $cancelDateFormat = $cancelDate->modify('+3 day'); $cancelDateFormatted = $cancelDateFormat->format('Y-m-d'); //get client $sql_getEmail = "SELECT * FROM client WHERE clientID = :pid"; $stmt_getEmail = $connect->prepare($sql_getEmail); $stmt_getEmail->execute(['pid' => $clientID]); $row_getEmail = $stmt_getEmail->fetch(PDO::FETCH_ASSOC); $email = $row_getEmail['email']; if ($appointDateTimeFormatted < $cancelDateFormatted) { echo "<script>alert('Cancellation of appointment must within 3 days before the appointment date. You can call our hotline for further instructions.');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } else { sendVerificationEmail($email, $body); $query_cancel_appoint = "UPDATE appointment SET status = :status, remark = :reason WHERE appointID = :appointID"; $stmnt_cancel_appoint = $connect->prepare($query_cancel_appoint); $stmnt_cancel_appoint->execute(['status' => $status, 'reason' => $reason, 'appointID' => $appointID]); echo "<script>window.location.replace('account.php')</script>"; } } if (isset($_POST['resched'])) { $appointID = $_GET['appointID']; $timestamp = date('Y-m-d H:i:s'); $clientID = $_SESSION['id']; $email_appoint = $_SESSION['email']; $date = $_POST['date']; $doctor = $_POST['doctor']; $start = $_POST['start']; $cancel_status = 'Cancelled'; $sql_checkResched = "SELECT appointmentDate FROM appointment WHERE appointID = :appointID"; $stmt_checkResched = $connect->prepare($sql_checkResched); $stmt_checkResched->execute(['appointID' => $appointID]); $row_checkResched = $stmt_checkResched->fetch(PDO::FETCH_ASSOC); $appointDate = $row_checkResched['appointmentDate']; $appointDateTime = new DateTime($appointDate); $appointDateTimeFormatted = $appointDateTime->format('Y-m-d'); $reschedDate = new DateTime(); $reschedDateFormat = $reschedDate->modify('+3 day'); $reschedDateFormatted = $reschedDateFormat->format('Y-m-d'); //get client id $sql_getID = "SELECT clientID FROM client WHERE clientID = :pid"; $stmt_getID = $connect->prepare($sql_getID); $stmt_getID->execute(['pid' => $clientID]); $row_getID = $stmt_getID->fetch(PDO::FETCH_ASSOC); $patient_id = $row_getID['clientID']; //get dentist name $sql_getDentist = "SELECT Salutation,firstName,middleName,lastName FROM dentist WHERE doctorID = :docID"; $stmt_getDentist = $connect->prepare($sql_getDentist); $stmt_getDentist->execute(['docID' => $doctor]); $row_getDentist = $stmt_getDentist->fetch(PDO::FETCH_ASSOC); $dentist_name = $row_getDentist['Salutation'] . " " . $row_getDentist['firstName'] . " " . $row_getDentist['middleName'] . " " . $row_getDentist['lastName']; //explode service with option of 2 values $service = $_POST['service']; $service_explode = explode('|', $service); $startto = $start; $starttime = new DateTime($startto); $starttotime = $starttime->format('H:i'); //$endtime = strtotime($startto)+ 60* 60; //adding 1hour --3600 secs is 1 hour-- $endtime = new DateTime($startto . $service_explode[1]); //adding duration based on the selected duration $endtotime = $endtime->format('H:i:'); //format date and time to string for email html $dateAppoint = new DateTime($date); $dateAppointFormat = $dateAppoint->format('d M Y'); $timeStartFormat = $starttime->format('g:i a'); $timeEndFormat = $endtime->format('g:i a'); $timeAppoint = $timeStartFormat . " - " . $timeEndFormat; //checking for availability $check = $connect->prepare("SELECT * FROM appointment WHERE appointmentDate = :date AND doctorID = :doctor AND status != :status"); $check->execute(['date' => $date, 'doctor' => $doctor, 'status' => $cancel_status]); $rowTimeCheck = $check->fetch(PDO::FETCH_ASSOC); $starttimeCheck = $rowTimeCheck['start']; $endtimeCheck = $rowTimeCheck['end']; //check holiday $check3 = "SELECT * FROM events"; $stmt_check3 = $connect->prepare($check3); $stmt_check3->execute(); $rowCheck3 = $stmt_check3->fetch(PDO::FETCH_ASSOC); $holiday = $rowCheck3['allDay']; $holiday_title = $rowCheck3['holiday']; if (empty($date) || empty($doctor) || empty($start) || empty($service)) { echo "<script>alert('Please fill all fields to continue making an appointment');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } else if ($date == $holiday) { echo "<script>alert('This day is " . $holiday_title . " is not available. Please select another date');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } else if ($starttimeCheck > $starttotime && $endtimeCheck < $endtotime) { #-> Check time is in between start and end time echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } elseif (($starttimeCheck > $starttotime && $starttimeCheck < $endtotime) || ($endtimeCheck > $starttotime && $endtimeCheck < $endtotime)) { #-> Check start or end time is in between start and end time echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } elseif ($starttimeCheck == $starttotime || $endtimeCheck == $endtotime) { #-> Check start or end time is at the border of start and end time echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } elseif ($starttotime > $starttimeCheck && $endtotime < $endtimeCheck) { #-> start and end time is in between the check start and end time. echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } else if ($appointDateTimeFormatted < $reschedDateFormatted) { echo "<script>alert('Rescheduling of appointment must within 3 days before the appointment date. You can call our hotline for further instructions.');window.location.replace('account.php?appoint=" . $appointID . "')</script>"; } else if (!isset($_POST['terms'])) { echo "<script>alert('Please read the terms and conditions and checked');window.location.replace('account.php?appointID=" . $appointID . "')</script>"; } else { $status = 'Pending'; $view = 0; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Thank You!</h1> <p style="text-align:justify" align="justify">Your appointment has been rescheduled</p> </div> <div class="one-col" style="padding:2%"> <table style="border-collapse:collapse; width:100%" width="100%"> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Appoint ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $appointID . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Dentist</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $dentist_name . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Date</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $dateAppointFormat . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Time</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $timeAppoint . '</td> </tr> </table> </div> , </div> </body> </html>'; $verified = 1; $image_name = $_FILES['preDiag_file']['tmp_name']; $folder = "image/pre_diag/"; $image_path = $folder . $_FILES['preDiag_file']['name']; move_uploaded_file($image_name, $image_path); $sql_reschedUpdate = "UPDATE appointment SET doctorID = :dentistID, appointmentDate = :appointDate, start = :start, end = :end, service = :service, status = :status, prediag_img = :path, view = :view, timestamp = :timestamp WHERE appointID = :appointID"; $stmt_reschedUpdate = $connect->prepare($sql_reschedUpdate); $stmt_reschedUpdate->execute(['dentistID' => $doctor, 'appointDate' => $date, 'start' => $starttotime, 'end' => $endtotime, 'service' => $service_explode[0], 'status' => $status, 'path' => $image_path, 'view' => $view, 'timestamp' => $timestamp, 'appointID' => $appointID]); sendVerificationEmail($email_appoint, $body); echo "<script>window.location.replace('account.php')</script>"; } } //update account if (isset($_POST['account_update'])) { $accountID = $_SESSION['id']; $fname = $_POST['fname']; $lname = $_POST['lname']; $contact = $_POST['contact']; $email = $_POST['email']; $uname = $_POST['uname']; //check old path $sql_getpath = "SELECT image FROM client WHERE clientID = :id"; $stmt_getpath = $connect->prepare($sql_getpath); $stmt_getpath->execute(['id' => $accountID]); $row_getpath = $stmt_getpath->fetch(PDO::FETCH_ASSOC); $oldpath = $row_getpath['image']; //uploading image $image_name = $_FILES['profile']['name']; $image_tmp_name = $_FILES['profile']['tmp_name']; $folder = "image/profile_patient/"; $path = $folder . $image_name; if (empty($fname) || empty($lname) || empty($contact) || empty($email) || empty($uname)) { echo "<script>alert('Info not updated')</script>"; } else { $sql_updateAccount = "UPDATE client SET firstName = :fname, lastName = :lname, userName = :uname, email = :email, contact = :contact, image = :image WHERE clientID = :id"; $stmt_updateAccount = $connect->prepare($sql_updateAccount); if (empty($image_tmp_name)) { $stmt_updateAccount->execute(['fname' => $fname, 'lname' => $lname, 'uname' => $uname, 'email' => $email, 'contact' => $contact, 'image' => $oldpath, 'id' => $accountID]); echo "<script>alert('Account updated');window.location.replace('account.php');</script>"; } else { $stmt_updateAccount->execute(['fname' => $fname, 'lname' => $lname, 'uname' => $uname, 'email' => $email, 'contact' => $contact, 'image' => $path, 'id' => $accountID]); move_uploaded_file($image_tmp_name, $path); echo "<script>alert('Account updated');window.location.replace('account.php');</script>"; } } } ?> <file_sep><?php session_start(); if(!empty($_SESSION['ogliadmin'])){ echo "<script>window.location.replace('index.php')</script>"; } include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <!-- <script src="https://kit.fontawesome.com/0c5646b481.js"></script> --> <link rel="stylesheet" href="../css/style.css"> </head> <body> <main class="login-main"> <div class="login-box"> <h3>Administration</h3> <form method="POST" class="login-form"> <div class="textbox"> <!-- <label for="adminName">Username</label><br> --> <i class="fas fa-user"></i> <input type="text" name="username" placeholder="Enter Username" required> </div> <div class="textbox"> <!-- <label for="adminPassword">Password</label><br> --> <i class="fas fa-lock"></i> <input type="password" name="password" placeholder="Enter Password" required> </div> <input class="admin-btn" type="submit" name="login" value="Sign In"> </form> </div> </main> </body> </html> <?php if(isset($_POST['login'])){ $adminName = $_POST['username']; $adminPassword = $_POST['<PASSWORD>']; $sql = "SELECT * FROM administrator WHERE username = ?"; $stmt = $connect->prepare($sql); $stmt->execute([$adminName]); $rows1 = $stmt->fetch(PDO::FETCH_ASSOC); if($rows1){ $password_check = password_verify($adminPassword,$rows1['password']); if($password_check == false){ echo "<script>alert('Password incorrect');window.location('admin-login.php')</script>"; }else if($password_check == true){ session_start(); $_SESSION['ogliadmin'] = $rows1['id']; $_SESSION['ogliadminID'] = $rows1['adminID']; $_SESSION['lastName'] = $rows['lastName']; $_SESSION['firstName'] = $rows['firstName']; echo"<script>alert('Log in Success');window.location.replace('index.php')</script>;"; }else{ echo "<script>alert('Error');window.location('sign-in.php')</script>"; } }else{ echo "<script>alert('User Not Found');window.location('sign-in.php')</script>"; } } ?><file_sep><?php session_start(); include '../config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>CMS | Home</title> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Home</div> </div> <?php ?> <div class="cms_home"> <div class="cms_home_container"> <div class="sections"> <div class="brand-container"> <?php $sql_brand = "SELECT brand FROM cms_home"; $stmnt_brand = $connect->prepare($sql_brand); $stmnt_brand->execute(); $row_brand = $stmnt_brand->fetch(PDO::FETCH_ASSOC); $brand = $row_brand['brand']; ?> <div class="brand-content"> <img src="<?php echo $brand ?>" alt=""> </div> <div class="brand-overlay"> <span id="brand"><i class="fas fa-edit"></i></span> </div> </div> </div> <div class="sections home"> <?php $sql_cms_home = "SELECT * FROM cms_home"; $stmt_cms_home = $connect->prepare($sql_cms_home); $stmt_cms_home->execute(); $row = $stmt_cms_home->fetch(PDO::FETCH_ASSOC); ?> <div class="sec1-bg"> <div class="sec1-header"> <a href="?editID=<?php echo $row['homeID'] ?>"><i class="fas fa-edit edit"></i></a> </div> <div class="sec1-container" style="background: linear-gradient(rgb(246, 249, 250, 1),rgba(39, 174, 96,0.5)), url('../image/<?php echo $row['bg'] ?>') no-repeat;"> <div class="text-container"> <span><?php echo $row['text'] ?></span> </div> </div> </div> </div> </div> </div> </main> </div> <!-- modal --> <div id="modal_brand" class="modal"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close_brand">&times;</span> <h2>Update Brand</h2> </div> <form action="" method="POST" enctype="multipart/form-data"> <div class="modal-body modal-body_brand"> <div class="brand-container"> <?php $sql_viewbrand = "SELECT brand FROM cms_home"; $stmnt_viewbrand = $connect->prepare($sql_viewbrand); $stmnt_viewbrand->execute(); $row_viewbrand = $stmnt_viewbrand->fetch(PDO::FETCH_ASSOC); $viewbrand = $row_viewbrand['brand']; ?> <div class="brand-content"> <img src="<?php echo $viewbrand ?>" alt="" id="previewBrand"> </div> <div class="brand-overlay"> <input type="file" name="brandFile" id="brandFile" class="brandFile" size="60"> <label for="brandFile" class="brandBtn custom-file-label">Select&nbsp;Image</label> </div> </div> <div class="brand_btn_container"> <input type="submit" name="updateBrand" value="Update"> </div> </div> </form> </div> </div> <!-- modal --> <div id="modalEdit" class="modal"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $homeID = $_GET['editID']; $sql_eachSection = "SELECT * FROM cms_home WHERE homeID = :homeID"; $stmt_eachSection = $connect->prepare($sql_eachSection); $stmt_eachSection->execute(['homeID' => $homeID]); $row_eachSection = $stmt_eachSection->fetch(PDO::FETCH_ASSOC); ?> <span class="close" id="edit_close">&times;</span> <h2>Update Banner</h2> </div> <div class="modal-body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="section-container"> <div class="section-bg"> <div class="sect-bg-content"> <img src="<?php echo $row_eachSection['bg'] ?>" class="bg_img" id="bg_toUpdate" alt="" width="300"> <label for="bg_img-btn" class="file-btn-label">Select Background Image <input type="file" name="bg_update" class="file-btn" id="bg_img-btn" onchange="updateBg(event)" size="60"> </label> </div> </div> <div class="section-txt"><textarea name="bg_text" id="mytextarea" class="bg_text mytextarea"><?php echo $row_eachSection['text'] ?></textarea></div> <div class="section-btn"><input type="submit" name="section1_update" class="button section-update_btn" value="Update"></div> </div> </form> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="js/script.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script src="js/cms_home.js"></script> <script> var updateBg = function(event) { var output = document.getElementById('bg_toUpdate'); output.src = URL.createObjectURL(event.target.files[0]); }; tinymce.init({ selector: '.mytextarea', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); </script> </body> </html> <?php if (isset($_GET['editID'])) { $editid = $_GET['editID']; $_SESSION['editID'] = $editid; echo "<script>var edit_modal= document.getElementById('modalEdit')</script>"; echo "<script> edit_modal.style.display='block'</script>"; }; if (isset($_GET['edit_store'])) { echo "<script>const store_editModal = document.getElementById('modal_storeSched');</script>"; echo "<script>store_editModal.classList.add('modal_show');</script>"; } if (isset($_POST['updateBrand'])) { $sql_oldpath = "SELECT brand FROM cms_home"; $stmt_oldpath = $connect->prepare($sql_oldpath); $stmt_oldpath->execute(); $row_oldpath = $stmt_oldpath->fetch(PDO::FETCH_ASSOC); $oldpath = $row_oldpath['brand']; $file_name = $_FILES['brandFile']['name']; $file_tmp_name = $_FILES['brandFile']['tmp_name']; $folder = '../image/branding/'; $path = $folder . bin2hex(random_bytes('4')) . $file_name; $sql_brandFile = "UPDATE cms_home SET brand = :path"; $stmt_brandFile = $connect->prepare($sql_brandFile); if (empty($file_tmp_name)) { $stmt_brandFile->execute(['path' => $oldpath]); } else { if (!unlink($oldpath)) { echo "<script>alert('Something went wrong. Please try again');window.location.replace('cms-home.php')</script>"; } else { move_uploaded_file($file_tmp_name, $path); $stmt_brandFile->execute(['path' => $path]); echo "<script>alert('Update Successfully');window.location.replace('cms-home.php')</script>"; } } } if (isset($_POST['section1_update'])) { $homeID = $_GET['editID']; $bg = $_POST['bg_update']; $txt = $_POST['bg_text']; $check_home = "SELECT * FROM cms_home WHERE homeID = :homeID"; $stmt_home = $connect->prepare($check_home); $stmt_home->execute(['homeID' => $homeID]); $row_home = $stmt_home->fetch(PDO::FETCH_ASSOC); $curBG = $row_home['bg']; $file_name = $_FILES['bg_update']['name']; $file_tmp_name = $_FILES['bg_update']['tmp_name']; $directory = '../image/'; $path = $directory . bin2hex(random_bytes('4')) . $file_name; $sql_update_home = "UPDATE cms_home SET text = :txt, bg = :bg WHERE homeID = :homeID"; $smt_update_home = $connect->prepare($sql_update_home); if ((empty($file_tmp_name))) { $smt_update_home->execute(['txt' => $txt, 'bg' => $curBG, 'homeID' => $homeID]); echo "<script>alert('Updated Successfully');window.location.replace('cms-home.php')</script>"; exit(); } else { if (!unlink($curBG)) { echo "<script>alert('Error')</script>"; } else { move_uploaded_file($file_tmp_name, $path); $smt_update_home->execute(['txt' => $txt, 'bg' => $path, 'homeID' => $homeID]); echo "<script>alert('Updated Successfully');window.location.replace('cms-home.php')</script>"; exit(); } } } if (isset($_POST['edit_openhour'])) { $id = $_GET['edit_store']; $day = $_POST['day']; $start = $_POST['start']; $starttime = new DateTime($start); $starttotime = $starttime->format('H:i'); $end = $_POST['end']; $endtime = new DateTime($end); $endtotime = $endtime->format('H:i'); $sql_updateStore = "UPDATE openhour_tbl SET day = :day, start = :start, end = :end WHERE id = :id"; $stmt_updateStore = $connect->prepare($sql_updateStore); $stmt_updateStore->execute(['day' => $day, 'start' => $starttotime, 'end' => $endtotime, 'id' => $id]); echo "<script>alert('Update successfully');window.location.replace('cms-home.php#openhour')</script>"; } ?> <script> const edit_close = $('#edit_close'); // When the user clicks on <span> (x), close the modal edit_close.on('click', function() { edit_modal.style.display = "none"; window.location.replace('cms-home.php'); }); //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); </script><file_sep>!(function(t) { 'function' == typeof define && define.amd ? define([ 'jquery', 'datatables.net', 'datatables.net-buttons' ], function(e) { return t(e, window, document); }) : 'object' == typeof exports ? (module.exports = function(e, n) { return ( e || (e = window), (n && n.fn.dataTable) || (n = require('datatables.net')(e, n).$), n.fn.dataTable.Buttons || require('datatables.net-buttons')(e, n), t(n, e, e.document) ); }) : t(jQuery, window, document); })(function(t, e, n, o) { 'use strict'; var a = t.fn.dataTable, r = n.createElement('a'), i = function(t) { r.href = t; var e = r.host; return ( -1 === e.indexOf('/') && 0 !== r.pathname.indexOf('/') && (e += '/'), r.protocol + '//' + e + r.pathname + r.search ); }; return ( (a.ext.buttons.print = { className: 'buttons-print', text: function(t) { return t.i18n('buttons.print', 'Print'); }, action: function(n, a, r, d) { var s = a.buttons.exportData(t.extend({ decodeEntities: !1 }, d.exportOptions)), u = a.buttons.exportInfo(d), l = a .columns(d.exportOptions.columns) .flatten() .map(function(t) { return a.settings()[0].aoColumns[a.column(t).index()].sClass; }) .toArray(), c = function(t, e) { for (var n = '<tr>', a = 0, r = t.length; a < r; a++) { var i = null === t[a] || t[a] === o ? '' : t[a]; n += '<' + e + ' ' + (l[a] ? 'class="' + l[a] + '"' : '') + '>' + i + '</' + e + '>'; } return n + '</tr>'; }, f = '<table class="' + a.table().node().className + '">'; if (((f += '<thead>'), d.repeatingHead.logo)) { var m = [ 'left', 'right', 'center' ].indexOf(d.repeatingHead.logoPosition) > 0 ? d.repeatingHead.logoPosition : 'right'; f += '<tr><th colspan="' + s.header.length + '" style="padding: 0;margin: 0;text-align: ' + m + ';"><img style="' + d.repeatingHead.logoStyle + '" src="' + d.repeatingHead.logo + '"/></th></tr>'; } d.repeatingHead.title && (f += '<tr><th colspan="' + s.header.length + '">' + d.repeatingHead.title + '</th></tr>'), d.header && (f += c(s.header, 'th')), (f += '</thead>'), (f += '<tbody>'); for (var h = 0, p = s.body.length; h < p; h++) f += c(s.body[h], 'td'); (f += '</tbody>'), d.footer && s.footer && (f += '<tfoot>' + c(s.footer, 'th') + '</tfoot>'), (f += '</table>'); var g = e.open('', ''); g.document.close(); var b = '<title>' + u.title + '</title>'; t('style, link').each(function() { var e; b += ('link' === (e = t(this).clone()[0]).nodeName.toLowerCase() && (e.href = i(e.href)), e.outerHTML); }); try { g.document.head.innerHTML = b; } catch (n) { t(g.document.head).html(b); } (g.document.body.innerHTML = '<h1>' + u.title + '</h1><div>' + (u.messageTop || '') + '</div>' + f + '<div>' + (u.messageBottom || '') + '</div>'), t(g.document.body).addClass('dt-print-view'), t('img', g.document.body).each(function(t, e) { e.setAttribute('src', i(e.getAttribute('src'))); }), d.customize && d.customize(g, d, a); var v = function() { d.autoPrint && (g.print(), g.close()); }; navigator.userAgent.match(/Trident\/\d.\d/) ? v() : g.setTimeout(v, 1e3); }, title: '*', messageTop: '*', messageBottom: '*', repeatingHead: {}, exportOptions: {}, header: !0, footer: !1, autoPrint: !0, customize: null }), a.Buttons ); }); <file_sep><?php session_start(); require 'config/control.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/gallery.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> </head> <body> <?php include 'header.php'; ?> <div class="page-container"> <main> <section> <h1>Gallery</h1> <div class="row"> <div class="filters-group-wrap"> <div class="filters-group"> <p class="filter-label">Filter</p> <div class="btn-group filter-options"> <button class="btn btn--primary" data-group="Facilities">Facilities</button> <button class="btn btn--primary" data-group="Services">Services</button> </div> </div> </div> </div> <div id="grid" class="masonry"> <?php $sql_gallery_imgs = "SELECT * FROM cms_gallery"; $stmt_gallery_imgs = $connect->prepare($sql_gallery_imgs); $stmt_gallery_imgs->execute(); $rows_gallery_imgs = $stmt_gallery_imgs->fetchAll(); foreach ($rows_gallery_imgs as $gallery_img) { ?> <figure class="picture-item" data-groups='["<?php echo $gallery_img['category'] ?>"]'> <a href="image/<?php echo $gallery_img['image'] ?>"><img src="image/<?php echo $gallery_img['image'] ?>" title="<?php echo $gallery_img['title'] . "\n" . $gallery_img['description'] ?>"></a> </figure> <?php } ?> <!-- <div class="col-1@sm col-1@xs my-sizer-element"></div> --> </div> </section> </main> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </div> <!-- script js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/main.js"></script> <script src="js/simple-lightbox.min.js"></script> <script src="js/shuffle.js"></script> <script src="js/gallery.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script> $(function() { var lightbox = $('.picture-item a').simpleLightbox({ captionDelay: 1000 }); }); </script> </body> </html><file_sep>const signSlider = () => { const signUpButton = document.querySelector('#signUp'); const signInButton = document.querySelector('#signIn'); const cont = document.querySelector('#container'); signUpButton.addEventListener('click', () => { cont.classList.add('right-panel-active'); }); signInButton.addEventListener('click', () => { cont.classList.remove('right-panel-active'); }); }; signSlider(); <file_sep><?php session_start(); include '../config/control.php'; $val = $_POST['val']; $apply = $_POST['apply']; $sql = "UPDATE cms_testi SET switch = :apply WHERE id = :val"; $stmt = $connect->prepare($sql); $stmt->execute(['apply'=>$apply,'val'=>$val]) ?><file_sep><?php include 'controllers/signout.php' ?> <!-- preloader --> <div class="loader"> <span></span> <span></span> <span></span> </div> <header class="header"> <nav class="nav"> <?php $sql_brand = "SELECT brand FROM cms_home"; $stmnt_brand = $connect->prepare($sql_brand); $stmnt_brand->execute(); $row_brand = $stmnt_brand->fetch(PDO::FETCH_ASSOC); $brand = $row_brand['brand']; ?> <div class="brand"> <a href="index.php"><img src="image/<?php echo $brand ?>" alt=""></a> </div> <ul class="nav-links"> <li><a href="index.php">Home</a></li> <li> <label for="drop-1" class="submenu">About</label> <a href="about.php">About</a> <input type="checkbox" id="drop-1" /> <ul> <li><a href="about.php#about">About us</a></li> <li><a href="about.php#ourTeam">Our Dentist</a></li> <li><a href="about.php#testimonials">Testimonials</a></li> </ul> </li> <li><a href="service.php">Services</a></li> <li><a href="index.php#contact">Contact</a></li> <li><a href="gallery.php">Gallery</a></li> <li><a href="?setAppoint=1">Get Appointment</a></li> <?php if (!isset($_SESSION['id'])) { ?> <li><a href="member.php">Member</a></li> <?php } else { ?> <li class="myAcc"><a href="account.html">My Account</a></li> <?php } ?> </ul> <?php if (isset($_SESSION['id'])) { $idd = $_SESSION['id']; $sql = "SELECT * FROM client WHERE id = :id OR clientID = :clientID"; $stmnt = $connect->prepare($sql); $stmnt->execute(['id' => $idd, 'clientID' => $idd]); $rows = $stmnt->fetch(PDO::FETCH_ASSOC); ?> <span class="user-avatar" id="userAvatar"> <?php if (empty($rows['image'])) { ?> <img src="image/smile.jpeg" alt="" class="avatar"> <?php } else { ?> <img src="<?php echo $rows['image'] ?>" alt="" class="avatar"> <?php } ?> <div class="user-menu" id="avatarMenu"> <ul class="user-menu-list"> <li><a href="account.php">My Account</a></li> <li><a href="?signout=<?php echo $_SESSION['id'] ?>" onclick="return confirm('Are you sure you want to sign out?')">Sign out</a></li> </ul> </div> </span> <?php } else { ?> <span class="user-avatar just-fill" id="userAvatar"> </span> <?php } ?> <div class="burger"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> </div> </nav> </header> <?php if (isset($_GET['setAppoint'])) { if (!isset($_SESSION['id'])) { echo "<script>alert('Please sign in to continue to set an appointment. Thank you!'); window.location ='member.php'</script>"; } else { echo "<script>window.location = 'appoint.php'</script>"; } } ?><file_sep><?php // require_once 'controllers/authController.php'; require 'config/control.php'; include 'controllers/verify.php'; if (isset($_GET['token'])) { $token = $_GET['token']; verifyUser($token); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/member.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> </head> <body> <?php include 'header.php'; ?> <div class="page-container"> <main> <section> <div class="container" id="container"> <div class="form-container sign-up-container"> <form action="controllers/signController.php" method="POST" id="signupForm"> <h1>Create Account</h1> <!-- <div class="social-container"> --> <p id="form-message"></p> <!-- </div> --> <input id="fname" type="text" name="fname" placeholder="First Name"> <input id="lname" type="text" name="lname" placeholder="Last Name"> <input id="email" type="text" name="email" placeholder="Email"> <input id="contact" type="text" name="contact" placeholder="Contact Number"> <input id="username" type="text" name="username" placeholder="Username"> <input id="password" type="<PASSWORD>" name="password" placeholder="<PASSWORD>"> <input id="cpassword" type="<PASSWORD>" name="cpassword" placeholder="<PASSWORD>"> <button id="signup" type="submit" name="signup" class="button">Sign Up</button> </form> </div> <div class="form-container sign-in-container"> <form action="controllers/signupController.php" method="POST" id="signinForm"> <h1>Sign in</h1> <!-- <div class="social-container"> --> <p id="signin_message"></p> <!-- </div> --> <!-- <span>or use your email for registration</span> --> <input id="uname" type="text" name="uname" placeholder="Username"> <input id="pwd" type="<PASSWORD>" name="pwd" placeholder="<PASSWORD>"> <a href="">Forgot your password?</a> <button id="signin" type="submit" name="signin" class="button">Sign In</button> </form> </div> <div class="overlay-container"> <div class="overlay"> <div class="overlay-panel overlay-left"> <h1>Welcome Back!</h1> <p>We want to be part of yours.</p> <button class="ghost" id="signIn">Sign In</button> </div> <div class="overlay-panel overlay-right"> <h1>Smile, Friend!</h1> <p>Every smile has a story, we want to be part of yours.</p> <button class="ghost" id="signUp">Sign Up</button> </div> </div> </div> </div> </section> </main> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </div> <!-- script js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/sign.js"></script> <script src="js/main.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script> $(document).ready(function() { $("#signupForm").submit(function(e) { e.preventDefault(); const fname = $("#fname").val(); const lname = $("#lname").val(); const username = $("#username").val(); const email = $("#email").val(); const contact = $("#contact").val(); const password = $("#password").val(); const cpassword = $("#cpassword").val(); const signup = $("#signup").val(); $("#form-message").load("controllers/signController.php", { fname: fname, lname: lname, username: username, email: email, contact: contact, password: <PASSWORD>, cpassword: <PASSWORD>, signup: signup }); }); $("#signinForm").submit(function(event) { event.preventDefault(); const uname = $("#uname").val(); const pwd = $("#pwd").val(); const signin = $("#signin").val(); $("#signin_message").load("controllers/signupController.php", { uname: uname, pwd: pwd, signin: signin }); }); }); </script> </body> </html><file_sep><?php session_start(); if (empty($_SESSION['email'])) { echo "<script>window.location.replace('index.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Thank You</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/ty.css"> <link rel="stylesheet" href="css/loader.css"> </head> <body> <!-- preloader --> <div class="loader"> <span></span> <span></span> <span></span> </div> <main> <section class="thankyou-section"> <div class="header"> <img src="image/dpom_logo.png" alt=""> </div> <div class="content"> <h1>thank you!</h1> <p>You are one step away to complete your sign up.</p> <p>We've sent an email to <?php echo $_SESSION['email'] ?> to verify your account. Please click the link in that email to continue.</p> <a href="index.php"><button class="ghost">Back to home page</button></a> </div> <div class="footer"> <h4>&copy; Dela Paz-Oglimen Dental Care Clinic '08</h4> <div class="social-media"> <span><i class="fab fa-facebook-f fb"></i></span> <span><i class="fab fa-twitter tw"></i></span> <span><i class="fab fa-instagram ig"></i></span> </div> </div> </section> </main> <!-- script js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="js/main.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> </body> </html><file_sep><?php require '../../config/control.php'; $year = '2019'; $status = 'Cancelled'; $sql = "SELECT MONTHNAME(appointmentDate) month_cancel,count(*) count_cancel FROM appointment WHERE YEAR(appointmentDate)=:year AND status = :status GROUP BY MONTH(appointmentDate)"; $stmt = $connect->prepare($sql); $stmt->execute(['year'=>$year,'status'=>$status]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $json_array = array(); echo json_encode($rows,JSON_NUMERIC_CHECK); ?><file_sep><?php require_once 'controllers/authController.php'; if (empty($_SESSION['ogliadmin'])) { echo "<script>window.location.replace('sign-in.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><NAME> | ADMIN</title> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <link href='../fullcalendar/core/main.min.css' rel='stylesheet' /> <link href='../fullcalendar/daygrid/main.min.css' rel='stylesheet' /> <link href='../fullcalendar/timegrid/main.min.css' rel='stylesheet' /> <link href='../fullcalendar/list/main.min.css' rel='stylesheet' /> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <?php $id = $_GET['patient']; $sql_patientInfo = $connect->prepare("SELECT * FROM client WHERE clientID = ?"); $sql_patientInfo->execute([$id]); $row_patientInfo = $sql_patientInfo->fetch(PDO::FETCH_ASSOC); ?> <div class="main-header__heading"> <a href="patients.php"><span>Patient List</span></a> / <span class="patient-title"><?php echo $row_patientInfo['lastName'] . "," . $row_patientInfo['firstName'] ?>'s Appointments</span> </div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <div class="appoint_table"> <div class="header__sort"> <a href="?patient=<?php echo $id ?>&&set=<?php echo $id ?>"><button class="button patient_set"><i class="fas fa-calendar-check check"></i>&nbsp;Set&nbsp;an&nbsp;appointment</button></a> <div class="add"> <a href="patients.php" class="button patient_set"><i class="fas fa-user check"></i>&nbsp;Back</a> </div> </div> <table class="list__tbl display dt-responsive nowrap patient_list" id="patient-list"> <thead> <tr> <th>Patient ID</th> <th>Appointment ID</th> <th>Dentist</th> <th>Service</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $eachPatient_id = $_GET['patient']; $sql_eachPatient = $connect->prepare("SELECT * FROM appointment WHERE clientID = :id"); $sql_eachPatient->execute(['id' => $eachPatient_id]); $rows_eachPatient = $sql_eachPatient->fetchAll(); foreach ($rows_eachPatient as $eachPatient) { $dentistName = $eachPatient['doctorID']; $query_dentist = $connect->prepare("SELECT * FROM dentist WHERE doctorID = ?"); $query_dentist->execute([$dentistName]); $row_dentistName = $query_dentist->fetch(PDO::FETCH_ASSOC); $salut = $row_dentistName['Salutation']; $dfn = $row_dentistName['firstName']; $dmn = $row_dentistName['middleName']; $dln = $row_dentistName['lastName']; $dname = $salut . $dfn . " " . $dmn . " " . $dln; ?> <tr> <td><?php echo $eachPatient['clientID'] ?></td> <td><?php echo $eachPatient['appointID'] ?></td> <td><?php echo $dname ?></td> <td><?php echo $eachPatient['service'] ?></td> <td><?php echo $eachPatient['status'] ?></td> <td> <a href="?patient=<?php echo $eachPatient_id ?>&&appoint=<?php echo $eachPatient['appointID'] ?>"><i class="fas fa-eye eye"></i></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- MODAL --> <div id="modal__view" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close">&times;</span> <?php $appoint = $_GET['appoint']; $patient = $_GET['patient']; $stmt_summary = $connect->prepare("SELECT * FROM appointment WHERE appointID = :appoint"); $stmt_summary->execute(['appoint' => $appoint]); $row_summary = $stmt_summary->fetch(PDO::FETCH_ASSOC); $date_fetch = new DateTime($row_summary['appointmentDate']); $start_fetch = new DateTime($row_summary['start']); $end_fetch = new DateTime($row_summary['end']); $schedTime = date_format($start_fetch, 'g:i a') . "-" . date_format($end_fetch, 'g:i a'); $schedDate = date_format($date_fetch, 'd M Y'); $dentist_ID = $row_summary['doctorID']; $stmt_fetchDentist = $connect->prepare("SELECT * FROM dentist WHERE doctorID = :dentist"); $stmt_fetchDentist->execute(['dentist' => $dentist_ID]); $row_fetchDentist = $stmt_fetchDentist->fetch(PDO::FETCH_ASSOC); $salut = $row_fetchDentist['Salutation']; $dfn = $row_fetchDentist['firstName']; $dmn = $row_fetchDentist['middleName']; $dln = $row_fetchDentist['lastName']; $dfullname = $salut . " " . $dfn . " " . $dmn . " " . $dln; $stmt_fetchPatientInfo = $connect->prepare("SELECT * FROM client WHERE clientID = :patient"); $stmt_fetchPatientInfo->execute(['patient' => $patient]); $row_fetchPatientInfo = $stmt_fetchPatientInfo->fetch(PDO::FETCH_ASSOC); $fn = $row_fetchPatientInfo['firstName']; $mn = $row_fetchPatientInfo['middleName']; $ln = $row_fetchPatientInfo['lastName']; $patient_name = $fn . " " . $mn . " " . $ln ?> <span class="modal_header-title"><?php echo $patient_name ?></span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="modal-view-body_container"> <div class="view__info"> <div class="patient_info_content"> <div class="patient_textbox"> <span>Appointment Id:</span> <span><?php echo $row_summary['appointID'] ?></span> </div> <div class="patient_textbox"> <span>Dentist:</span> <span><?php echo $dfullname ?></span> </div> <div class="patient_textbox"> <span>Service:</span> <span><?php echo $row_summary['service'] ?></span> </div> <div class="patient_textbox"> <span>Scheduled Date:</span> <span><?php echo $schedDate ?></span> </div> <div class="patient_textbox"> <span>Scheduled Time:</span> <span><?php echo $schedTime ?></span> </div> </div> <div class="pre_diagnostic"> <div class="prediag_header"> <h3>Pre-diagnostic image</h3> </div> <div class="prediag_img_container"> <img src="../<?php echo $row_summary['prediag_img'] ?>" alt=""> </div> </div> </div> <div class="appoint_info_content"> <div class="remarks"> <h3>Remarks</h3> <textarea class="remark-box" name="remark"><?php echo $row_summary['remark'] ?></textarea> <div class="button-container"> <input type="submit" name="update_remark" class="button patient_update-btn" value="Save" onclick="confirmation('Is the patient already done to his/her appointment?')"> </div> </div> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> <!-- SET APPOINTMENT --> <div id="modal__setAppoint" class="modal view"> <!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <span class="close" id="close_setAppoint">&times;</span> <?php $patient = $_GET['patient']; $stmt_fetchPatientSet = $connect->prepare("SELECT * FROM client WHERE clientID = :patient"); $stmt_fetchPatientSet->execute(['patient' => $patient]); $row_fetchPatientSet = $stmt_fetchPatientSet->fetch(PDO::FETCH_ASSOC); $fn = $row_fetchPatientSet['firstName']; $mn = $row_fetchPatientSet['middleName']; $ln = $row_fetchPatientSet['lastName']; $patient_name = $fn . " " . $mn . " " . $ln ?> <span class="modal_header-title"><?php echo $patient_name ?></span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="modal-view-body_container"> <div class="view__info"> <div class="patient_info_content"> <div class="patient_textbox"> <span>Patient Id:</span> <span><?php echo $row_fetchPatientSet['clientID'] ?></span> </div> <div class="patient_textbox"> <span>Date:</span> <span class="setInput"> <input type="text" name="date" id="strDate"> </span> </div> <div class="patient_textbox"> <span>Service:</span> <span class="setInput"> <select name="service" id="service"> <option selected disabled>Select Service</option> <?php $stmt_service = $connect->prepare("SELECT * FROM service"); $stmt_service->execute(); $rows_service = $stmt_service->fetchAll(); foreach ($rows_service as $service) { $hour = $service['hour']; $min = $service['min']; $duration = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $service['title'] . ' | ' . $duration ?>"><?php echo $service['title'] ?></option> <?php } ?> </select> </span> </div> <div class="patient_textbox"> <span>Dentist</span> <span class="setInput"> <select name="dentist" id="dentist"> <option selected disabled>Select Dentist</option> </select> </span> </div> <div class="patient_textbox"> <span>Scheduled Time:</span> <span class="setInput"> <select name="start" id="starttime"> <option selected disabled>Select Time</option> </select> </span> </div> </div> <div class="appoint_info_content"> <div class="setCalendar"> <div id="calendarSet"></div> </div> </div> </div> <div class="button-container"> <input type="submit" name="setAppoint" class="button patient_set set_appoint" value="Set appointment" onclick=" return confirm('Set appointment for this patient?')"> </div> </div> </form> </div> <div class="modal-footer"> <h6><NAME> Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="js/script.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src='../fullcalendar/core/main.min.js'></script> <script src='../fullcalendar/daygrid/main.min.js'></script> <script src='../fullcalendar/timegrid/main.min.js'></script> <script src='../fullcalendar/interaction/main.min.js'></script> <script src='../fullcalendar/list/main.min.js'></script> <script src='../fullcalendar/moment/main.min.js'></script> <script src='../fullcalendar/moment-timezone/main.min.js'></script> <script src="../js/moment.min.js"></script> <script src="js/setCalendar.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(document).ready(function() { $(".patient_list").DataTable({ responsive: true, pageLength: 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [4], orderable: false }] }); $("#dentist").on('change', function() { var doctorID = $("#dentist").val(); var date = $("#strDate").val(); $select = $('#starttime'); $.ajax({ url: '../time.php', type: 'POST', data: { doctorID: doctorID, date: date }, dataType: 'JSON', success: function(data) { $select.html(''); //iterate over the data and append a select option $select.append('<option value="" selected disabled>Please Select Time</option>'); $.each(data.optionTime, function(key, value) { const hide_time = value.option; $.each(data.time, function(key, value) { const startTheTime = value.starts; if (jQuery.inArray(startTheTime, hide_time) !== -1) { $("#starttime").append( "<option disabled value=" + startTheTime + ">" + startTheTime + "</option>" ); } else { $("#starttime").append( "<option value=" + startTheTime + ">" + startTheTime + "</option>" ); } }); var found = {}; $('#starttime option').each(function() { var $this = $(this); if (found[$this.attr('value')] && $this.prop('disabled') == false) { $this.remove(); } else { found[$this.attr('value')] = true; } }); }); } }) }); $('#strDate').change(function() { var strDate = $("#strDate").val(); $.ajax({ url: "../doctor-sched.php", type: 'POST', dataType: "json", data: { strDate: strDate }, success: function(response) { $selectDentist = $('#dentist'); $selectDentist.html(''); //iterate over the data and append a select option $selectDentist.append('<option value="" selected disabled>Please Select Dentist</option>'); $.each(response.doctor, function(key, value) { $("#dentist").append( "<option value=" + value.doctorID + ">" + value.doctorName + "</option>" ); }); } }) }); $("#strDate").datepicker({ minDate: 0, showAnim: 'fadeIn', dateFormat: 'yy-mm-dd' }); }) </script> </body> </html> <?php if (isset($_GET['appoint'])) { echo "<script>var viewAppoint_modal= document.getElementById('modal__view')</script>"; echo "<script> viewAppoint_modal.style.display='block'</script>"; } if (isset($_GET['set'])) { echo "<script>var modal__setAppoint = document.getElementById('modal__setAppoint')</script>"; echo "<script> modal__setAppoint.style.display='block'</script>"; } ?> <script> const close = $('#close'); // When the user clicks on <span> (x), close the modal close.on('click', function() { viewAppoint_modal.style.display = "none"; window.location.replace('patient.php?patient=<?php echo $eachPatient_id ?>'); }); const closeAppoint = $('#close_setAppoint'); // When the user clicks on <span> (x), close the modal closeAppoint.on('click', function() { modal__setAppoint.style.display = "none"; window.location.replace('patient.php?patient=<?php echo $eachPatient_id ?>'); }); const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); function confirmationLogout(anchor) { var conf = confirm('Are you sure want to SIGN OUT?'); if (conf) window.location = anchor.attr("href"); } </script><file_sep><?php require '../config/control.php'; require_once 'emailController.php'; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Good day!</h1> <p style="text-align:justify" align="justify">Your scheduled appointment is tomorrow. Thank you</p> </div> </div> </body> </html>'; $sql_appoint = "SELECT * FROM appointment"; $stmt_appoint = $connect->prepare($sql_appoint); $stmt_appoint->execute(); $rows_appoint = $stmt_appoint->fetchAll(); foreach ($rows_appoint as $row) { $appointDate = $row['appointmentDate']; $clientID = $row['clientID']; $sql_patient = "SELECT * FROM client WHERE clientID = :clientID"; $stmt_patient = $connect->prepare($sql_patient); $stmt_patient->execute(['clientID' => $clientID]); $rows_patient = $stmt_patient->fetch(PDO::FETCH_ASSOC); $email_appoint = $rows_patient['email']; $today = new DateTime(); $todayy = $today->format('Y-m-d'); $beforeAppoint = new DateTime($appointDate); $beforeAppoint->modify('-1 day'); $beforeAppointt = $beforeAppoint->format('Y-m-d'); if ($beforeAppointt == $todayy) { sendVerificationEmail($email_appoint, $body); } } <file_sep><?php session_start(); if (empty($_SESSION['id'])) { echo "<script>window.location.replace('member.php')</script>"; } require_once 'controllers/appointController.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link href='fullcalendar/core/main.min.css' rel='stylesheet' /> <link href='fullcalendar/daygrid/main.min.css' rel='stylesheet' /> <link href='fullcalendar/timegrid/main.min.css' rel='stylesheet' /> <link href='fullcalendar/list/main.min.css' rel='stylesheet' /> <link rel="stylesheet" href="css/appoint.css"> <link rel="stylesheet" href="css/modal.css"> </head> <body> <?php include 'header.php'; ?> <div class="page-container"> <main> <section class="section-appoint"> <p class="ribbon"> <span class="text"> <strong class="bold">Note:</strong> For Major operations, we must first conduct a check up to learn more about the details of your sitution. Please select check-up under services. Thank you! </span> </p> <div class="appoint-container"> <div class="appoint-content appoint-left"> <div id="calendar" class="calendar"> </div> </div> <div class="appoint-content appoint-right"> <?php include('errors.php'); ?> <form action="appoint.php" method="POST" id="appoint_form" enctype="multipart/form-data"> <div class="accordion-item"> <div class="title"> <span><i class="far fa-calendar-check"></i><span class="titler">DATE</span></span> </div> <ul class="accordion-content"> <input type="text" id="strDate" name="date" data-value="date" class="date" value="<?php echo $date ?>"> </ul> </div> <div class="accordion-item"> <div class="title"> <span><i class="fas fa-user-md"></i><span class="titler">Dentist</span></span> </div> <ul class="accordion-content"> <li> <select name="doctor" id="doctor" class="doctor"> <option selected value="<?php echo $doctor ?>"><?php echo $dentist_name ?></option> </select> </li> </ul> </div> <div class="accordion-item"> <div class="title"> <span><i class="far fa-clock"></i><span class="titler">Time Slot</span></span> </div> <ul class="accordion-content"> <li> <select name="start" id="starttime" class="time_slot"> <option selected value="<?php echo $start ?>"><?php echo $start ?></option> </select> </li> </ul> </div> <div class="accordion-item"> <div class="title"> <span><i class="fas fa-tooth"></i><span class="titler">Services</span></span> </div> <ul class="accordion-content"> <li> <select name="service" id="service" class="services"> <option value="<?php echo $service ?>" selected><?php echo $titleService ?></option> <?php if (!isset($_SESSION['id'])) { ?> <?php $queryService = $connect->prepare("SELECT * FROM service"); $queryService->execute(); while ($rowService = $queryService->fetch(PDO::FETCH_ASSOC)) { $hour = $rowService['hour']; $min = $rowService['min']; $duration = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $rowService['title'] . ' | ' . $duration ?>"><?php echo $rowService['title'] ?></option> <?php } ?> <?php } else if (isset($_SESSION['id'])) { ?> <?php $cid = $_SESSION['id']; $sql_check_ifDone = "SELECT * FROM client WHERE clientID = :cid"; $stmt_check_ifDOne = $connect->prepare($sql_check_ifDone); $stmt_check_ifDOne->execute(['cid' => $cid]); $row_check_ifDone = $stmt_check_ifDOne->fetch(PDO::FETCH_ASSOC); $checkup = $row_check_ifDone['checkup']; if ($checkup == 1) { ?> <?php $queryService = $connect->prepare("SELECT * FROM service"); $queryService->execute(); while ($rowService = $queryService->fetch(PDO::FETCH_ASSOC)) { $hour = $rowService['hour']; $min = $rowService['min']; $duration = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $rowService['title'] . ' | ' . $duration ?>"><?php echo $rowService['title'] ?></option> <?php } ?> <?php } else { ?> <?php $Checkup = 'Checkup'; $Check_up = 'Check-up'; $CheckUp = 'Check up'; $Check_Up = 'Check up'; $Check_Up = 'Check Up'; $checkup = 'checkup'; $sql_checkUpOnly = "SELECT * FROM service WHERE title = :Checkup || title = :Check_up || title = :CheckUp || title = :Check_Up || title = :checkup "; $stmt_checkUpOnly = $connect->prepare($sql_checkUpOnly); $stmt_checkUpOnly->execute(['Checkup' => $Checkup, 'Check_up' => $Check_up, 'CheckUp' => $CheckUp, 'Check_Up' => $Check_Up, 'checkup' => $checkup]); $row_checkUpOnly = $stmt_checkUpOnly->fetch(PDO::FETCH_ASSOC); $hour = $row_checkUpOnly['hour']; $min = $row_checkUpOnly['min']; $durationCheckup = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $row_checkUpOnly['title'] . ' | ' . $durationCheckup ?>"><?php echo $row_checkUpOnly['title'] ?></option> <?php } ?> <?php } ?> </select> </li> </ul> </div> <div class="accordion-item"> <div class="title"> <span><i class="fas fa-file-medical"></i><span class="pre-diag_title">Pre-Diagnostic (Please upload image of your mouth/teeth condition) <span class="pre-diag_optional">*Optional</span></span></span> </div> <ul class="accordion-content"> <li> <input type="file" class="pre-diag_file" name="preDiag_file" id="pre-diag_file" size="60"> </li> </ul> </div> <div class="appoint-submit"> <span><input class="agree" id="terms" type="checkbox" name="terms"><span id="term_btn">I agree to terms and conditions</span></span> <input type="submit" id="submit" name="submit" class="button btn" value="Set appointment"> </div> </form> </div> </div> </section> </main> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </div> <!-- The Modal --> <div id="term_modal" class="modal"> <!-- Modal content --> <div class="modal-content term-content"> <div class="modal-header"> <span class="close" id="close_modal">&times;</span> <h2>Terms & conditions</h2> </div> <div class="modal-body"> <div class="terms_content"> <p>We are always pleased to assist our clients whenever we can. This document gives details of our terms and conditions of service. If, however, you have any queries or need clarification, please contact us and a member of our team will be happy to help you.</p> <h5>Treatment planning:</h5> <p> Once your treatment plan has been agreed with the Dentist, we will provide you with a written estimate of your services. If this plan changes due to radiographic or clinical findings, we will inform you and discuss this with you accordingly.</p> <h5>Consent forms:</h5> <p>Certain treatments require completion of a written consent form. This is in to ensure that we have explained the treatment, aftercare and any risk to you thoroughly, before any of these treatments are carried out. It also allows you to make an informed decision before agreeing to treatment.</p> <h5>Fees:</h5> <p> Oglimen Dental Care does not offer credit and we require fees to be settled at the appointment where treatment is provided.
Where treatment incurs a laboratory fee, at least 50% of the total fee is due at the appointment where impressions are taken. Fees for certain treatments like Dental Implants and clear braces are taken in staged payments at each visit. We will discuss and plan a schedule of payment for you.</p> <h5>Late cancellation or missed appointments:</h5> <p>Oglimen Dental Care reserves in the event of a missed appointment or an appointment canceled with less than 24-hour notice. For appointments longer than 1 hour, we require at least 72 hours. Late for appointments In order to be fair to the other patients, if you are more than 10 minutes, please be aware that you may be asked to reschedule your appointment.</p> <h5>Guarantee:</h5> <p>The patient has followed all post treatment maintenance recommendations made by our dentists. No treatment is guaranteed for more than 1 year. Some treatments may have a guarantee of less than 1 year, and in this case you will be informed by your Dentist either verbally or in writing, or both.</p> <h5>Personal Details:</h5> <p>It is very important that you give a full medical history and details of any medication you take. Should these change in any way, it is very important for you to tell your Dentist. It is the patient’s responsibility to inform the clinic of any changes in either personal details and/or their medical history.</p> <h5>Use of Images and X-rays:</h5> <p>Aldridge Dental Practice may use images and x-rays of your smile and teeth only, for marketing and educational purposes on website, and on promotional and educational literature. Your name will never be published, and identity will never be disclosed. However, if you DO NOT wish for us to use your images and x-rays in this way, please let us know.</p> <h5>Use of patient contact details:</h5> <p>At Oglimen Dental Care the health of our patients is our highest priority, and we also like to keep our patients informed of various important changes at the clinic and of our latest special offers. We like to remind our patients of their appointments, when they are due for appointments, and other various important reminders. On this note, you may be periodically contacted by the clinic via phone, text, email or by letter in the post. If you DO NOT wish to be contacted by the clinic by any or all of these means, please let us know.</p> <h5>Complaint’s policy:</h5> <p>Complaints can be made in writing by filling out a simple complaints form available from reception. Complaints should be made to Oglimen Dental Care Complaints Manager’, and should be clear, so that they can be dealt with efficiently.</p> <h5>No tolerance/Abuse policy:</h5> <p>Oglimen Dental Care we operate a zero tolerance policy to abuse to our Dentists and staff, loud/disorderly/drunken behavior, persistent missing and late cancelation of appointments (after multiple warnings). In these situations, Aldridge Dental Practice reserves the right to refuse treatment and admission.</p> <h5>Data Protection Act:</h5> <p>We store all patient personal details on a secure computer system in accordance with the Data Protection Act. All clinical notes, digital radiographs, digital photographs etc remain the property of Oglimen Dental Care. Copies of notes, radiographs and photographs can be made available on request, and Oglimen Dental Care reserves the right to charge an administration fee for these.</p> </div> </div> </div> </div> <!-- script js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src='js/fullcalendar.js'></script> <script src="js/main.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script src='fullcalendar/core/main.min.js'></script> <script src='fullcalendar/daygrid/main.min.js'></script> <script src='fullcalendar/timegrid/main.min.js'></script> <script src='fullcalendar/interaction/main.min.js'></script> <script src='fullcalendar/list/main.min.js'></script> <script src='fullcalendar/moment/main.min.js'></script> <script src='fullcalendar/moment-timezone/main.min.js'></script> <script src="js/appoint.js"></script> <!-- <script> $(document).ready(function() { $("#doctor").on('change', function() { var doctorID = $("#doctor").val(); var date = $("#strDate").val(); $select = $('#starttime'); $.ajax({ url: 'time.php', type: 'POST', data: { doctorID: doctorID, date: date }, dataType: 'JSON', success: function(data) { $select.html(''); //iterate over the data and append a select option $select.append('<option value="" selected disabled>Please Select Time</option>'); console.log(data.optionTime); console.log(data.time); // const hide_time = data.optionTime; // const hide_time2 = hide_time[0]; // const hide_the_time = hide_time2.option; // console.log(hide_the_time); // for (i = 0; i < data.optionTime.length; i++) { // var optTime = data.optionTime[i]; // var new_object = $.extend({}, optTime); // console.log(new_object); // } $.each(data.optionTime, function(key, value) { const hide_time = value.option; $.each(data.time, function(key, value) { // console.log(value.starts); const startTheTime = value.starts; // $.each(data.optionTime, function(key, value) { // const hide_time = value.option; // for (i = 0; i < hide_time.length; i++) { // const hideTheTime = hide_time[i].startoftime; // console.log(hideTheTime); // } // }); if (jQuery.inArray(startTheTime, hide_time) !== -1) { $("#starttime").append( "<option disabled value=" + startTheTime + ">" + startTheTime + "</option>" ); } else { $("#starttime").append( "<option value=" + startTheTime + ">" + startTheTime + "</option>" ); } // console.log(startTheTime); }); var found = {}; $('#starttime option').each(function() { var $this = $(this); if (found[$this.attr('value')] && $this.prop('disabled') == false) { $this.remove(); // found[$this.attr('value')] = true; } else { // $this.remove(); found[$this.attr('value')] = true; } }); }); } }) }); $('#strDate').change(function() { var strDate = $("#strDate").val(); $.ajax({ url: "doctor-sched.php", type: 'POST', dataType: "json", data: { strDate: strDate }, success: function(response) { $selectDentist = $('#doctor'); $selectDentist.html(''); //iterate over the data and append a select option $selectDentist.append('<option value="" selected disabled>Please Select Dentist</option>'); $.each(response.doctor, function(key, value) { $("#doctor").append( "<option value=" + value.doctorID + ">" + value.doctorName + "</option>" ); }); } }) }); $('#accordion').find('.accordion__toggle').click(function() { if ($(this).hasClass('disable')) { alert("Please complete the above details"); } else { $(this).next().slideToggle('fast'); $(".accordion__content").not($(this).next()).slideUp('fast'); } }); $('select').change(function() { if ($(this).val() != "") { $(this).parent().next('.accordion__toggle').removeClass('disable'); } else { $(this).parent().nextAll('.accordion__toggle').addClass('disable'); } }); $("#strDate").datepicker({ minDate: 0, showAnim: 'fadeIn', dateFormat: 'yy-mm-dd' }); $('form input[type="submit"]').prop("disabled", true); $('.agree').click(function() { if ($(this).prop("checked") == true) { $('form input[type="submit"]').prop("disabled", false); } else { $('form input[type="submit"]').prop("disabled", true); $('form input[type="submit"]').addClass('term_unchecked'); } }) }); </script> --> </body> </html><file_sep><?php include '../../config/control.php'; $sql_updateEnvelope = "UPDATE inquiry SET view_notif = 1 WHERE view_notif=0"; $stmt_updateEnvelope = $connect->prepare($sql_updateEnvelope); $stmt_updateEnvelope->execute(); $sql_envelopeContent = "SELECT * FROM inquiry ORDER BY time_stamp DESC LIMIT 5"; $stmt_envelopeContent = $connect->prepare($sql_envelopeContent); $stmt_envelopeContent->execute(); $result = ''; while ($rows = $stmt_envelopeContent->fetch(PDO::FETCH_ASSOC)) { $timestamp = new DateTime($rows['time_stamp']); $time_sent = date_format($timestamp, 'd M Y g:i a'); $result .= '<li class="envelope__links__list"> <a href="message.php?replyID=' . $rows['msgID'] . '" class="bell__list"> <div class="envelope__list__container"> <span class="list__header">' . $rows['email'] . '</span> </div> <div class="bell__info__container"> <span class="list__info">' . substr($rows["message"], 0, 20) . '</span> <span class="list__time"><em>' . $time_sent . '</em></span> </div> </a> </li>'; } if (!empty($result)) { print $result; } <file_sep><?php include 'config/control.php'; function splitTimeIntoIntervals($work_starts, $work_ends, $break_starts = null, $break_ends = null, $minutes_per_interval = 60) { $intervals = array(); $time = date("H:i", strtotime($work_starts)); $first_after_break = false; while (strtotime($time) < strtotime($work_ends)) { // if at least one of the arguments associated with breaks is mising - act like there is no break if ($break_starts == null || $break_starts == null) { $time_starts = date("H:i", strtotime($time)); $time_ends = date("H:i", strtotime($time_starts . "+$minutes_per_interval minutes")); } // if the break start/end time is specified else { if ($first_after_break == true) { //first start time after break $time = (date("H:i", strtotime($break_ends))); $first_after_break = false; } $time_starts = (date("H:i", strtotime($time))); $time_ends = date("H:i", strtotime($time_starts . "+$minutes_per_interval minutes")); //if end_time intersects break_start and break_end times if (timesIntersects($time_starts, $time_ends, $break_starts, $break_ends)) { $time_ends = date("g:ia", strtotime($break_starts)); $first_after_break = true; } } //if end_time is after work_ends if (date("H:i", strtotime($time_ends)) > date("H:i", strtotime($work_ends))) { $time_ends = date("H:i", strtotime($work_ends)); } $intervals[] = array('starts' => date("g:ia", strtotime($time_starts)), 'ends' => date("g:ia", strtotime($time_ends))); $time = $time_ends; } return $intervals; } function timesIntersects($time1_from, $time1_till, $time2_from, $time2_till) { $out; $time1_st = strtotime($time1_from); $time1_end = strtotime($time1_till); $time2_st = strtotime($time2_from); $time2_end = strtotime($time2_till); $duration1 = $time1_end - $time1_st; $duration2 = $time2_end - $time2_st; $time1_length = date("i", strtotime($time1_till . "-$time1_from")); if ( (($time1_st <= $time2_st && $time2_st <= $time1_end && $time1_end <= $time2_end) || ($time1_st <= $time2_st && $time2_st <= $time2_end && $time2_end <= $time1_end) && ($duration1 >= $duration2)) || ($time1_st <= $time2_st && $time2_st <= $time1_end && $time1_end <= $time2_end) && ($duration1 <= $duration2) ) { return true; } return false; } // $data = splitTimeIntoIntervals('9:00 am','5:00 pm','12:00 pm','1:00 pm'); // echo json_encode(array('time'=>$data)); function getTimeRange($startTime, $endTime, $format = 'g:ia') { $arrayTime = array(); $intervalTime = new DateInterval('PT30M'); $realEnd = new DateTime($endTime); $realEnd->add($intervalTime); $period = new DatePeriod(new DateTime($startTime), $intervalTime, $realEnd); foreach ($period as $realTime) { // $real_time = $realTime->format($format); // $arrayTime[] = array("startoftime" => $real_time); $arrayTime[] = $realTime->format($format); } return $arrayTime; } if (isset($_POST['doctorID'])) { $doctorID = $_POST['doctorID']; $date = $_POST['date']; $status = 'Cancelled'; $queryTime = $connect->prepare("SELECT * FROM schedule WHERE doctorID=?"); $queryTime->execute([$doctorID]); $rowTime = $queryTime->fetch(PDO::FETCH_ASSOC); $doctorID = $rowTime['doctorID']; $data = splitTimeIntoIntervals($rowTime['starttime'], $rowTime['endtime'], $rowTime['breakstart'], $rowTime['breakend']); $queryCheck2 = $connect->prepare("SELECT count(*) FROM appointment WHERE doctorID=? AND appointmentDate=? AND status != 'Cancelled'"); $queryCheck2->execute([$doctorID, $date]); $countCheck2 = $queryCheck2->fetchColumn(); if ($countCheck2 > 0) { $queryCheck = $connect->prepare("SELECT * FROM appointment WHERE doctorID=? AND appointmentDate=? AND status != 'Cancelled'"); $queryCheck->execute([$doctorID, $date]); $rowCheck = $queryCheck->fetchAll(); foreach ($rowCheck as $rowCheck) { $check_start = $rowCheck['start']; $check_end = $rowCheck['end']; $realCheckTime[] = array('option' => getTimeRange($check_start, $check_end)); } $json = array( 'time' => $data, 'optionTime' => $realCheckTime ); echo json_encode($json); } else { $queryCheck = $connect->prepare("SELECT * FROM appointment WHERE doctorID=? AND appointmentDate=? AND status != 'Cancelled'"); $queryCheck->execute([$doctorID, $date]); $rowCheck = $queryCheck->fetch(PDO::FETCH_ASSOC); $check_start = $rowCheck['start']; $check_end = $rowCheck['end']; $realCheckTime[] = array('option' => getTimeRange($check_start, $check_end)); $json = array( 'time' => $data, 'optionTime' => $realCheckTime ); echo json_encode($json); } }; <file_sep>const brandUpdate = () => { const brandBtn = document.querySelector('#brand'); const brandModal = document.querySelector('#modal_brand'); const brandClose = document.querySelector('#close_brand'); brandBtn.addEventListener('click', () => { brandModal.classList.add('modal_show'); }); brandClose.addEventListener('click', () => { brandModal.classList.remove('modal_show'); }); }; brandUpdate(); const brandImg = () => { const brandFile = document.querySelector('#brandFile'); const previewBrand = document.querySelector('#previewBrand'); brandFile.addEventListener('change', (e) => { previewBrand.src = URL.createObjectURL(e.target.files[0]); }); }; brandImg(); <file_sep><?php session_start(); require '../config/control.php'; require_once '../controllers/emailSign.php'; if (isset($_POST['signup'])) { $firstname = $_POST['fname']; $lastname = $_POST['lname']; $email = $_POST['email']; $contact = $_POST['contact']; $username = $_POST['username']; $password = $_POST['password']; $cpassword = $_POST['cpassword']; $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $shuffled = str_shuffle($str); $generatedID = substr($shuffled, 0, 8); $idd = $generatedID; $status = 'Not Verfied'; $timestamp = date('Y-m-d h:i:s'); $errorEmpty = false; $errorEmail = false; $errorPhone = false; $errorExistUser = false; $errorExistEmail = false; $errorPwd = false; if (empty($firstname) || empty($lastname) || empty($email) || empty($username) || empty($contact) || empty($password) || empty($cpassword)) { // $errors['empty'] = "Please fill all fields"; echo "<span class='form-error'>Please fill all fields</span>"; $errorEmpty = true; } else if (strlen($contact) != 11) { echo "<span class='form-error'>Phone number should be 11 digits</span>"; $errorPhone = true; } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // $errors['email'] = "Please input a valid email"; echo "<span class='form-error'>Please input a valid email</span>"; $errorEmail = true; } else if (strlen($password) <= 8) { // $errors['password'] = "Password must have 8 or more characters"; echo "<span class='form-error'>Password must have 8 or more characters</span>"; $errorPwd = true; } else if ($password !== $cpassword) { // $errors['password'] = "Passwords do not match. Please try again"; echo "<span class='form-error'>Passwords do not match. Please try again</span>"; $errorPwd = true; } else { //check username $query_register = "SELECT * FROM client WHERE userName = :username"; $check_query_reg = $connect->prepare($query_register); $check_query_reg->execute(['username' => $username]); $row_query_reg = $check_query_reg->fetch(PDO::FETCH_ASSOC); //check email $query_register2 = "SELECT * FROM client WHERE email = :email"; $check_query_reg2 = $connect->prepare($query_register2); $check_query_reg2->execute(['email' => $email]); $row_query_reg2 = $check_query_reg2->fetch(PDO::FETCH_ASSOC); if ($row_query_reg > 0) { // $errors['username'] = "Username already exist"; echo "<span class='form-error'>Username already exist</span>"; $errorExistUser = true; } else if ($row_query_reg2 > 0) { //email already registered // $errors['email'] = "Email already have an account"; echo "<span class='form-error'>Email already have an account</span>"; $errorExistEmail = true; } else { try { $hashedpwd = password_hash($password, PASSWORD_DEFAULT); $token = bin2hex(random_bytes(50)); $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> @import url("https://fonts.googleapis.com/css?family=Poppins:400,500&display=swap"); *{ margin: 0; padding: 0; border: 0; box-sizing: border-box; } body{ font-family: "Poppins", sans-serif; background: #d8dbdb; font-size: 18px; max-width: 800px; margin: 0 auto; padding: 2%; color: #565859; } #wrapper{ background: #f6faff; } img{ max-width: 100%; } header{ width: 90%; display: flex; justify-content: center; align-items: center; } #logo{ max-width: 180px; margin: 2% 0 0 5%; } .banner{ margin-bottom: 3%; } .one-col{ padding: 2%; } h1{ letter-spacing: 1%; } p{ text-align: justify; } .button-holder{ margin: 2% 0 0 5%; } button { border-radius: 20px; border: 1px solid #89029b; background: #89029b; color: rgb(43, 39, 39); font-size: 12px; font-weight: bold; padding: 12px 45px; letter-spacing: 1px; text-transform: uppercase; transition: transform 80ms ease-in; cursor: pointer; margin: 15px 0; } button.ghost { margin-top: 20px; background: transparent; border-color: rgb(43, 39, 39); } button.ghost:hover { background: #89029b; color: white; border-color: #89029b; } button.ghost:focus { outline: none; } button:active { transform: scale(0.95); } </style> </head> <body style="font-family: "Poppins", sans-serif;background: #d8dbdb;font-size: 18px;max-width: 800px;margin: 0 auto;padding: 2%;color: #565859;"> <div id="wrapper" style="background: #f6faff;"> <header style="width: 90%;display: flex;justify-content: center;align-items: center;"> <div id="logo" style="max-width: 180px;margin: 2% 0 0 5%;"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width: 100%;"> </div> </header> <div class="banner" style="margin-bottom: 3%;"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width: 100%;"> </div> <div class="one-col" style="padding: 2%;"> <h1 style="letter-spacing: 1%;">Thank You!</h1> <p style="text-align: justify;">Please click the link below in order to verify your email.</p> </div> <div class="button-holder" style="margin: 2% 0 0 5%;"> <a href="http://localhost/OgliMen/member.php?token=' . $token . '" target="_blank"><button class="ghost" style="border-radius: 20px;border: 1px solid #89029b;background: transparent;color: rgb(43, 39, 39);font-size: 12px;font-weight: bold;padding: 12px 45px;letter-spacing: 1px;text-transform: uppercase;transition: transform 80ms ease-in;cursor: pointer;margin: 15px 0;margin-top: 20px;border-color: rgb(43, 39, 39);">Verify</button></a> </div> </div> </body> </html>'; $verified = false; $insert_register = "INSERT INTO client (clientID,firstName,lastName,userName,<PASSWORD>,email,contact,status,verified,token,date) VALUES (:clientID, :firstName, :lastName, :userName, :<PASSWORD>, :email, :contact, :status, :verified, :token,:ts)"; $stmt_register = $connect->prepare($insert_register); $stmt_register->execute(['clientID' => $idd, 'firstName' => $firstname, 'lastName' => $lastname, 'userName' => $username, 'password' => <PASSWORD>, 'email' => $email, 'contact' => $contact, 'status' => $status, 'verified' => $verified, 'token' => $token, 'ts' => $timestamp]); echo "<span class='form__success'>Loading...</span>"; $client_id = $connect->lastInsertId(); // $_SESSION['id'] = $client_id; // $_SESSION['username'] = $username; // $_SESSION['name'] = $firstname . " " . $lastname; $_SESSION['email'] = $email; $_SESSION['verified'] = $verified; sendVerificationEmail($email, $body); echo "<script>window.location.replace('ty.php')</script>"; // exit(); } catch (Exception $e) { echo "Message: " . $e->getMessage(); } } } }; ?> <script> $("#fname, #lname, #username, #email, #password, #cpassword, #contact").removeClass("input-error"); const errorEmpty = "<?php echo $errorEmpty ?>"; const errorEmail = "<?php echo $errorEmail ?>"; const errorExistUser = "<?php echo $errorExistUser ?>"; const errorExistEmail = "<?php echo $errorExistEmail ?>"; const errorPwd = "<?php echo $errorPwd ?>"; const errorPhone = "<?php echo $errorPhone ?>"; if (errorEmpty == true) { $("#fname, #lname, #username, #email, #password, #cpassword, #contact").addClass("input-error"); } if (errorEmail == true) { $("#email").addClass("input-error"); } if (errorExistUser == true) { $("#username").addClass("input-error"); } if (errorExistEmail == true) { $("#email").addClass("input-error"); } if (errorPwd == true) { $("#password, #cpassword").addClass("input-error"); } if (errorPhone == true) { $("#contact").addClass("input-error"); } if (errorEmpty == false && errorEmail == false && errorExistUser == false && errorExistEmail == false && errorPwd == false && errorPhone == false) { $("#fname, #lname, #username, #email, #password, #cp<PASSWORD>, #contact").val(""); }; </script><file_sep><?php session_start(); // require '../config/control.php'; require 'config/control.php'; require_once 'emailController.php'; // require_once 'appointController.php'; date_default_timezone_set('Asia/Manila'); $errors = array(); $errorss = array(); $firstname = ""; $lastname = ""; $email = ""; $username = ""; $password = ""; $cpassword = ""; $message = ""; $empty = ""; // if (isset($_POST['signup'])) { // $firstname = $_POST['fname']; // $lastname = $_POST['lname']; // $email = $_POST['email']; // $username = $_POST['username']; // $password = $_POST['password']; // $cpassword = $_POST['cpassword']; // $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // $shuffled = str_shuffle($str); // $generatedID = substr($shuffled, 0, 8); // $idd = $generatedID; // $status = 'Not Verfied'; // $timestamp = date('Y-m-d h:i:s'); // $errorEmpty = false; // $errorEmail = false; // $errorExistUser = false; // $errorExistEmail = false; // $errorPwd = false; // if (empty($firstname) || empty($lastname) || empty($email) || empty($username) || empty($password) || empty($cpassword)) { // // $errors['empty'] = "Please fill all fields"; // echo "<span class='form-error'>Please fill all fields</span>"; // $errorEmpty = true; // } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // // $errors['email'] = "Please input a valid email"; // echo "<span class='form-error'>Please input a valid email</span>"; // $errorEmail = true; // } else if (strlen($password) <= 8) { // // $errors['password'] = "Password must have 8 or more characters"; // echo "<span class='form-error'>Password must have 8 or more characters</span>"; // $errorPassword = true; // } else if ($password !== $cpassword) { // // $errors['password'] = "Passwords do not match. Please try again"; // echo "<span class='form-error'>Passwords do not match. Please try again</span>"; // $errorPassword = true; // } else { // //check username // $query_register = "SELECT * FROM client WHERE userName = :username"; // $check_query_reg = $connect->prepare($query_register); // $check_query_reg->execute(['username' => $username]); // $row_query_reg = $check_query_reg->fetch(PDO::FETCH_ASSOC); // //check email // $query_register2 = "SELECT * FROM client WHERE email = :email"; // $check_query_reg2 = $connect->prepare($query_register2); // $check_query_reg2->execute(['email' => $email]); // $row_query_reg2 = $check_query_reg2->fetch(PDO::FETCH_ASSOC); // if ($row_query_reg > 0) { // // $errors['username'] = "Username already exist"; // echo "<span class='form-error'>Username already exist</span>"; // $errorExistUser = true; // } else if ($row_query_reg2 > 0) { // //email already registered // // $errors['email'] = "Email already have an account"; // echo "<span class='form-error'>Email already have an account</span>"; // $errorExistEmail = true; // } else { // try { // $hashedpwd = password_hash($password, PASSWORD_DEFAULT); // $token = bin2hex(random_bytes(50)); // $body = '<!DOCTYPE html> // <html lang="en"> // <head> // <style type="text/css"> // @import url("https://fonts.googleapis.com/css?family=Poppins:400,500&display=swap"); // *{ // margin: 0; // padding: 0; // border: 0; // box-sizing: border-box; // } // body{ // font-family: "Poppins", sans-serif; // background: #d8dbdb; // font-size: 18px; // max-width: 800px; // margin: 0 auto; // padding: 2%; // color: #565859; // } // #wrapper{ // background: #f6faff; // } // img{ // max-width: 100%; // } // header{ // width: 90%; // display: flex; // justify-content: center; // align-items: center; // } // #logo{ // max-width: 180px; // margin: 2% 0 0 5%; // } // .banner{ // margin-bottom: 3%; // } // .one-col{ // padding: 2%; // } // h1{ // letter-spacing: 1%; // } // p{ // text-align: justify; // } // .button-holder{ // margin: 2% 0 0 5%; // } // button { // border-radius: 20px; // border: 1px solid #89029b; // background: #89029b; // color: rgb(43, 39, 39); // font-size: 12px; // font-weight: bold; // padding: 12px 45px; // letter-spacing: 1px; // text-transform: uppercase; // transition: transform 80ms ease-in; // cursor: pointer; // margin: 15px 0; // } // button.ghost { // margin-top: 20px; // background: transparent; // border-color: rgb(43, 39, 39); // } // button.ghost:hover { // background: #89029b; // color: white; // border-color: #89029b; // } // button.ghost:focus { // outline: none; // } // button:active { // transform: scale(0.95); // } // </style> // </head> // <body style="font-family: "Poppins", sans-serif;background: #d8dbdb;font-size: 18px;max-width: 800px;margin: 0 auto;padding: 2%;color: #565859;"> // <div id="wrapper" style="background: #f6faff;"> // <header style="width: 90%;display: flex;justify-content: center;align-items: center;"> // <div id="logo" style="max-width: 180px;margin: 2% 0 0 5%;"> // <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width: 100%;"> // </div> // </header> // <div class="banner" style="margin-bottom: 3%;"> // <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width: 100%;"> // </div> // <div class="one-col" style="padding: 2%;"> // <h1 style="letter-spacing: 1%;">Thank You!</h1> // <p style="text-align: justify;">Please click the link below in order to verify your email.</p> // </div> // <div class="button-holder" style="margin: 2% 0 0 5%;"> // <a href="http://localhost/OgliMen/member.php?token=' . $token . '" target="_blank"><button class="ghost" style="border-radius: 20px;border: 1px solid #89029b;background: transparent;color: rgb(43, 39, 39);font-size: 12px;font-weight: bold;padding: 12px 45px;letter-spacing: 1px;text-transform: uppercase;transition: transform 80ms ease-in;cursor: pointer;margin: 15px 0;margin-top: 20px;border-color: rgb(43, 39, 39);">Verify</button></a> // </div> // </div> // </body> // </html>'; // $verified = false; // $insert_register = "INSERT INTO client (clientID,firstName,lastName,userName,password,email,status,verified,token,date) // VALUES (:clientID, :firstName, :lastName, :userName, :password, :email, :status, :verified, :token,:ts)"; // $stmt_register = $connect->prepare($insert_register); // $stmt_register->execute(['clientID' => $idd, 'firstName' => $firstname, 'lastName' => $lastname, 'userName' => $username, 'password' => <PASSWORD>, 'email' => $email, 'status' => $status, 'verified' => $verified, 'token' => $token, 'ts' => $timestamp]); // echo "<span class='form__success'>Loading...</span>"; // $client_id = $connect->lastInsertId(); // // $_SESSION['id'] = $client_id; // // $_SESSION['username'] = $username; // // $_SESSION['name'] = $firstname . " " . $lastname; // $_SESSION['email'] = $email; // $_SESSION['verified'] = $verified; // sendVerificationEmail($email, $body); // echo "<script>window.location.replace('ty.php')</script>"; // // exit(); // } catch (Exception $e) { // echo "Message: " . $e->getMessage(); // } // } // } // }; //sign in validation // if (isset($_POST['signin'])) { // $username = $_POST['username']; // $password = $_POST['password']; // if (empty($username) || empty($password)) { // $errorss['empty'] = "Please fill all fields"; // } else { // $sql_signin = "SELECT * FROM client WHERE email = :email OR userName= :username LIMIT 1"; // $stmt_check_id = $connect->prepare($sql_signin); // $stmt_check_id->execute(['email' => $username, 'username' => $username]); // $row_check_id = $stmt_check_id->fetch(PDO::FETCH_ASSOC); // if ($row_check_id) { // $password_check = password_verify($password, $row_check_id['password']); // if ($password_check == false) { // $errorss['password'] = "<PASSWORD>"; // } else { // if (count($errorss) === 0) { // $_SESSION['id'] = $row_check_id['clientID']; // $_SESSION['username'] = $row_check_id['userName']; // $_SESSION['name'] = $row_check_id['firstName'] . " " . $row_check_id['middleName'] . " " . $row_check_id['lastName']; // $_SESSION['email'] = $row_check_id['email']; // $_SESSION['verified'] = $row_check_id['verified']; // echo "<script>window.location.replace('index.php')</script>"; // exit(); // } // } // } else { // $errorss['username'] = "Username/Email do not exist"; // } // } // }; //Update if (isset($_POST['update'])) { $id = $_SESSION['id']; $firstname = $_POST['fname']; $middlename = $_POST['mname']; $lastname = $_POST['lname']; $username = $_POST['uname']; $email = $_POST['email']; $contact = $_POST['contact']; $password = $_POST['password']; if (empty($firstname) || empty($lastname) || empty($username) || empty($email) || empty($password)) { $errors['empty'] = "Required fields must not be blank"; } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Invalid Email"; } else { $sql_check = "SELECT * FROM client WHERE id = :id OR clientID = :clientID"; $stmnt_check = $connect->prepare($sql_check); $stmnt_check->execute(['id' => $id, 'clientID' => $id]); $rows_update = $stmnt_check->fetch(PDO::FETCH_ASSOC); if ($rows_update) { $password_check = password_verify($password, $rows_update['password']); if ($password_check == false) { $errors['password'] = "<PASSWORD>"; } else if ($password_check == true) { if (count($errors) === 0) { $sql_update = "UPDATE client SET firstName = :fname, middleName = :mname, lastName = :lname, userName = :uname, email = :email, contact = :contact WHERE id = :id OR clientID = :clientID"; $stmnt_update = $connect->prepare($sql_update); $stmnt_update->execute(['fname' => $firstname, 'mname' => $middlename, 'lname' => $lastname, 'uname' => $username, 'email' => $email, 'contact' => $contact, 'id' => $id, 'clientID' => $id]); echo "<script>alert('Updated Successfully');window.location.replace('account.php')</script>"; exit(); } } } } } //PASSWORD UPDATE if (isset($_POST['updatepwd'])) { $id = $_SESSION['id']; $newpwd = $_POST['newpwd']; $cnewpwd = $_POST['cnewpwd']; $oldpwd = $_POST['oldpwd']; if (empty($newpwd) || empty($cnewpwd) || empty($oldpwd)) { $errorss['empty'] = "Please fill up the fields"; } else if ($newpwd !== $cnewpwd) { $errorss['password'] = "Password do not matched"; } else { $sql_check = "SELECT * FROM client WHERE id = :id OR clientID = :clientID"; $stmnt_check = $connect->prepare($sql_check); $stmnt_check->execute(['id' => $id, 'clientID' => $id]); $rows_update = $stmnt_check->fetch(PDO::FETCH_ASSOC); if ($rows_update) { $pwd_check = password_verify($oldpwd, $rows_update['password']); if ($pwd_check == false) { $errorss['password'] = "<PASSWORD>"; } else if ($pwd_check == true) { if (count($errorss) === 0) { $hashednewpwd = password_hash($newpwd, PASSWORD_DEFAULT); $sql_update_pwd = "UPDATE client SET password = :<PASSWORD> WHERE id = :id OR clientID = :clientID"; $stmnt_update_pwd = $connect->prepare($sql_update_pwd); $stmnt_update_pwd->execute(['newpwd' => $hashednewpwd, 'id' => $id, 'clientID' => $id]); echo "<script>alert('Updated Successfully');window.location.replace('account.php')</script>"; exit(); } } } } } //Contact Form if (isset($_POST['send'])) { $timestamp = date('Y-m-d H:i:s'); $firstname = $_POST['fname']; $lastname = $_POST['lname']; $email = $_POST['email']; $message = $_POST['message']; $status = 'Unread'; $view_notif = 0; $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $shuffled = str_shuffle($str); $generatedID = substr($shuffled, 0, 8); $msgid = $generatedID; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> @import url("https://fonts.googleapis.com/css?family=Poppins:400,500&display=swap"); *{ margin: 0; padding: 0; border: 0; box-sizing: border-box; } body{ font-family: "Poppins", sans-serif; background: #d8dbdb; font-size: 18px; max-width: 800px; margin: 0 auto; padding: 2%; color: #565859; } #wrapper{ background: #f6faff; } img{ max-width: 100%; } header{ width: 90%; display: flex; justify-content: center; align-items: center; } #logo{ max-width: 180px; margin: 2% 0 0 5%; } .banner{ margin-bottom: 3%; } .one-col{ padding: 2%; } h1{ letter-spacing: 1%; } p{ text-align: justify; } .button-holder{ margin: 2% 0 0 5%; } button { border-radius: 20px; border: 1px solid #89029b; background: #89029b; color: rgb(43, 39, 39); font-size: 12px; font-weight: bold; padding: 12px 45px; letter-spacing: 1px; text-transform: uppercase; transition: transform 80ms ease-in; cursor: pointer; margin: 15px 0; } button.ghost { margin-top: 20px; background: transparent; border-color: rgb(43, 39, 39); } button.ghost:hover { background: #89029b; color: white; border-color: #89029b; } button.ghost:focus { outline: none; } button:active { transform: scale(0.95); } </style> </head> <body style="font-family: "Poppins", sans-serif;background: #d8dbdb;font-size: 18px;max-width: 800px;margin: 0 auto;padding: 2%;color: #565859;"> <div id="wrapper" style="background: #f6faff;"> <header style="width: 90%;display: flex;justify-content: center;align-items: center;"> <div id="logo" style="max-width: 180px;margin: 2% 0 0 5%;"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width: 100%;"> </div> </header> <div class="banner" style="margin-bottom: 3%;"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width: 100%;"> </div> <div class="one-col" style="padding: 2%;"> <h1 style="letter-spacing: 1%;">Good Day!</h1> <p style="text-align: justify;">Thank you for messaging us. We will respond to you as soon as we can.</p> </div> </div> </body> </html>'; if (empty($firstname) || empty($lastname) || empty($email) || empty($message)) { $errors['empty'] = "Please fill all fields"; echo "<script>window.location='index.php#contact'</script>"; } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Please input a valid email"; echo "<script>window.location='index.php#contact'</script>"; } if (count($errors) === 0) { try { sendVerificationEmail($email, $body); sendEmailInquiry($email, $message); $query_inq = "INSERT INTO inquiry (msgID,first_name,last_name,email,message,status,view_notif,time_stamp) VALUES (:msgID,:fname,:lname,:email,:msg,:status,:view,:ts)"; $stmt_inq = $connect->prepare($query_inq); $stmt_inq->execute(['msgID' => $msgid, 'fname' => $firstname, 'lname' => $lastname, 'email' => $email, 'msg' => $message, 'status' => $status, 'view' => $view_notif, 'ts' => $timestamp]); echo "<script>alert('Message Sent');window.location.replace('index.php#contact')</script>"; // exec("wget -qO- contact.php?process_email_queue=1 &> /dev/null &"); } catch (Exception $e) { echo "Message: " . $e->getMessage(); } } }; <file_sep><?php include '../config/control.php'; $query_holiday = $connect->prepare("SELECT * FROM events"); $query_holiday->execute(); $json_array = array(); while($rows=$query_holiday->fetch(PDO::FETCH_ASSOC)){ $json_array[] = array( 'title' => $rows["holiday"], 'start' => $rows["allDay"], 'backgroundColor' => '#1e824c' ); } echo json_encode($json_array); ?><file_sep><?php include 'control/control.php'; $query = $connect->prepare("SELECT * FROM test2"); $query->execute(); $json_array = array(); while($rows=$query->fetch(PDO::FETCH_ASSOC)){ $json_array[] = $rows; } echo json_encode($json_array); ?><file_sep><?php session_start(); include '../config/control.php'; foreach ($_FILES['serviceimages']['name'] as $i => $value) { $services = "Services"; $image_name2 = $_FILES['serviceimages']['tmp_name'][$i]; $folder2 = "../image/gallery/"; $image_path2 = $folder . $_FILES['serviceimages']['name'][$i]; move_uploaded_file($image_name2, $image_path2); $sql_insertImage2 = "INSERT INTO cms_gallery (image,category) VALUES (:path,:services)"; $stmt_insertImage2 = $connect->prepare($sql_insertImage2); $stmt_insertImage2->execute(['path' => $image_path2, 'services' => $services]); } echo "image uploaded successfully"; echo "<script>window.location.replace('cms-gallery.php')</script>"; <file_sep><div class="menu-icon bg-purple"><i class="fas fa-bars icon-m"></i></div> <header class="header"> <div class="search-container"> </div> <div class="header__icons"> <div class="icon__notif"> <span class="icon__container bell" id="bell"><i class="fas fa-bell"></i> <?php $view = 0; $sql_fetchbell = "SELECT count(*) FROM appointment WHERE view = :view"; $stmt_fetchbell = $connect->prepare($sql_fetchbell); $stmt_fetchbell->execute(['view' => $view]); $count_fetchbell = $stmt_fetchbell->fetchColumn(); ?> <div id="bell_count"> <?php if ($count_fetchbell > 0) { echo "<span class='bounce bell__count'>$count_fetchbell</span>"; } ?> </div> <span class="tooltiptext">Appointment</span> <div class="bell__content" id="bell__content"> <ul class="bell__links" id="bell__links"></ul> </div> </span> <span class="icon__container envelope" id="envelope"><i class="fas fa-envelope"></i> <?php $view = 0; $sql_fetchEnvelope = "SELECT count(*) FROM inquiry WHERE view_notif = :view"; $stmt_fetchEnvelope = $connect->prepare($sql_fetchEnvelope); $stmt_fetchEnvelope->execute(['view' => $view]); $count_fetchEnvelope = $stmt_fetchEnvelope->fetchColumn(); ?> <div id="envelope_count"> <?php if ($count_fetchEnvelope > 0) { echo "<span class='bounce envelope__count'>$count_fetchEnvelope</span>"; } ?> </div> <span class="tooltiptext">Inquiry</span> <div class="envelope__content" id="envelope__content"> <ul class="envelope__links" id="envelope__links"></ul> </div> </span> </div> <?php $idd = $_SESSION['ogliadmin']; $sqlavatar = "SELECT * FROM administrator WHERE id = ?"; $stmt2 = $connect->prepare($sqlavatar); $stmt2->execute([$idd]); $rows2 = $stmt2->fetch(PDO::FETCH_ASSOC); ?> <div class="header__avatar"> <?php if ($rows2['image'] === NULL) { ?> <img src="../image/icons/user.png" alt="Avatar" class="avatar"> <?php } else { ?> <img src="<?php echo $rows2['image'] ?>" alt="Avatar" class="avatar"> <?php } ?> <div class="avatar__main-content"> <?php $adminID = $_SESSION['ogliadmin']; $sql_admin = "SELECT * FROM administrator WHERE id = :adminID"; $stmt_admin = $connect->prepare($sql_admin); $stmt_admin->execute(['adminID' => $adminID]); $row_admin = $stmt_admin->fetch(PDO::FETCH_ASSOC); $fn = $row_admin['firstName']; $mn = $row_admin['middleName']; $ln = $row_admin['lastName']; ?> <div class="avatar__content"> <ul class="avatar__links"> <li class="avatar__links__list salem"><strong><?php echo $fn . " " . $mn . " " . $ln ?></strong></li> <li class="avatar__links__list"><a href="" class="salem"> Setting</a></li> <li class="avatar__links__list"><a href="sign-out.php" class="salem" onclick="return confirm('Sign out?')" id="sign-out">Sign Out</a></li> </ul> </div> </div> </div> </div> </header> <!-- <div class="envelope__content"> <ul class="envelope__links"></ul> </div> --> <aside class="sidenav"> <div class="logo__container"> <img class="logo" src="../image/dpom_logo.png" alt=""> </div> <div id="accordion" class="sidenav__list"> <a href="index.php"> <div class="sidenav__list-item"><span><i class="fas fa-chart-line"></i></span>&nbsp;Dashboard</div> </a> <a href="appoint-list.php"> <div class="sidenav__list-item"><i class="fas fa-calendar-check"></i>&nbsp;Appointment</div> </a> <a href="message.php"> <div class="sidenav__list-item"><span><i class="fas fa-envelope-open-text"></i></span>&nbsp;Messages</div> </a> <div class="sidenav__list-item accordion-toggle"><i class="fas fa-user-circle"></i>&nbsp;Accounts</div> <div class="accordion-content"> <ul class="accordion__list"> <a href="admin.php"> <li class="accordion__list-item "><span><i class="fas fa-users"></i></span>&nbsp;Admin</li> </a> <a href="patients.php"> <li class="accordion__list-item "><span><i class="fas fa-user-alt"></i></span>&nbsp;Patients&nbsp;Record</li> </a> </ul> </div> <div class="sidenav__list-item accordion-toggle"><span><i class="fas fa-tv"></i>&nbsp;Content&nbsp;Management</span></div> <div class="accordion-content"> <ul class="accordion__list"> <a href="cms-home.php"> <li class="accordion__list-item "><span><i class="fas fa-home"></i></span>&nbsp;Home</li> </a> <a href="cms-service.php"> <li class="accordion__list-item "><span><i class="fas fa-teeth-open"></i></span>&nbsp;Service</li> </a> <a href="cms-gallery.php"> <li class="accordion__list-item "><span><i class="fas fa-images"></i></span>&nbsp;Gallery</li> </a> <a href="cms-about.php"> <li class="accordion__list-item "><span><i class="fas fa-align-center"></i></span>&nbsp;About&nbsp;Us</li> </a> <a href="cms-contact.php"> <li class="accordion__list-item "><span><i class="fas fa-address-book"></i></span>&nbsp;Contact</li> </a> <a href="cms-testi.php"> <li class="accordion__list-item "><span><i class="fas fa-bullhorn"></i></span>&nbsp;Testimonials</li> </a> </ul> <div class="sidenav__list-item accordion-sub_toggle"><span><i class="fas fa-folder-open"></i></span>&nbsp;File&nbsp;Maintenance</div> <div class="accordion-content_sub"> <ul class="accordion__list"> <a href="dentist.php"> <li class="accordion__list-item "><span><i class="fas fa-user-md"></i></span>&nbsp;Dentist</li> </a> <a href="service.php"> <li class="accordion__list-item "><span><i class="fas fa-teeth"></i></span>&nbsp;Services</li> </a> </ul> </div> </div> <div class="sidenav__list-item accordion-toggle"><span><i class="fas fa-file"></i></span>&nbsp;Reports</div> <div class="accordion-content"> <ul class="accordion__list"> <a href="appoint-history.php"> <li class="accordion__list-item "><span><i class="fas fa-file-medical"></i></span>&nbsp;Appointment&nbsp;Record</li> </a> </ul> </div> </div> <div class="sidenav__close-icon wisteria"> &times; </div> </aside> <footer class="footer"> <div class="footer__copyright">&copy; 2019 OGLIMEN Dental Clinic</div> </footer><file_sep><?php include '../config/control.php'; $verified = 1; $status = 'Approved'; $query = $connect->prepare("SELECT * FROM appointment WHERE verified=:verified AND status = :status"); $query->execute(['verified'=>$verified,'status'=>$status]); $json_array = array(); while($rows=$query->fetch(PDO::FETCH_ASSOC)){ $docID = $rows['doctorID']; $query4 = $connect->prepare("SELECT * FROM dentist WHERE doctorID = :did"); $query4->execute(['did'=>$docID]); while($rows4=$query4->fetch(PDO::FETCH_ASSOC)){ $docName = $rows4['Salutation']." ".$rows4['firstName']." ".$rows4['lastName']; $json_array[] = array( 'doctorID' => $rows["doctorID"], 'title' => $rows["service"]." - ".$docName, 'start' => $rows["appointmentDate"]." ".$rows["start"], 'end' => $rows["appointmentDate"]." ".$rows["end"], 'color' => 'rgba(145, 61, 136, 1)' ); } } echo json_encode($json_array); <file_sep><?php require_once 'controllers/authController.php'; if (empty($_SESSION['ogliadmin'])) { echo "<script>window.location.replace('sign-in.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Messages</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/w/dt/dt-1.10.18/r-2.2.2/datatables.min.css" /> <script type="text/javascript" src="https://cdn.datatables.net/w/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script> $(document).ready(function() { $("#message").DataTable({ responsive: true, pageLength: 5, "aaSorting": [], "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [3], orderable: false }] }); tinymce.init({ selector: '#reply', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Messages</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <table class="list__tbl display dt-responsive nowrap" id="message"> <thead> <tr> <th>Msg Id</th> <th>Email</th> <th>Message</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_inquiry = "SELECT * FROM inquiry ORDER BY time_stamp DESC"; $stmt_inquiry = $connect->prepare($sql_inquiry); $stmt_inquiry->execute(); $rows_inquiry = $stmt_inquiry->fetchAll(); foreach ($rows_inquiry as $message) { $message_id = $message['msgID']; ?> <tr> <td><?php echo $message_id ?></td> <td><?php echo $message['email'] ?></td> <td><?php echo substr($message['message'], 0, 50) ?></td> <td><?php echo $message['status'] ?></td> <td> <div class="icon_container"> <a href="?replyID=<?php echo $message_id ?>"><i class="fas fa-reply reply"></i></a>&nbsp; <a href="?deleteID=<?php echo $message_id ?>" onclick="return confirm('Are you sure you want to delete this message?')"><i class="fas fa-trash bin"></i></a> </div> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- EDIT MODAL --> <div id="modal__edit" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $msg_id = $_GET['replyID']; $sql_msg = "SELECT * FROM inquiry WHERE msgID = :msgId"; $stmt_msg = $connect->prepare($sql_msg); $stmt_msg->execute(['msgId' => $msg_id]); $row_msg = $stmt_msg->fetch(PDO::FETCH_ASSOC); $time_stamp = new DateTime($row_msg['time_stamp']); $timestamp = $time_stamp->format('d M Y, H:i a'); $email = $row_msg['email']; $name = $row_msg['first_name'] . " " . $row_msg['last_name']; ?> <span class="close" id="edit_close">&times;</span> <span class="modal_header-title"><i class="fas fa-reply"></i>&nbsp;Reply <span><?php echo $row_msg['email'] ?></span></span> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="message-container"> <div class="message-header"> <div class="message-info"> <span><?php echo $email ?></span> <span class="caret-down inquirer"><i class="fas fa-caret-down"></i></span> <div class="inquirer_container"> <ul class="inquirer-info"> <li>from: <span class="email"><?php echo $email ?></span></li> <li>name: <span><?php echo $name ?></span></li> <li>email: <span><?php echo $email ?></span></li> <li>reply to: <span><?php echo $email ?></span></li> <li>date: <span><?php echo $timestamp ?></span></li> </ul> </div> </div> <div class="message-timestamp"><?php echo $timestamp ?></div> </div> <div class="message-content"><?php echo $row_msg['message'] ?></div> <?php $sql_eachReplied = "SELECT * FROM reply WHERE msgID = :msgID"; $stmt_eachReplied = $connect->prepare($sql_eachReplied); $stmt_eachReplied->execute(['msgID' => $msg_id]); $row_eachReplied = $stmt_eachReplied->fetchAll(PDO::FETCH_ASSOC); foreach ($row_eachReplied as $eachReplied) { $replied = $eachReplied['reply']; $timestampReplied = new DateTime($eachReplied['timestamp']); $time_eachReplied = $timestampReplied->format('d M Y, H:i a'); if ($eachReplied['replyID'] > 0) { ?> <div class="message-replied"> <div class="replyTime"> <span><i class="fas fa-reply"></i>&nbsp;Reply</span> <span><?php echo $time_eachReplied ?></span> </div> <div class="replyMsg"> <?php echo $replied ?> </div> </div> <?php } else { ?> <?php } } ?> <div class="message-reply_container"> <textarea name="reply" class="message-reply" id="reply"></textarea> </div> <div class="message-send"> <input type="submit" class="button replybtn" name="replybtn" value="Send"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y') ?></h6> </div> </div> </div> <!-- END EDIT MODAL --> </main> </div> </body> </html> <?php if (isset($_GET['replyID'])) { $replyid = $_GET['replyID']; $read = 'Read'; $unread = 'Unread'; $sql_reply_update = "UPDATE inquiry SET status = :read WHERE msgID=:id"; $stmt_reply_update = $connect->prepare($sql_reply_update); $stmt_reply_update->execute(['read' => $read, 'id' => $replyid]); // $sql_eachEmail = "SELECT * FROM inquiry WHERE msgID =:msgId"; // $stmt_eachEmail = $connect->prepare($sql_eachEmail); // $stmt_eachEmail->execute(['msgId' => $replyid]); // $row_eachEmail = $stmt_eachEmail->fetch(PDO::FETCH_ASSOC); // $_SESSION['eachEmail'] = $row_eachEmail['email']; // $_SESSION['msg'] = $row_eachEmail['message']; // $_SESSION['msgid'] = $replyid; echo "<script>var edit_modal= document.getElementById('modal__edit')</script>"; echo "<script> edit_modal.style.display='block'</script>"; }; if (isset($_GET['deleteID'])) { $replyid = $_GET['deleteID']; $sql_del = "DELETE FROM inquiry WHERE msgID =:msgid"; $stmt_del = $connect->prepare($sql_del); $stmt_del->execute(['msgid' => $replyid]); echo "<script>alert('Message was deleted successfully');window.location.replace('message.php')</script>"; } ?> <script> const edit_close = $('#edit_close'); // When the user clicks on <span> (x), close the modal edit_close.on('click', function() { edit_modal.style.display = "none"; window.location.replace('message.php'); }); //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Confirmation for DELETE function confirmDelete(anchor) { var conf = confirm('Are you sure want to delete this service?'); if (conf) window.location = anchor.attr("href"); }; </script><file_sep><?php include '../config/control.php'; $verified_false = 1; $status = 'Pending'; $query_pending = $connect->prepare("SELECT * FROM appointment WHERE verified=:verified AND status = :status"); $query_pending->execute(['verified' => $verified_false, 'status' => $status]); $pending_array = array(); while ($rows = $query_pending->fetch(PDO::FETCH_ASSOC)) { $docID = $rows['doctorID']; $query4 = $connect->prepare("SELECT * FROM dentist WHERE doctorID = ?"); $query4->execute([$docID]); while ($rows4 = $query4->fetch(PDO::FETCH_ASSOC)) { $docName = $rows4['Salutation'] . " " . $rows4['firstName'] . " " . $rows4['lastName']; $pending_array[] = array( 'doctorID' => $rows["doctorID"], 'title' => "PENDING" . " : " . $rows["service"] . " - " . $docName, 'start' => $rows["appointmentDate"] . " " . $rows["start"], 'end' => $rows["appointmentDate"] . " " . $rows["end"], 'color' => '#f22613' ); // $json_array[] = $rows; } } echo json_encode($pending_array); <file_sep><?php require_once 'controllers/fileController.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script src="https://cdn.tiny.cloud/1/0jw0mynqqwsv2n9jb8hlp77zg9bv7vmefh1fczbszk651w7s/tinymce/5/tinymce.min.js"></script> <script> $(document).ready(function(){ $("#service_table").DataTable({ responsive: true, pageLength : 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs:[ { targets: [2], orderable: false } ] }); tinymce.init({ selector: '.mytextarea', resize: false, toolbar_drawer: 'floating', menubar: 'format', mobile: { theme: 'silver' } }); }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading">Services</div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <div class="appoint_table"> <div class="header__sort"> <div class="add"> <a href="?categoryAddId=1"><button class="addbtn__dentist left"><i class="fas fa-plus"></i><span class="add-span">&nbsp;Add&nbsp;New&nbsp;Category</span></button></a> </div> <div class="add"> <a href="service.php"><button class="addbtn__dentist right" onclick="document.getElementById('modal__add').style.display='block'"><span class="add-span">Services</span></button></a> </div> </div> <table class="list__tbl display dt-responsive nowrap" id="service_table"> <thead> <tr> <th>Catgeory ID</th> <th>Category Title</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_category = "SELECT * FROM categories"; $stmt_category = $connect->prepare($sql_category); $stmt_category->execute(); $rows_category = $stmt_category->fetchAll(); foreach($rows_category as $category){ $category_id = $category['category_id']; ?> <tr> <td><?php echo $category_id?></td> <td><?php echo $category['category']?></td> <td> <div class="icon_container"> <a href="?viewID=<?php echo $category_id?>"><i class="fas fa-eye eye"></i></a>&nbsp; <a href="?editID=<?php echo $category_id?>"><i class="fas fa-edit edit"></i></a>&nbsp; <a href="?deleteID=<?php echo $category_id?>" onclick="return confirm('Are you sure you want to delete this service category?')"><i class="fas fa-trash bin"></i></a> </div> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <!-- MODAL --> <!-- View MODAL --> <div id="modal__view" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $category_id = $_GET['viewID']; $sql_viewCategory = "SELECT * FROM categories WHERE category_id = :id"; $stmt_viewCategory = $connect->prepare($sql_viewCategory); $stmt_viewCategory->execute(['id'=>$category_id]); $row_viewCategory = $stmt_viewCategory->fetch(PDO::FETCH_ASSOC); ?> <span class="close" id="close_view">&times;</span> <h2><?php echo $row_viewCategory['category']?></h2> </div> <div class="modal-body view_body"> <div class="category-content"> <div class="textbox category-text"> <span><?php echo $row_viewCategory['category']?></span> </div> <div class="descriptionBox"> <?php echo $row_viewCategory['description']?> </div> <!-- <div class="button-container"> <input type="submit" name="add_category" class="button add-btn" value="Add"> </div> --> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- ADD MODAL --> <div id="modal__add" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close_add">&times;</span> <h2>Add New Category</h2> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="category-content"> <?php if(count($errors) > 0){ ?> <div class="form__error"> <?php foreach($errors as $error){?> <li style="list-style:none"><?php echo $error?></li> <?php }?> </div> <?php }?> <div class="textbox category-text"> <input type="text" id="title" name="title" placeholder="Category Title"> </div> <div class="descriptionBox"><textarea name="description" class="mytextarea"></textarea></div> <div class="button-container"> <input type="submit" name="add_category" class="button add-btn" value="Add"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- EDIT MODAL --> <div id="modal__edit" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <?php $category_id = $_GET['editID']; $sql_eachCategory = "SELECT * FROM categories WHERE category_id = :id"; $stmt_eachCategory = $connect->prepare($sql_eachCategory); $stmt_eachCategory->execute(['id'=>$category_id]); $row_eachCategory = $stmt_eachCategory->fetch(PDO::FETCH_ASSOC); $categoryTitle = $row_eachCategory['category']; ?> <span class="close" id="edit_close">&times;</span> <h2>Update <?php echo $title?></h2> </div> <div class="modal-body view_body"> <form action="" method="POST"> <div class="category-content"> <?php if(count($errors) > 0){ ?> <div class="form__error"> <?php foreach($errors as $error){?> <li style="list-style:none"><?php echo $error?></li> <?php }?> </div> <?php } ?> <div class="textbox category-text"> <input type="text" id="title" name="title" value="<?php echo $categoryTitle?>"> </div> <div class="descriptionBox"><textarea name="description" class="mytextarea"><?php echo $row_eachCategory['description']?></textarea></div> <div class="button-container"> <input type="submit" name="update_category" class="button add-btn" value="Update"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- END EDIT MODAL --> </main> </div> </body> </html> <?php if(isset($_GET['categoryAddId'])){ $addID = $_GET['categoryAddId']; echo "<script>var add_modal= document.getElementById('modal__add')</script>"; echo "<script> add_modal.style.display='block'</script>"; } if(isset($_GET['viewID'])){ echo "<script>var view_modal= document.getElementById('modal__view')</script>"; echo "<script> view_modal.style.display='block'</script>"; } if(isset($_GET['editID'])){ $editid = $_GET['editID']; $_SESSION['dentistEditID'] = $editid; echo "<script>var edit_modal= document.getElementById('modal__edit')</script>"; echo "<script> edit_modal.style.display='block'</script>"; }; ?> <script> const add_close = $('#close_add'); // When the user clicks on <span> (x), close the modal add_close.on('click', function() { add_modal.style.display = "none"; window.location.replace('service-category.php'); }); const view_close = $('#close_view'); // When the user clicks on <span> (x), close the modal view_close.on('click', function() { view_modal.style.display = "none"; window.location.replace('service-category.php'); }); const edit_close = $('#edit_close'); // When the user clicks on <span> (x), close the modal edit_close.on('click', function() { edit_modal.style.display = "none"; window.location.replace('service-category.php'); }); //hide/show nav const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); </script> <file_sep><?php session_start(); require_once '../config/control.php'; $errors = array(); $success = array(); $title = ""; $empty = ""; $successUpdate = ""; if(isset($_POST['add_category'])){ $title = $_POST['title']; $description = $_POST['description']; $sql_categ= "SELECT * FROM categories WHERE category = :title"; $stmt_categ = $connect->prepare($sql_categ); $stmt_categ->execute(['title'=>$title]); $rows_categ = $stmt_categ->fetch(PDO::FETCH_ASSOC); if(empty($title)){ $errors['empty'] = "Please fill all fields"; }else if($rows_categ > 1){ $errors['title'] = "Service category already exist";; }else{ $query_addCategory = "INSERT INTO categories (category,description) VALUE(:title,:des)"; $stmt_addCategory = $connect->prepare($query_addCategory); $stmt_addCategory->execute(['title'=>$title,'des'=>$description]); echo "<script>alert('Successfully added a new category!');window.location.replace('service-category.php')</script>"; } } if(isset($_POST['update_category'])){ $id = $_GET['editID']; $title = $_POST['title']; if(empty($title)){ $errors['empty'] = "Please do not leave blank the title"; }else{ $query_updateCategory= "UPDATE categories SET category = :title WHERE category_id =:id"; $stmt_updateCategory = $connect->prepare($query_updateCategory); $stmt_updateCategory->execute(['title'=>$title,'id'=>$id]); echo "<script>alert('Successfully updated the category!');window.location.replace('service-category.php')</script>"; } } if(isset($_GET['deleteID'])){ $category_id = $_GET['deleteID']; $sql_deleteCategory = "DELETE FROM categories WHERE category_id = :id"; $stmt_deleteCategory = $connect->prepare($sql_deleteCategory); $stmt_deleteCategory -> execute(['id'=>$category_id]); echo "<script>alert('Category deleted');window.location.replace('service-category.php')</script>"; } ?><file_sep> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var now = new Date();//today's date var today = now.setDate(now.getDate()); var calendar = new FullCalendar.Calendar(calendarEl, { height: 400, plugins: [ 'interaction', 'dayGrid', 'timeGrid','moment','momentTimezone'], header: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridDay' }, defaultView: 'dayGridMonth', validRange: { start: today }, selectable: false, editable: false, navLinks: true, eventLimit: true, // allow "more" link when too many events eventSources:[ '../events/event.php', '../events/event_pending.php', { url: '../events/event_holiday.php', rendering: 'background' }, ], eventOverlap:false, slotEventOverlap: false }); calendar.render(); }); <file_sep><?php function getTimeRange($startTime, $endTime, $format = 'g:ia') { $arrayTime = array(); $intervalTime = new DateInterval('PT1H'); $realEnd = new DateTime($endTime); $realEnd->add($intervalTime); $period = new DatePeriod(new DateTime($startTime), $intervalTime, $realEnd); foreach ($period as $realTime) { $arrayTime[] = $realTime->format($format); } return $arrayTime; } $time = getTimeRange('7:00', '9:00'); echo json_encode($time); <file_sep><?php session_start(); include 'config/control.php'; if(isset($_POST['strDate'])){ $date = $_POST['strDate']; $date2 = new DateTime($date); $date3 = $date2->format('D'); $sql_checkSched = "SELECT * FROM schedule"; $stmt_checkSched = $connect->prepare($sql_checkSched); $stmt_checkSched->execute(); $json_array = array(); while($row_checkSched=$stmt_checkSched->fetch(PDO::FETCH_ASSOC)){ $day = explode(',',$row_checkSched["day"]); $did = $row_checkSched['doctorID']; $sql_checkDentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmt_checkDentist = $connect->prepare($sql_checkDentist); $stmt_checkDentist->execute(['did'=>$did]); while($row_checkDentist=$stmt_checkDentist->fetch(PDO::FETCH_ASSOC)){ $salut = $row_checkDentist['Salutation']; $ln = $row_checkDentist['lastName']; $mn = $row_checkDentist['middleName']; $fn = $row_checkDentist['firstName']; if(in_array($date3,$day)){ $json_array[] = array( 'doctorID' => $row_checkSched["doctorID"], 'doctorName' => $salut."".$fn." ".$mn." ".$ln, 'day' => $day, 'start' => $row_checkSched["starttime"], 'end' => $row_checkSched["endtime"], 'breakstart' => $row_checkSched["breakstart"], 'breakend' => $row_checkSched["breakend"] ); } } } $json = json_encode(array('doctor'=>$json_array)); echo $json; } <file_sep><?php session_start(); require '../config/control.php'; require_once 'emailController.php'; require_once 'smsController.php'; date_default_timezone_set('Asia/Manila'); //appointment approved if (isset($_POST['approve'])) { $appointID = $_GET['viewID']; $pid = $_SESSION['patientID']; $email = $_SESSION['email']; $name = $_SESSION['name']; $dentist = $_SESSION['dentist_name']; $date_info = $_SESSION['date']; $start_info = $_SESSION['start']; $end_info = $_SESSION['end']; $timestamp = date('Y-m-d H:i:s'); $stmt_viewAppoint = $connect->prepare("SELECT * FROM appointment WHERE appointID = :appoint"); $stmt_viewAppoint->execute(['appoint' => $appointID]); $row_viewAppoint = $stmt_viewAppoint->fetch(PDO::FETCH_ASSOC); $viewAppoint = $row_viewAppoint['appointID']; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src=http://oglimendentalcare.com/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://oglimendentalcare.com/image/branding/brand.png" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Good day, ' . $name . ' </h1> <p style="text-align:justify" align="justify">Your appointment has been approved. Please vist us on the day of your appointment. Thank you!</p> </div> <div class="one-col" style="padding:2%"> <table style="border-collapse:collapse; width:100%" width="100%"> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Appoint ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $appointID . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">My ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $pid . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Dentist</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $dentist . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Date</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . date_format($date_info, 'd M Y') . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Time</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . date_format($start_info, 'g:i a') . "-" . date_format($end_info, 'g:i a') . '</td> </tr> </table> </div> </div> </body> </html>'; $approve = 'Approved'; $verify = 1; $sql_approve_appoint = "UPDATE appointment SET verified = :verify, status =:approve, timestamp = :ts WHERE appointID =:appointID"; $stmt_approve_appoint = $connect->prepare($sql_approve_appoint); $stmt_approve_appoint->execute(['verify' => $verify, 'approve' => $approve, 'ts' => $timestamp, 'appointID' => $appointID]); echo "<script>window.location.replace('appoint-list.php?viewID=" . $appointID . "')</script>"; sendEmailInquiry($email, $body); $result = itexmo($contact, $textMsg, "TR-ROBBI193582_6X9BF"); if ($result == "") { echo "iTexMo: No response from server!!!"; } else if ($result == 0) { echo "Message Sent!"; } else { echo "Error Num " . $result . " was encountered!"; } } //cancellation of appointment if (isset($_POST['cancel'])) { $appointID = $_GET['cancelID']; $pid = $_SESSION['patientID']; $email = $_SESSION['email']; $name = $_SESSION['name']; $dentist = $_SESSION['dentist_name']; $date_info = $_SESSION['date']; $start_info = $_SESSION['start']; $end_info = $_SESSION['end']; $reason = $_POST['reason']; $timestamp = date('Y-m-d H:i:s'); $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Good day, ' . $name . ' </h1> <p style="text-align:justify" align="justify">Your appointment has been cancelled</p> </div> <div class="one-col" style="padding:2%"> <h4 style="letter-spacing:1%">Reason of cancellation</h4> <p style="text-align:justify" align="justify">' . $reason . '</p> </div> <div class="one-col" style="padding:2%"> <table style="border-collapse:collapse; width:100%" width="100%"> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Appoint ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $appointID . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">My ID</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $pid . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Dentist</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . $dentist . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Date</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . date_format($date_info, 'd M Y') . '</td> </tr> <tr style="width:60%" width="60%"> <th style="font-size:14px; padding:8px; text-align:left; background-color:#4CAF50; color:white; width:40%" align="left" bgcolor="#4CAF50" width="40%">Time</th> <td style="font-size:14px; padding:8px; text-align:left" align="left">' . date_format($start_info, 'g:i a') . "-" . date_format($end_info, 'g:i a') . '</td> </tr> </table> </div> </div> </body> </html>'; $cancel = 'Cancelled'; $sql_cancel_appoint = "UPDATE appointment SET status = :cancel, remark = :reason, timestamp = :ts WHERE appointID = :appointID"; $stmt_cancel_appoint = $connect->prepare($sql_cancel_appoint); $stmt_cancel_appoint->execute(['cancel' => $cancel, 'reason' => $reason, 'ts' => $timestamp, 'appointID' => $appointID]); sendEmailInquiry($email, $body); echo "<script>window.location.replace('appoint-list.php');</script>"; } if (isset($_POST['done'])) { $timestamp = date('Y-m-d H:i:s'); $appointID = $_GET['viewID']; $remark = $_POST['remark']; $name = $_SESSION['name']; $email = $_SESSION['email']; $done = 'Done'; $checkup = 1; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css">tr:nth-child(even) {background-color:#f2f2f2}</style> </head> <body style="background:#d8dbdb; color:#565859; font-family:"Poppins", sans-serif; font-size:18px; margin:0 auto; max-width:800px; padding:2%"> <div id="wrapper" style="background:#f6faff"> <header style="align-items:center; display:flex; justify-content:center; width:90%" width="90%"> <div id="logo" style="margin:2% 0 0 5%; max-width:180px"> <img src=http://oglimendentalcare.com/image/dpom_logo.png" alt="" style="max-width:100%"> </div> </header> <div class="banner" style="margin-bottom:3%"> <img src="http://oglimendentalcare.com/image/branding/brand.png" alt="" style="max-width:100%"> </div> <div class="one-col" style="padding:2%"> <h1 style="letter-spacing:1%">Good day, ' . $name . ' </h1> <p style="text-align:justify" align="justify">Your appointment has been done. Thank you!</p> <p>For more information, you can call us (+63) 925 759 7983</p> </div> </div> </body> </html>'; //fetch the client id to be use in updating the client table status $sql_checkInfo = "SELECT * FROM appointment WHERE appointID =:appointID"; $stmt_checkInfo = $connect->prepare($sql_checkInfo); $stmt_checkInfo->execute(['appointID' => $appointID]); $row_checkInfo = $stmt_checkInfo->fetch(PDO::FETCH_ASSOC); $pid = $row_checkInfo['clientID']; //update the status to done $sql_done_appoint = "UPDATE appointment SET status = :done, remark = :remark, timestamp = :ts WHERE appointID = :appointID"; $stmt_done_appoint = $connect->prepare($sql_done_appoint); $stmt_done_appoint->execute(['done' => $done, 'remark' => $remark, 'ts' => $timestamp, 'appointID' => $appointID]); //update check up to 1 so patients can now see all the services in the select box $sql_checkupDone = "UPDATE client SET checkup = :checkup WHERE clientID = :pid"; $stmt_checkupDone = $connect->prepare($sql_checkupDone); $stmt_checkupDone->execute(['checkup' => $checkup, 'pid' => $pid]); sendEmailInquiry($email, $body); echo "<script>window.location.replace('appoint-list.php');</script>"; } if (isset($_POST['resched'])) { $timestamp = date('Y-m-d H:i:s'); $appointID = $_GET['viewID']; $remark = $_POST['remark']; $name = $_SESSION['name']; $email = $_SESSION['email']; $done = 'Done'; $checkup = 1; //fetch the client id to be use in updating the client table status $sql_checkInfo = "SELECT * FROM appointment WHERE appointID =:appointID"; $stmt_checkInfo = $connect->prepare($sql_checkInfo); $stmt_checkInfo->execute(['appointID' => $appointID]); $row_checkInfo = $stmt_checkInfo->fetch(PDO::FETCH_ASSOC); $pid = $row_checkInfo['clientID']; //update the status to done $sql_done_appoint = "UPDATE appointment SET status = :done, remark = :remark, timestamp = :ts WHERE appointID = :appointID"; $stmt_done_appoint = $connect->prepare($sql_done_appoint); $stmt_done_appoint->execute(['done' => $done, 'remark' => $remark, 'ts' => $timestamp, 'appointID' => $appointID]); //update check up to 1 so patients can now see all the services in the select box $sql_checkupDone = "UPDATE client SET checkup = :checkup WHERE clientID = :pid"; $stmt_checkupDone = $connect->prepare($sql_checkupDone); $stmt_checkupDone->execute(['checkup' => $checkup, 'pid' => $pid]); echo "<script>window.location.replace('patient.php?patient=" . $pid . "&&set=" . $pid . "');</script>"; } //reply message if (isset($_POST['replybtn'])) { $msg_id = $_GET['replyID']; // $msg_id = $_SESSION['msgid']; // $email = $_SESSION['eachEmail']; // $msg = $_SESSION['msg']; $sql_eachEmail = "SELECT * FROM inquiry WHERE msgID =:msgId"; $stmt_eachEmail = $connect->prepare($sql_eachEmail); $stmt_eachEmail->execute(['msgId' => $msg_id]); $row_eachEmail = $stmt_eachEmail->fetch(PDO::FETCH_ASSOC); $email = $row_eachEmail['email']; $msg = $row_eachEmail['message']; $reply = $_POST['reply']; $timestamp = date('Y-m-d H:i:s'); // $body = $reply; if (empty($reply)) { echo "<script>alert('Empty Message box');window.location.reload()</script>"; } else { try { sendEmailInquiry($email, $reply); $sql_replyMsg = "INSERT INTO reply (inquiryID,email,msg,reply,timestamp) VALUES (:inqID,:email,:msg,:reply,:ts)"; $stmt_replyMsg = $connect->prepare($sql_replyMsg); $stmt_replyMsg->execute(['inqID' => $msg_id, 'email' => $email, 'msg' => $msg, 'reply' => $reply, 'ts' => $timestamp]); echo "<script>alert('Message Sent');window.location.replace('message.php?replyID=$msg_id');</script>"; } catch (Exception $e) { echo "Message: " . $e->getMessage(); } } }; //update remark if (isset($_POST['update_remark'])) { $getAppoint = $_GET['appoint']; $getPatient = $_GET['patient']; $remark = $_POST['remark']; $sql_updateRemark = "UPDATE appointment SET remark = :remark WHERE appointID = :appoint"; $stmt_updateRemark = $connect->prepare($sql_updateRemark); $stmt_updateRemark->execute(['remark' => $remark, 'appoint' => $getAppoint]); echo "<script>alert('Update remark successfully');window.location.replace('patient.php?patient=" . $getPatient . "&&appoint=" . $getAppoint . "')</script>"; } //setappoint if (isset($_POST['setAppoint'])) { $timestamp = date('Y-m-d H:i:s'); $patientID = $_GET['patient']; $date = $_POST['date']; $dentist = $_POST['dentist']; $start = $_POST['start']; $cancel_status = 'Cancelled'; //explode service with option of 2 values $service = $_POST['service']; $service_explode = explode('|', $service); //time string $startto = $start; $starttime = new DateTime($startto); $starttotime = $starttime->format('H:i'); $endtime = new DateTime($startto . $service_explode[1]); //adding duration based on the selected duration $endtotime = $endtime->format('H:i:'); //fetch Email from client $stmt_email = $connect->prepare("SELECT * FROM client WHERE clientID = :patient"); $stmt_email->execute(['patient' => $patientID]); $row_email = $stmt_email->fetch(PDO::FETCH_ASSOC); $email = $row_email['email']; $myid = $row_email['clientID']; //checking time $check = $connect->prepare("SELECT * FROM appointment WHERE appointmentDate = :date AND doctorID = :dentist AND status != :status"); $check->execute(['date' => $date, 'dentist' => $dentist, 'status' => $cancel_status]); $rowTimeCheck = $check->fetch(PDO::FETCH_ASSOC); $starttimeCheck = $rowTimeCheck['start']; $endtimeCheck = $rowTimeCheck['end']; //count $check2 = $connect->prepare("SELECT count(*) FROM appointment WHERE clientID = :clientID AND appointmentDate= :date AND status != :cancel_status"); $check2->execute(['clientID' => $patientID, 'date' => $date, 'cancel_status' => $cancel_status]); $rowCheck2 = $check2->fetchColumn(); //check holiday $check3 = "SELECT * FROM events"; $stmt_check3 = $connect->prepare($check3); $stmt_check3->execute(); $rowCheck3 = $stmt_check3->fetch(PDO::FETCH_ASSOC); $holiday = $rowCheck3['allDay']; $holiday_title = $rowCheck3['holiday']; if (empty($date) || empty($dentist) || empty($start) || empty($service)) { echo "<script>alert('Please fill all fields to continue making an appointment');window.location.replace('patient.php?patient=" . $patientID . "&&set=" . $patientID . "')</script>"; } else if ($date == $holiday) { echo "<script>alert('This day is " . $holiday_title . " is not available. Please select another date');window.location.replace('patient.php?patient=" . $patientID . "&&set=" . $patientID . "')</script>"; } else if ($rowCheck2 > 0) { echo "<script>alert('Already booked an appointment on this day " . $date . "');window.location.replace('patient.php?patient=" . $patientID . "&&set=" . $patientID . "')</script>"; } else if ($starttimeCheck > $starttotime && $endtimeCheck < $endtotime) { #-> Check time is in between start and end time echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace(''patient.php?patient=" . $patientID . "&&set=" . $patientID . "'')</script>"; } elseif (($starttimeCheck > $starttotime && $starttimeCheck < $endtotime) || ($endtimeCheck > $starttotime && $endtimeCheck < $endtotime)) { #-> Check start or end time is in between start and end time echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace(''patient.php?patient=" . $patientID . "&&set=" . $patientID . "'')</script>"; } elseif ($starttimeCheck == $starttotime || $endtimeCheck == $endtotime) { #-> Check start or end time is at the border of start and end time echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace(''patient.php?patient=" . $patientID . "&&set=" . $patientID . "'')</script>"; } elseif ($starttotime > $starttimeCheck && $endtotime < $endtimeCheck) { #-> start and end time is in between the check start and end time. echo "<script>alert('Time Slot is unavailable. Please click the day of the calendar to view the current time slot available.');window.location.replace(''patient.php?patient=" . $patientID . "&&set=" . $patientID . "'')</script>"; } else { $appointID = bin2hex(random_bytes('4')); // $token_appoint = bin2hex(random_bytes(50)); $status = 'Approved'; $view = 0; $verified = 1; $body = '<!DOCTYPE html> <html lang="en"> <head> <style type="text/css"> @import url("https://fonts.googleapis.com/css?family=Poppins:400,500&display=swap"); </style> </head> <body style="font-family: "Poppins", sans-serif;background: #d8dbdb;font-size: 18px;max-width: 800px;margin: 0 auto;padding: 2%;color: #565859;"> <div id="wrapper" style="background: #f6faff;"> <header style="width: 90%;display: flex;justify-content: center;align-items: center;"> <div id="logo" style="max-width: 180px;margin: 2% 0 0 5%;"> <img src="http://localhost/OgliMen/image/dpom_logo.png" alt="" style="max-width: 100%;"> </div> </header> <div class="banner" style="margin-bottom: 3%;"> <img src="http://localhost/OgliMen/image/smile.jpeg" alt="" style="max-width: 100%;"> </div> <div class="one-col" style="padding: 2%;"> <h1 style="letter-spacing: 1%;">Good day, </h1> <p style="text-align: justify;">Your rescheduled appointment:</p> <table> <tbody> <tr> <th>Appointment ID</th> <td>:</td> <td>' . $appointID . '</td> </tr> <tr> <th>My ID</th> <td>:</td> <td>' . $myid . '</td> </tr> <tr> <th>Dentist</th> <td>:</td> <td>' . $dentist . '</td> </tr> <tr> <th>Schedule Date</th> <td>:</td> <td>' . date_format($date, 'd M Y') . '</td> </tr> <tr> <th>Schedule Time</th> <td>:</td> <td>' . date_format($starttotime, 'g:i a') . "-" . date_format($endtotime, 'g:i a') . '</td> </tr> </tbody> </table> </div> <p>Please visit Dela Paz-Oglimen Dental Care Clinic on your appointment day</p><br> <p>2nd Flr. <NAME>, Km. 30 Brgy. Burol, <NAME>wy,Dasmariñas, Cavite Cavite City 4114</p> </div> </body> </html>'; $sql = "INSERT INTO appointment (appointID,clientID,doctorID,appointmentDate,start,end,service,status,verified,view,timestamp) value (:appointID,:patient,:doctor,:date,:starttotime,:endtotime,:service,:status,:verified,:view,:ts)"; $stmt_insert_appoint = $connect->prepare($sql); $stmt_insert_appoint->execute(['appointID' => $appointID, 'patient' => $patientID, 'doctor' => $dentist, 'date' => $date, 'starttotime' => $starttotime, 'endtotime' => $endtotime, 'service' => $service_explode[0], 'status' => $status, 'verified' => $verified, 'view' => $view, 'ts' => $timestamp]); sendEmailInquiry($email, $body); echo "<script>window.location.replace('patient.php?patient=" . $patientID . "')</script>"; } } //add new admin if (isset($_POST['add_admin'])) { $timestamp = date('Y-m-d H:i:s'); $id_admin = bin2hex(random_bytes(5)); $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $contact = $_POST['contact']; $status = 'Active'; //get the last row in the database table $sql_get_id = "SELECT * FROM administrator ORDER by id DESC LIMIT 1"; $stmt_get_id = $connect->prepare($sql_get_id); $stmt_get_id->execute(); $row_get_id = $stmt_get_id->fetch(PDO::FETCH_ASSOC); $n = $row_get_id['id']; $in_zero = str_pad($n + 1, 3, 0, STR_PAD_LEFT); $username = date('Y') . $in_zero . $lname; $hashedpwd = password_hash($username, PASSWORD_DEFAULT); $image_name = $_FILES['admin_image']['tmp_name']; $folder = "../image/profile_admin/"; $image_path = $folder . $_FILES['admin_image']['name']; move_uploaded_file($image_name, $image_path); if (empty($fname) || empty($lname)) { echo "<script>alert('Empty fields');window.location.replace('admin.php')</script>"; } else { try { $sql_insert_admin = "INSERT INTO administrator (adminID,firstName,lastName,contact,email,username,password,image,status,date) VALUES (:id,:fname,:lname,:contact,:email,:uname,:pwd,:img,:status,:date)"; $stmt_insert_admin = $connect->prepare($sql_insert_admin); $stmt_insert_admin->execute(['id' => $id_admin, 'fname' => $fname, 'lname' => $lname, 'contact' => $contact, 'email' => $email, 'uname' => $username, 'pwd' => <PASSWORD>, 'img' => $image_path, 'status' => $status, 'date' => $timestamp]); echo "<script>alert('Add successfully')</script>"; } catch (Exception $e) { echo "Message:" . $e->getMessage(); } } } //update admin info if (isset($_POST['update_admin'])) { $id = $_GET['edit']; $timestamp = date('Y-m-d H:i:s'); $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $contact = $_POST['contact']; $username = $_POST['uname']; $password = $_POST['pwd']; if (empty($fname) || empty($lname) || empty($password)) { echo "<script>alert('Empty fields');window.location.replace('admin.php')</script>"; } else { $sql_admin_pwd = "SELECT * FROM administrator WHERE adminID = :id"; $stmt_admin_pwd = $connect->prepare($sql_admin_pwd); $stmt_admin_pwd->execute(['id' => $id]); $row_admin_pwd = $stmt_admin_pwd->fetch(PDO::FETCH_ASSOC); $pwd = $row_admin_pwd['<PASSWORD>']; $path = $row_admin_pwd['image']; $check_admin_pwd = password_verify($password, $pwd); if ($check_admin_pwd == false) { echo "<script>alert('Incorrect password');window.location.replace('admin.php?edit=" . $id . "')</script>"; } else if ($check_admin_pwd == true) { $image_name = $_FILES['file_update']['tmp_name']; $folder = "../image/profile_admin/"; $image_path = $folder . substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 3) . $_FILES['file_update']['name']; $admin_update = "UPDATE administrator SET firstName = :fname, lastName = :lname, username = :uname, contact = :contact, email = :email, image = :img WHERE adminID = :id"; $stmt_admin_update = $connect->prepare($admin_update); $with_old_img = ['fname' => $fname, 'lname' => $lname, 'uname' => $username, 'contact' => $contact, 'email' => $email, 'img' => $path, 'id' => $id]; $with_new_img = ['fname' => $fname, 'lname' => $lname, 'uname' => $username, 'contact' => $contact, 'email' => $email, 'img' => $image_path, 'id' => $id]; if (empty($image_name)) { try { $stmt_admin_update->execute($with_old_img); echo "<script>alert('Update Successfully');window.location.replace('admin.php?edit=" . $id . "')</script>"; } catch (Exception $e) { echo "Message:" . $e->getMessage(); } } else { if (!unlink($path)) { echo "<script>alert('You have an error.');window.location.replace('admin.php?edit=" . $id . "')</script>"; } else { try { move_uploaded_file($image_name, $image_path); $stmt_admin_update->execute($with_new_img); echo "<script>alert('Update successfully');window.location.replace('admin.php?edit=" . $id . "')</script>"; } catch (Exception $e) { echo "Message:" . $e->getMessage(); } } } } } } <file_sep><?php session_start(); date_default_timezone_set('Asia/Manila'); require '../config/control.php'; require_once '../controllers/emailSign.php'; if (isset($_POST['signin'])) { $uname = $_POST['uname']; $pass = $_POST['pwd']; $Empty = false; $User = false; $Pass = false; if (empty($uname) || empty($pass)) { // $errorss['empty'] = "Please fill all fields"; echo "<span class='form-error'>Please fill all fields</span>"; $Empty = true; } else { $sql_signin = "SELECT * FROM client WHERE email = :email OR userName= :username LIMIT 1"; $stmt_check_id = $connect->prepare($sql_signin); $stmt_check_id->execute(['email' => $uname, 'username' => $uname]); $row_check_id = $stmt_check_id->fetch(PDO::FETCH_ASSOC); if ($row_check_id) { $password_check = password_verify($pass, $row_check_id['password']); if ($password_check == false) { echo "<span class='form-error'>incorrect Username/Password</span>"; $Pass = true; } else { $_SESSION['id'] = $row_check_id['clientID']; $_SESSION['username'] = $row_check_id['userName']; $_SESSION['name'] = $row_check_id['firstName'] . " " . $row_check_id['middleName'] . " " . $row_check_id['lastName']; $_SESSION['email'] = $row_check_id['email']; $_SESSION['verified'] = $row_check_id['verified']; echo "<script>window.location.replace('index.php')</script>"; exit(); } } else { echo "<span class='form-error'>Username/Email do not exist</span>"; $User = true; } } }; ?> <script> $("#uname,#pwd").removeClass("input-error"); const Empty = "<?php echo $Empty ?>"; const User = "<?php echo $User ?>"; const Pass = "<?php echo $Pass ?>"; if (Empty == true) { $("#uname, #pwd").addClass("input-error"); } if (User == true) { $("#uname").addClass("input-error"); } if (Pass == true) { $("#pwd").addClass("input-error"); } if (Empty == false && User == false && Pass == false) { $("#uname, #pwd").val(""); } </script><file_sep><?php session_start(); require_once 'controllers/appointController.php'; if (empty($_SESSION['id'])) { echo "<script>window.location.replace('member.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/nav.css"> <link rel="stylesheet" href="css/loader.css"> <link rel="stylesheet" href="css/simplelightbox.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/b-1.5.6/b-print-1.5.6/r-2.2.2/datatables.min.css" /> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link href='fullcalendar/core/main.min.css' rel='stylesheet' /> <link href='fullcalendar/daygrid/main.min.css' rel='stylesheet' /> <link href='fullcalendar/timegrid/main.min.css' rel='stylesheet' /> <link href='fullcalendar/list/main.min.css' rel='stylesheet' /> <link rel="stylesheet" href="css/account.css"> <link rel="stylesheet" href="css/modal.css"> </head> <body> <?php include 'header.php'; ?> <div class="page-container"> <main> <div class="grid-container"> <aside class="sidebar"> <?php $idd = $_SESSION['id']; $sql_acc_patient = "SELECT * FROM client WHERE id = :id || clientID = :cid"; $stmt_acc_patient = $connect->prepare($sql_acc_patient); $stmt_acc_patient->execute(['id' => $idd, 'cid' => $idd]); $row_acc_patient = $stmt_acc_patient->fetch(PDO::FETCH_ASSOC); $profile_pic = $row_acc_patient['image']; $fn = $row_acc_patient['firstName']; $ln = $row_acc_patient['lastName']; $name = $fn . " " . $ln; $user = $row_acc_patient['userName']; $email = $row_acc_patient['email']; $contact = $row_acc_patient['contact']; ?> <div class="profile-account-container"> <a href="<?php echo (empty($profile_pic)) ? 'image/smile3.jpeg' : $profile_pic ?>"><img src="<?php echo (empty($profile_pic)) ? 'image/smile3.jpeg' : $profile_pic ?>" alt="" class="profile-avatar"></a> </div> <div class="navi-container"> <nav class="navi"> <li><?php echo $name ?></li> <li><?php echo $user ?></li> <li><?php echo $email ?></li> <li><?php echo $contact ?></li> </nav> </div> <button id="edit_account_btn"><i class="fas fa-edit"></i></button> </aside> <section class="section-account"> <div class="account-container"> <table class="list-tbl display dt-responsive nowrap" id="account-table"> <thead> <tr> <th>Appoint ID</th> <th>Service</th> <th>Schedule Date</th> <th>Schedule Time</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $idd = $_SESSION['id']; $sql_apoint = "SELECT * FROM appointment WHERE clientID = :clientID ORDER BY timestamp DESC"; $stmnt_appoint = $connect->prepare($sql_apoint); $stmnt_appoint->execute(['clientID' => $idd]); $rows_appoint = $stmnt_appoint->fetchAll(PDO::FETCH_ASSOC); foreach ($rows_appoint as $rows) { $date = new DateTime($rows['appointmentDate']); $start = new DateTime($rows['start']); $end = new DateTime($rows['end']); $did = $rows['doctorID']; $sql_dentist = "SELECT * FROM dentist WHERE doctorID = :did"; $stmnt_dentist = $connect->prepare($sql_dentist); $stmnt_dentist->execute(['did' => $did]); $rows_dentist = $stmnt_dentist->fetch(PDO::FETCH_ASSOC); $salut = $rows_dentist['Salutation']; $dfn = $rows_dentist['firstName']; $dmn = $rows_dentist['middleName']; $dln = $rows_dentist['lastName']; $dfullname = $salut . " " . $dfn . " " . $dmn . " " . $dln; ?> <tr> <td><?php echo $rows['appointID'] ?></td> <td><?php echo $rows['service'] ?></td> <!-- <td><?php echo $dfullname ?></td> --> <td><?php echo date_format($date, 'd M Y') ?></td> <td><?php echo date_format($start, 'g:i a') . "-" . date_format($end, 'g:i a') ?></td> <td class="status"> <?php if ($rows['status'] == 'Pending') { ?> <p class="gold"><?php echo $rows['status'] ?></p> <?php } else if ($rows['status'] == 'Cancelled') { ?> <p class="firebrick"><?php echo $rows['status'] ?></p> <?php } else if ($rows['status'] == 'Approved') { ?> <p class="purple"><?php echo $rows['status'] ?></p> <?php } else { ?> <p class="green"><?php echo $rows['status'] ?></p> <?php } ?> </td> <td class="action"> <a href="?view=<?php echo $rows['appointID'] ?>"><i class="fas fa-eye view"></i></a> <?php if ($rows['status'] == 'Cancelled' || $rows['status'] == 'Done') { ?> <span></span> <?php } else { ?> <a href="?cancel=<?php echo $rows['appointID'] ?>"> <i class="fas fa-calendar-times close" id="cancel"></i> </a> <?php } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </section> </div> </main> <footer> <div class="footer-contents"> <div class="footer-info"> <p>&copy;2019 All Rights Reserved, Dela Paz-Oglimen Dental Care Clinic</p> </div> <div class="footer-social"> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> </div> </div> </footer> </div> <!-- View Modal --> <div id="view_modal" class="modal account-modal"> <!-- Modal content --> <div class="modal-content account-modal-content"> <div class="modal-header account-modal-header"> <span class="close" id="close_view_modal">&times;</span> <h3>Appointment Details</h3> </div> <div class="modal-body account-modal-body"> <div class="account-details"> <div class="title"> <span>Appointment ID:</span> <span>Service:</span> <span>Dentist:</span> <span>Date:</span> <span>Time:<span> </div> <?php $appointID = $_GET['view']; $sql_appoint_details = "SELECT * FROM appointment WHERE appointID = :id"; $stmt_appoint_details = $connect->prepare($sql_appoint_details); $stmt_appoint_details->execute(['id' => $appointID]); $row_appoint_details = $stmt_appoint_details->fetch(PDO::FETCH_ASSOC); //account details $appoint_id = $row_appoint_details['appointID']; $service = $row_appoint_details['service']; $dentistID = $row_appoint_details['doctorID']; $img = $row_appoint_details['prediag_img']; //fetch dentist info from dentist table $sql_fetchDentistInfo = "SELECT * FROM dentist WHERE doctorID = :dentistID"; $stmt_fetchDentistInfo = $connect->prepare($sql_fetchDentistInfo); $stmt_fetchDentistInfo->execute(['dentistID' => $dentistID]); $row_fetchDentistInfo = $stmt_fetchDentistInfo->fetch(PDO::FETCH_ASSOC); $salut = $row_fetchDentistInfo['Salutation']; $dentist_fn = $row_fetchDentistInfo['firstName']; $dentist_ln = $row_fetchDentistInfo['lastName']; $dentist_name = $salut . " " . $dentist_fn . " " . $dentist_ln; //time to string format $date = new DateTime($row_appoint_details['appointmentDate']); $dateFormatted = $date->format('d M Y'); $startTime = new DateTime($row_appoint_details['start']); $startFormatted = $startTime->format('g:i a'); $endTime = new DateTime($row_appoint_details['end']); $endFormatted = $endTime->format('g:i a'); $newTime = $startFormatted . " - " . $endFormatted; ?> <div class="details"> <span><?php echo $appoint_id ?></span> <span><?php echo $service ?></span> <span><?php echo $dentist_name ?></span> <span><?php echo $dateFormatted ?></span> <span><?php echo $newTime ?></span> </div> </div> <div class="pre-diagnostic"> <span>My pre-diagnostic uploaded image</span> <div class="img_container"> <img src="<?php echo $img ?>" alt=""> </div> </div> <div class="button_container"> <?php $status = $row_appoint_details['status']; if ($status == 'Cancelled' || $status == 'Done') { } else { ?> <a href="?appointID=<?php echo $appointID ?>" class="button">Reschedule appointment</a> <?php } ?> </div> </div> </div> </div> <!-- Cancel Modal --> <div id="cancel_modal" class="modal account-modal"> <!-- Modal content --> <div class="modal-content account-modal-content"> <div class="modal-header account-modal-header cancel-header"> <span class="close_modal" id="close_cancel_modal">&times;</span> <h3>Are you sure you want to cancel your appointment?</h3> </div> <div class="modal-body account-modal-body"> <p class="warning"> <strong>Warning:</strong> Frequent cancel of appointment may result blocking your account</span> </p> <div class="account-details"> <div class="title"> <span>Appointment ID:</span> <span>Service:</span> <span>Dentist:</span> <span>Date:</span> <span>Time:<span> </div> <?php $cancelID = $_GET['cancel']; $sql_appoint_details = "SELECT * FROM appointment WHERE appointID = :id"; $stmt_appoint_details = $connect->prepare($sql_appoint_details); $stmt_appoint_details->execute(['id' => $cancelID]); $row_appoint_details = $stmt_appoint_details->fetch(PDO::FETCH_ASSOC); //account details $appoint_id = $row_appoint_details['appointID']; $service = $row_appoint_details['service']; $dentistID = $row_appoint_details['doctorID']; //fetch dentist info from dentist table $sql_fetchDentistInfo = "SELECT * FROM dentist WHERE doctorID = :dentistID"; $stmt_fetchDentistInfo = $connect->prepare($sql_fetchDentistInfo); $stmt_fetchDentistInfo->execute(['dentistID' => $dentistID]); $row_fetchDentistInfo = $stmt_fetchDentistInfo->fetch(PDO::FETCH_ASSOC); $salut = $row_fetchDentistInfo['Salutation']; $dentist_fn = $row_fetchDentistInfo['firstName']; $dentist_ln = $row_fetchDentistInfo['lastName']; $dentist_name = $salut . " " . $dentist_fn . " " . $dentist_ln; //time to string format $date = new DateTime($row_appoint_details['appointmentDate']); $dateFormatted = $date->format('d M Y'); $startTime = new DateTime($row_appoint_details['start']); $startFormatted = $startTime->format('g:i a'); $endTime = new DateTime($row_appoint_details['end']); $endFormatted = $endTime->format('g:i a'); $newTime = $startFormatted . " - " . $endFormatted; ?> <div class="details"> <span><?php echo $appoint_id ?></span> <span><?php echo $service ?></span> <span><?php echo $dentist_name ?></span> <span><?php echo $dateFormatted ?></span> <span><?php echo $newTime ?></span> </div> </div> <h4>Please tell us your reason of cancellation.</h4> <form action="" method="POST"> <div class="remarks"> <textarea name="reason" class="remark-box"></textarea> </div> <div class="button_container"> <input type="submit" name="cancelYes" value="Yes" class="button btn-cancel"> <!-- <a href="?cancelYes=<?php echo $appoint_id ?>"><button class="button cancel-btn">YES</button></a> --> <button class="button" id="no_button">NO</button> </div> </form> </div> </div> </div> <!-- Edit Account Modal --> <div id="account_modal" class="modal account-modal"> <!-- Modal content --> <div class="modal-content account-modal-content-reschedule"> <div class="modal-header"> <span class="close" id="close_account_modal">&times;</span> <h3>Edit Account Info</h3> </div> <?php $accountID = $_SESSION['id']; $sql_account = "SELECT * FROM client WHERE clientID = :accountID"; $stmt_account = $connect->prepare($sql_account); $stmt_account->execute(['accountID' => $accountID]); $row_account = $stmt_account->fetch(PDO::FETCH_ASSOC); $fname = $row_account['firstName']; $lname = $row_account['lastName']; $uname = $row_account['userName']; $email = $row_account['email']; $contact = $row_account['contact']; $image = $row_account['image']; ?> <div class="modal-body account_body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="account_body_content"> <div class="account_profile"> <div class="account_img_container"> <img src="<?php echo (empty($image)) ? 'image/smile.jpeg' : $image ?>" alt="" id="account_img"> </div> <input type="file" name="profile" id="account_profile_file" accept="image/*"> </div> <div class="account_details"> <input type="text" name="fname" value="<?php echo $fname ?>"> <input type="text" name="lname" value="<?php echo $lname ?>"> <input type="text" name="contact" value="<?php echo $contact ?>"> <input type="email" name="email" value="<?php echo $email ?>"> <input type="text" name="uname" value="<?php echo $uname ?>"> </div> </div> <div class="account_button"> <input type="submit" name="account_update" value="UPDATE" class="button update_btn"> </div> </form> </div> </div> </div> <!-- Resched Modal --> <div id="resched_modal" class="modal account-modal"> <!-- Modal content --> <div class="modal-content account-modal-content-reschedule"> <div class="modal-header"> <span class="close" id="close_resched_modal">&times;</span> <h3>Reschedule Appointment</h3> </div> <div class="modal-body reschedule_appointment_container"> <div class="reschedule_appointment_content"> <?php $appointID = $_GET['appointID']; $sql_fetchAppointment = "SELECT * FROM appointment WHERE appointID = :pid"; $stmt_fetchAppointment = $connect->prepare($sql_fetchAppointment); $stmt_fetchAppointment->execute(['pid' => $appointID]); $rows_fetchAppointment = $stmt_fetchAppointment->fetch(PDO::FETCH_ASSOC); $dentist_id = $rows_fetchAppointment['doctorID']; //fetching dentist $sql_fetchDentist = "SELECT * FROM dentist WHERE doctorID = :dentistID"; $stmt_fetchDentist = $connect->prepare($sql_fetchDentist); $stmt_fetchDentist->execute(['dentistID' => $dentist_id]); $row_fetchDentist = $stmt_fetchDentist->fetch(PDO::FETCH_ASSOC); $salut = $row_fetchDentist['Salutation']; $dentist_fn = $row_fetchDentist['firstName']; $dentist_ln = $row_fetchDentist['lastName']; $dentist_name = $salut . " " . $dentist_fn . " " . $dentist_ln; //time to string format $startTime = new DateTime($rows_fetchAppointment['start']); $startFormatted = $startTime->format('g:i a'); $endTime = new DateTime($rows_fetchAppointment['end']); $endFormatted = $endTime->format('g:i a'); $newTime = $startFormatted . " - " . $endFormatted; ?> <form action="" method="POST" enctype="multipart/form-data"> <div class="appointment_container"> <div class="appointment_content"> <input type="text" id="strDate" name="date" data-value="date" class="date" value="<?php echo $rows_fetchAppointment['appointmentDate'] ?>"> <select name="doctor" id="doctor" class="doctor"> <option value="<?php echo $dentist_name ?>" selected><?php echo $dentist_name ?></option> <option disabled>Select your dentist</option> </select> <select name="start" id="starttime" class="time_slot"> <option selected><?php echo $startFormatted ?></option> <option disabled>----Select your a time slot-----</option> </select> <select name="service" id="" class="services"> <?php $serviceTitle = $rows_fetchAppointment['service']; $sqlService = $connect->prepare("SELECT * FROM service where title = :title"); $sqlService->execute(['title' => $serviceTitle]); $rowServe = $sqlService->fetch(PDO::FETCH_ASSOC); $hr = $rowServe['hour']; $mn = $rowServe['min']; $dur = "+" . $hr . " " . "hour" . " " . $mn . " " . "min"; $servTitle = $rowServe['title']; ?> <option value="<?php echo $servTitle . ' | ' . $dur ?>" selected><?php echo $servTitle ?></option> <option disabled>---------------------------</option> <?php if (!isset($_SESSION['id'])) { ?> <?php $queryService = $connect->prepare("SELECT * FROM service"); $queryService->execute(); while ($rowService = $queryService->fetch(PDO::FETCH_ASSOC)) { $hour = $rowService['hour']; $min = $rowService['min']; $duration = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $rowService['title'] . ' | ' . $duration ?>"><?php echo $rowService['title'] ?></option> <?php } ?> <?php } else if (isset($_SESSION['id'])) { ?> <?php $cid = $_SESSION['id']; $sql_check_ifDone = "SELECT * FROM client WHERE clientID = :cid"; $stmt_check_ifDOne = $connect->prepare($sql_check_ifDone); $stmt_check_ifDOne->execute(['cid' => $cid]); $row_check_ifDone = $stmt_check_ifDOne->fetch(PDO::FETCH_ASSOC); $checkup = $row_check_ifDone['checkup']; if ($checkup == 1) { ?> <?php $queryService = $connect->prepare("SELECT * FROM service"); $queryService->execute(); while ($rowService = $queryService->fetch(PDO::FETCH_ASSOC)) { $hour = $rowService['hour']; $min = $rowService['min']; $duration = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $rowService['title'] . ' | ' . $duration ?>"><?php echo $rowService['title'] ?></option> <?php } ?> <?php } else { ?> <?php $Checkup = 'Checkup'; $Check_up = 'Check-up'; $CheckUp = 'Check up'; $Check_Up = 'Check up'; $Check_Up = 'Check Up'; $checkup = 'checkup'; $sql_checkUpOnly = "SELECT * FROM service WHERE title = :Checkup || title = :Check_up || title = :CheckUp || title = :Check_Up || title = :checkup "; $stmt_checkUpOnly = $connect->prepare($sql_checkUpOnly); $stmt_checkUpOnly->execute(['Checkup' => $Checkup, 'Check_up' => $Check_up, 'CheckUp' => $CheckUp, 'Check_Up' => $Check_Up, 'checkup' => $checkup]); $row_checkUpOnly = $stmt_checkUpOnly->fetch(PDO::FETCH_ASSOC); $hour = $row_checkUpOnly['hour']; $min = $row_checkUpOnly['min']; $durationCheckup = "+" . $hour . " " . "hour" . " " . $min . " " . "min"; ?> <option value="<?php echo $row_checkUpOnly['title'] . ' | ' . $durationCheckup ?>"><?php echo $row_checkUpOnly['title'] ?></option> <?php } ?> <?php } ?> </select> <input type="file" class="pre-diag_file" name="preDiag_file" id="pre-diag_file" size="60"> </div> <div class="button_container"> <span><input class="agree" type="checkbox" name="terms"><span id="term_btn">&nbsp;I agree to terms and conditions</span></span> <input type="submit" name="resched" value="Submit" class="button"> </div> </div> </form> <div class="calendar_container"> <div id="calendar" class="calendar"></div> </div> </div> </div> </div> <div id="term_modal" class="modal account-modal"> <!-- Modal content --> <div class="modal-content account-modal-content-reschedule"> <div class=" modal-header"> <span class="close" id="close_modal">&times;</span> <h2>Terms & conditions</h2> </div> <div class="modal-body"> <div class="terms_content"> <p>We are always pleased to assist our clients whenever we can. This document gives details of our terms and conditions of service. If, however, you have any queries or need clarification, please contact us and a member of our team will be happy to help you.</p> <h5>Treatment planning:</h5> <p> Once your treatment plan has been agreed with the Dentist, we will provide you with a written estimate of your services. If this plan changes due to radiographic or clinical findings, we will inform you and discuss this with you accordingly.</p> <h5>Consent forms:</h5> <p>Certain treatments require completion of a written consent form. This is in to ensure that we have explained the treatment, aftercare and any risk to you thoroughly, before any of these treatments are carried out. It also allows you to make an informed decision before agreeing to treatment.</p> <h5>Fees:</h5> <p> Oglimen Dental Care does not offer credit and we require fees to be settled at the appointment where treatment is provided.
Where treatment incurs a laboratory fee, at least 50% of the total fee is due at the appointment where impressions are taken. Fees for certain treatments like Dental Implants and clear braces are taken in staged payments at each visit. We will discuss and plan a schedule of payment for you.</p> <h5>Late cancellation or missed appointments:</h5> <p>Oglimen Dental Care reserves in the event of a missed appointment or an appointment canceled with less than 24-hour notice. For appointments longer than 1 hour, we require at least 72 hours. Late for appointments In order to be fair to the other patients, if you are more than 10 minutes, please be aware that you may be asked to reschedule your appointment.</p> <h5>Guarantee:</h5> <p>The patient has followed all post treatment maintenance recommendations made by our dentists. No treatment is guaranteed for more than 1 year. Some treatments may have a guarantee of less than 1 year, and in this case you will be informed by your Dentist either verbally or in writing, or both.</p> <h5>Personal Details:</h5> <p>It is very important that you give a full medical history and details of any medication you take. Should these change in any way, it is very important for you to tell your Dentist. It is the patient’s responsibility to inform the clinic of any changes in either personal details and/or their medical history.</p> <h5>Use of Images and X-rays:</h5> <p>Aldridge Dental Practice may use images and x-rays of your smile and teeth only, for marketing and educational purposes on website, and on promotional and educational literature. Your name will never be published, and identity will never be disclosed. However, if you DO NOT wish for us to use your images and x-rays in this way, please let us know.</p> <h5>Use of patient contact details:</h5> <p>At Oglimen Dental Care the health of our patients is our highest priority, and we also like to keep our patients informed of various important changes at the clinic and of our latest special offers. We like to remind our patients of their appointments, when they are due for appointments, and other various important reminders. On this note, you may be periodically contacted by the clinic via phone, text, email or by letter in the post. If you DO NOT wish to be contacted by the clinic by any or all of these means, please let us know.</p> <h5>Complaint’s policy:</h5> <p>Complaints can be made in writing by filling out a simple complaints form available from reception. Complaints should be made to Oglimen Dental Care Complaints Manager’, and should be clear, so that they can be dealt with efficiently.</p> <h5>No tolerance/Abuse policy:</h5> <p>Oglimen Dental Care we operate a zero tolerance policy to abuse to our Dentists and staff, loud/disorderly/drunken behavior, persistent missing and late cancelation of appointments (after multiple warnings). In these situations, Aldridge Dental Practice reserves the right to refuse treatment and admission.</p> <h5>Data Protection Act:</h5> <p>We store all patient personal details on a secure computer system in accordance with the Data Protection Act. All clinical notes, digital radiographs, digital photographs etc remain the property of Oglimen Dental Care. Copies of notes, radiographs and photographs can be made available on request, and Oglimen Dental Care reserves the right to charge an administration fee for these.</p> </div> </div> </div> </div> <!-- script js --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="js/main.js"></script> <script src="js/shortcode.js"></script> <script src="js/simple-lightbox.min.js"></script> <script src="https://kit.fontawesome.com/0c5646b481.js" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/b-1.5.6/b-print-1.5.6/r-2.2.2/datatables.min.js"></script> <script src='js/fullcalendar.js'></script> <script src='fullcalendar/core/main.min.js'></script> <script src='fullcalendar/daygrid/main.min.js'></script> <script src='fullcalendar/timegrid/main.min.js'></script> <script src='fullcalendar/interaction/main.min.js'></script> <script src='fullcalendar/list/main.min.js'></script> <script src='fullcalendar/moment/main.min.js'></script> <script src='fullcalendar/moment-timezone/main.min.js'></script> <script src="js/appoint.js"></script> <script> $(document).ready(function() { $('#account-table').DataTable({ aaSorting: [], responsive: true, pageLength: 5, lengthChange: false, language: { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs: [{ targets: [5], orderable: false }, { responsivePriority: 1, targets: 0 }, { responsivePriority: 2, targets: 5 }, { responsivePriority: 3, targets: 4 } ] }); $(function() { const lightbox = $('.profile-account-container a').simpleLightbox(); }); }) </script> </body> </html> <?php include 'action.php'; ?><file_sep><?php require '../config/control.php'; if (isset($_POST['category'])) { $category = $_POST['category']; $sql_fetchService1 = "SELECT * FROM service WHERE category= :category"; $stmt_fetchService1 = $connect->prepare($sql_fetchService1); $stmt_fetchService1->execute(['category' => $category]); $row_fetchService = $stmt_fetchService1->fetch(PDO::FETCH_ASSOC); $service_title = $row_fetchService['category']; $sql_fetchService = "SELECT * FROM service WHERE category= :category"; $stmt_fetchService = $connect->prepare($sql_fetchService); $stmt_fetchService->execute(['category' => $category]); $rows_fetchService = $stmt_fetchService->fetchAll(); $output = ''; $output .= '<h1>' . $service_title . '</h1>'; foreach ($rows_fetchService as $fetchService) { $output .= ' <div class="service-box"> <div class="service-box-img"> <img src="' . 'image/' . $fetchService['image'] . '" alt=""> </div> <div class="service-box-info"> <h3>' . $fetchService['title'] . '</h3> <p>' . $fetchService['description'] . '</p> </div> </div> '; } echo $output; } <file_sep><?php require_once 'controllers/authController.php'; if(empty($_SESSION['ogliadmin'])){ echo "<script>window.location.replace('sign-in.php')</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><NAME> | ADMIN</title> <link rel="stylesheet" href="../css/style.css"> <script src="https://kit.fontawesome.com/0c5646b481.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="../js/jquery-3.4.1.min.js"></script> <script src="js/script.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.css"/> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/r-2.2.2/datatables.min.js"></script> <script> $(document).ready(function(){ $(".patient_list").DataTable({ responsive: true, pageLength : 5, "lengthChange": false, "language": { search: '<i class="fas fa-search" aria-hidden="true"></i>', searchPlaceholder: 'Search...' }, columnDefs:[ { targets: [5], orderable: false } ] }); }) </script> </head> <body> <div class="grid-container"> <?php include 'nav.php'; ?> <main class="main"> <div class="main-header"> <div class="main-header__heading"> <a href="patients.php"><span>Administrator</span></a> </span> </div> </div> <div class="main-cards appoint__cards"> <div class="card card-1"> <div class="header__sort"> <button class="button patient_set" id="add_admin"><i class="fas fa-user-plus icon-s"></i>&nbsp;Add&nbsp;new&nbsp;admin</button> </div> <table class="list__tbl display dt-responsive nowrap patient_list" id="patient_list"> <thead> <tr> <th>No.</th> <th>Admin id</th> <th>First Name</th> <th>Last Name</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql_admins = $connect->prepare("SELECT * FROM administrator"); $sql_admins->execute(); $rows_admins = $sql_admins->fetchAll(); foreach($rows_admins as $admins){ ?> <tr> <td><?php echo $admins['id']?></td> <td><?php echo $admins['adminID']?></td> <td><?php echo $admins['firstName']?></td> <td><?php echo $admins['lastName']?></td> <td><?php echo $admins['status']?></td> <td> <a href="?view=<?php echo $admins['adminID']?>"><i class="fas fa-eye eye"></i></a> <a href="?edit=<?php echo $admins['adminID']?>"><i class="fas fa-edit eye"></i></a> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <!-- MODAL --> <div id="modal__view" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close">&times;</span> <?php $adminID = $_GET['view']; $sql_admin = "SELECT * FROM administrator WHERE adminID = :adminID"; $stmt_admin = $connect->prepare($sql_admin); $stmt_admin ->execute(['adminID'=>$adminID]); $row_admin = $stmt_admin->fetch(PDO::FETCH_ASSOC); $fname = $row_admin['firstName']; $lname = $row_admin['firstName']; $admin_name = $fname." ".$lname; ?> <h2><?php echo $admin_name?></h2> </div> <div class="modal-body view_body"> <div class="modal-view-body_container"> <div class="view__info"> <div class="appoint_info_content admin_img-content"> <div class="admin_img-container"> <img src="<?php echo $row_admin['image']?>" alt=""> </div> </div> <div class="patient_info_content"> <div class="patient_textbox"> <span>Admin Id:</span> <span><?php echo $row_admin['adminID']?></span> </div> <div class="patient_textbox"> <span>First Name:</span> <span><?php echo $fname?></span> </div> <div class="patient_textbox"> <span>Last Name:</span> <span><?php echo $lname?></span> </div> <div class="patient_textbox"> <span>Username:</span> <span><?php echo $row_admin['username']?></span> </div> <div class="patient_textbox"> <span>Email:</span> <span><?php echo $row_admin['email']?></span> </div> <div class="patient_textbox"> <span>Contact:</span> <span><?php echo $row_admin['contact']?></span> </div> <div class="patient_textbox"> <span>Type:</span> <span><?php echo $row_admin['type']?></span> </div> <div class="patient_textbox"> <span>Status:</span> <span><?php echo $row_admin['status']?></span> </div> </div> </div> </div> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- MODAL --> <div id="modal__add" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close_add">&times;</span> <h2>Add new admin</h2> </div> <div class="modal-body view_body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="modal-view-body_container"> <div class="view__info"> <div class="appoint_info_content admin_img-content"> <div class="admin_img-container"> <img src="../image/icons/user.png" alt="" id="img_add"> </div> <div class="button-container admin-add"> <label for="add_image" class="file-btn-label">Select Image</label> <input type="file" name="admin_image" class="file-btn" id="add_image" onchange="addimg(event)" size="60"> </div> </div> <div class="patient_info_content"> <div class="patient_textbox admin_textbox"> <span>First Name:</span> <span><input type="text" name="fname"></span> </div> <div class="patient_textbox admin_textbox"> <span>Last Name:</span> <span><input type="text" name="lname"></span> </div> <div class="patient_textbox admin_textbox"> <span>Email:</span> <span><input type="email" name="email"></span> </div> <div class="patient_textbox admin_textbox"> <span>Contact:</span> <span><input type="text" name="contact"></span> </div> </div> </div> <div class="button-container"> <input type="submit" name="add_admin" class="button" value="Add"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <!-- MODAL --> <div id="modal__edit" class="modal view"> <!-- Modal content --> <div class="modal-content view-content"> <div class="modal-header"> <span class="close" id="close_edit">&times;</span> <?php $edit = $_GET['edit']; $sql_edit_admin = "SELECT * FROM administrator WHERE adminID = :adminID"; $stmt_edit_admin = $connect->prepare($sql_edit_admin); $stmt_edit_admin ->execute(['adminID'=>$edit]); $row_edit_admin = $stmt_edit_admin->fetch(PDO::FETCH_ASSOC); $fname = $row_edit_admin['firstName']; $lname = $row_edit_admin['lastName']; $uname = $row_edit_admin['username']; $email = $row_edit_admin['email']; $contact = $row_edit_admin['contact']; $status = $row_edit_admin['status']; $name = $fname." ".$lname; ?> <span class="modal_header-title"><?php echo $name?></span> </div> <div class="modal-body view_body"> <form action="" method="POST" enctype="multipart/form-data"> <div class="modal-view-body_container"> <div class="view__info"> <div class="appoint_info_content admin_img-content"> <div class="admin_img-container"> <img src="<?php echo $row_edit_admin['image']?>" alt="" id="edit_img"> </div> <div class="button-container admin-add"> <label for="dentist_img" class="file-btn-label">Select Image</label> <input type="file" name="file_update" class="file-btn" id="dentist_img" onchange="editimg(event)" size="60"> </div> </div> <div class="patient_info_content"> <div class="patient_textbox"> <span>Admin&nbsp;Id:</span> <span style="background:lightgrey; padding: 2px 5px"><?php echo $row_edit_admin['adminID']?></span> </div> <div class="patient_textbox admin_textbox"> <span>First&nbsp;Name:</span> <span><input type="text" name="fname" value="<?php echo $fname?>"></span> </div> <div class="patient_textbox admin_textbox"> <span>Last&nbsp;Name:</span> <span><input type="text" name="lname" value="<?php echo $lname?>"></span> </div> <div class="patient_textbox admin_textbox"> <span>Username:</span> <span><input type="text" name="uname" value="<?php echo $uname?>"></span> </div> <div class="patient_textbox admin_textbox"> <span>Email:</span> <span><input type="email" name="email" value="<?php echo $email?>"></span> </div> <div class="patient_textbox admin_textbox"> <span>Contact:</span> <span><input type="text" name="contact" value="<?php echo $contact?>"></span> </div> <div class="patient_textbox admin_textbox"> <span>Enter Password:</span> <span><input type="password" name="pwd"></span> </div> </div> </div> <div class="button-container"> <input type="submit" name="update_admin" class="button" value="Update"> </div> </div> </form> </div> <div class="modal-footer"> <h6>Dela Paz-Oglimen Dental Care Clinic &copy; 2008-<?php echo date('Y')?></h6> </div> </div> </div> <script> // view selected image var addimg = function(event) { var output = document.getElementById('img_add'); output.src = URL.createObjectURL(event.target.files[0]); }; var editimg = function(event) { var output = document.getElementById('edit_img'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> </body> </html> <?php if(isset($_GET['view'])){ echo "<script>var modal__view = document.getElementById('modal__view')</script>"; echo "<script> modal__view.style.display='block'</script>"; } if(isset($_GET['edit'])){ echo "<script>var modal__edit = document.getElementById('modal__edit')</script>"; echo "<script> modal__edit.style.display='block'</script>"; } ?> <script> const add_admin = $('#add_admin'); //when user click the add button. show modal add_admin.on('click',function(){ const modal_add = document.getElementById('modal__add'); modal_add.style.display = 'block'; }); const close = $('#close'); // When the user clicks on <span> (x), close the modal close.on('click', function() { modal__view.style.display = "none"; window.location.replace('admin.php'); }); const close_add = $('#close_add'); // When the user clicks on <span> (x), close the modal close_add.on('click', function() { modal__view.style.display = "none"; window.location.replace('admin.php'); }); const close_edit = $('#close_edit'); // When the user clicks on <span> (x), close the modal close_edit.on('click', function() { modal__edit.style.display = "none"; window.location.replace('admin.php'); }); const menuIconEl = $('.menu-icon'); const sidenavEl = $('.sidenav'); const sidenavCloseEl = $('.sidenav__close-icon'); // Add and remove provided class names function toggleClassName(el, className) { if (el.hasClass(className)) { el.removeClass(className); } else { el.addClass(className); } } // Open the side nav on click menuIconEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); // Close the side nav on click sidenavCloseEl.on('click', function() { toggleClassName(sidenavEl, 'active'); }); function confirmationLogout(anchor) { var conf = confirm('Are you sure want to SIGN OUT?'); if(conf) window.location=anchor.attr("href"); } </script>
c092f741abc0edef9449885d842146379b6e8b78
[ "JavaScript", "PHP" ]
65
JavaScript
kornbif/dental_clinic_final
a483d3d92073086b7bcc769d11e0114b8f379f17
d0577b1ebff7c42f74ff2376aa2ae239d447bcba
refs/heads/master
<file_sep>const https = require('https'); const qs = require('querystring'); let tokenGH; const configToken = newToken => { tokenGH = newToken; }; const makeRequest = (options, dataToSend = false) => { return new Promise((resolve, reject) => { let data = ''; const req = https.request(options, res => { res.on('data', chunk => { data += chunk.toString('utf8'); }); res.on('end', () => { resolve(JSON.parse(data)); }); }); req.on('error', e => { reject(e); }); if (dataToSend !== false) { req.write(dataToSend); } req.end(); }); }; const fetchInfoFromGHAPI = path => { const options = { host: 'api.github.com', path, method: 'GET', headers: { Authorization: `token ${tokenGH}`, 'user-agent': 'node.js', }, }; return makeRequest(options); }; const putLabelsInPR = (path, labelsArray) => { const formData = JSON.stringify({ labels: labelsArray, }); const options = { host: 'api.github.com', path, method: 'POST', headers: { Authorization: `token ${tokenGH}`, 'user-agent': 'node.js', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': formData.length, }, }; return makeRequest(options, formData); }; module.exports = { configToken, fetchInfoFromGHAPI, putLabelsInPR, }; <file_sep># Hook This project facilitates the use of git and allows to have a certain security at the time of performing different commands. Features: - When you make a merge and then a push to master, beta or staging if the branch you're going to merge does not have a pull request will not allow you to make the push and will inform you of the pull request that you must do. - Once you have merged a branch and done the push, if all went well to the merged branch will be added the label "merged in master/beta/staging" depending on where you made the merge. ## Requeriments You should have already installed (with [Homebrew](http://brew.sh) if you're on Mac). You should have already installed and **running**: - Node ## Local Installation ### 1. Node.js version This repository requires Node.js version 8.15.0, for that we recommend you to use `nvm`. ```bash brew install nvm nvm install 8.15.0 nvm use 8.15.0 ``` ### 2. Clone Github repo in your home ``` cd ~ git clone https://github.com/AlbertHernandez/hook.git ``` ### 3. Create Github Token #### 3.1. Verify your email address, if it hasn't been verified yet. #### 3.2. In the upper-right corner of any page, click your profile photo, then click Settings. #### 3.3. In the left sidebar, click Developer settings. #### 3.4. In the left sidebar, click Personal access tokens. #### 3.5. Click Generate new token. #### 3.6. Give your token a descriptive name. #### 3.7. Select the scopes, or permissions, you'd like to grant this token. To use your token to access repositories from the command line, select repo. (we recommend giving all permissions) #### 3.8. Click Generate token. #### 3.9. Click to copy the token to your clipboard. ### 4. Config your token in the proyect #### 4.1. Open token file ``` cd git-hooks open hooks/util/token.js ``` #### 4.2. Paste your Github Token where it says 'PUT HERE YOUR TOKEN'; ### 5. Update your hooks ``` rm -r .git/hooks ln -s ~/git-hooks/hooks .git ``` ### Common problems solutions: If you get into trouble around node modules (because previous installation, or node version upgrade) just: ``` rm -rf node_modules npm install ``` <file_sep>#!/usr/bin/env node const removeWhiteSpaces = array => array.filter(element => element !== ''); const removeDuplicates = array => [...new Set(array)]; const removeFirst2Caracters = array => array.map(element => element.substring(2)); const removeNotAllowed = (array, noPermitidos) => array.filter(element => !(element in noPermitidos)); module.exports = { removeNotAllowed, removeWhiteSpaces, removeDuplicates, removeFirst2Caracters, }; <file_sep>const tokenAuth = 'PUT HERE YOUR TOKEN'; const getTokenAuth = () => tokenAuth; module.exports = { getTokenAuth, }; <file_sep>#!/usr/bin/env node const util = require('./util'); const gitCommand = require('./gitCommands'); const token = require('./token'); const ghAPI = require('./ghAPI'); const notAllowedBranches = { staging: true, beta: true, master: true, }; let pullRequest; const inicialize = tokenAuth => { ghAPI.configToken(tokenAuth); }; const getPullRequest = async () => { if (pullRequest !== undefined) { return pullRequest; } const tokenAuth = token.getTokenAuth(); inicialize(tokenAuth); const urlRepo = gitCommand.getURLGitHub(); const path = `/repos/${urlRepo}/pulls?state=all`; pullRequest = await ghAPI.fetchInfoFromGHAPI(path); return pullRequest; }; const getBranchOfPr = pr => pr.head.ref; const existPullRequestInBranches = (branches, pullRequestArray = []) => { const branchWithPR = {}; const branchWithoutPR = {}; branches.forEach(branch => { branchWithoutPR[branch] = true; if (!branchWithPR[branch]) { for (let indexPR = 0; indexPR < pullRequestArray.length; indexPR += 1) { const pr = getBranchOfPr(pullRequestArray[indexPR]); branchWithPR[pr] = true; if (pr === branch) { delete branchWithoutPR[branch]; indexPR += 1; branchWithPR[branch] = true; break; } } } else { delete branchWithoutPR[branch]; branchWithPR[branch] = true; } }); return Object.keys(branchWithoutPR); }; const getBranchesContainsCommitID = arrayBranches => { const array = util.removeWhiteSpaces( arrayBranches.reduce( (previous, commitID) => [ ...previous, ...gitCommand.getBranchesContainsCommitIDWithoutClean(commitID), ], [], ), ); const withoutRepites = util.removeDuplicates(array); return util.removeFirst2Caracters(withoutRepites); }; const getBranchesPendingToPush = () => { const currentBranch = gitCommand.getCurrentBranch(); const IDCommitNotPush = gitCommand.getIDCommitNotPushInBranch(currentBranch); const branchArrayWithoutFilter = getBranchesContainsCommitID(IDCommitNotPush); const branchArrayToCheckPR = util.removeNotAllowed( branchArrayWithoutFilter, notAllowedBranches, ); return branchArrayToCheckPR; }; const getNonCreatedPRBranches = async arrayBranches => { const listPR = await getPullRequest(); return existPullRequestInBranches(arrayBranches, listPR); }; const Check = () => { const currentBranch = gitCommand.getCurrentBranch(); return currentBranch in notAllowedBranches; }; const getNumberPR = async branches => { const listPR = await getPullRequest(); const res = listPR .filter(pr => branches.includes(pr.head.ref)) .map(pr => pr.number); return res; }; const putLabelInBranches = async branches => { const urlRepo = gitCommand.getURLGitHub(); const tokenAuth = token.getTokenAuth(); inicialize(tokenAuth); const numberOfAllPR = await getNumberPR(branches); const currentBranch = gitCommand.getCurrentBranch(); const labels = [`Merged in ${currentBranch}`]; numberOfAllPR.forEach(async numberOfPR => { const path = `/repos/${urlRepo}/issues/${numberOfPR}/labels`; await ghAPI.putLabelsInPR(path, labels); }); }; module.exports = { getBranchesPendingToPush, getNonCreatedPRBranches, Check, putLabelInBranches, };
8a1d64c8161b25fee6fdf3ff58a5ee59923c306c
[ "JavaScript", "Markdown" ]
5
JavaScript
AlbertHernandez/git-hooks
f1131fa5d98fa024604d18cb5de36e750f5ff698
46714f725a1595a458077d3c56f7622c285d0b5d
refs/heads/master
<repo_name>jeontable/Stimulating-the-Brain-with-Python3<file_sep>/CH09/001.py class Car: def __init__(self): self.color = 0xFF0000 self.wheel_size = 16 self.displacement = 2000 def forward(self): pass def backward(self): pass def turnleft(self): pass def turnright(self): pass if __name__ == '__main__': mycar = Car() print('0x{:02X}'.format(mycar.color))<file_sep>/CH11/open3.py class open3: def __init__(self, file): self.fhand = open(file, 'r') def __enter__(self): return self.fhand def __exit__(self, ext, exv, trb): self.fhand.close() with open3('files/test.txt') as out: print(out.read())<file_sep>/CH06/CH06.py a = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} print(a.get('name')) b = 4 print("ffdsa") print("ffdsa") if b == 4: print("fdasf") print("fdadf") else: print("fdsafdsafdsafds") print(range(0,5))<file_sep>/CH09/InstanceCounter.py class InstanceCounter: count = 0 def __init__(self): InstanceCounter.count += 1 @classmethod def print_instance_count(cls): print(cls.count) @staticmethod def print_instance_count2(): print(InstanceCounter.count) a = InstanceCounter() InstanceCounter.print_instance_count() b = InstanceCounter() InstanceCounter.print_instance_count() c = InstanceCounter() c.print_instance_count() d = InstanceCounter() d.print_instance_count2() InstanceCounter.print_instance_count2()<file_sep>/CH09/clsmethod1.py class TestClass: korea = None @classmethod def print_TestClass(cls): print(cls) TestClass.print_TestClass() TestClass.korea = 82 print(TestClass.korea) obj = TestClass() obj.print_TestClass() obj.korea = 83 print(obj.korea) print(TestClass.korea)<file_sep>/CH09/Calculator.py class Calculator: total = None total2 = [] @staticmethod def plus(a, b): return a + b @staticmethod def minus(a, b): return a - b print('{0} + {1} = {2}'.format(3, 4, Calculator.plus(3, 4))) Calculator.total = 3 print(Calculator.total) print('--------------------------------') a = Calculator() b = Calculator() a.total = 4 b.total = 5 print(a.total) print(b.total) print(a.total) print(b.total) print('--------------------------------') print(a.total2) a.total2.append(4) print(b.total2) print(a.total2) b.total2.append(5) print(b.total2) print(a.total2)<file_sep>/CH09/InstanceVar.py class InstanceVar: text_list = [] def __init__(self): pass def add(self, text): self.text_list.append(text) def print_list(self): print(self.text_list) a = InstanceVar() a.add('a') a.add('a') a.print_list() b = InstanceVar() b.add('b') b.print_list() a.print_list() print(a is b) print(a) print(b) print(a.text_list is b.text_list)<file_sep>/CH09/decorator1.py class MyDecorator: def __init__(self, f): print("Initializing MyDecorator...") self.func = f print(self.func) def __call__(self): print ('Begin :{0}'.format(self.func.__name__)) self.func() print ('End :{0}'.format(self.func.__name__)) def print_hello2(): print('hello.') print(print_hello2) print_hello2 = MyDecorator(print_hello2) print(print_hello2) print_hello2() <file_sep>/CH03/CH03.py print(hex(15)) print(hex(12345)) a = 0x3039 print(hex(a)) print("------------------") exponent = 0b11111111111 mantissa = 0b1111111111111111111111111111111111111111111111111111 print(exponent) print(mantissa) exponent1 = 0b100000000000 mantissa1 = 0b10000000000000000000000000000000000000000000000000000 print(exponent1) print(mantissa1) exponent2 = 0b111111111111 mantissa2= 0b11111111111111111111111111111111111111111111111111111 print(exponent2) print(mantissa2) import math print(math.pi) print(math.e)<file_sep>/README.md # Stimulating-the-Brain-with-Python3 ====== 이 저장소는 '뇌를 자극하는 파이썬3'을 학습하면서 실습한 코드를 저장하려는 목적으로 생성되었습니다. <file_sep>/CH09/generator1.py def YourRange(start, end): current = start while current < end: yield current current += 1 for i in YourRange(0,4): print(i)<file_sep>/CH05/CH05.py a = [1,2,3,4] b = [1,2,3,4] print(len(a)) a[3] = 8 print(a) c = a + b print(c) a = (1,2,3) print(a) print(type(a)) b = 1,2,3,4 print(b) print("---------딕셔너리-----------------------") dic1 = {"안녕":24, "안녕21":21} dic2 = {} dic2['파이썬'] = "www.python.org" dic2['마이크로소프트'] = "www.python.org" dic2['애플'] = "www.python.org" print(dic1) print(dic2) print(type(dic1)) print(dic1.keys()) print(dic1.values()) print(dic1.items()) print("애플" in dic2.keys()) print("www.python.org" in dic2.values()) dic2.pop('애플') print(dic2) dic2.clear() print(dic2)<file_sep>/CH11/read_160728.py file = open('files/test.txt', 'r') str = file.read() print(str) file.close()<file_sep>/CH11/openwith_160728.py with open('files/test.txt', 'r') as out: str = out.read() print(str) #It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:<file_sep>/CH08/main.py print('name : {0}'.format(__name__)) if not __name__ == '__main__': print("메인프로그램임") from mypackage import mod1 mod1.test() <file_sep>/CH09/scope.py class HasPrivate: def __init__(self): self.public2 = 'Public.' self.__private2 = 'Private.' def print_from_internal2(self): return self.public2, self.__private2 def print_from_internal(self): print(self.public2) print(self.__private2) print(print_from_internal2(self)) obj = HasPrivate() obj.print_from_internal() <file_sep>/CH07/001.py # 기본값, 혹은 아규먼트 지정 def print_string(text='기본값', count=10): for i in range(count): print(text) print_string(count=6) # 가변 매개변수 print('-----------------------------------------------------------------------') def merge_string(*text_list): result = 0 for s in text_list: result = result + s return result # print(merge_string('아버지가', '방에', '들어가신다')) print(merge_string(3, 4, 5,34,43,43,43,5,45,4)) # 사전 형식의 가변 매개변수 print('-----------------------------------------------------------------------') def merge_string2(**text_list): result = '' for key, value in text_list.items(): print('{0} -_- {1}'.format(key, value)) return result merge_string2(name='호날두', age=35) # 일반 agument와 가변 arguments 같이 쓰기 print('-----------------------------------------------------------------------') def print_args(argc, *argv): for i in range(argc): print(argv[i]) print_args(4, '홍', '길', '동', '전', '꿀', '잼') # 일반, 가변을 같이 쓰는데, 가변 매개변수를 먼저 쓸 때 # 일반 매개변수는 반드시 키워드 매개변수로 호출해야 함. print('-----------------------------------------------------------------------') def print_args(*argv, argc): for i in range(argc): print(argv[i]) print_args('홍', '길', '동', '전', '꿀', '잼', argc=3) # 여러 개의 return print('-----------------------------------------------------------------------') def my_abs(arg): if arg < 0: return arg * -1 else: return arg print(my_abs(-1)) print(my_abs(1)) # return 문 없이 함수가 종료되면 호출자에게 None 보냄 print('-----------------------------------------------------------------------') def my_abs(arg): if arg < 0: return arg * -1 elif arg > 0: return arg print(my_abs(0)) # 값없이 return 해도 None 전달됨 print('-----------------------------------------------------------------------') def my_abs2(arg): return print(my_abs2(0)) # 함수 밖의 변수, 함수 안의 변수 print('-----------------------------------------------------------------------') def scope_test(): a = 1 print('a:{0}'.format(a)) a = 0 scope_test() print(a) # 글로벌 변수 print('-------글로벌 변수---------------------------------------------------------------') def scope_test2(): global k10 #전역적으로 생성하고, 지역변수 막음 k10 = 1 print('a:{0}'.format(k10)) #함수 호출 이전에 k10 사용하면 에러남 undefinded된 상태기 때문 scope_test2() print(k10) # 재귀 함수 print('-------재귀 함수---------------------------------------------------------------') def some_func(count): if count > 0: some_func(count-1) print(count) some_func(5) # 팩토리얼 print('-------팩토리얼---------------------------------------------------------------') def fact(n): if n == 0: return 1 else: return fact(n-1)*n print(fact(5)) # 함수를 변수에 담아 사용하기 print('-------함수를 변수에 담아 사용하기---------------------------------------------------------------') def print_something(a): print(a) p = print_something p(123) p('abc') # 함수를 변수에 담아 사용하기2 print('-------함수를 변수에 담아 사용하기2---------------------------------------------------------------') def plus(a, b): return a+b def minus(a, b): return a-b flist = [plus, minus] print(flist[0](3,4)) print(flist[1](5,1)) # 함수를 변수에 담아 사용하기3 print('-------함수를 변수에 담아 사용하기3---------------------------------------------------------------') def hello_korean(): print('안녕하세요') def hello_english(): print('hello') def greet(hello): hello() greet(hello_korean) # Nested Function print('-------Nested Function---------------------------------------------------------------') import math def stddev(*args): def mean(): return sum(args)/len(args) def variance(m): total = 0 for arg in args: total += (arg - m)**2 return total/(len(args)-1) v = variance(mean()) return math.sqrt(v) print(stddev(6,7,8,9,10)) # 구현 잠시 미루기 print('-------구현 잠시 미루기-----------------------------------------------------------') def empty_func(): pass empty_func() print(empty_func())<file_sep>/CH11/write_160728.py file = open('files/test.txt', 'w') file.write('hello') file.close()<file_sep>/CH04/CH04.py hello = 'hello' world = 'world' helloworld = hello + world print(helloworld) print("-------------") s = 'good mornindg' print(s[0:6]) print(('L' in hello)) print(('l' in hello)) k = ["a", 'fda'] print(s.find('d')) print(s.rfind('d')) print(s.count('d')) print("fdsafdsafsafsa".isalpha()) print("가나다라마".isalpha()) print("543543543".isnumeric()) print("54354354dsaf한글s3".isalnum()) a = "hello, world" b = a.split(",") c = a.replace("hello","hi") print(a) print(b) print(type(b)) print(c) kk = 'My name is {0}. I am {1} years old'.format(34,"fdsaf") print(kk) kk = 'My name is {name}. I am {age} years old' print(kk.format(age=45, name="fdsaf")) # b = input("두번째 수를 입력하세요") # a = input("첫번째 수를 입력하세요") # c = int(a) * int(b) # print("{a1} * {a2} = {a3}".format(a1=a, a2=b, a3=c)) k1 = 0b1 print(k1) k2 = 0b10 print(k2) k3 = 0b100 print(k3) k11 = k1 << 1 print(k11) k12 = k1 << 2 print(k12) k12 = k1 << 3 print(k12) k12 = k1 << 4 print(k12) k12 = k1 << 5 print(k12) k12 = k1 << 6 print(k12) k12 = k1 << 7 print(k12) k12 = k1 << 8 print(k12) k12 = k1 << 9 print(k12) k12 = k1 << 10 print(k12) k12 = k1 << 11 print(k12) k12 = k1 << 12 print(k12) k12 = k1 << 13 print(k12) k12 = k1 << 14 print(k12) k12 = k1 << 15 print(k12) k12 = k1 << 16 print(k12) k12 = k1 << 17 print(k12) k21 = k3 >> 1 print(k21) a = -1 print(a) print(a << 1) print(a << 2) print(a << 3) print(a << 4) print(a << 5) a = 1 print(a << 5) b = 32 print(hex(32)) print(15&1)<file_sep>/CH11/cnxtmana1.py import struct packed = struct.pack('i', 123434343) print(packed) for b in packed: print(b) unpacked = struct.unpack('i', packed) print(unpacked) print(type(unpacked[0]))<file_sep>/CH08/CH08_160728.py # import calculator # # print(calculator.plus(3, 4)) # print(calculator.minus(3, 4)) # print(calculator.multiply(3, 4)) # # # from calculator import * from calculator import plus, korea import sys print(plus(3, 4)) print(korea) for path in sys.path: print(path) print(sys.builtin_module_names)
79ceca6e57b8f9c912cd3ed758b3d5f046fdb352
[ "Markdown", "Python" ]
21
Python
jeontable/Stimulating-the-Brain-with-Python3
46719a7766bfbe987ad4409befb93ded9325f488
1e8241a49694adadfbf01b87a204cb5fc02169e3
refs/heads/master
<repo_name>Hiblet/StringSim1<file_sep>/StringSim1/FormulaAddInUtils.h #pragma once #ifndef FORMULAADDINUTILS_H__ #define FORMULAADDINUTILS_H__ #include "FormulaAddIn.h" class FormulaAddInUtils { // Function To Actually Set A String On A Return (inc GlobalAlloc) static void DoSetString(FormulaAddInData* pReturnValue, const wchar_t* pString); // Fix a Bug from Pre 10.5, should be retired static void DoResetNull(int nNumArgs, FormulaAddInData* pArgs); public: // Function To Set A String On A Return (inc GlobalAlloc) static void SetString(FormulaAddInData *pReturnValue, const wchar_t *pString); // Correct NULL and return success value static long ReturnError(const wchar_t *pString, FormulaAddInData *pReturnValue, int nNumArgs, FormulaAddInData *pArgs); // Correct NULL and return success value static long ReturnSuccess(int nNumArgs, FormulaAddInData *pArgs); // Copy From Source To Target static void CopyValue(const FormulaAddInData *source, FormulaAddInData *target); }; #endif<file_sep>/ReadMe.MD # StringSim1 ## Introduction A project to set up an x64 DLL for use as a FormulaAddIn function in Alteryx ## Notes This is working!<file_sep>/StringSim1/StringSim1.h #pragma once #ifdef STRINGSIM1_EXPORTS #define STRINGSIM1_API __declspec(dllexport) #else #define STRINGSIM1_API __declspec(dllimport) #endif #ifndef STRINGSIM1_H__ #define STRINGSIM1_H__ #include <string> #include "FormulaAddIn.h" // Formula function signature. The function exposed in the <Dll><EntryPoint> of the // FormulaAddIn XML MUST have exactly this signature. // this MUST be thread safe // // return 1 for success // If 1, place return value in pReturnValue. If returning a string, it MUST be allocated with // GlobalAlloc and will be free'd with GlobalFree // or 0 for failure. // If 0, place a string in the pReturnValue that represents the error message // Again, the string MUST be allocated with GlobalAlloc typedef long(_stdcall * FormulaAddInPlugin)(int nNumArgs, FormulaAddInData *pArgs, FormulaAddInData *pReturnValue); #endif<file_sep>/StringSim1/FormulaAddIn.h #pragma once #ifndef FORMULAADDIN_H__ #define FORMULAADDIN_H__ #include <string> const int nVarType_DOUBLE = 1; const int nVarType_WCHAR = 2; // API definition for Formula functions plug ins struct FormulaAddInData { int nVarType; // 1 for double, 2 for wchar_t int isNull; // 1 if NULL, 0 if valid double dVal; // valid if nVarType==1 && isNull==0 const wchar_t * pVal; // valid if nVarType==2 && isNull==0 inline FormulaAddInData() { memset(this, 0, sizeof(*this)); // Requires <string> } }; #endif
a323e99831883481c3cd41710f4ddb4f170274bf
[ "Markdown", "C++" ]
4
C++
Hiblet/StringSim1
c9e2997ac4a31bcbf01a3d24049fc2ad652aadfa
eb4beadbf542ea417c99e5dde77324fa5935951b
refs/heads/master
<repo_name>josephjojy/ParkingApp<file_sep>/README.md # ParkingApp This is a Parking Maintenance App. Runs on Android. Still a prototype. <file_sep>/app/src/main/java/com/example/parkingapp/MainActivity.java package com.example.parkingapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button entry,exit; TextView vp1,vp2,vp3,vp4,vp5,gd1,gd2; int[] tot={20,20,20,20,20,20,20}; int i; String s,st; Spinner pgsel; String[] park = { "VP-1","VP-2", "VP-3", "VP-4", "VP-5" ,"GD-1" ,"GD-2"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); entry=findViewById(R.id.entry); exit=findViewById(R.id.exit); vp1=findViewById(R.id.vp1); vp2=findViewById(R.id.vp2); vp3=findViewById(R.id.vp3); vp4=findViewById(R.id.vp4); vp5=findViewById(R.id.vp5); gd1=findViewById(R.id.gd1); gd2=findViewById(R.id.gd2); pgsel=findViewById(R.id.pgsel); /* Selecting from the spinner which parking lot */ ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, park); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); pgsel.setAdapter(adapter); pgsel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { st=String.valueOf(pgsel.getSelectedItem()); i=pgsel.getSelectedItemPosition(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); /* Modifying the parking space available accordingly */ entry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tot[i]!=0) { tot[i] -= 1; s = park[i]+"\n" + tot[i]; switch(i) { case 0: { vp1.setText(s); if (tot[i] == 0) vp1.setBackgroundColor(0xffcc0000); break; } case 1: { vp2.setText(s); if (tot[i] == 0) vp2.setBackgroundColor(0xffcc0000); break; } case 2: { vp3.setText(s); if (tot[i] == 0) vp3.setBackgroundColor(0xffcc0000); break; } case 3: { vp4.setText(s); if (tot[i] == 0) vp4.setBackgroundColor(0xffcc0000); break; } case 4: { vp5.setText(s); if (tot[i] == 0) vp5.setBackgroundColor(0xffcc0000); break; } case 5: { gd1.setText(s); if (tot[i] == 0) gd1.setBackgroundColor(0xffcc0000); break; } case 6: { gd2.setText(s); if (tot[i] == 0) gd2.setBackgroundColor(0xffcc0000); break; } } } } }); exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tot[i]!=20) { tot[i]+= 1; s = park[i]+"\n" + tot[i]; switch(i) { case 0: { vp1.setText(s); if (tot[i] > 0) vp1.setBackgroundColor(0xff00cc00); break; } case 1: { vp2.setText(s); if (tot[i] > 0) vp2.setBackgroundColor(0xff00cc00); break; } case 2: { vp3.setText(s); if (tot[i] > 0) vp3.setBackgroundColor(0xff00cc00); break; } case 3: { vp4.setText(s); if (tot[i] > 0) vp4.setBackgroundColor(0xff00cc00); break; } case 4: { vp5.setText(s); if (tot[i] > 0) vp5.setBackgroundColor(0xff00cc00); break; } case 5: { gd1.setText(s); if (tot[i] > 0) gd1.setBackgroundColor(0xff00cc00); break; } case 6: { gd2.setText(s); if (tot[i] > 0) gd2.setBackgroundColor(0xff00cc00); break; } } } } }); } }
93c6695d69ff172bb9ae8cab0dfaf7fb18dbfc02
[ "Markdown", "Java" ]
2
Markdown
josephjojy/ParkingApp
58541964044d2306eea1ad2efa98d6c0f370a0f2
5f0ef0610e2c82fac42f168c20b2c45c0c2e7a5c
refs/heads/master
<repo_name>ymlgithub/whutapi<file_sep>/src/main/java/com/ymlyj666/api/whutapi/config/Swagger2Config.java package com.ymlyj666.api.whutapi.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Created by 19110 on 2016/11/29. */ @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket buildDocket() { return new Docket(DocumentationType.SWAGGER_2) .useDefaultResponseMessages(false) .apiInfo(buildApiInf()) .select() .apis(RequestHandlerSelectors.basePackage("com.ymlyj666.api.whutapi.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo buildApiInf() { return new ApiInfoBuilder() .title("武汉理工大学API") .contact(new Contact("杨明亮", "https://ymlyj666.com", "<EMAIL>")) .version("1.1") .build(); } } <file_sep>/src/main/java/com/ymlyj666/api/whutapi/model/JWCData.java package com.ymlyj666.api.whutapi.model; import com.ymlyj666.sdk.whutsdk.jwc.model.BasicStudentInfo; import com.ymlyj666.sdk.whutsdk.jwc.model.Course; import com.ymlyj666.sdk.whutsdk.jwc.model.Score; import com.ymlyj666.sdk.whutsdk.jwc.model.XFTJ; import java.util.List; /** * Created by 19110 on 2017/2/18. */ public class JWCData { private String uid; private BasicStudentInfo basicStudentInfo; private Course[][] courses; private List<Score> scores; private XFTJ xftj; public JWCData(String uid, BasicStudentInfo basicStudentInfo, Course[][] courses, List<Score> scores, XFTJ xftj) { this.uid = uid; this.basicStudentInfo = basicStudentInfo; this.courses = courses; this.scores = scores; this.xftj = xftj; } public JWCData() { } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public BasicStudentInfo getBasicStudentInfo() { return basicStudentInfo; } public void setBasicStudentInfo(BasicStudentInfo basicStudentInfo) { this.basicStudentInfo = basicStudentInfo; } public Course[][] getCourses() { return courses; } public void setCourses(Course[][] courses) { this.courses = courses; } public List<Score> getScores() { return scores; } public void setScores(List<Score> scores) { this.scores = scores; } public XFTJ getXftj() { return xftj; } public void setXftj(XFTJ xftj) { this.xftj = xftj; } } <file_sep>/src/main/java/com/ymlyj666/api/whutapi/controller/JwcController.java package com.ymlyj666.api.whutapi.controller; import com.ymlyj666.api.whutapi.model.JWCData; import com.ymlyj666.api.whutapi.model.Response; import com.ymlyj666.sdk.whutsdk.exception.LoginException; import com.ymlyj666.sdk.whutsdk.jwc.WHUTJwc; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; /** * Created by 19110 on 2017/2/18. */ @Api(description = "教务处") @RestController public class JwcController { @ApiOperation("获取教务处信息") @RequestMapping(value = "/jwc", method = RequestMethod.POST) public Response<JWCData> getJwcInfo(@ApiParam(value = "学号", required = true) @RequestParam("uid") String uid, @ApiParam(value = "密码", required = true) @RequestParam("pswd") String pswd, @ApiParam("获取基本信息") @RequestParam(value = "basicStudentInfo", required = false) Boolean basicStudentInfo, @ApiParam("获取课表") @RequestParam(value = "courses", required = false) Boolean courses, @ApiParam("获取成绩") @RequestParam(value = "scores", required = false) Boolean scores, @ApiParam("获取学分统计") @RequestParam(value = "xftj", required = false) Boolean xftj ) throws IOException { WHUTJwc whutJwc = new WHUTJwc(uid, pswd, 5); if (!whutJwc.login()) { throw new LoginException(); } JWCData jwcData = new JWCData(); jwcData.setUid(uid); if (basicStudentInfo != null && basicStudentInfo) { jwcData.setBasicStudentInfo(whutJwc.getBasicStudentInfo()); } if (courses != null && courses) { jwcData.setCourses(whutJwc.getCourses()); } if (scores != null && scores) { jwcData.setScores(whutJwc.getScores()); } if (xftj != null && xftj) { jwcData.setXftj(whutJwc.getXFTJ()); } return new Response<>(jwcData); } } <file_sep>/README.md # WHUT API 作者:杨明亮 邮箱:<EMAIL> 有问题欢迎邮件联系我。 ## 武汉理工大学相关网站API - 教务处登录验证 - 学生基本信息 - 课表查询 - 成绩查询 - 学分统计、排名 - 可以打包部署到自己的服务器使用 ## 部署方式 本人服务器资源有限,不再提供API在线调用服务,如有需要请自行部署。 将本项目bin目录中的*whutapi-${版本号}.war*拷贝到tomcat的webapps目录下,启动tomcat,访问*http(s)://ip:端口号/whutapi-${版本号}/* 即可看到API文档。 ## 其它 Java环境,欢迎使用 *武汉理工大学相关网站sdk* https://github.com/ymlgithub/whutsdk<file_sep>/src/main/java/com/ymlyj666/api/whutapi/config/InterceptorRegistrant.java package com.ymlyj666.api.whutapi.config; import com.ymlyj666.api.whutapi.interceptor.CrossFieldInterceptor; import com.ymlyj666.api.whutapi.interceptor.RequestCounter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by 19110 on 2016/8/5. */ @Configuration public class InterceptorRegistrant extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { //添加拦截器,可以无限添加 registry.addInterceptor(requestCounter()); registry.addInterceptor(crossFieldInterceptor()); } @Bean public RequestCounter requestCounter() { return new RequestCounter(); } @Bean public CrossFieldInterceptor crossFieldInterceptor() { return new CrossFieldInterceptor(); } } <file_sep>/src/main/java/com/ymlyj666/api/whutapi/config/ErrorsHandler.java package com.ymlyj666.api.whutapi.config; import com.ymlyj666.api.whutapi.model.Response; import com.ymlyj666.sdk.whutsdk.exception.LoginException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by 19110 on 2017/2/21. */ @Configuration @ControllerAdvice @RestController public class ErrorsHandler implements ErrorController { private static final Logger log = LoggerFactory.getLogger(ErrorsHandler.class); @ExceptionHandler(LoginException.class) public Response onLoginException(LoginException e) { return Response.WRONG_UID_OR_PSWD; } @ExceptionHandler(IOException.class) public Response onIOException(IOException e) { log.error(e.getMessage(), e); return new Response<>(e); } @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public Response onNotFound(NoHandlerFoundException e) { log.info(e.getMessage(), e); return new Response(e); } @ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Response onThrowable(Throwable t) { log.error(t.getMessage(), t); return new Response(t); } @RequestMapping("/errors") public void onNotFound(HttpServletResponse response) throws IOException { log.warn("404"); response.sendRedirect("swagger-ui.html"); } @Override public String getErrorPath() { return "/errors"; } } <file_sep>/settings.gradle rootProject.name = 'whutapi'
e5a80c7f748c30939e51adf4bdd0cbd95c012ae4
[ "Markdown", "Java", "Gradle" ]
7
Java
ymlgithub/whutapi
03ce4ec584b3b8e336513603b7e7dca3b289c42d
0b9f3bf96f2294a07737af8af0dc75a072b93509
refs/heads/master
<repo_name>hamzadals/geolocation-finder<file_sep>/README.md # geolocation-finder Created with CodeSandbox <file_sep>/src/Map1.jsx import React, { useState,useEffect } from "react"; import L from "leaflet"; import { Map, TileLayer, Marker, Popup } from "react-leaflet"; import "leaflet/dist/leaflet.css"; import './styles.css' const Map1 = (props) => { const {lat,lng} = props console.log(lat) console.log(lng) let zoom=6 // const position = [lat1, lng1] const Icon = L.icon({ iconUrl: 'https://unpkg.com/leaflet@1.6.0/dist/images/marker-icon.png', iconSize: [38, 95], // size of the icon shadowSize: [50, 64], // size of the shadow iconAnchor: [22, 94], // point of the icon which will correspond to marker's location shadowAnchor: [4, 62], // the same for the shadow popupAnchor: [-3, -76] }); return ( <Map className="map"center={[lat,lng]} zoom={zoom}> <TileLayer attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <Marker position={[lat,lng]} icon={Icon}> <Popup> A pretty CSS3 popup. <br /> Easily customizable. </Popup> </Marker> </Map> ); }; export default Map1; <file_sep>/src/Output.jsx import React from "react"; import "./styles.css"; const Output = ({ ip, country, current_time, isp }) => { let time; if (current_time != null) time = current_time.substr(0, 10); return ( <div className="output"> <ul> <li>IP <strong>{ip}</strong></li><div className="bd"></div> <li>Country <strong>{country}</strong></li><div className="bd"></div> <li>TimeZone <strong>{time}</strong></li><div className="bd"></div> <li>ISP <strong>{isp}</strong></li> </ul> </div> ); }; export default Output;
d7b07ba22033c813bd98d0107ee45bc5a22ce298
[ "Markdown", "JavaScript" ]
3
Markdown
hamzadals/geolocation-finder
5cce78f21a56991c200d4f3e0fa42ebb18b1f5b4
903a98a2ed4c4f9e653b303d84b8c3e011b642dd
refs/heads/master
<file_sep>namespace PenaltyCalculation.Migrations { using System; using System.Data.Entity.Migrations; public partial class firstMigration : DbMigration { public override void Up() { CreateTable( "dbo.Country", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Value = c.String(), CreatedAt = c.DateTime(nullable: false), UpdatedAt = c.DateTime(nullable: false), Deleted = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.CountrySettings", c => new { Id = c.Int(nullable: false, identity: true), CountryId = c.Int(nullable: false), PenaltyPrice = c.Double(nullable: false), CreatedAt = c.DateTime(nullable: false), UpdatedAt = c.DateTime(nullable: false), Deleted = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Country", t => t.CountryId, cascadeDelete: true) .Index(t => t.CountryId); CreateTable( "dbo.Holidays", c => new { Id = c.Int(nullable: false, identity: true), CountryId = c.Int(nullable: false), Holiday = c.DateTime(nullable: false), CreatedAt = c.DateTime(nullable: false), UpdatedAt = c.DateTime(nullable: false), Deleted = c.String(), }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.CountrySettings", "CountryId", "dbo.Country"); DropIndex("dbo.CountrySettings", new[] { "CountryId" }); DropTable("dbo.Holidays"); DropTable("dbo.CountrySettings"); DropTable("dbo.Country"); } } } <file_sep>using PenaltyCalculation.Entities; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PenaltyCalculation.Entities { public class PenaltyDbContext : DbContext { public PenaltyDbContext() : base("name=myConnectionString") { } public DbSet<Country> Country { get; set; } public DbSet<CountrySettings> CountrySettings { get; set; } public DbSet<Holidays> Holidays { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); base.OnModelCreating(modelBuilder); } } }<file_sep>using PenaltyCalculation.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PenaltyCalculation.Models { public class ViewModel { public DateTime DateChecked { get; set; } public DateTime DateReturned { get; set; } public string CountryValues { get; set; } } }<file_sep>using MyProjectIndirimix.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; namespace PenaltyCalculation.Entities { public class Holidays : BaseEntity { public int CountryId { get; set; } public DateTime Holiday { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MyProjectIndirimix.Models { public class BaseEntity { public int Id { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } public string Deleted { get; set; } } }<file_sep>using MyProjectIndirimix.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PenaltyCalculation.Entities { public class Country : BaseEntity { public string Name { get; set; } public string Value { get; set; } } }<file_sep>using PenaltyCalculation.Entities; using PenaltyCalculation.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; namespace PenaltyCalculation.Controllers { public class HomeController : Controller { PenaltyDbContext DBContext = new PenaltyDbContext(); public ActionResult Index() { ViewBag.countryValues = new SelectList(DBContext.Country, "Value", "Name"); return View(); } [HttpPost] public ActionResult Index(ViewModel form) { int dayCount = 0; DateTime startDate = form.DateChecked; DateTime finishDate = form.DateReturned; TimeSpan totalDay = finishDate - startDate; double sumDay = totalDay.TotalDays; var Language = ConfigurationManager.AppSettings["Language"]; if (form.CountryValues == Language) { var trCountry = DBContext.Country.Where(x => x.Value == Language).ToList(); for (int i = 0; i < sumDay; i++) { if (startDate.DayOfWeek == DayOfWeek.Sunday || startDate.DayOfWeek == DayOfWeek.Saturday) { startDate = startDate.AddDays(1); continue; } else { dayCount++; } startDate = startDate.AddDays(1); } if (dayCount > 10) { int priceDay = dayCount - 10; ViewBag.PenaltyPrice = priceDay * 5; } } ViewBag.countryValues = new SelectList(DBContext.Country, "Value", "Name"); return View(); } } }
95d429a7f2f703c9558cf53423731cab09d674c7
[ "C#" ]
7
C#
atakangemici/PenaltyCalculation
ccab196ec92142591d1d2e83b0bd30b088783f34
7735250faa0116ba4b879c992548785d43855199
refs/heads/master
<repo_name>agv-polsl/omni_robot_workspace<file_sep>/src/omni_steering_pkg/src/omni_steering_test.cpp #include "ros/ros.h" #include "std_msgs/Float64.h" #include <cmath> #include <iostream> #include <termios.h> #include "lib/steeringNodeHandler.h" using namespace std; using namespace SNH; // Parameters #define L 0.04 // distance between body center and wheel center #define r 0.01905 // wheel radius #define sqrt3 1.732050807568877193176604123436845839023590087890625 #define sqrt32 0.8660254037844385965883020617184229195117950439453125 double Vxm; double Vym; double omegaP; double Vleft, Vright, Vback; enum{ UP = 65, DOWN = 66, RIGHT = 67, LEFT = 68, SPACE = 32 }; void inverseKinematicsMobile(){ Vleft = -(Vxm/2.0) - (sqrt32*Vym) + (L*omegaP); Vright = -(Vxm/2.0) + (sqrt32*Vym) + (L*omegaP); Vback = Vxm + omegaP; return; } // Function to get the currently pressed key int getch() { static struct termios oldt, newt; tcgetattr( STDIN_FILENO, &oldt); // save old settings newt = oldt; newt.c_lflag &= ~(ICANON); // disable buffering tcsetattr( STDIN_FILENO, TCSANOW, &newt); // apply new settings auto c = getchar(); // read character (non-blocking) tcsetattr( STDIN_FILENO, TCSANOW, &oldt); // restore old settings return c; } int main(int argc, char **argv){ ros::init(argc, argv, "Omni_steering"); // Frequency of loop(node) must be highest as possible // because it's reading keyboard actions ros::NodeHandle n; steeringNodeHandler steeringnodehandler(n); ros::Rate loop_rate(1000); Vxm = 0.0; Vym = 0.0; omegaP = 0.0; double speed = 10; inverseKinematicsMobile(); steeringnodehandler.updateVelMsgs(Vleft, Vback, Vright); while (ros::ok()){ auto keyPressed = getch(); // call your non-blocking input function // ROS_ERROR_STREAM("button pressed: " << c); switch (keyPressed){ case UP: ROS_ERROR_STREAM("UP"); Vxm = 0.0; Vym = speed; omegaP = 0.0; break; case DOWN: ROS_ERROR_STREAM("DOWN"); Vxm = 0.0; Vym = -speed; omegaP = 0.0; break; case LEFT: ROS_ERROR_STREAM("LEFT"); Vxm = -speed; Vym = 0.0; omegaP = 0.0; break; case RIGHT: ROS_ERROR_STREAM("RIGHT"); Vxm = speed; Vym = 0.0; omegaP = 0.0; break; case SPACE: ROS_ERROR_STREAM("SPACE"); Vxm = 0.0; Vym = 0.0; omegaP = 0.0; break; default: Vxm = 0.0; Vym = 0.0; omegaP = 0.0; break; } inverseKinematicsMobile(); steeringnodehandler.updateVelMsgs(Vleft, Vback, Vright); steeringnodehandler.publishVelocities(); ros::spinOnce(); loop_rate.sleep(); } return 0; }<file_sep>/src/omni_steering_pkg/src/lib/steeringNodeHandler.h // steeringNodeHandler.h #ifndef STEERING_NODE_HANDLER_H // include guard #define STEERING_NODE_HANDLER_H #include <iostream> #include "ros/ros.h" #include <iostream> #include "std_msgs/Float64.h" namespace SNH{ class steeringNodeHandler{ private: void initializePublishers(ros::NodeHandle& n); public: // Joint topic names std::string left_joint_cmd_topic = "omni_robot/left_joint_velocity_controller/command"; std::string right_joint_cmd_topic = "omni_robot/right_joint_velocity_controller/command"; std::string back_joint_cmd_topic = "omni_robot/back_joint_velocity_controller/command"; // Objects used for publishing data into specified topic ros::Publisher VletfPub; ros::Publisher VrightPub; ros::Publisher VbackPub; // Messages using to publish velocity to joints std_msgs::Float64 VleftMsg; std_msgs::Float64 VrightMsg; std_msgs::Float64 VbackMsg; steeringNodeHandler(ros::NodeHandle& n); void publishVelocities(); void updateVelMsgs(double Vleft, double Vback, double Vright); void printVels(); }; } #endif /* STEERING_NODE_HANDLER_H */<file_sep>/src/omni_steering_pkg/src/test_node.py #!/usr/bin/env python import rospy from keyboard_reader import Key def callback(data): rospy.loginfo(data) def listener(): rospy.init_node('listener', anonymous=True) rospy.Subscriber('keyboard', Key, callback) # spin() simply keeps python from exiting until this node is stopped rospy.spin() if __name__ == '__main__': listener() # import getch # import rospy # from std_msgs.msg import String #String message # from std_msgs.msg import Int8 # def keys(): # pub = rospy.Publisher('key',Int8,queue_size=10) # "key" is the publisher name # rospy.init_node('keypress',anonymous=True) # rate = rospy.Rate(10)#try removing this line ans see what happens # while not rospy.is_shutdown(): # k=ord(getch.getch())# this is used to convert the keypress event in the keyboard or joypad , joystick to a ord value # if ((k>=65)&(k<=68)|(k==115)|(k==113)|(k==97)):# to filter only the up , dowm ,left , right key /// this line can be removed or more key can be added to this # rospy.loginfo(str(k))# to print on terminal # pub.publish(k)#to publish # #rospy.loginfo(str(k)) # #rate.sleep() # #s=115,e=101,g=103,b=98 # if __name__=='__main__': # try: # keys() # except rospy.ROSInterruptException: # pass <file_sep>/src/omni_steering_pkg/CMakeLists.txt cmake_minimum_required(VERSION 2.8.3) project(omni_steering_pkg) ## Compile as C++11, supported in ROS Kinetic and newer # add_compile_options(-std=c++11) ## Find catkin macros and libraries ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) ## is used, also find other catkin packages ## Find catkin and any catkin packages find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg message_generation ) add_message_files( FILES omni_velocity.msg ) generate_messages( DEPENDENCIES std_msgs ) ## Declare a catkin package catkin_package( CATKIN_DEPENDS message_runtime ) ## Build talker and listener include_directories(include ${catkin_INCLUDE_DIRS} lib) add_executable(omni_steering_test_node src/omni_steering_test.cpp src/lib/steeringNodeHandler.cpp ) add_executable(encoder_node src/encoder.cpp ) target_link_libraries(omni_steering_test_node ${catkin_LIBRARIES}) target_link_libraries(encoder_node ${catkin_LIBRARIES}) add_dependencies(encoder_node ${encoder_node_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) add_dependencies(omni_steering_test_node ${omni_steering_test_node_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) <file_sep>/src/omni_steering_pkg/src/lib/steeringNodeHandler.cpp #include "steeringNodeHandler.h" using namespace SNH; void steeringNodeHandler::initializePublishers(ros::NodeHandle& n){ this->VletfPub = n.advertise<std_msgs::Float64>(left_joint_cmd_topic, 1000); this->VrightPub = n.advertise<std_msgs::Float64>(right_joint_cmd_topic, 1000); this->VbackPub = n.advertise<std_msgs::Float64>(back_joint_cmd_topic, 1000); } steeringNodeHandler::steeringNodeHandler(ros::NodeHandle& n){ this->initializePublishers(n); this->VleftMsg.data = 0.0; this->VrightMsg.data = 0.0; this->VbackMsg.data = 0.0; } void steeringNodeHandler::publishVelocities(){ VletfPub.publish(this->VleftMsg); VrightPub.publish(this->VrightMsg); VbackPub.publish(this->VbackMsg); } void steeringNodeHandler::updateVelMsgs(double Vleft, double Vback, double Vright){ this->VleftMsg.data = Vleft; this->VrightMsg.data = Vright; this->VbackMsg.data = Vback; } void steeringNodeHandler::printVels(){ ROS_ERROR_STREAM("Vleft: " << this->VleftMsg.data); ROS_ERROR_STREAM("Vright: "<< this->VrightMsg.data); ROS_ERROR_STREAM("Vback: " << this->VbackMsg.data); } <file_sep>/src/omni_steering_pkg/src/encoder.cpp #include "ros/ros.h" #include <sensor_msgs/JointState.h> #include <std_msgs/Float32.h> #include <omni_steering_pkg/omni_velocity.h> ros::Publisher js_publisher; long double lw_pos_current; // left wheel position long double bw_pos_current; // back wheel position long double rw_pos_current; // right wheel position long double lw_pos_prev; long double bw_pos_prev; long double rw_pos_prev; long double lw_velocity; long double bw_velocity; long double rw_velocity; long double duration; ros::Time timeCurrent; ros::Time timePrevious; omni_steering_pkg::omni_velocity vel_msg; void onJointMessage(const sensor_msgs::JointState::ConstPtr& input){ timeCurrent = ros::Time::now(); for (int i = 0; i < input->name.size(); i++){ if (input->name[i][4] == 'b'){ bw_pos_current = input->position[i]; } else if (input->name[i][4] == 'l'){ lw_pos_current = input->position[i]; } else if (input->name[i][4] == 'r'){ rw_pos_current = input->position[i]; } } duration = (timeCurrent - timePrevious).toSec(); bw_velocity = (bw_pos_current - bw_pos_prev)/duration; lw_velocity = (lw_pos_current - lw_pos_prev)/duration; rw_velocity = (rw_pos_current - rw_pos_prev)/duration; vel_msg.lw_vel = lw_velocity; vel_msg.bw_vel = bw_velocity; vel_msg.rw_vel = rw_velocity; js_publisher.publish(vel_msg); timePrevious = timeCurrent; bw_pos_prev = bw_pos_current; lw_pos_prev = lw_pos_current; rw_pos_prev = rw_pos_current; return; } int main(int argc, char **argv){ ros::init(argc, argv,"encoder"); ros::NodeHandle nh; // waits until it recieves the first /clock message while (!ros::Time::waitForValid()){} // Initializing JointState topic subscriber ros::Subscriber js_subscriber = nh.subscribe("/omni_robot/joint_states",1,onJointMessage); js_publisher = nh.advertise<omni_steering_pkg::omni_velocity>("/wheel_velocity", 1); // Loop processing callbacks ros::spin(); return 0; } <file_sep>/run_gazebo.sh killall gzserver killall gzclient killall rosmaster roslaunch omni_robot velocity_controller.launch
056a79a3ab385bf37c887069bae4761ea2b05c99
[ "Python", "CMake", "C++", "Shell" ]
7
C++
agv-polsl/omni_robot_workspace
5364a96406671ff1b542e88d4c7547e724b6259b
83ca91c88cb8d58e674ed7c697115248e6ecfc39
refs/heads/main
<repo_name>manuelmartin-developer/Devops<file_sep>/Clase47_Docker_II/routes/entries.js const router = require('express').Router(); const entries = require('../controllers/entries') //Endpoints //GET router.get('/entries', entries.getEntries) // POST router.post('/entries',entries.createEntry) // PUT // DELETE // para el alumno... module.exports = router<file_sep>/Clase48_Docker_compose_III/models/product.js const mongoose = require("mongoose"); /* { title: 'test product', price: 13.5, description: 'lorem ipsum set', image: 'https://i.pravatar.cc', category: 'electronic', id:0 } */ const productSchema = new mongoose.Schema({ title: { type: String, unique:true, required:true }, price: Number, description: String, image: { type: String, validate: { validator: function(text) { return text.indexOf('https://') === 0; }, message: 'la URL de la imagen debe empezar por https://' } }, category: String, id: Number }) module.exports = mongoose.model('Product',productSchema) <file_sep>/Clase47_Docker_II/controllers/products.js const Product = require("../models/product"); const products = { getProducts: async (req, res) => { // Fetch de productos let products; try { req.params.id ? (products = await Product.find({ id: Number(req.params.id) })) : (products = await Product.find()); // array objetos console.log(products); res.status(200).json({ products }); } catch (error) { res.status(400).json({ error: error.message }); } }, createProduct: async (req, res) => { let prod = new Product(req.body); // producto a guardar try { const new_product = await prod.save(); // guardar en BBDD console.log(new_product); // {} let products = await Product.find(); // [] let data = [new_product, { products_before: products }]; // [{new},{products_before}] res.status(201).json(data); } catch (error) { res.status(400).json({ error: error.message }); } }, }; module.exports = products; <file_sep>/Clase47_Docker_II/controllers/pages.js const product = require('../utils/product') const pages = { home: (req, res) => { let msj = "Esta es la Home desde PUG!!!" let title= "Home" res.status(200).render("template",{msj,title}); }, about: (req, res) => { let msj = "Esto es About desde PUG!!!" let title= "About" res.status(200).render("template",{msj,title}); }, contact: (req, res) => { res.status(200).send("Esto es contact"); }, location: (req, res) => { res.status(200).send("Esto ess location"); }, pictures: (req, res) => { console.log(req.params); let msj = "Esto es pictures" msj += req.params.id ? ". ID:" + req.params.id : ""; let id = req.params.id res.status(200).render("pictures",{msj,id}); }, products: async (req, res) => { // Fetch de productos let products; req.params.id? products = await product.getProductById(req.params.id): products = await product.getAllProducts() // array objetos res.status(200).render("products",{products}); }, createProduct: async (req,res) => { console.log("*******************"); let prod = req.body // producto a guardar const response = await product.addProduct(prod) console.log(response); res.status(201).json(response) } }; module.exports = pages; <file_sep>/Clase47_Docker_II/utils/product.js const fetch = require('node-fetch') const product = { getAllProducts: async () => { const res = await fetch('https://fakestoreapi.com/products') const data = await res.json() return data }, getProductById: async (id) => { const res = await fetch('https://fakestoreapi.com/products/'+id) const data = await res.json() return [data] }, // Enviar un objeto /* { title: 'test product', price: 13.5, description: 'lorem ipsum set', image: 'https://i.pravatar.cc', category: 'electronic' } */ addProduct: async (product) => { const res = await fetch('https://fakestoreapi.com/products',{ method:"POST", headers: { 'Content-Type': 'application/json' }, body:JSON.stringify(product) }) const data = await res.json() return data } } module.exports = product /* product .addProduct( { title: 'test product', price: 13.5, description: 'lorem ipsum set', image: 'https://i.pravatar.cc', category: 'electronic' }) .then((data)=>console.log(data)) */ /* product .getAllProducts() .then((data)=>console.log(data)) */ /* product .getProductById(5) .then((data)=>console.log(data)) */<file_sep>/Clase47_Docker_II/app.js const express = require('express') require("dotenv").config() // Carga variables de configuracion // require('./utils/db') // lanzar BBDD con Mongoose const pages = require('./routes/pages') const products = require('./routes/products') const entries = require('./routes/entries') const app = express() const port = 3000 // http://localhost:3000/products?key=123hola // function hasApiKey (req,res,next){ // const API_KEY = req.query.key; // if(API_KEY && API_KEY==="123hola"){ // next(); // }else{ // res.status(403).send("403 - Forbidden. You shall not pass"); // } // } // Motor de vistar app.set('view engine', 'pug'); app.set('views','./views'); // Middlewares // app.use(hasApiKey) // Para comprobar Api Key app.use(express.json()); // para convertir a JSON // Rutas // http://localhost:3000/about --> WEB --> vista // http://localhost:3000/api/products --> API --> objeto app.use('/',pages); // para las vistas de la WEB // app.use('/api',products) // para la API app.use('/api',entries) // para la API app.get('*', (req, res) => { res.status(404).send("Sorry...404 Not found"); }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
67f63f7eee0702eac76d8f3d26a5b8ba95c45dec
[ "JavaScript" ]
6
JavaScript
manuelmartin-developer/Devops
3983543a0b38aab095488a0c25756b40a8f6988e
0922285d0177d32e475cda6585c3abff41cfa396
refs/heads/master
<repo_name>Usui22750/pi_livebox<file_sep>/livebox/input.py import tty, sys, termios _save_setting = None def save_setting(): global _save_setting if not _save_setting: fd = sys.stdin.fileno() _save_setting = termios.tcgetattr(fd) def restablish_setting(): global _save_setting if _save_setting: fd = sys.stdin.fileno() termios.tcsetattr(fd, termios.TCSADRAIN, _save_setting) def get_char(): tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) return ch <file_sep>/livebox/init.py import requests import json def init_ip(): with open('./livebox.json', 'r+') as file: try: data = json.load(file) except: data = {} init_ip = True found_ip = None if 'ip' in data: ret = requests.get(data['ip']) found_ip = data['ip'] if ret.status_code == 200: init_ip = False if init_ip: ip = "http://192.168.1.{}:8080" for i in range(0, 255): format_ip = ip.format(i) try: ret = requests.get(format_ip, timeout=0.01) except: continue if ret.status_code == 200: data['ip'] = format_ip found_ip = format_ip break with open('./livebox.json', 'w+') as file: json.dump(data, fp=file) return found_ip <file_sep>/livebox/command.py import requests def _send_command(ip, command): command_ip = "{}:8080/remoteControl/cmd?operation=01&key={}&mode=0".format(ip, str(command)) requests.get(command_ip) def on_off(ip): _send_command(ip, 116) def zero(ip): _send_command(ip, 512) def one(ip): _send_command(ip, 513) def two(ip): _send_command(ip, 514) def three(ip): _send_command(ip, 515) def four(ip): _send_command(ip, 516) def five(ip): _send_command(ip, 517) def six(ip): _send_command(ip, 518) def seven(ip): _send_command(ip, 519) def eight(ip): _send_command(ip, 520) def nine(ip): _send_command(ip, 521) def channel_plus(ip): _send_command(ip, 402) def channel_minus(ip): _send_command(ip, 403) def sound_plus(ip): _send_command(ip, 115) def sound_minus(ip): _send_command(ip, 114) def sound_mute(ip): _send_command(ip, 113) def up(ip): _send_command(ip, 103) def down(ip): _send_command(ip, 108) def left(ip): _send_command(ip, 105) def right(ip): _send_command(ip, 116) def ok(ip): _send_command(ip, 352) def back(ip): _send_command(ip, 158) def menu(ip): _send_command(ip, 139) def play_pause(ip): _send_command(ip, 164) def backward(ip): _send_command(ip, 168) def forward(ip): _send_command(ip, 159) def record(ip): _send_command(ip, 167) def video_on_demand(ip): _send_command(ip, 393) <file_sep>/livebox/__init__.py from livebox.init import init_ip from livebox.input import get_char __all__ = ['init_ip', 'get_char'] <file_sep>/main.py from livebox import init_ip, get_char from livebox import command ip = init_ip()
ac65988db9e58f2a46247b442602971bc78b0f23
[ "Python" ]
5
Python
Usui22750/pi_livebox
606d0429f1603d99cc30141c34d2c3cfed18708b
aacf314016e9f0084442b9fb4d3538b3550cc8b3
refs/heads/master
<file_sep> def makeHibbard(H): h = [1] i = 0 while(h[i]<H): h.append((2**i)-1) i += 1 f = open("Hibbard.txt",'w') h = h[2:] h.sort() index = 0 while h[index]<H: index +=1 h = h[:index] for i in h: f.write(str(i)) f.write(' ') f.close # print('hib',h) def makeSedgewickA(H): h = [0] i = 0 while(h[i]<H): h.append(((4**i)+3*2**(i-1))+1) i += 1 h[1] = 1 h = h[1:] h.sort() index = 0 while h[index]<H: index +=1 h = h[:index] f = open("SedgewickA.txt",'w') for i in h: f.write(str(i)) f.write(' ') f.close # print('sedgea',h) def makeSedgewickB(H): h = [0] i = 0 while(h[i]<H): h.append(4**(i+1)-6*2**(i)+1) i += 1 i = 0 while(h[i]<H): h.append(9*(4**(i-1)-2**(i-1))+1) i += 1 h.sort() index = 0 while h[index]<H: index +=1 h = h[3:index] f = open("SedgewickB.txt",'w') for i in h: f.write(str(i)) f.write(' ') f.close # print('sedgeb',h) def makePratt(H): h = [0] p = [0] q = [0] i = 0 j = 0 while(p[i]<H): p.append(2**i) i += 1 while(q[j]<H): q.append(3**j) j += 1 h = p+q h.sort() # print('p=',p,'\nq=',q,'\nh=',h) for i in range(0,len(p)): for j in range(0,len(q)): temp = (p[i]*q[j]) if temp not in h: h.append(temp) h.sort() index = 0 while h[index]<H: index +=1 h = h[3:index] f = open("Pratt.txt",'w') for i in h: f.write(str(i)) f.write(' ') f.close # print('prat',h) def main(): H = int(input('what is the largest gap value desired?')) h = makeHibbard(H) p = makePratt(H) s1 = makeSedgewickA(H) s2 = makeSedgewickB(H) main() <file_sep>0 def main(): a = [] index = 0 gaps = [] fname = ['gaps.txt'] swaps = 0 comps = 0 for i in fname: with open(i) as f: line = f.readline() line = line.split() gaps.append(0) for l in line: gaps.append(int(l)) index+=1 gaps.reverse() print(gaps) with open('input.txt')as file: for i in range(0,5000,1): try: t = file.readline() a.append(int(t.rstrip())) except ValueError: break #loop for each sequence for k in range(0,len(gaps),1): #for each gap for gap in gaps: #for each item in list for j in range(gap, len(a), 1): comps += 1 if a[j]<a[j-gap]: a[j],a[j-gap] = a[j-gap],a[j] swaps += 1 for p in range(j,0,-(gap)): try: comps += 1 if a[p]<a[p-gap]: swaps += 1 a[p],a[p-gap] = a[p-gap],a[p] except IndexError: break print(a) f = open('output.txt','w') for i in range(0,len(a)): f.write(str(a[i])) f.write('\n') f.close() f = open('Comparison.doc','w') f.write('comparisons = ') f.write(str(comps)) f.write('\n') f.write('swaps = ') f.write(str(swaps)) f.close print('comps =', comps,'\n','swaps =', swaps) main()
a7ad86f34b98eb6b164f2ab7f170fca2085dd5db
[ "Python" ]
2
Python
htulpmada/Shellsort
e8ad03109b4f87d38787371b2f594324c33408e4
8a8f74d7240dbc77fae31a34bc99b451aeca19ee
refs/heads/master
<repo_name>gmlunesa/zhat<file_sep>/README.md # zhat [![Open Source Love](https://badges.frapsoft.com/os/mit/mit.svg?v=102)](https://github.com/ellerbrock/open-source-badge/) A TCP based chat room. ### Overview - **Transmission Control Protocol (TCP)** is one of the main protocols of the Internet protocol suite. - TCP provides reliable, ordered, and error-checked delivery of a stream of octets (bytes) between applications running on hosts communicating by an IP network. [via](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) ### Structure - **Server** provides a port for messages, transmits incoming messages to all connected clients - **Client** can send and receive messages in real time, with multi-threading and an asynchronous I/O framework. ### Technical Details - **Python:** v3.6+ [via](https://www.python.org/) - **ZeroMQ:** a brokerless messaging library [via](https://zeromq.org/) ### Contact - [<EMAIL>](mailto:<EMAIL>) [![forthebadge](http://forthebadge.com/badges/built-with-love.svg)](http://forthebadge.com) <file_sep>/client.py import zmq import argparse import configparser import sys import threading class Client(object): def __init__(self, server_host, server_port, chat_pipe, username): self.server_host = server_host self.server_port = server_port self.chat_socket = None self.chat_pipe = chat_pipe self.username = username self.context = zmq.Context() self.poller = zmq.Poller() def connect_to_server(self): self.chat_socket = self.context.socket(zmq.REQ) connect_address = 'tcp://{}:{}'.format( self.server_host, self.server_port) self.chat_socket.connect(connect_address) def register_poller(self): self.poller.register(self.chat_socket, zmq.POLLIN) def reconnect_to_server(self): # Reset connection self.poller.unregister(self.chat_socket) self.chat_socket.setsockopt(zmq.LINGER, 0) self.chat_socket.close() self.connect_to_server() self.register_poller() # Receive input from user def receive_input(self): return self.chat_pipe.recv_string() def send_message(self, message): data = { 'username': self.username, 'message': message, } self.chat_socket.send_json(data) def receive_reply(self): self.chat_socket.recv() def check_message(self): events = dict(self.poller.poll(3000)) return events.get(self.chat_socket) == zmq.POLLIN def client_constant_loop(self): self.connect_to_server() self.register_poller() while True: message = self.receive_input() self.send_message(message) if self.check_message(): self.receive_reply() else: self.reconnect_to_server() def run(self): thread = threading.Thread(target=self.client_constant_loop) thread.start() def parse_args(): parser = argparse.ArgumentParser(description='Client for teezeepee') # Please specify your username parser.add_argument('username', type=str, help='Specified username') parser.add_argument('--config-file', type=str, help='Default path for configuration file.') return parser.parse_args() if '__main__' == __name__: try: args = parse_args() config_file = args.config_file if args.config_file is not None else 'tzp.cfg' config = configparser.ConfigParser() config.read(config_file) config = config['default'] client = Client(args.username, config['server_host'], config['chat_port']) client.client_constant_loop() except KeyboardInterrupt: pass<file_sep>/tzp.py import zmq import curses import argparse import configparser import threading import time from curses import wrapper from client import Client from ui import UI def parse_args(): parser = argparse.ArgumentParser(description='Client for teezeepee') # Please specify your username parser.add_argument('username', type=str, help='Specified username') parser.add_argument('--config-file', type=str, help='Default path for configuration file.') return parser.parse_args() def display_section(window, display): window_lines, window_cols = window.getmaxyx() bottom_line = window_lines - 1 window.bkgd(curses.A_NORMAL) window.scrollok(1) while True: window.addstr(bottom_line, 1, display.recv_string()) window.move(bottom_line, 1) window.scroll(1) window.refresh() def input_section(window, chat_sender): window.bkgd(curses.A_NORMAL) window.clear() window.box() window.refresh() while True: window.clear() window.box() window.refresh() s = window.getstr(1, 1).decode('utf-8') if s is not None and s != "": chat_sender.send_string(s) # Short pause time.sleep(0.01) def main(stdscr): config_file = args.config_file if args.config_file is not None else 'tzp.cfg' config = configparser.ConfigParser() config.read(config_file) config = config['default'] receiver = zmq.Context().instance().socket(zmq.PAIR) receiver.bind("inproc://clientchat") sender = zmq.Context().instance().socket(zmq.PAIR) sender.connect("inproc://clientchat") client = Client(args.username, config['server_host'], config['chat_port'], receiver) client.run() show_receiver = zmq.Context().instance().socket(zmq.PAIR) show_receiver.bind("inproc://clientdisplay") show_sender = zmq.Context().instance().socket(zmq.PAIR) show_sender.connect("inproc://clientdisplay") ui = UI(config['server_host'], config['display_port'], show_sender) ui.run() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.echo() curses.curs_set(0) window_height = curses.LINES window_width = curses.COLS divider = int(window_height * 0.5) history_screen = stdscr.subpad(divider, window_width, 0, 0) input_screen = stdscr.subpad(window_height - divider, window_width, divider, 0) history_thread = threading.Thread(target=display_section, args=(history_screen, show_receiver)) history_thread.daemon = True history_thread.start() input_thread = threading.Thread(target=input_section, args=(input_screen, sender)) input_thread.daemon = True input_thread.start() history_thread.join() input_thread.join() if '__main__' == __name__: try: args = parse_args() wrapper(main) except KeyboardInterrupt as e: pass except: raise <file_sep>/ui.py import argparse import configparser import sys import threading import zmq class UI(object): def __init__(self, server_host, server_port, ui_pipe): self.server_host = server_host self.server_port = server_port self.context = zmq.Context() self.ui_sock = None self.ui_pipe = ui_pipe self.poller = zmq.Poller() def connect_to_server(self): self.ui_sock = self.context.socket(zmq.SUB) self.ui_sock.setsockopt_string(zmq.SUBSCRIBE, '') connect_address = 'tcp://{}:{}'.format( self.server_host, self.server_port) self.ui_sock.connect(connect_address) self.poller.register(self.ui_sock, zmq.POLLIN) def refresh(self): data = self.ui_sock.recv_json() username, message = data['username'], data['message'] self.ui_pipe.send_string('{}: {}'.format(username, message)) def check_message(self): events = self.poller.poll() return self.ui_sock in events def display_constant_loop(self): self.connect_to_server() while True: self.refresh() def run(self): thread = threading.Thread(target=self.display_constant_loop) thread.daemon = True thread.start() <file_sep>/server.py import zmq import argparse import configparser class Server(object): def __init__(self, chat_interface, chat_port, show_interface, show_port): self.context = zmq.Context() self.chat_interface = chat_interface self.chat_port = chat_port self.show_interface = show_interface self.show_port = show_port self.chat_socket = None self.show_socket = None # Bind respective TCP ports to corresponding sockets def bind_tcp_ports(self): # Reply Module self.chat_socket = self.context.socket(zmq.REP) chat_socket_bind_string = 'tcp://{}:{}'.format(self.chat_interface, self.chat_port) self.chat_socket.bind(chat_socket_bind_string) self.show_socket = self.context.socket(zmq.PUB) show_bind_string = 'tcp://{}:{}'.format(self.show_interface, self.show_port) self.show_socket.bind(show_bind_string) # Return list based on received zmq message def get_message(self): msg = self.chat_socket.recv_json() username = msg['username'] message = msg['message'] return [username, message] # Refresh screen def refresh(self, username, message): data = { 'username' : username, 'message' : message, } self.chat_socket.send(b'\x00') self.show_socket.send_json(data) # Constant loop to receive messages def forever_loop(self): self.bind_tcp_ports() while True: username, message = self.get_message() self.refresh(username, message) # Function to parse argument in the command line def parse_args(): parser = argparse.ArgumentParser(description='Server for teezeepee') parser.add_argument('--config-file', type=str, help='Default path for configuration file.') return parser.parse_args() if '__main__' == __name__: try: args = parse_args() config_file = args.config_file if args.config_file is not None else 'tzp.cfg' config = configparser.ConfigParser() config.read(config_file) config = config['default'] server = Server('*', config['chat_port'], '*', config['display_port']) server.forever_loop() except KeyboardInterrupt: pass
9c285ee99a4cec5f009c0a6e42aa44addb98db51
[ "Markdown", "Python" ]
5
Markdown
gmlunesa/zhat
3bf62625d102bd40274fcd39c91f21c169e334a8
d01da27dfde9afafdaea36b6c893fc0f92ff5657
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Sat Aug 29 13:56:56 2020 @author: VVincent """ #startNumber = 2000 #endNumber = 3200 startNumber = int(input("Provide the starting number: ")) endNumber = int(input("Provide the ending number: ")) listNumber = [] stringNumbers="" for i in range(startNumber, endNumber+1): if(i%7==0 and i%5!=0): listNumber.append(i) if stringNumbers=='': stringNumbers = stringNumbers+str(i) else: stringNumbers = stringNumbers+','+str(i) # print in single line print(stringNumbers)<file_sep># -*- coding: utf-8 -*- """ Created on Sat Aug 29 14:26:19 2020 @author: VVincent """ firstName = input("First Name: ") lastName = input("Last Name:") #fullName = firstName.lower() + ' ' + lastName.lower() fullName = firstName.strip() + ' ' + lastName.strip() print(fullName[::-1])<file_sep># -*- coding: utf-8 -*- """ Created on Sat Aug 29 15:00:06 2020 @author: VVincent """ #Python program to calcualte the volume of sphere with formula V=4/3 * pi * r^3 import math def getVolume(): return lambda r:(4/3)*round(math.pi, 3)*r*r*r sphereDia = float(input("Enter diameter: ")) volume=getVolume() print("Volume: ", round(volume(sphereDia), 3))
10d071a90938da3d3cee573f22672283697f7073
[ "Python" ]
3
Python
vinovstudent/INeuron
c07854b813c46d3794e7173c3c1a578688e1c0b5
5054f38202786a176f692194a76e7b66d151a610
refs/heads/main
<repo_name>UberJason/PageTabViewForWatch<file_sep>/README.md # PageTabViewStyle for watchOS Layout Bug In watchOS 7, PageTabViewStyle was introduced to support paging. Unfortunately, when attempting to use the PageTabViewStyle in a less-than-full-screen size, the content views don't align well. See screenshots below. <img width=1000 src="https://github.com/UberJason/PageTabViewForWatch/blob/main/Simulator%20%2B%20Code.png"> <img src="https://github.com/UberJason/PageTabViewForWatch/blob/main/Simulator.png"> Steps to reproduce: 1. Run this project in a simulator. 2. Observe the layout in the preview, in the application, and in the view debugger. From the view debugger, it appears that although the PageController is sized appropriately, the hosting controller still assumes full size, and also aligns its content at the bottom. Even attempting to enclose the content in an explicit frame with `.top` alignment doesn't appear to help. <img width=1000 src="https://github.com/UberJason/PageTabViewForWatch/blob/main/View%20Debugger.png"><file_sep>/PageTabViewForWatch WatchKit Extension/ContentView.swift // // ContentView.swift // PageTabViewForWatch WatchKit Extension // // Created by <NAME> on 8/3/20. // import SwiftUI struct ContentView: View { var body: some View { VStack { TabView { Rectangle().foregroundColor(.red).frame(maxHeight: 50, alignment: .top) Rectangle().foregroundColor(.blue).frame(maxHeight: 50, alignment: .top) Rectangle().foregroundColor(.green).frame(maxHeight: 50, alignment: .top) } .tabViewStyle(PageTabViewStyle()) .frame(maxHeight: 50) Button("Push Me") { print("push me") } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
1eefcfb05bfddda2bb3b0c0203430ad26665164d
[ "Markdown", "Swift" ]
2
Markdown
UberJason/PageTabViewForWatch
a862d922e07e49594480737d0e8e6dabdb428fdf
ff142b335ea27a6f9831336decb6260dce214ff9
refs/heads/master
<file_sep>import { uploadAttachment } from '../attachment'; jest.mock('fs'); jest.mock('inquirer'); jest.mock('messaging-api-messenger'); jest.mock('recursive-readdir'); jest.mock('../../../shared/log'); jest.mock('../../../shared/getConfig'); const inquirer = require('inquirer'); const { MessengerClient } = require('messaging-api-messenger'); const readdir = require('recursive-readdir'); const log = require('../../../shared/log'); const getConfig = require('../../../shared/getConfig'); const MOCK_FILE_WITH_PLATFORM = { messenger: { accessToken: '__PUT_YOUR_ACCESS_TOKEN_HERE__', appId: '__APP_ID__', appSecret: '__APP_SECRET__', verifyToken: '__verifyToken__', }, }; let _client; describe('uploadAttachment', () => { beforeEach(() => { _client = { getPageInfo: jest.fn(), uploadAttachment: jest.fn(), }; MessengerClient.connect = jest.fn(() => _client); getConfig.mockReturnValue(MOCK_FILE_WITH_PLATFORM.messenger); readdir.mockResolvedValue([ { name: 'The X-Files', }, ]); inquirer.prompt = jest.fn(); inquirer.prompt.mockResolvedValue({ confirm: true, }); process.exit = jest.fn(); }); it('be defined', () => { expect(uploadAttachment).toBeDefined(); }); describe('resolve', () => { it('--yes should work', async () => { const ctx = { argv: { '--force': true, '--yes': true }, }; await uploadAttachment(ctx); expect(inquirer.prompt).not.toBeCalled(); expect(log.print).not.toBeCalledWith('bye'); }); it('--token should work', async () => { const ctx = { argv: { '--force': true, '--yes': true, '--token': '12345' }, }; await uploadAttachment(ctx); expect(MessengerClient.connect).toBeCalledWith('12345'); }); }); describe('reject', () => { it('reject when `accessToken` not found in config file', async () => { const ctx = { argv: {}, }; getConfig.mockReturnValueOnce({ appId: '__APP_ID__', appSecret: '__APP_SECRET__', verifyToken: '__verifyToken__', }); await uploadAttachment(ctx); expect(process.exit).toBeCalled(); expect(log.error).toBeCalledWith( 'accessToken is not found in config file' ); }); it('exit when user does not confirm force upload', async () => { const ctx = { argv: { '--force': true, }, }; inquirer.prompt.mockResolvedValue({ confirm: false, }); await uploadAttachment(ctx); expect(inquirer.prompt).toBeCalledWith([ { type: 'confirm', message: 'Are you sure you want to force upload all assets?', name: 'confirm', }, ]); expect(process.exit).toBeCalled(); }); }); }); <file_sep>/* @flow */ import { type Event } from './Event'; type ViberUser = { id: string, name: string, avatar: string, country: string, language: string, api_version: number, }; type SubscribedEvent = { event: 'subscribed', timestamp: number, user: ViberUser, message_token: number, }; type UnsubscribedEvent = { event: 'unsubscribed', timestamp: number, user_id: string, message_token: number, }; type ConversationStartedEvent = { event: 'conversation_started', timestamp: number, message_token: number, type: 'open', context: string, user: ViberUser, subscribed: false, }; type DeliveredEvent = { event: 'delivered', timestamp: number, message_token: number, user_id: string, }; type SeenEvent = { event: 'seen', timestamp: number, message_token: number, user_id: string, }; type FailedEvent = { event: 'failed', timestamp: number, message_token: number, user_id: string, desc: string, }; type ViberMessage = { type: | 'text' | 'picture' | 'video' | 'file' | 'sticker' | 'contact' | 'url' | 'location', text?: string, media?: string, location?: { lat: string, lot: string, }, contact?: { name: string, phone_number: string, }, tracking_data?: string, file_name?: string, file_size?: number, duration?: number, sticker_id?: number, }; type MessageEvent = { event: 'message', timestamp: number, message_token: number, sender: ViberUser, message: ViberMessage, }; export type ViberRawEvent = | SubscribedEvent | UnsubscribedEvent | ConversationStartedEvent | DeliveredEvent | SeenEvent | FailedEvent | MessageEvent; export default class ViberEvent implements Event { _rawEvent: ViberRawEvent; constructor(rawEvent: ViberRawEvent) { this._rawEvent = rawEvent; } /** * Underlying raw event from Viber. * */ get rawEvent(): ViberRawEvent { return this._rawEvent; } /** * Determine if the event is a message event. * */ get isMessage(): boolean { return this._rawEvent.event === 'message'; } /** * The message object from Viber raw event. * */ get message(): ?ViberMessage { if (this.isMessage) { return ((this._rawEvent: any): MessageEvent).message; } return null; } /** * Determine if the event is a message event which includes text. * */ get isText(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'text' ); } /** * The text string from Viber raw event. * */ get text(): ?string { if (this.isMessage) { return ((this.message: any): ViberMessage).text || null; } return null; } /** * Determine if the event is a message event which includes picture. * */ get isPicture(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'picture' ); } /** * The picture URL from Viber raw event. * */ get picture(): ?string { if (this.isPicture) { return ((this.message: any): ViberMessage).media; } return null; } /** * Determine if the event is a message event which includes video. * */ get isVideo(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'video' ); } /** * The video URL from Viber raw event. * */ get video(): ?string { if (this.isVideo) { return ((this.message: any): ViberMessage).media; } return null; } /** * Determine if the event is a message event which includes file. * */ get isFile(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'file' ); } /** * The file URL from Viber raw event. * */ get file(): ?string { if (this.isFile) { return ((this.message: any): ViberMessage).media; } return null; } /** * Determine if the event is a message event which includes sticker. * */ get isSticker(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'sticker' ); } /** * The sticker id from Viber raw event. * */ get sticker(): ?number { if (this.isSticker) { return ((this.message: any): ViberMessage).sticker_id; } return null; } /** * Determine if the event is a message event which includes contact. * */ get isContact(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'contact' ); } /** * The contact object from Viber raw event. * */ get contact(): ?Object { if (this.isContact) { return ((this.message: any): ViberMessage).contact; } return null; } /** * Determine if the event is a message event which includes URL. * */ get isURL(): boolean { return this.isMessage && ((this.message: any): ViberMessage).type === 'url'; } /** * The URL from Viber raw event. * */ get url(): ?string { if (this.isURL) { return ((this.message: any): ViberMessage).media; } return null; } /** * Determine if the event is a message event which includes location. * */ get isLocation(): boolean { return ( this.isMessage && ((this.message: any): ViberMessage).type === 'location' ); } /** * The location object from Viber raw event. * */ get location(): ?Object { if (this.isLocation) { return ((this.message: any): ViberMessage).location; } return null; } /** * Determine if the event is a subscribed event. * */ get isSubscribed(): boolean { return this._rawEvent.event === 'subscribed'; } /** * The subscribed payload from Viber raw event. * */ get subscribed(): ?SubscribedEvent { if (this.isSubscribed) { return (this._rawEvent: any); } return null; } /** * Determine if the event is an unsubscribed event. * */ get isUnsubscribed(): boolean { return this._rawEvent.event === 'unsubscribed'; } /** * The unsubscribed payload from Viber raw event. * */ get unsubscribed(): ?UnsubscribedEvent { if (this.isUnsubscribed) { return (this._rawEvent: any); } return null; } /** * Determine if the event is a conversation_started event. * */ get isConversationStarted(): boolean { return this._rawEvent.event === 'conversation_started'; } /** * The conversation started payload from Viber raw event. * */ get conversationStarted(): ?ConversationStartedEvent { if (this.isConversationStarted) { return (this._rawEvent: any); } return null; } /** * Determine if the event is a delivered event. * */ get isDelivered(): boolean { return this._rawEvent.event === 'delivered'; } /** * The delivered payload from Viber raw event. * */ get delivered(): ?DeliveredEvent { if (this.isDelivered) { return (this._rawEvent: any); } return null; } /** * Determine if the event is a seen event. * */ get isSeen(): boolean { return this._rawEvent.event === 'seen'; } /** * The seen payload from Viber raw event. * */ get seen(): ?SeenEvent { if (this.isSeen) { return (this._rawEvent: any); } return null; } /** * Determine if the event is a failed event. * */ get isFailed(): boolean { return this._rawEvent.event === 'failed'; } /** * The failed payload from Viber raw event. * */ get failed(): ?FailedEvent { if (this.isFailed) { return (this._rawEvent: any); } return null; } } <file_sep>/* @flow */ import warning from 'warning'; import { type SessionStore } from '../session/SessionStore'; import Bot from './Bot'; import TestConnector from './TestConnector'; export default class TestBot extends Bot { constructor({ sessionStore, fallbackMethods, }: { sessionStore: SessionStore, fallbackMethods?: boolean } = {}) { warning( false, '`TestBot` is under heavy development. API may change between any versions.' ); const connector = new TestConnector({ fallbackMethods }); super({ connector, sessionStore, sync: true }); } async runTests(tests: Array<string>) { const client = ((this.connector: any): TestConnector).client; const requestHandler = this.createRequestHandler(); const rawEvents = tests.map(t => this._createRawEventFromTest(t)); const result = []; for (let i = 0; i < tests.length; i++) { /* eslint-disable no-await-in-loop */ const test = tests[i]; await requestHandler({ payload: '__GET_STARTED__', }); client.mockReset(); // TODO: how to get errors from out of try catch boundary await requestHandler(rawEvents[i]); result.push({ input: test, output: { calls: client.calls, error: null, }, }); client.mockReset(); /* eslint-enable no-await-in-loop */ } return result; } _createRawEventFromTest(test: string) { if (/^\/payload /.test(test)) { const payload = test.split('/payload ')[1]; return { payload, }; } return { message: { text: test, }, }; } } <file_sep>const verifySlackWebhook = () => (req, res, next) => { const { body, params } = req; if (params && params.type && params.type === 'url_verification') { res.end(req.params.challenge); } else if (body && body.type && body.type === 'url_verification') { res.end(req.body.challenge); } else { return next(); } }; export default verifySlackWebhook; <file_sep>import micro from 'micro'; import shortid from 'shortid'; import connectNgrok from '../connectNgrok'; import createRequestHandler from './createRequestHandler'; function createServer(bot, config = {}) { config.verifyToken = config.verifyToken || bot.connector.verifyToken || shortid.generate(); const server = micro(createRequestHandler(bot, config)); const _listen = server.listen.bind(server); server.listen = (...args) => { _listen(...args); if (config.ngrok) { connectNgrok(args[0], (err, url) => { console.log(`webhook url: ${url}/`); }); } if (bot.connector.platform === 'messenger') { console.log(`verify token: ${config.verifyToken}`); } }; return server; } export default createServer; <file_sep>import path from 'path'; export default function loadModule(modulePath) { let mod; try { mod = require(path.resolve(modulePath)); // eslint-disable-line import/no-dynamic-require } catch (err) {} // eslint-disable-line if (!mod) return null; if (typeof mod === 'object' && mod.default) { return mod.default; } return mod; } <file_sep>/* @flow */ import Redis from 'ioredis'; import isNumber from 'lodash/isNumber'; import { type CacheStore } from './CacheStore'; export default class RedisCacheStore implements CacheStore { _redis: Redis; _prefix: string = ''; /* Support all of args supported by `ioredis`: - new Redis() // Connect to 127.0.0.1:6379 - new Redis(6380) // 127.0.0.1:6380 - new Redis(6379, '192.168.1.1') // 192.168.1.1:6379 - new Redis('/tmp/redis.sock') - new Redis({ port: 6379, // Redis port host: '127.0.0.1', // Redis host family: 4, // 4 (IPv4) or 6 (IPv6) password: '<PASSWORD>', db: 0 }) // Connect to 127.0.0.1:6380, db 4, using password "<PASSWORD>" - new Redis('redis://:authpassword@127.0.0.1:6380/4') */ constructor(...args: any) { this._redis = new Redis(...args); } async get(key: string): Promise<mixed> { const val = await this._redis.get(`${this._prefix}${key}`); return this._unserialize(val); } async all(): Promise<Array<mixed>> { let [cursor, keys] = await this._redis.scan('0'); while (cursor !== '0') { /* eslint-disable no-await-in-loop */ const [nextCursor, newkeys] = await this._redis.scan(cursor); cursor = nextCursor; keys = keys.concat(newkeys); } return this._redis.mget(keys); } async put(key: string, value: mixed, minutes: number): Promise<void> { await this._redis.setex( `${this._prefix}${key}`, minutes * 60, this._serialize(value) ); } async forget(key: string): Promise<void> { await this._redis.del(`${this._prefix}${key}`); } async flush(): Promise<void> { await this._redis.flushdb(); } getRedis(): Redis { return this._redis; } getPrefix(): string { return this._prefix; } setPrefix(prefix: string): void { this._prefix = prefix ? `${prefix}:` : ''; } _serialize(value: mixed) { return isNumber(value) ? value : JSON.stringify(value); } _unserialize(value: mixed) { return isNumber(value) ? value : JSON.parse((value: any)); } } <file_sep>/* @flow */ import path from 'path'; export function toAbsolutePath(relativeOrAbsolutePath: string): string { if ( path.isAbsolute(relativeOrAbsolutePath) || relativeOrAbsolutePath.startsWith('~') ) { return relativeOrAbsolutePath; } return path.join(process.cwd(), relativeOrAbsolutePath); } <file_sep>import verifySlackWebhook from '../verifySlackWebhook'; const middleware = verifySlackWebhook(); const createContext = body => ({ request: { body, }, response: {}, }); it('should correctly response the challenge is an url_verification event', () => { const ctx = createContext({ token: '<KEY>', challenge: 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d', type: 'url_verification', }); const next = jest.fn(); middleware(ctx, next); expect(ctx.response.body).toBe( 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d' ); expect(next).not.toBeCalled(); }); it('should call next when request is not an url_verification event', () => { const ctx = createContext({ event: {}, type: 'event_callback', }); const next = jest.fn(); middleware(ctx, next); expect(next).toBeCalled(); }); <file_sep>const { ConsoleBot, middleware } = require('bottender'); const { handler: rxHandler } = require('rx-handler'); const { from } = require('rxjs'); const { debounceTime } = require('rxjs/operators'); const bot = new ConsoleBot(); const handler = rxHandler(); const handlerOberverable = from(handler); bot.onEvent(middleware([handler])); bot.createRuntime(); const handlerObserver = handlerOberverable.pipe(debounceTime(1000)); handlerObserver.subscribe(async context => { console.log(''); // log the message from bot to next line. await context.sendText(`Your final message is "${context.event.text}"`); }); <file_sep>import { json, send } from 'micro'; const verifyLineWebhook = bot => async (req, res) => { const body = await json(req); if (bot.connector.isWebhookVerifyRequest(body)) { send(res, 200); return true; } return false; }; export default verifyLineWebhook; <file_sep>import path from 'path'; import fs from 'fs-extra'; import TestBot from '../../../bot/TestBot'; import loadModule from '../../shared/loadModule'; import { error, print } from '../../shared/log'; import getSubArgs from './utils/getSubArgs'; const test = async ctx => { const argv = getSubArgs(ctx.argv, { '--out-file': String, '-o': '--out-file', }); const inputFile = argv._[1]; const outputFile = argv['--out-file']; const inputFilePath = path.resolve(inputFile); const tests = await fs.readJson(inputFilePath); const bot = new TestBot(); // FIXME: how to find handler and initialState? // find from ./handler or ./src/handler const handler = loadModule('handler') || loadModule('src/handler'); if (!handler) { error('cannot find handler'); return process.exit(1); } bot.onEvent(handler); print('start running tests...'); const result = await bot.runTests(tests); if (outputFile) { const outputFilePath = path.resolve(outputFile); await fs.writeJson(outputFilePath, result); } else { // TODO: how to prettify output console.log(JSON.stringify(result, null, 2)); } }; export default test; <file_sep>/* @flow */ export { default as getAttachment } from './getAttachment'; <file_sep>import getSubArgs from '../getSubArgs'; it('should be defined', () => { expect(getSubArgs).toBeDefined(); }); it('should parse args as expect', () => { const args = ['messenger', 'profile', 'set', '--force']; const ctx = { argv: { _: args, '--token': '__FAKE_TOKEN__', }, }; const result = getSubArgs(ctx.argv, { '--force': Boolean, }); expect(result).toEqual({ _: ['messenger', 'profile', 'set'], '--token': '__FAKE_TOKEN__', '--force': true, }); }); it('should parse args as expect', () => { const args = [ 'messenger', 'persona', 'delete', '--id', '__FAKE_PERSONA_ID__', ]; const ctx = { argv: { _: args, '--token': '__FAKE_TOKEN__', }, }; const result = getSubArgs(ctx.argv, { '--id': String, }); expect(result).toEqual({ _: ['messenger', 'persona', 'delete'], '--token': '__FAKE_TOKEN__', '--id': '__FAKE_PERSONA_ID__', }); }); it('should handle args abbreviation', () => { const args = ['messenger', 'persona', 'delete', '-f', 'other-args']; const ctx = { argv: { _: args, '--token': '__FAKE_TOKEN__', }, }; const result = getSubArgs(ctx.argv, { '--force': Boolean, '-f': '--force', }); expect(result).toEqual({ _: ['messenger', 'persona', 'delete', 'other-args'], '--token': '__FAKE_TOKEN__', '--force': true, }); }); <file_sep>module.exports = require('./lib/koa'); <file_sep>const verifyLineWebhook = bot => ({ request, response }, next) => { if (bot.connector.isWebhookVerifyRequest(request.body)) { response.status = 200; } else { return next(); } }; export default verifyLineWebhook; <file_sep>/* @flow */ import Handler from './Handler'; export default class SlackHandler extends Handler {} <file_sep>const { MessengerBot } = require('bottender'); const { createServer } = require('bottender/express'); const config = require('./bottender.config'); const bot = new MessengerBot(config.messenger); bot.onEvent(async context => { await context.sendText('Hello World'); }); const server = createServer(bot, config); server.listen(5000, () => { console.log('server is running on 5000 port...'); }); <file_sep>import micro from 'micro'; import verifyMessengerSignature from '../verifyMessengerSignature'; jest.mock('micro'); const bot = { connector: { verifySignature: jest.fn(), }, }; const middleware = verifyMessengerSignature(bot); const createReqRes = () => [ { headers: { 'x-hub-signature': 'signature from messenger', }, }, { send: jest.fn(), status: jest.fn(), }, ]; it('should do nothing when verification pass', async () => { const [req, res] = createReqRes(); micro.text.mockResolvedValueOnce('raw body from messenger'); bot.connector.verifySignature.mockReturnValueOnce(true); await middleware(req, res); expect(micro.send).not.toBeCalled(); }); it('should send 400 when verification fail', async () => { const [req, res] = createReqRes(); micro.text.mockReturnValueOnce('raw body from messenger'); bot.connector.verifySignature.mockReturnValueOnce(false); await middleware(req, res); expect(micro.send).toBeCalledWith(res, 400, { error: { message: 'Messenger Signature Validation Failed!', request: { rawBody: 'raw body from messenger', headers: { 'x-hub-signature': 'signature from messenger', }, }, }, }); }); <file_sep>export type ConsoleClient = { sendText(text: string): void, }; <file_sep>import verifyViberSignature from '../verifyViberSignature'; const bot = { connector: { verifySignature: jest.fn(), }, }; const middleware = verifyViberSignature(bot); const createReqRes = () => [ { rawBody: 'raw body from viber', headers: { 'x-viber-content-signature': 'signature from viber', }, }, { send: jest.fn(), status: jest.fn(), }, ]; beforeEach(() => { console.error = jest.fn(); }); it('should call next when verification pass', () => { const [req, res] = createReqRes(); const next = jest.fn(); bot.connector.verifySignature.mockReturnValueOnce(true); middleware(req, res, next); expect(next).toBeCalled(); }); it('should send 400 when verification fail', () => { const [req, res] = createReqRes(); const next = jest.fn(); bot.connector.verifySignature.mockReturnValueOnce(false); middleware(req, res, next); expect(res.status).toBeCalledWith(400); expect(res.send).toBeCalledWith({ error: { message: 'Viber Signature Validation Failed!', request: { rawBody: req.rawBody, headers: { 'x-viber-content-signature': req.headers['x-viber-content-signature'], }, }, }, }); }); <file_sep>const verifySlackWebhook = () => ({ request, response }, next) => { if (request.body.type === 'url_verification') { response.body = request.body.challenge; } else { return next(); } }; export default verifySlackWebhook; <file_sep>import { send, text } from 'micro'; const verifyViberSignature = bot => async (req, res) => { const rawBody = await text(req); const verified = bot.connector.verifySignature( rawBody, req.headers['x-viber-content-signature'] ); if (!verified) { send(res, 400, { error: { message: 'Viber Signature Validation Failed!', request: { rawBody, headers: { 'x-viber-content-signature': req.headers['x-viber-content-signature'], }, }, }, }); } return verified; }; export default verifyViberSignature; <file_sep>import isEmpty from 'lodash/isEmpty'; function createMiddleware(bot) { const requestHandler = bot.createRequestHandler(); return async (req, res, next) => { if (isEmpty(req.query) && !req.body) { throw new Error( 'createMiddleware(): Missing query and body, you may need a body parser. Use `restify.plugins.bodyParser()` before this middleware.' ); } const response = await requestHandler( { ...req.query, ...req.body, }, { req, res, } ); if (response) { res.send(response.status || 200, response.body || '', response.headers); } else { res.send(200); } return next(); }; } export default createMiddleware; <file_sep>import sh from '..'; jest.mock('../init'); jest.mock('../help'); jest.mock('../test'); describe('sh cli', () => { it('should exist', () => { expect(sh).toBeDefined(); }); it('should return init module', () => { const init = require('../init').default; expect(sh.init).toEqual(init); }); it('should return help module', () => { const help = require('../help').default; expect(sh.help).toEqual(help); }); it('should return test module', () => { const test = require('../test').default; expect(sh.test).toEqual(test); }); }); <file_sep>import restify from 'restify'; import registerRoutes from './registerRoutes'; function createServer(bot, config = {}) { const server = restify.createServer(); server.use(restify.plugins.queryParser()); server.use(restify.plugins.bodyParser()); registerRoutes(server, bot, config); return server; } export default createServer; <file_sep>import bodyParser from 'body-parser'; import express from 'express'; import registerRoutes from './registerRoutes'; function createServer(bot, config = {}) { const server = express(); server.use(bodyParser.urlencoded({ extended: false })); server.use( bodyParser.json({ verify: (req, res, buf) => { req.rawBody = buf.toString(); }, }) ); registerRoutes(server, bot, config); return server; } export default createServer; <file_sep>import micro from 'micro'; import verifyLineSignature from '../verifyLineSignature'; jest.mock('micro'); const bot = { connector: { verifySignature: jest.fn(), }, }; const middleware = verifyLineSignature(bot); const createReqRes = () => [ { headers: { 'x-line-signature': 'signature from line', }, }, { send: jest.fn(), status: jest.fn(), }, ]; it('should do nothing when verification pass', async () => { const [req, res] = createReqRes(); micro.text.mockResolvedValueOnce('raw body from line'); bot.connector.verifySignature.mockReturnValueOnce(true); await middleware(req, res); expect(micro.send).not.toBeCalled(); }); it('should send 400 when verification fail', async () => { const [req, res] = createReqRes(); micro.text.mockReturnValueOnce('raw body from line'); bot.connector.verifySignature.mockReturnValueOnce(false); await middleware(req, res); expect(micro.send).toBeCalledWith(res, 400, { error: { message: 'LINE Signature Validation Failed!', request: { rawBody: 'raw body from line', headers: { 'x-line-signature': 'signature from line', }, }, }, }); }); <file_sep>import { RTMClient } from '@slack/client'; import SlackBot from '../SlackBot'; import SlackConnector from '../SlackConnector'; jest.mock('@slack/client'); beforeEach(() => { console.error = jest.fn(); }); it('should construct bot with SlackConnector', () => { const bot = new SlackBot({ accessToken: 'zzzzzZZZZZ', }); expect(bot).toBeDefined(); expect(bot.onEvent).toBeDefined(); expect(bot.createRequestHandler).toBeDefined(); expect(bot.connector).toBeDefined(); expect(bot.connector).toBeInstanceOf(SlackConnector); }); describe('createRtmRuntime', () => { it('should work', () => { const bot = new SlackBot({ accessToken: 'zzzzzZZZZZ', }); const start = jest.fn(); const on = jest.fn(); const handler = jest.fn(); RTMClient.mockImplementation(() => ({ on, start, })); bot.createRequestHandler = jest.fn(() => handler); bot.createRtmRuntime(); expect(on).toBeCalledWith('message', handler); expect(start).toHaveBeenCalledTimes(1); }); }); <file_sep>/* @flow */ export { default as ContextSimulator } from './ContextSimulator'; <file_sep>/* @flow */ import EventEmitter from 'events'; import TestContext from '../context/TestContext'; import TestEvent, { type TestRawEvent } from '../context/TestEvent'; import { type Session } from '../session/Session'; import { type TestClient } from '../context/TestClient'; import { type Connector } from './Connector'; type TestRequestBody = TestRawEvent; type ConstructorOptions = {| client?: TestClient, fallbackMethods?: boolean, |}; const testClient = { calls: [], callMethod(name, args) { this.calls.push({ name, args, }); }, mockReset() { this.calls = []; }, }; export default class TestConnector implements Connector<TestRequestBody> { _client: TestClient; _fallbackMethods: boolean; constructor({ client, fallbackMethods }: ConstructorOptions = {}) { this._client = client || testClient; this._fallbackMethods = fallbackMethods || false; } get platform(): string { return 'test'; } get client(): TestClient { return this._client; } getUniqueSessionKey(): string { return '1'; } async updateSession(session: Session): Promise<void> { if (!session.user) { session.user = { id: '1', name: 'you', _updatedAt: new Date().toISOString(), }; } Object.freeze(session.user); Object.defineProperty(session, 'user', { configurable: false, enumerable: true, writable: false, value: session.user, }); } mapRequestToEvents(body: TestRequestBody): Array<TestEvent> { return [new TestEvent(body)]; } createContext(params: { event: TestEvent, session: ?Session, initialState: ?Object, requestContext: ?Object, emitter?: ?EventEmitter, }) { return new TestContext({ ...params, client: this._client, fallbackMethods: this._fallbackMethods, }); } } <file_sep>import TestBot from '../TestBot'; import TestConnector from '../TestConnector'; it('should construct bot with TestConnector', () => { const bot = new TestBot(); expect(bot).toBeDefined(); expect(bot.onEvent).toBeDefined(); expect(bot.createRequestHandler).toBeDefined(); expect(bot.connector).toBeDefined(); expect(bot.connector).toBeInstanceOf(TestConnector); }); it('should export runTests method', () => { const bot = new TestBot(); expect(bot.runTests).toBeDefined(); }); describe('runTests', () => { it('should work', async () => { const bot = new TestBot(); const handler = async context => { if (context.event.text === 'hello') { await context.sendText('hello +1'); } else if (context.event.text === 'world') { await context.sendText('world +1'); } }; bot.onEvent(handler); const result = await bot.runTests(['hello', 'world']); expect(result).toEqual([ { input: 'hello', output: { calls: [{ args: ['hello +1'], name: 'sendText' }], error: null, }, }, { input: 'world', output: { calls: [{ args: ['world +1'], name: 'sendText' }], error: null, }, }, ]); }); xit('should handle error', async () => { const bot = new TestBot(); const handler = async () => { throw new Error('xxx'); }; bot.onEvent(handler); const result = await bot.runTests(['hello', 'world']); expect(result).toEqual([ { input: 'hello', output: { calls: [], error: {}, }, }, { input: 'world', output: { calls: [], error: {}, }, }, ]); }); }); <file_sep>module.exports = require('./lib/test-utils'); <file_sep>import verifyMessengerSignature from '../verifyMessengerSignature'; const bot = { connector: { verifySignature: jest.fn(), }, }; const middleware = verifyMessengerSignature(bot); const createContext = () => ({ request: { rawBody: 'raw body from messenger', headers: { 'x-hub-signature': 'signature from messenger', }, }, response: {}, }); beforeEach(() => { console.error = jest.fn(); }); it('should call next when verification pass', () => { const ctx = createContext(); const next = jest.fn(); bot.connector.verifySignature.mockReturnValueOnce(true); middleware(ctx, next); expect(next).toBeCalled(); }); it('should send 400 when verification fail', () => { const ctx = createContext(); const next = jest.fn(); bot.connector.verifySignature.mockReturnValueOnce(false); middleware(ctx, next); expect(ctx.response.status).toBe(400); expect(ctx.response.body.error.message).toBe( 'Messenger Signature Validation Failed!' ); }); <file_sep>import ClassifierHandler from '../ClassifierHandler'; const setup = () => { const classifier = { predict: jest.fn(), }; const builder = new ClassifierHandler(classifier, 0.3); return { builder, classifier, }; }; describe('#constructor', () => { it('should construct without error', () => { const { builder } = setup(); expect(ClassifierHandler).toBeDefined(); expect(builder).toBeInstanceOf(ClassifierHandler); }); }); describe('#onIntent', () => { it('should return this', () => { const { builder } = setup(); const handler = () => {}; expect(builder.onIntent('intent_1', handler)).toBe(builder); }); it('handler should be called with context when intent match', async () => { const { builder, classifier } = setup(); const result = { intents: [ { name: 'intent_1', score: 0.5 }, { name: 'intent_2', score: 0.25 }, { name: 'intent_3', score: 0.25 }, ], }; classifier.predict.mockResolvedValue(result); const handler1 = jest.fn(); const handler2 = jest.fn(); builder.onIntent('intent_1', handler1).onIntent('intent_2', handler2); const context = { event: { isText: true, message: { text: 'Hello World', }, }, }; await builder.build()(context); expect(handler1).toBeCalledWith(context, result); expect(handler2).not.toBeCalled(); }); it('should not throw when matched intent handler undefiend', async () => { const { builder, classifier } = setup(); const result = { intents: [ { name: 'intent_1', score: 0.5 }, { name: 'intent_2', score: 0.25 }, { name: 'intent_3', score: 0.25 }, ], }; classifier.predict.mockResolvedValue(result); const handler2 = jest.fn(); builder.onIntent('intent_2', handler2); const context = { event: { isText: true, message: { text: 'Hello World', }, }, }; let error; try { await builder.build()(context); } catch (err) { error = err; } expect(error).toBeUndefined(); }); }); describe('#onUnmatched', () => { it('should return this', () => { const { builder } = setup(); const handler = () => {}; expect(builder.onUnmatched(handler)).toBe(builder); }); it('handler should be called with context when under threshold', async () => { const { builder, classifier } = setup(); const result = { intents: [ { name: 'intent_1', score: 0.25 }, { name: 'intent_2', score: 0.25 }, { name: 'intent_3', score: 0.25 }, { name: 'intent_4', score: 0.25 }, ], }; classifier.predict.mockResolvedValue(result); const handler = jest.fn(); builder.onUnmatched(handler); const context = { event: { isText: true, message: { text: 'Hello World', }, }, }; await builder.build()(context); expect(handler).toBeCalledWith(context, result); }); it('should not throw when no unmatched handler', async () => { const { builder, classifier } = setup(); const result = { intents: [ { name: 'intent_1', score: 0.25 }, { name: 'intent_2', score: 0.25 }, { name: 'intent_3', score: 0.25 }, { name: 'intent_4', score: 0.25 }, ], }; classifier.predict.mockResolvedValue(result); const context = { event: { isText: true, message: { text: 'Hello World', }, }, }; let error; try { await builder.build()(context); } catch (err) { error = err; } expect(error).toBeUndefined(); }); }); describe('#build', () => { it('should return a function', () => { const { builder } = setup(); expect(builder.build()).toBeInstanceOf(Function); }); }); <file_sep>/* @flow */ import { type Session } from './Session'; export interface SessionStore { init(): Promise<SessionStore>; read(key: string): Promise<Session | null>; all(): Promise<Array<Session>>; write(key: string, sess: Session): Promise<void>; destroy(key: string): Promise<void>; } <file_sep>require('dotenv').config(); module.exports = { messenger: { accessToken: process.env.ACCESS_TOKEN, verifyToken: process.env.VERIFY_TOKEN, appId: process.env.APP_ID, appSecret: process.env.APP_SECRET, profile: { get_started: { payload: 'GET_STARTED', }, persistent_menu: [ { locale: 'default', composer_input_disabled: false, call_to_actions: [ { type: 'postback', title: '__TITLE_HERE__', payload: '__PAYLOAD_HERE__', }, { type: 'web_url', title: '__TITLE_HERE__', url: 'http://example.com', }, ], }, ], greeting: [ { locale: 'default', text: 'Hello!', }, ], whitelisted_domains: ['http://example.com'], }, }, }; <file_sep>/* @flow */ import EventEmitter from 'events'; import { type Session } from '../session/Session'; export interface Connector<B> { +platform: string; getUniqueSessionKey(body: B, requestContext?: ?Object): ?string; updateSession(session: Session, body: B): Promise<void>; mapRequestToEvents(body: B): Array<any>; createContext(params: { event: any, session: ?Session, initialState: ?Object, requestContext: ?Object, emitter?: ?EventEmitter, }): any; } <file_sep>import ViberBot from '../ViberBot'; import ViberConnector from '../ViberConnector'; it('should construct bot with ViberConnector', () => { const bot = new ViberBot({ accessToken: 'FAKE_TOKEN', }); expect(bot).toBeDefined(); expect(bot.onEvent).toBeDefined(); expect(bot.createRequestHandler).toBeDefined(); expect(bot.connector).toBeDefined(); expect(bot.connector).toBeInstanceOf(ViberConnector); }); <file_sep>import createMockInstance from 'jest-create-mock-instance'; const MessagingAPILine = jest.genMockFromModule('messaging-api-line'); const { Line, LineClient } = require.requireActual('messaging-api-line'); MessagingAPILine.Line = Line; MessagingAPILine.LineClient.connect = jest.fn(() => createMockInstance(LineClient) ); module.exports = MessagingAPILine; <file_sep>import path from 'path'; import { toAbsolutePath } from '../path'; describe('#toAbsolutePath', () => { it('should return absolute path directly', () => { expect(toAbsolutePath('/foo/bar')).toBe('/foo/bar'); expect(toAbsolutePath('/baz/..')).toBe('/baz/..'); expect(toAbsolutePath('~/')).toBe('~/'); }); it('should transform relative path to absolute path', () => { const cwd = process.cwd(); expect(toAbsolutePath('.')).toBe(`${cwd}`); expect(toAbsolutePath('..')).toBe(path.join(cwd, '..')); expect(toAbsolutePath('bar/baz')).toBe(path.join(cwd, 'bar', 'baz')); }); }); <file_sep>const { ViberBot, ViberHandler } = require('bottender'); const { createServer } = require('bottender/express'); const config = require('./bottender.config').viber; const bot = new ViberBot({ accessToken: config.accessToken, }); const handler = new ViberHandler() .onDelivered(() => { console.log('delivered'); }) .onSeen(() => { console.log('seen'); }) .onFailed(() => { console.log('failed'); }) .onText(/yo/i, async context => { await context.sendText('Hi there!'); }) .onEvent(async context => { await context.sendText("I don't know what you say."); }) .onError(async context => { await context.sendText('Something wrong happened.'); }); bot.onEvent(handler); const server = createServer(bot); server.listen(5000, () => { console.log('server is running on 5000 port...'); }); <file_sep>import { json, send } from 'micro'; const verifySlackWebhook = () => async (req, res) => { const body = await json(req); if (body.type === 'url_verification') { send(res, 200, body.challenge); } }; export default verifySlackWebhook; <file_sep>const verifyMessengerWebhook = ({ verifyToken }) => ({ request, response }) => { if ( request.query['hub.mode'] === 'subscribe' && request.query['hub.verify_token'] === verifyToken ) { response.body = request.query['hub.challenge']; } else { console.error('Failed validation. Make sure the validation tokens match.'); response.status = 403; } }; export default verifyMessengerWebhook; <file_sep>import TestEvent from '../TestEvent'; const textMessage = { message: { text: 'Hello, world', }, }; const payload = { payload: 'A_PAYLOAD', }; it('#rawEvent', () => { expect(new TestEvent(textMessage).rawEvent).toEqual(textMessage); expect(new TestEvent(payload).rawEvent).toEqual(payload); }); it('#isMessage', () => { expect(new TestEvent(textMessage).isMessage).toEqual(true); expect(new TestEvent(payload).isMessage).toEqual(false); }); it('#message', () => { expect(new TestEvent(textMessage).message).toEqual({ text: 'Hello, world', }); expect(new TestEvent(payload).message).toEqual(null); }); it('#isText', () => { expect(new TestEvent(textMessage).isText).toEqual(true); expect(new TestEvent(payload).isText).toEqual(false); }); it('text', () => { expect(new TestEvent(textMessage).text).toEqual('Hello, world'); expect(new TestEvent(payload).text).toEqual(null); }); it('#isPayload', () => { expect(new TestEvent(textMessage).isPayload).toEqual(false); expect(new TestEvent(payload).isPayload).toEqual(true); }); it('payload', () => { expect(new TestEvent(textMessage).payload).toEqual(null); expect(new TestEvent(payload).payload).toEqual('A_PAYLOAD'); }); <file_sep>/* @flow */ import EventEmitter from 'events'; import sleep from 'delay'; import warning from 'warning'; import { ViberClient } from 'messaging-api-viber'; import { type Session } from '../session/Session'; import Context from './Context'; import ViberEvent from './ViberEvent'; import { type PlatformContext } from './PlatformContext'; type Options = {| client: ViberClient, event: ViberEvent, session: ?Session, initialState: ?Object, requestContext: ?Object, emitter: ?EventEmitter, |}; class ViberContext extends Context implements PlatformContext { _client: ViberClient = this._client; _event: ViberEvent = this._event; _session: ?Session = this.session; constructor({ client, event, session, initialState, requestContext, emitter, }: Options) { super({ client, event, session, initialState, requestContext, emitter }); } /** * The name of the platform. * */ get platform(): string { return 'viber'; } /** * Delay and show indicators for milliseconds. * */ async typing(milliseconds: number): Promise<void> { if (milliseconds > 0) { await sleep(milliseconds); } } /** * Send text to the owner of the session. * */ async sendText(text: string, options?: Object): Promise<any> { if (!this._session) { warning( false, 'sendText: should not be called in context without session' ); return; } this._isHandled = true; return this._client.sendText(this._session.user.id, text, options); } /** * Get user details from the owner of the session. * */ async getUserDetails(): Promise<?Object> { if (!this._session) { warning( false, 'getUserDetails: should not be called in context without session' ); return null; } return this._client.getUserDetails(this._session.user.id); } /** * Get user online status from the owner of the session. * */ async getOnlineStatus(): Promise<?Object> { if (!this._session) { warning( false, 'getOnlineStatus: should not be called in context without session' ); return null; } const status = await this._client.getOnlineStatus([this._session.user.id]); return status[0]; } } const sendMethods = [ 'sendMessage', 'sendPicture', 'sendVideo', 'sendFile', 'sendContact', 'sendLocation', 'sendURL', 'sendSticker', 'sendCarouselContent', ]; sendMethods.forEach(method => { Object.defineProperty(ViberContext.prototype, `${method}`, { enumerable: false, configurable: true, writable: true, async value(...args) { if (!this._session) { warning( false, `${method}: should not be called in context without session` ); return; } this._isHandled = true; return this._client[method](this._session.user.id, ...args); }, }); }); export default ViberContext; <file_sep>import compose from 'koa-compose'; import { type Builder } from './Handler'; type Middleware = (context?: any, next?: Middleware) => {}; const middleware = (m: Array<Middleware | Builder>) => compose(m.map(item => (item.build ? item.build() : item))); export default middleware; <file_sep>/* @flow */ import RedisCacheStore from '../cache/RedisCacheStore'; import CacheBasedSessionStore from './CacheBasedSessionStore'; import { type SessionStore } from './SessionStore'; const MINUTES_IN_ONE_YEAR = 365 * 24 * 60; type RedisOption = | number | string | { port?: number, host?: string, family?: number, password?: string, db?: number, }; export default class RedisSessionStore extends CacheBasedSessionStore implements SessionStore { constructor(arg: RedisOption, expiresIn: number) { const cache = new RedisCacheStore(arg); super(cache, expiresIn || MINUTES_IN_ONE_YEAR); } } <file_sep>const verifyMessengerWebhook = ({ verifyToken }) => (req, res) => { if ( req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === verifyToken ) { res.send(req.query['hub.challenge']); } else { console.error('Failed validation. Make sure the validation tokens match.'); res.sendStatus(403); } }; export default verifyMessengerWebhook; <file_sep>/* @flow */ import { type Event } from './Event'; type TelegramUser = { id: number, first_name: string, last_name?: string, username?: string, language_code?: string, }; type Photo = Array<{ file_id: string, width: number, height: number, }>; type Audio = { file_id: string, width: number, height: number, }; type Document = { file_id: string, }; type Sticker = { file_id: string, width: number, height: number, }; type Video = { file_id: string, width: number, height: number, duration: number, }; type Voice = { file_id: string, duration: number, }; type VideoNote = { file_id: string, length: number, duration: number, }; type Contact = { phone_number: string, first_name: string, }; type Location = {| longitude: number, latitude: number, |}; type Venue = { location: Location, title: string, address: string, }; type File = { file_id: string, }; type Game = { title: string, description: string, photo: Array<{ file_id: string, width: number, height: number, }>, }; type Message = { message_id: number, from: TelegramUser, chat: { id: number, first_name: string, last_name: string, type: 'private', }, date: number, text: string, entities: Array<{ type: 'bot_command', offset: number, length: number, }>, reply_to_message?: Message, photo?: Photo, game?: Game, audio?: Audio, document?: Document, sticker?: Sticker, video?: Video, voice?: Voice, video_note?: VideoNote, contact?: Contact, location?: Location, venue?: Venue, file?: File, }; type InlineQuery = { id: string, from: TelegramUser, location?: Location, query: string, offset: string, }; type ChosenInlineResult = { result_id: string, from: TelegramUser, location?: Location, inline_message_id?: string, query: string, }; type CallbackQuery = { from: TelegramUser, message: Message, chat_instance: string, data: string, }; type ShippingAddress = { country_code: string, state: string, city: string, street_line1: string, street_line2: string, post_code: string, }; type ShippingQuery = { id: string, from: TelegramUser, invoice_payload: string, shipping_address: ShippingAddress, }; type OrderInfo = { name?: string, phone_number?: string, email?: string, shipping_address?: ShippingAddress, }; type PreCheckoutQuery = { id: string, from: TelegramUser, currency: string, total_amount: number, invoice_payload: string, shipping_option_id?: string, order_info?: OrderInfo, }; export type TelegramRawEvent = { update_id: number, message?: Message, edited_message?: Message, channel_post?: Message, edited_channel_post?: Message, inline_query?: InlineQuery, chosen_inline_result?: ChosenInlineResult, callback_query?: CallbackQuery, shipping_query?: ShippingQuery, pre_checkout_query?: PreCheckoutQuery, }; export default class TelegramEvent implements Event { _rawEvent: TelegramRawEvent; constructor(rawEvent: TelegramRawEvent) { this._rawEvent = rawEvent; } /** * Underlying raw event from Telegram. * */ get rawEvent(): TelegramRawEvent { return this._rawEvent; } /** * Determine if the event is a message event. * */ get isMessage(): boolean { return !!this._rawEvent.message; } /** * The message object from Telegram raw event. * */ get message(): ?Message { return this._rawEvent.message || null; } /** * Determine if the event is a message event which includes text. * */ get isText(): boolean { return this.isMessage && typeof (this.message: any).text === 'string'; } /** * The text string from Telegram raw event. * */ get text(): ?string { if (this.isText) { return (this.message: any).text; } return null; } /** * Determine if the event which include reply to message. * */ get isReplyToMessage(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return ( !!message.reply_to_message && typeof message.reply_to_message === 'object' ); } /** * The Message object from Telegram raw event which includes reply_to_message. * */ get replyToMessage(): ?Message { if (this.isReplyToMessage) { return (this.message: any).reply_to_message; } return null; } /** * Determine if the event is a message event which includes audio. * */ get isAudio(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.audio && typeof message.audio === 'object'; } /** * The audio object from Telegram raw event. * */ get audio(): ?Audio { if (this.isAudio) { return (this.message: any).audio; } return null; } /** * Determine if the event is a message event which includes document. * */ get isDocument(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.document && typeof message.document === 'object'; } /** * The document object from Telegram raw event. * */ get document(): ?Document { if (this.isDocument) { return (this.message: any).document; } return null; } /** * Determine if the event is a message event which includes game. * */ get isGame(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.game && typeof message.game === 'object'; } /** * The game object from Telegram raw event. * */ get game(): ?Game { if (this.isGame) { return (this.message: any).game; } return null; } /** * Determine if the event is a message event which includes photo. * */ get isPhoto(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.photo && message.photo.length > 0; } /** * The photo object from Telegram raw event. * */ get photo(): ?Photo { if (this.isPhoto) { return (this.message: any).photo; } return null; } /** * Determine if the event is a message event which includes sticker. * */ get isSticker(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.sticker && typeof message.sticker === 'object'; } /** * The sticker object from Telegram raw event. * */ get sticker(): ?Sticker { if (this.isSticker) { return (this.message: any).sticker; } return null; } /** * Determine if the event is a message event which includes video. * */ get isVideo(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.video && typeof message.video === 'object'; } /** * The video object from Telegram raw event. * */ get video(): ?Video { if (this.isVideo) { return (this.message: any).video; } return null; } /** * Determine if the event is a message event which includes voice. * */ get isVoice(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.voice && typeof message.voice === 'object'; } /** * The voice object from Telegram raw event. * */ get voice(): ?Voice { if (this.isVoice) { return (this.message: any).voice; } return null; } /** * Determine if the event is a message event which includes video note. * */ get isVideoNote(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.video_note && typeof message.video_note === 'object'; } /** * The video note object from Telegram raw event. * */ get videoNote(): ?VideoNote { if (this.isVideoNote) { return (this.message: any).video_note; } return null; } /** * Determine if the event is a message event which includes contact. * */ get isContact(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.contact && typeof message.contact === 'object'; } /** * The contact object from Telegram raw event. * */ get contact(): ?Contact { if (this.isContact) { return (this.message: any).contact; } return null; } /** * Determine if the event is a message event which includes location. * */ get isLocation(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.location && typeof message.location === 'object'; } /** * The location object from Telegram raw event. * */ get location(): ?Location { if (this.isLocation) { return (this.message: any).location; } return null; } /** * Determine if the event is a message event which includes venue. * */ get isVenue(): boolean { if (!this.isMessage) return false; const message: Message = (this.message: any); return !!message.venue && typeof message.venue === 'object'; } /** * The venue object from Telegram raw event. * */ get venue(): ?Venue { if (this.isVenue) { return (this.message: any).venue; } return null; } /** * Determine if the event is an edited message event. * */ get isEditedMessage(): boolean { return !!this.editedMessage && typeof this.editedMessage === 'object'; } /** * The edited message from Telegram raw event. * */ get editedMessage(): ?Message { return this._rawEvent.edited_message || null; } /** * Determine if the event is a channel post event. * */ get isChannelPost(): boolean { return !!this.channelPost && typeof this.channelPost === 'object'; } /** * The channel post from Telegram raw event. * */ get channelPost(): ?Message { return this._rawEvent.channel_post || null; } /** * Determine if the event is an edited channel post event. * */ get isEditedChannelPost(): boolean { return ( !!this.editedChannelPost && typeof this.editedChannelPost === 'object' ); } /** * The edited channel post from Telegram raw event. * */ get editedChannelPost(): ?Message { return this._rawEvent.edited_channel_post || null; } /** * Determine if the event is an inline query event. * */ get isInlineQuery(): boolean { return !!this.inlineQuery && typeof this.inlineQuery === 'object'; } /** * The inline query from Telegram raw event. * */ get inlineQuery(): ?InlineQuery { return this._rawEvent.inline_query || null; } /** * Determine if the event is a chosen inline result event. * */ get isChosenInlineResult(): boolean { return ( !!this.chosenInlineResult && typeof this.chosenInlineResult === 'object' ); } /** * The chosen inline result from Telegram raw event. * */ get chosenInlineResult(): ?ChosenInlineResult { return this._rawEvent.chosen_inline_result || null; } /** * Determine if the event is a callback query event. * */ get isCallbackQuery(): boolean { return !!this.callbackQuery && typeof this.callbackQuery === 'object'; } /** * The callback query from Telegram raw event. * */ get callbackQuery(): ?CallbackQuery { return this._rawEvent.callback_query || null; } /** * Determine if the event is a callback query event. * */ get isPayload(): boolean { return this.isCallbackQuery; } /** * The payload string from Telegram raw event. * */ get payload(): ?string { if (this.isPayload) { return (this.callbackQuery: any).data; } return null; } /** * Determine if the event is a shipping query event. * */ get isShippingQuery(): boolean { return !!this.shippingQuery && typeof this.shippingQuery === 'object'; } /** * The shipping query from Telegram raw event. * */ get shippingQuery(): ?ShippingQuery { return this._rawEvent.shipping_query || null; } /** * Determine if the event is a pre checkout query event. * */ get isPreCheckoutQuery(): boolean { return !!this.preCheckoutQuery && typeof this.preCheckoutQuery === 'object'; } /** * The pre checkout query from Telegram raw event. * */ get preCheckoutQuery(): ?PreCheckoutQuery { return this._rawEvent.pre_checkout_query || null; } } <file_sep>import jsonfile from 'jsonfile'; import getAttachment from '../getAttachment'; jest.spyOn(jsonfile, 'readFileSync'); beforeEach(() => { jsonfile.readFileSync.mockReturnValue({ messenger: { 'test.jpg': { attachment_id: '1591074914293017', pageId: '1134713619902816', uploaded_at: 1511499731235, checksum: '74a5a3dea048513deeaa2c2ea448f45b653c1783101e3a8c9feb5901691c3b8e5603e28501b39e841283eb52dcd2408e370bcd7ddd195f0326ff5ce26fe45bb3', }, 'example.png': { attachment_id: '1591074914203918', pageId: '1134713619902816', uploaded_at: 1511499731946, checksum: 'c4cb482b6e7eb1a79f101e3a8c9feb92216392ea448f45b6519f0fb127420f498e055a86b723b86b3436204ea7d30de2d494580b563c947841421f80c6328de', }, }, }); }); it('should be defined', () => { expect(getAttachment).toBeDefined(); }); it('should return object with id', () => { const attachment = getAttachment('test.jpg'); expect(attachment.id).toBe('1591074914293017'); }); <file_sep>import invariant from 'invariant'; let ngrok; /* eslint-disable global-require, no-empty, import/no-extraneous-dependencies */ try { ngrok = require('ngrok'); } catch (err) {} /* eslint-enable */ const connectNgrok = (port, ngrokHandler) => { invariant( ngrok, 'You must install `ngrok` npm package using `npm install ngrok` or `yarn add ngrok` to connect ngrok.' ); if (typeof port === 'number') { return ngrok.connect(port, ngrokHandler); } return ngrok.connect(ngrokHandler); }; export default connectNgrok; <file_sep>import line from '..'; jest.mock('../menu'); describe('LINE cli', () => { it('should exist', () => { expect(line).toBeDefined(); }); it('should return menu module', () => { const menu = require('../menu').default; expect(line.menu).toEqual(menu); }); }); <file_sep>export type TestClient = { calls: Array<{ name: string, args: Array<any>, }>, callMethod(name: string, args: Array<any>): void, mockReset(): void, }; <file_sep>import CacheBasedSessionStore from '../CacheBasedSessionStore'; import MemorySessionStore from '../MemorySessionStore'; it('should be instanceof CacheBasedSessionStore', () => { expect(new MemorySessionStore()).toBeInstanceOf(CacheBasedSessionStore); expect(new MemorySessionStore(500)).toBeInstanceOf(CacheBasedSessionStore); }); <file_sep>/* @flow */ export interface Event { +rawEvent: ?{}; +isMessage: boolean; +isText: boolean; +message: ?{}; } <file_sep>const verifyMessengerSignature = bot => (req, res, next) => { if ( bot.connector.verifySignature(req.rawBody, req.headers['x-hub-signature']) ) { return next(); } const error = { message: 'Messenger Signature Validation Failed!', request: { rawBody: req.rawBody, headers: { 'x-hub-signature': req.headers['x-hub-signature'], }, }, }; console.error(error); res.status(400); res.send({ error }); }; export default verifyMessengerSignature; <file_sep>/* @flow */ export type Session = { [key: string]: any, }; <file_sep>/* @flow */ import { type Event } from './Event'; type Message = { text: string, }; export type TestRawEvent = { message?: Message, payload?: string, }; export default class TestEvent implements Event { _rawEvent: TestRawEvent; constructor(rawEvent: TestRawEvent) { this._rawEvent = rawEvent; } /** * Underlying raw event from Test. * */ get rawEvent(): TestRawEvent { return this._rawEvent; } /** * Determine if the event is a message event. * */ get isMessage(): boolean { return !!this._rawEvent.message; } /** * The message object from Test raw event. * */ get message(): ?Message { return this._rawEvent.message || null; } /** * Determine if the event is a message event which includes text. * */ get isText(): boolean { if (this.isMessage) { return true; } return false; } /** * The text string from Test raw event. * */ get text(): ?string { if (this.isText) { return ((this.message: any): Message).text; } return null; } /** * Determine if the event is a payload event. * */ get isPayload(): boolean { return !!this._rawEvent.payload; } /** * The payload string from Test raw event. * */ get payload(): ?string { return this._rawEvent.payload || null; } } <file_sep>import getArgs from './getArgs'; const getSubArgs = (argv, argsOptions, argOptions = { permissive: true }) => { const { _, ...rest } = argv; return { ...getArgs(_, argsOptions, argOptions), ...rest, }; }; export default getSubArgs; <file_sep>import readline from 'readline'; import once from 'once'; import ConsoleBot from '../ConsoleBot'; import ConsoleConnector from '../ConsoleConnector'; jest.mock('readline'); it('should construct bot with ConsoleConnector', () => { const bot = new ConsoleBot(); expect(bot).toBeDefined(); expect(bot.onEvent).toBeDefined(); expect(bot.createRequestHandler).toBeDefined(); expect(bot.connector).toBeDefined(); expect(bot.connector).toBeInstanceOf(ConsoleConnector); }); it('should export createRuntime method', () => { const bot = new ConsoleBot(); expect(bot.createRuntime).toBeDefined(); }); describe('createRuntime', () => { beforeEach(() => { process.stdout.write = jest.fn(); process.exit = jest.fn(); }); it('should work', () => { const bot = new ConsoleBot(); const handler = jest.fn(); bot.onEvent(handler); readline.createInterface.mockReturnValue({ once: once((string, fn) => fn()), close: jest.fn(), }); bot.createRuntime(); expect(readline.createInterface).toBeCalledWith({ input: process.stdin, output: process.stdout, }); expect(process.stdout.write).toBeCalledWith('You > '); }); it('should exit when entering /quit', () => { const bot = new ConsoleBot(); const handler = jest.fn(); bot.onEvent(handler); readline.createInterface.mockReturnValue({ once: once((string, fn) => fn('/quit')), close: jest.fn(), }); bot.createRuntime(); expect(process.exit).toBeCalled(); }); it('should exit when entering /exit', () => { const bot = new ConsoleBot(); const handler = jest.fn(); bot.onEvent(handler); readline.createInterface.mockReturnValue({ once: once((string, fn) => fn('/exit')), close: jest.fn(), }); bot.createRuntime(); expect(process.exit).toBeCalled(); }); it('should call handler with text event when receive random text', async () => { const bot = new ConsoleBot(); let context; bot.onEvent(ctx => { context = ctx; }); readline.createInterface.mockReturnValue({ once: once((string, fn) => fn('random text')), close: jest.fn(), }); bot.createRuntime(); await new Promise(process.nextTick); expect(context.event.isText).toBe(true); expect(context.event.text).toBe('random text'); }); it('should call handler with payload event when receive /payload <payload>', async () => { const bot = new ConsoleBot(); let context; bot.onEvent(ctx => { context = ctx; }); readline.createInterface.mockReturnValue({ once: once((string, fn) => fn('/payload A_PAYLOAD')), close: jest.fn(), }); bot.createRuntime(); await new Promise(process.nextTick); expect(context.event.isPayload).toBe(true); expect(context.event.payload).toBe('A_PAYLOAD'); }); }); <file_sep>export default class ClassifierHandler { constructor(classifier, threshold) { this._classifier = classifier; this._threshold = threshold; this._intentHandlers = []; this._unmatchedHandler = null; } onIntent(intent, handler) { this._intentHandlers.push({ intent, handler: handler.build ? handler.build() : handler, }); return this; } onUnmatched(handler) { this._unmatchedHandler = handler.build ? handler.build() : handler; return this; } build() { return async context => { if (context.event.isText) { const result = await this._classifier.predict(context.event.text); const intent = result.intents.sort((a, b) => { if (a.score > b.score) return -1; if (a.score < b.score) return 1; return 0; })[0]; if (intent.score > this._threshold) { const intentHandler = this._findMatchIntentHandler(intent.name); if (intentHandler) { await intentHandler.handler(context, result); } } else if (this._unmatchedHandler) { await this._unmatchedHandler(context, result); } } }; } _findMatchIntentHandler(intent) { return this._intentHandlers.find( intentHandler => intentHandler.intent === intent ); } } <file_sep>import createMockInstance from 'jest-create-mock-instance'; const MessagingAPIMessenger = jest.genMockFromModule('messaging-api-messenger'); const { MessengerClient } = require.requireActual('messaging-api-messenger'); MessagingAPIMessenger.MessengerClient.connect = jest.fn(() => createMockInstance(MessengerClient) ); module.exports = MessagingAPIMessenger; <file_sep>import path from 'path'; import get from 'lodash/get'; import jsonfile from 'jsonfile'; import pkgDir from 'pkg-dir'; const getAttachment = filename => { const rootPath = pkgDir.sync(); const pathOfLockFile = path.resolve(rootPath, 'bottender-lock.json'); const lockfile = jsonfile.readFileSync(pathOfLockFile); return { id: get(lockfile, ['messenger', filename, 'attachment_id']), }; }; export default getAttachment; <file_sep>import { delivery, echoMessage as echo, read } from './MessengerEvent.spec'; jest.mock('delay'); jest.mock('messaging-api-messenger'); jest.mock('warning'); let MessengerClient; let MessengerContext; let MessengerEvent; let warning; beforeEach(() => { /* eslint-disable global-require */ MessengerClient = require('messaging-api-messenger').MessengerClient; MessengerContext = require('../MessengerContext').default; MessengerEvent = require('../MessengerEvent').default; warning = require('warning'); /* eslint-enable global-require */ }); const _rawEvent = { sender: { id: '1423587017700273' }, recipient: { id: '404217156637689' }, timestamp: 1491796363181, message: { mid: 'mid.$cAAE1UUyiiwthh0NPrVbVf4HFNDGl', seq: 348847, text: 'There is no royal road to learning.', }, }; const userSession = { user: { id: 'fakeUserId', }, }; const setup = ( { session = userSession, customAccessToken, rawEvent = _rawEvent } = { session: userSession, customAccessToken: undefined, _rawEvent, } ) => { const client = MessengerClient.connect(); const args = { client, event: new MessengerEvent(rawEvent), session, customAccessToken, }; const context = new MessengerContext(args); return { context, session, client, }; }; describe('#sendTemplate', () => { it('should call client.sendTemplate', async () => { const { context, client, session } = setup(); await context.sendTemplate({ template_type: 'button', text: 'title', buttons: [ { type: 'postback', title: 'Start Chatting', payload: 'USER_DEFINED_PAYLOAD', }, ], }); expect(client.sendTemplate).toBeCalledWith( session.user.id, { template_type: 'button', text: 'title', buttons: [ { type: 'postback', title: 'Start Chatting', payload: 'USER_DEFINED_PAYLOAD', }, ], }, { messaging_type: 'RESPONSE', } ); }); }); describe('#sendGenericTemplate', () => { it('should call client.sendGenericTemplate', async () => { const { context, client, session } = setup(); const elements = {}; const ratio = ''; await context.sendGenericTemplate(elements, { image_aspect_ratio: ratio }); expect(client.sendGenericTemplate).toBeCalledWith( session.user.id, elements, { image_aspect_ratio: ratio, messaging_type: 'RESPONSE', } ); }); it('can call with tag', async () => { const { context, client, session } = setup(); const elements = {}; await context.sendGenericTemplate(elements, { tag: 'ISSUE_RESOLUTION' }); expect(client.sendGenericTemplate).toBeCalledWith( session.user.id, elements, { messaging_type: 'MESSAGE_TAG', tag: 'ISSUE_RESOLUTION', } ); }); it('can call with custom messaging_type', async () => { const { context, client, session } = setup(); const elements = {}; await context.sendGenericTemplate(elements, { messaging_type: 'UPDATE' }); expect(client.sendGenericTemplate).toBeCalledWith( session.user.id, elements, { messaging_type: 'UPDATE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const elements = {}; const ratio = ''; await context.sendGenericTemplate(elements, { image_aspect_ratio: ratio }); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const elements = {}; const ratio = ''; await context.sendGenericTemplate(elements, { image_aspect_ratio: ratio }); expect(warning).toBeCalledWith( false, 'sendGenericTemplate: should not be called in context without session' ); expect(client.sendGenericTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const elements = {}; const ratio = ''; await context.sendGenericTemplate(elements, { image_aspect_ratio: ratio }); expect(warning).toBeCalledWith( false, 'sendGenericTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendGenericTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const elements = {}; const ratio = ''; await context.sendGenericTemplate(elements, { image_aspect_ratio: ratio }); expect(warning).toBeCalledWith( false, 'sendGenericTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendGenericTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const elements = {}; const ratio = ''; await context.sendGenericTemplate(elements, { image_aspect_ratio: ratio }); expect(warning).toBeCalledWith( false, 'sendGenericTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendGenericTemplate).not.toBeCalled(); }); }); describe('#sendButtonTemplate', () => { it('should call client.sendButtonTemplate', async () => { const { context, client, session } = setup(); const buttons = []; await context.sendButtonTemplate('yayaya', buttons); expect(client.sendButtonTemplate).toBeCalledWith( session.user.id, 'yayaya', buttons, { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const buttons = []; await context.sendButtonTemplate('yayaya', buttons); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const buttons = []; await context.sendButtonTemplate('yayaya', buttons); expect(warning).toBeCalledWith( false, 'sendButtonTemplate: should not be called in context without session' ); expect(client.sendButtonTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const buttons = []; await context.sendButtonTemplate('yayaya', buttons); expect(warning).toBeCalledWith( false, 'sendButtonTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendButtonTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const buttons = []; await context.sendButtonTemplate('yayaya', buttons); expect(warning).toBeCalledWith( false, 'sendButtonTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendButtonTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const buttons = []; await context.sendButtonTemplate('yayaya', buttons); expect(warning).toBeCalledWith( false, 'sendButtonTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendButtonTemplate).not.toBeCalled(); }); }); describe('#sendListTemplate', () => { it('should call client.sendListTemplate', async () => { const { context, client, session } = setup(); const elements = []; const buttons = []; await context.sendListTemplate(elements, buttons, { top_element_style: 'large', }); expect(client.sendListTemplate).toBeCalledWith( session.user.id, elements, buttons, { top_element_style: 'large', messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const elements = []; const buttons = []; await context.sendListTemplate(elements, buttons, 'large'); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const elements = []; const buttons = []; await context.sendListTemplate(elements, buttons, 'large'); expect(warning).toBeCalledWith( false, 'sendListTemplate: should not be called in context without session' ); expect(client.sendListTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const elements = []; const buttons = []; await context.sendListTemplate(elements, buttons, 'large'); expect(warning).toBeCalledWith( false, 'sendListTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendListTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const elements = []; const buttons = []; await context.sendListTemplate(elements, buttons, 'large'); expect(warning).toBeCalledWith( false, 'sendListTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendListTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const elements = []; const buttons = []; await context.sendListTemplate(elements, buttons, 'large'); expect(warning).toBeCalledWith( false, 'sendListTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendListTemplate).not.toBeCalled(); }); }); describe('#sendOpenGraphTemplate', () => { it('should call client.sendOpenGraphTemplate', async () => { const { context, client, session } = setup(); await context.sendOpenGraphTemplate([ { media_type: 'image', attachment_id: '1854626884821032', buttons: [ { type: 'web_url', url: 'https://en.wikipedia.org/wiki/Rickrolling', title: 'View Website', }, ], }, ]); expect(client.sendOpenGraphTemplate).toBeCalledWith( session.user.id, [ { media_type: 'image', attachment_id: '1854626884821032', buttons: [ { type: 'web_url', url: 'https://en.wikipedia.org/wiki/Rickrolling', title: 'View Website', }, ], }, ], { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const elements = []; await context.sendOpenGraphTemplate(elements); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const elements = []; await context.sendOpenGraphTemplate(elements); expect(warning).toBeCalledWith( false, 'sendOpenGraphTemplate: should not be called in context without session' ); expect(client.sendOpenGraphTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const elements = []; await context.sendOpenGraphTemplate(elements); expect(warning).toBeCalledWith( false, 'sendOpenGraphTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendOpenGraphTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const elements = []; await context.sendOpenGraphTemplate(elements); expect(warning).toBeCalledWith( false, 'sendOpenGraphTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendOpenGraphTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const elements = []; await context.sendOpenGraphTemplate(elements); expect(warning).toBeCalledWith( false, 'sendOpenGraphTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendOpenGraphTemplate).not.toBeCalled(); }); }); describe('#sendMediaTemplate', () => { it('should call client.sendMediaTemplate', async () => { const { context, client, session } = setup(); await context.sendMediaTemplate([ { url: 'https://open.spotify.com/track/7GhIk7Il098yCjg4BQjzvb', buttons: [ { type: 'web_url', url: 'https://en.wikipedia.org/wiki/Rickrolling', title: 'View More', }, ], }, ]); expect(client.sendMediaTemplate).toBeCalledWith( session.user.id, [ { url: 'https://open.spotify.com/track/7GhIk7Il098yCjg4BQjzvb', buttons: [ { type: 'web_url', url: 'https://en.wikipedia.org/wiki/Rickrolling', title: 'View More', }, ], }, ], { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const elements = []; await context.sendMediaTemplate(elements); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const elements = []; await context.sendMediaTemplate(elements); expect(warning).toBeCalledWith( false, 'sendMediaTemplate: should not be called in context without session' ); expect(client.sendMediaTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const elements = []; await context.sendMediaTemplate(elements); expect(warning).toBeCalledWith( false, 'sendMediaTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendMediaTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const elements = []; await context.sendMediaTemplate(elements); expect(warning).toBeCalledWith( false, 'sendMediaTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendMediaTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const elements = []; await context.sendMediaTemplate(elements); expect(warning).toBeCalledWith( false, 'sendMediaTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendMediaTemplate).not.toBeCalled(); }); }); describe('#sendReceiptTemplate', () => { it('should call client.sendReceiptTemplate', async () => { const { context, client, session } = setup(); const receipt = {}; await context.sendReceiptTemplate(receipt); expect(client.sendReceiptTemplate).toBeCalledWith( session.user.id, receipt, { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const receipt = {}; await context.sendReceiptTemplate(receipt); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const receipt = {}; await context.sendReceiptTemplate(receipt); expect(warning).toBeCalledWith( false, 'sendReceiptTemplate: should not be called in context without session' ); expect(client.sendReceiptTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const receipt = {}; await context.sendReceiptTemplate(receipt); expect(warning).toBeCalledWith( false, 'sendReceiptTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendReceiptTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const receipt = {}; await context.sendReceiptTemplate(receipt); expect(warning).toBeCalledWith( false, 'sendReceiptTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendReceiptTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const receipt = {}; await context.sendReceiptTemplate(receipt); expect(warning).toBeCalledWith( false, 'sendReceiptTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendReceiptTemplate).not.toBeCalled(); }); }); describe('#sendAirlineBoardingPassTemplate', () => { it('should call client.sendAirlineBoardingPassTemplate', async () => { const { context, client, session } = setup(); const boardingPass = {}; await context.sendAirlineBoardingPassTemplate(boardingPass); expect(client.sendAirlineBoardingPassTemplate).toBeCalledWith( session.user.id, boardingPass, { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const boardingPass = {}; await context.sendAirlineBoardingPassTemplate(boardingPass); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const boardingPass = {}; await context.sendAirlineBoardingPassTemplate(boardingPass); expect(warning).toBeCalledWith( false, 'sendAirlineBoardingPassTemplate: should not be called in context without session' ); expect(client.sendAirlineBoardingPassTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const boardingPass = {}; await context.sendAirlineBoardingPassTemplate(boardingPass); expect(warning).toBeCalledWith( false, 'sendAirlineBoardingPassTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineBoardingPassTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const boardingPass = {}; await context.sendAirlineBoardingPassTemplate(boardingPass); expect(warning).toBeCalledWith( false, 'sendAirlineBoardingPassTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineBoardingPassTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const boardingPass = {}; await context.sendAirlineBoardingPassTemplate(boardingPass); expect(warning).toBeCalledWith( false, 'sendAirlineBoardingPassTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineBoardingPassTemplate).not.toBeCalled(); }); }); describe('#sendAirlineCheckinTemplate', () => { it('should call client.sendAirlineCheckinTemplate', async () => { const { context, client, session } = setup(); const checkin = {}; await context.sendAirlineCheckinTemplate(checkin); expect(client.sendAirlineCheckinTemplate).toBeCalledWith( session.user.id, checkin, { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const checkin = {}; await context.sendAirlineCheckinTemplate(checkin); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const checkin = {}; await context.sendAirlineCheckinTemplate(checkin); expect(warning).toBeCalledWith( false, 'sendAirlineCheckinTemplate: should not be called in context without session' ); expect(client.sendAirlineCheckinTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const checkin = {}; await context.sendAirlineCheckinTemplate(checkin); expect(warning).toBeCalledWith( false, 'sendAirlineCheckinTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineCheckinTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const checkin = {}; await context.sendAirlineCheckinTemplate(checkin); expect(warning).toBeCalledWith( false, 'sendAirlineCheckinTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineCheckinTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const checkin = {}; await context.sendAirlineCheckinTemplate(checkin); expect(warning).toBeCalledWith( false, 'sendAirlineCheckinTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineCheckinTemplate).not.toBeCalled(); }); }); describe('#sendAirlineItineraryTemplate', () => { it('should call client.sendAirlineItineraryTemplate', async () => { const { context, client, session } = setup(); const itinerary = {}; await context.sendAirlineItineraryTemplate(itinerary); expect(client.sendAirlineItineraryTemplate).toBeCalledWith( session.user.id, itinerary, { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const itinerary = {}; await context.sendAirlineItineraryTemplate(itinerary); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const itinerary = {}; await context.sendAirlineItineraryTemplate(itinerary); expect(warning).toBeCalledWith( false, 'sendAirlineItineraryTemplate: should not be called in context without session' ); expect(client.sendAirlineItineraryTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const itinerary = {}; await context.sendAirlineItineraryTemplate(itinerary); expect(warning).toBeCalledWith( false, 'sendAirlineItineraryTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineItineraryTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const itinerary = {}; await context.sendAirlineItineraryTemplate(itinerary); expect(warning).toBeCalledWith( false, 'sendAirlineItineraryTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineItineraryTemplate).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const itinerary = {}; await context.sendAirlineItineraryTemplate(itinerary); expect(warning).toBeCalledWith( false, 'sendAirlineItineraryTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendAirlineItineraryTemplate).not.toBeCalled(); }); }); describe('#sendAirlineFlightUpdateTemplate', () => { it('should call client.sendAirlineFlightUpdateTemplate', async () => { const { context, client, session } = setup(); const flightUpdate = {}; await context.sendAirlineFlightUpdateTemplate(flightUpdate); expect(client.sendAirlineFlightUpdateTemplate).toBeCalledWith( session.user.id, flightUpdate, { messaging_type: 'RESPONSE', } ); }); it('should mark context as handled', async () => { const { context } = setup(); const flightUpdate = {}; await context.sendAirlineFlightUpdateTemplate(flightUpdate); expect(context.isHandled).toBe(true); }); it('should call warning and not to send if dont have session', async () => { const { context, client } = setup({ session: false }); const flightUpdate = {}; await context.sendAirlineFlightUpdateTemplate(flightUpdate); expect(warning).toBeCalledWith( false, 'sendAirlineFlightUpdateTemplate: should not be called in context without session' ); expect(client.sendImage).not.toBeCalled(); }); it('should call warning and not to send if created with read event', async () => { const { context, client } = setup({ rawEvent: read }); const flightUpdate = {}; await context.sendAirlineFlightUpdateTemplate(flightUpdate); expect(warning).toBeCalledWith( false, 'sendAirlineFlightUpdateTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendImage).not.toBeCalled(); }); it('should call warning and not to send if created with delivery event', async () => { const { context, client } = setup({ rawEvent: delivery }); const flightUpdate = {}; await context.sendAirlineFlightUpdateTemplate(flightUpdate); expect(warning).toBeCalledWith( false, 'sendAirlineFlightUpdateTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendImage).not.toBeCalled(); }); it('should call warning and not to send if created with echo event', async () => { const { context, client } = setup({ rawEvent: echo }); const flightUpdate = {}; await context.sendAirlineFlightUpdateTemplate(flightUpdate); expect(warning).toBeCalledWith( false, 'sendAirlineFlightUpdateTemplate: calling Send APIs in `message_reads`(event.isRead), `message_deliveries`(event.isDelivery) or `message_echoes`(event.isEcho) events may cause endless self-responding, so they are ignored by default.\nYou may like to turn off subscription of those events or handle them without Send APIs.' ); expect(client.sendImage).not.toBeCalled(); }); }); <file_sep>import micro from 'micro'; import verifySlackWebhook from '../verifySlackWebhook'; jest.mock('micro'); const middleware = verifySlackWebhook(); const createContext = body => ({ request: { body, }, response: {}, }); it('should not response the challenge if it is not an url_verification event', async () => { const { req, res } = createContext({ token: '<KEY>', challenge: 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d', }); micro.json.mockReturnValueOnce({ token: '<KEY>', challenge: 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d', }); await middleware(req, res); expect(micro.send).not.toBeCalled(); }); it('should correctly response the challenge if it is an url_verification event', async () => { const { req, res } = createContext({ token: '<KEY>', challenge: 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d', type: 'url_verification', }); micro.json.mockReturnValueOnce({ token: '<KEY>', challenge: 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d', type: 'url_verification', }); await middleware(req, res); expect(micro.send).toBeCalledWith( res, 200, 'kImeZUaSI0jJLowDasma5WEiffaScgsjnINWDlpapA9fB7uCB36d' ); }); <file_sep>/* @flow */ import { type CacheStore } from '../cache/CacheStore'; import { type Session } from './Session'; import { type SessionStore } from './SessionStore'; const MINUTES_IN_ONE_YEAR = 365 * 24 * 60; export default class CacheBasedSessionStore implements SessionStore { _cache: CacheStore; // The number of minutes to store the data in the session. _expiresIn: number; constructor(cache: CacheStore, expiresIn: number) { this._cache = cache; this._expiresIn = expiresIn || MINUTES_IN_ONE_YEAR; } async init(): Promise<CacheBasedSessionStore> { // $FlowFixMe return this; } async read(key: string): Promise<Session> { return (this._cache.get(key): any); } async all(): Promise<Array<Session>> { return (this._cache.all(): any); } async write(key: string, sess: Session): Promise<void> { this._cache.put(key, sess, this._expiresIn); } async destroy(key: string): Promise<void> { this._cache.forget(key); } } <file_sep>const verifySlackSignature = bot => (req, res, next) => { if (bot.connector.verifySignature(req.body.token)) { return next(); } const error = { message: 'Slack Verification Token Validation Failed!', request: { body: req.body, }, }; console.error(error); res.status(400); res.send({ error }); }; export default verifySlackSignature;
e6420450cbbc6260e91ddc109a9251512f1cca52
[ "JavaScript" ]
68
JavaScript
tech89/bottender
9b1f577b0be51ada39a0bfad21a88d073f836a02
eb5989045c873553796576d65b663f43844afcb8
refs/heads/master
<repo_name>NicoDB79/vip-template<file_sep>/VIP Module.xctemplate/___FILEBASENAME___Models.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import UIKit enum ___VARIABLE_ModuleName___Models { struct Request { } struct Response { } struct ___VARIABLE_ModuleName___Model { } } <file_sep>/VIP Module.xctemplate/___FILEBASENAME___Router.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation import UIKit class ___VARIABLE_ModuleName___Router { // MARK: Properties weak var view: UIViewController? // MARK: Static methods static func createModule() -> ___VARIABLE_ModuleName___ViewController { //MARK: Initialise components. let viewController = ___VARIABLE_ModuleName___ViewController() let presenter = ___VARIABLE_ModuleName___Presenter() let interactor = ___VARIABLE_ModuleName___Interactor() let router = ___VARIABLE_ModuleName___Router() //MARK: link VIP components. viewController.interactor = interactor viewController.router = router presenter.viewController = viewController interactor.presenter = presenter router.view = viewController return viewController } } extension ___VARIABLE_ModuleName___Router: ___VARIABLE_ModuleName___RouterProtocol { // TODO: Implement Router Methods } <file_sep>/README.md # VIP Template Xcode File Template for generating VIP modules: View, Interactor, Presenter, and Router. Written in Swift 5 # How To Install 1. Clone the repository 2. Navigate to Xcode Templates folder: ```~/Library/Developer/Xcode/Templates/```. If Templates folder doesn't exist, create it 3. Copy and paste the VIP Module.xctemplate in Templates folder # Use 1. Open Xcode 2. ```File -> New -> File``` or ```⌘ N``` 3. Scroll down till you see ```VIP Module``` template and choose it. 4. Set a name for your module. Examples: ```Home, Auth, SignIn``` # Generated Code Let's suppose we wanted to create the Home module. Here's how it would look: ### Contract ```HomeContract.swift``` ```swift import Foundation // MARK: View Protocol protocol HomeViewProtocol: class { } // MARK: Interactor Protocol protocol HomeInteractorProtocol { } // MARK: Presenter Protocol protocol HomePresenterProtocol { } // MARK: Router Protocol protocol HomeRouterProtocol { } ``` ### View ```HomeViewController.swift``` ```swift import UIKit class HomeViewController: UIViewController { // MARK: - Properties var interactor: HomeInteractorProtocol? var router: HomeRouterProtocol? // MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() } } extension HomeViewController: HomeViewProtocol{ // TODO: Implement View Output Methods } ``` ### Interactor ```HomeInteractor.swift``` ```swift import Foundation class HomeInteractor { // MARK: Properties var presenter: HomePresenterProtocol? } extension HomeInteractor: HomeInteractorProtocol { // TODO: Implement Interactor Methods } ``` ### Presenter ```HomePresenter.swift``` ```swift import Foundation class HomePresenter { // MARK: Properties weak var viewController: HomeViewProtocol? } extension HomePresenter: HomePresenterProtocol { // TODO: Implement Presenter Methods } ``` ### Router ```AuthRouter.swift``` ```swift import Foundation import UIKit class HomeRouter { // MARK: Properties weak var view: UIViewController? // MARK: Static methods static func createModule() -> UIViewController { //MARK: Initialise components. let viewController = HomeViewController() let presenter = HomePresenter() let interactor = HomeInteractor() let router = HomeRouter() //MARK: link VIP components. viewController.interactor = interactor viewController.router = router presenter.viewController = viewController interactor.presenter = presenter router.view = viewController return viewController } } extension HomeRouter: HomeRouterProtocol { // TODO: Implement Router Methods } ``` <file_sep>/VIP Module.xctemplate/___FILEBASENAME___Contract.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation // MARK: View Protocol protocol ___VARIABLE_ModuleName___ViewProtocol: class { } // MARK: Interactor Protocol protocol ___VARIABLE_ModuleName___InteractorProtocol { } // MARK: Presenter Protocol protocol ___VARIABLE_ModuleName___PresenterProtocol { } // MARK: Router Protocol protocol ___VARIABLE_ModuleName___RouterProtocol { } <file_sep>/VIP Module.xctemplate/___FILEBASENAME___Presenter.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation class ___VARIABLE_ModuleName___Presenter { // MARK: Properties weak var viewController: ___VARIABLE_ModuleName___ViewProtocol? } extension ___VARIABLE_ModuleName___Presenter: ___VARIABLE_ModuleName___PresenterProtocol { // TODO: Implement Presenter Methods } <file_sep>/VIP Module.xctemplate/___FILEBASENAME___Interactor.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // import Foundation class ___VARIABLE_ModuleName___Interactor { // MARK: Properties var presenter: ___VARIABLE_ModuleName___PresenterProtocol? } extension ___VARIABLE_ModuleName___Interactor: ___VARIABLE_ModuleName___InteractorProtocol { // TODO: Implement Interactor Methods }
bb26319ee35885f9c4bf60083879a8350f162bb8
[ "Swift", "Markdown" ]
6
Swift
NicoDB79/vip-template
a3d1898970fd3a5622811926fac3907756dd61f1
7ce8ec524ed2f7ade4e6cf5806201a1beff3b47c
refs/heads/master
<file_sep># Římské číslice Římské číslice představují způsob zápisu čísel pomocí několika vybraných písmen latinské abecedy ([Wikipedia](https://cs.wikipedia.org/wiki/%C5%98%C3%ADmsk%C3%A9_%C4%8D%C3%ADslice)). Naprogramujte převodník římských čísel (`string`) na číselnou podobu (`int`). Otestujte svůj algoritmus minimálně na následujících příkladech: ```csharp Console.WriteLine(calculator.RomanToArabic("I")); // 1 Console.WriteLine(calculator.RomanToArabic("VIII")); // 8 Console.WriteLine(calculator.RomanToArabic("XXI")); // 21 Console.WriteLine(calculator.RomanToArabic("CLXXIII")); // 173 Console.WriteLine(calculator.RomanToArabic("MDCLXVI")); // 1666 Console.WriteLine(calculator.RomanToArabic("MDCCCXXII")); // 1822 Console.WriteLine(calculator.RomanToArabic("MCMLIV")); // 1954 Console.WriteLine(calculator.RomanToArabic("MCMXC")); // 1990 Console.WriteLine(calculator.RomanToArabic("MMVIII")); // 2008 Console.WriteLine(calculator.RomanToArabic("MMXIV")); // 2014 ``` ## Challenges 1. Implementujte jako třídu, která budou funkčnost zapouzdřovat. 2. Vytvořte i opačný směr převodu, z číselné hodnoty `int` na římskou podobu `string`. 3. Vytvořte normalizátor zápisu, který převede libovolný římský vstup na standardní podobu, např. z `IIX` na `VIII`, nebo `IIII` na `IV`, atp. ## Inspirace ```csharp var calculator = new RomanNumeralsCalculator(); Console.WriteLine(calculator.RomanToArabic("I")); // 1 Console.WriteLine(calculator.RomanToArabic("VIII")); // 8 Console.WriteLine(calculator.RomanToArabic("XXI")); // 21 Console.WriteLine(calculator.RomanToArabic("CLXXIII")); // 173 Console.WriteLine(calculator.RomanToArabic("MDCLXVI")); // 1666 Console.WriteLine(calculator.RomanToArabic("MDCCCXXII")); // 1822 Console.WriteLine(calculator.RomanToArabic("MCMLIV")); // 1954 Console.WriteLine(calculator.RomanToArabic("MCMXC")); // 1990 Console.WriteLine(calculator.RomanToArabic("MMVIII")); // 2008 Console.WriteLine(calculator.RomanToArabic("MMXIV")); // 2014 public class RomanNumeralsCalculator { private Dictionary<char, int> charValues; public RomanNumeralsCalculator() { charValues = new Dictionary<char, int>(); charValues.Add('I', 1); charValues.Add('V', 5); charValues.Add('X', 10); charValues.Add('L', 50); charValues.Add('C', 100); charValues.Add('D', 500); charValues.Add('M', 1000); } public int RomanToArabic(string roman) { if (roman.Length == 0) return 0; roman = roman.ToUpper(); int total = 0; int lastValue = 0; for (int i = roman.Length - 1; i >= 0; i--) { int new_value = charValues[roman[i]]; // přičítáme nebo odečítáme? if (new_value < lastValue) { total -= new_value; } else { total += new_value; lastValue = new_value; } } return total; } } ``` <file_sep># Unikátní číslo v řadě Na vstupu je řada čísel. Všechna čísla jsou stejná až na jedno. Najděte ho! ``` 1, 2, 2, 2 => 1 1, 2, 1, 1 => 2 -2, 2, 2, 2 => -2 2, 2, 14, 2, 2 => 14 3, 3, 3, 3, 4 => 4 ``` Je zaručeno, že na vstupu jsou minimálně tři čísla. Je zaručeno, že vstup odpovídá zadání (např. neobsahuje třetí hodnotu). Pozor, na vstupu mohou být i velmi velké řady čísel. **Najděte co nejefektivnější postup, jak unikátní číslo co nejdříve objevit.** (Nepoužívejte LINQ, sestavte algoritmus pomocí primitivních operací - porovnání a přiřazení.) ## Challenge 1. Algoritmus sestavte nad tzv. streamem, tj. v každém kroku algoritmu máte k dispozici vždy jen poslední hodnotu řady, vše ostatní si musíte obstarat sami. Implementovat lze pomocí postupného cyklu s `Console.ReadLine()`, nad `IEnumerable<>`, nebo pomocí třídy `Stream`. 2. Rozšiřte algoritmus o detekci chybných vstupů - třetího různého čísla, malého počtu čísel, atp. 3. Přemýšlejte nad detekcí dvojnásobného výskytu hledaného čísla. Máme dlouho řadu stejných čísel a jedno jiné číslo je v řadě zamíchání 2x. Které to je? ## Inspirace ```csharp Console.WriteLine(GetUnique(new int[] { 1, 2, 2, 2 })); // 1 Console.WriteLine(GetUnique(new int[] { 1, 2, 1, 1 })); // 2 Console.WriteLine(GetUnique(new int[] { -2, 2, 2, 2 })); // -2 Console.WriteLine(GetUnique(new int[] { 2, 2, 14, 2, 2 })); // 14 Console.WriteLine(GetUnique(new int[] { 3, 3, 3, 3, 4 })); // 4 int GetUnique(IEnumerable<int> numbers) { int? prevNum = null; int? lastNum = null; bool diff = false; foreach (int n in numbers) { if (diff && (n == lastNum)) { return prevNum.Value; } if (n != lastNum) { if (lastNum != null) { diff = true; } if ((prevNum == lastNum) && lastNum.HasValue) { return n; } else if (prevNum == n) { return lastNum.Value; } else if ((lastNum == n) && prevNum.HasValue) { return prevNum.Value; } } prevNum = lastNum; lastNum = n; } return -1; } ``` <file_sep>while (true) { Console.Write("Zadejte výraz k výpočtu: "); string input = Console.ReadLine(); try { int result = Calculate(input); Console.WriteLine($"Výsledek: {result}"); } catch (DivideByZeroException) { Console.WriteLine("Chyba: Nelze dělit nulou!"); } catch (FormatException) { Console.WriteLine("Chyba: Nespravný formát vstupu!"); } catch (OverflowException) { Console.WriteLine("Chyba: Vstup nebo výsledek je mimo rozsah typu Int32!"); } catch (MyMissingOperatorException ex) { Console.WriteLine($"Chyba: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Chyba: {ex.Message}"); } Console.WriteLine(); } int Calculate(string input) { if (input.Contains("/")) { string[] parts = input.Split('/'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left / right; } else if (input.Contains("*")) { string[] parts = input.Split('*'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left * right; } else if (input.Contains("+")) { string[] parts = input.Split('+'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left + right; } else if (input.Contains("-")) { string[] parts = input.Split('-'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left - right; } throw new MyMissingOperatorException("Chybí operátor!"); } public class MyMissingOperatorException : Exception { public MyMissingOperatorException() : base() { } public MyMissingOperatorException(string message) : base(message) { } }<file_sep>var account1 = new BankAccount("Adam", 0); Console.WriteLine($"Account {account1.Number} was created for {account1.Owner} with {account1.Balance} initial balance."); account1.MakeDeposit(500, DateTime.Now, "Friend paid me back"); Console.WriteLine(account1.Balance); account1.MakeWithdrawal(100, DateTime.Now, "Rent payment"); Console.WriteLine(account1.Balance); Console.WriteLine(account1.GetAccountHistory()); var account2 = new BankAccount("David", 100); Console.WriteLine($"Account {account2.Number} was created for {account2.Owner} with {account2.Balance} initial balance."); account2.MakeDeposit(200, DateTime.Now, "Gift from parents"); account2.MakeWithdrawal(30, DateTime.Now, "Games subscription"); account2.MakeDeposit(1800, DateTime.Now, "Salary"); Console.WriteLine(account2.GetAccountHistory()); <file_sep>using System; namespace PolePocitaniCisel { class Program { static void Main(string[] args) { Console.Write("Zadej hausnumero:"); var vstup = Console.ReadLine(); int[] cetnostCislic = new int[10]; foreach (var prvek in vstup) { var cislice = Convert.ToInt32(prvek.ToString()); cetnostCislic[cislice] = cetnostCislic[cislice] + 1; } for (int i = 0; i < cetnostCislic.Length; i++) { Console.WriteLine($"Číslice {i} je tam {cetnostCislic[i]}x."); } } } } <file_sep>using System; using System.Data.SqlClient; namespace DatabaseConnector { class Program { static void Main(string[] args) { using var conn = new SqlConnection("***"); conn.Open(); using var cmd = new SqlCommand("SELECT COUNT(*) FROM Zapisnik", conn); Console.WriteLine(cmd.ExecuteScalar()); cmd.CommandText = "INSERT INTO Zapisnik(Jmeno, Obsah) VALUES('První pokus', 'Hokus pokus')"; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT COUNT(*) FROM Zapisnik"; Console.WriteLine(cmd.ExecuteScalar()); using var cmd2 = new SqlCommand("SELECT TOP 10 * FROM Customer", conn); using (var reader = cmd2.ExecuteReader()) { while (reader.Read()) { var firstName = reader["FirstName"]; var lastName = reader["LastName"]; Console.WriteLine($"Načten zákazník: {firstName} {lastName}"); } } } } } <file_sep># Kurzovní lístek - zpracování textových dat Česká národní banka publikuje oficiální kurzy měn pro každý den na svých webových stránkách: https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/ Pro snažší strojové zpracování publikuje vždy i strukturovanou textovou podobu: https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/denni_kurz.txt Data vypadají zhruba takto (počet řádků zkrácen): ``` 08.12.2021 #236 země|měna|množství|kód|kurz Austrálie|dolar|1|AUD|16,077 Brazílie|real|1|BRL|4,021 Bulharsko|lev|1|BGN|13,025 Čína|žen-min-pi|1|CNY|3,552 Dánsko|koruna|1|DKK|3,426 EMU|euro|1|EUR|25,475 ``` Napište miniaplikaci, která stáhne aktuální kurzovní lístek z webu ČNB a vypíše jej uživateli v této podobě: ![Exchange Rates](exchange-rates.png) ## Bude se vám hodit #### Získání obsahu webové stránky do string ```csharp using var httpClient = new HttpClient(); string pageContent = await httpClient.GetStringAsync(url); ``` `HttpClient` je třída, která nám umožňuje komunikovat s HTTP servery. `using` zajišťuje řádný úklid, když už není HttpClient potřeba, např. aby nezůstalo otevřené spojení na server, atp. `await` se používá při volání tzv. asynchronních operací, abychom neblokovali procesor, když čekáme na výsledek nějaké I/O akce. ## Challenge 1 Webu ČNB lze předat požadované datum, z kterého kurzovní lístek chceme: https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/denni_kurz.txt?date=07.12.2021 Vylepšete aplikaci tak, že do výstupu přidá informaci, jak se kurz změnil oproti hodnotě z předchozího dne (třeba v procentech). ## Challenge 2 Vypište tabulku, kde v řádcích i sloupcích budou jednotlivé měny a v příslušné buňce bude jejich vzájemný kurz, např. 1 EUR = 1,17 USD. Příklady výstupů: https://www.google.com/search?q=exchange+rates+cross+table&tbm=isch ## Inspirace ```csharp const string url = "https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/denni_kurz.txt"; using var httpClient = new HttpClient(); string cnbWebContent = await httpClient.GetStringAsync(url); var lines = cnbWebContent.Split('\n'); for (int i = 2; i < lines.Length; i++) { var line = lines[i]; if (!line.Contains("|")) { continue; } var segments = line.Split('|'); var country = segments[0]; var currencyName = segments[1]; var amount = Convert.ToDecimal(segments[2]); var currencyCode = segments[3]; var exchangeRate = segments[4]; Console.Write(country.PadRight(25)); Console.Write(currencyName.PadRight(15)); Console.Write(String.Format("{0:n2} ", exchangeRate).PadLeft(10)); Console.Write($"CZK / {amount} {currencyCode}"); Console.WriteLine(); } ```<file_sep>namespace DirReduction { [TestClass] public class DirReductionTests { [TestMethod] public void Test1() { string[] a = new string[] { "NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST" }; string[] b = new string[] { "WEST" }; CollectionAssert.AreEqual(b, DirReduction.dirReduc(a)); } [TestMethod] public void Test2() { string[] a = new string[] { "NORTH", "WEST", "SOUTH", "EAST" }; string[] b = new string[] { "NORTH", "WEST", "SOUTH", "EAST" }; CollectionAssert.AreEqual(b, DirReduction.dirReduc(a)); } } }<file_sep>Console.WriteLine("Zadejte číslo:"); var input = Console.ReadLine(); var output = DigitalRoot1_StringBased(input); Console.WriteLine($"Digital root: {output}"); var output2 = DigitalRoot2_Numeric(Convert.ToInt64(input)); Console.WriteLine($"Digital root: {output2}"); string DigitalRoot1_StringBased(string number) { if (number.Length == 1) { return number; } long sum = 0; foreach (char digit in number) { if (Char.IsDigit(digit)) { sum = sum + (int)Char.GetNumericValue(digit); } } return DigitalRoot1_StringBased(sum.ToString()); } long DigitalRoot2_Numeric(long number) { if (number < 10) { return number; } long sum = 0; do { sum = sum + number % 10; number = number / 10; } while (number > 1); sum = sum + number; return DigitalRoot2_Numeric(sum); } <file_sep># Bankovní účty II. (OOP základy) Navazujeme na předchozí cvičení [Bankovní účet](https://github.com/hakenr/Programiste.CSharp/tree/master/BankingOop#readme), na kterém jsme si ukazovali třídy a jejich základní členy (properties, methods, fields, constructor). Nyní rozšíříme model bankovnictví o různé typy účtů a podíváme se na základní aspekty *objektově orientovaného programování (OOP)*: * abstrakci, * zapouzdření, * dědičnost, * polymorfizmus. Úloha se překrývá s Microsoft tutorialem OOP: * https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/oop - anglicky * https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/tutorials/oop ## Výchozí stav Budeme pokračovat se zdrojovými kódy z minulého cvičení - třídy `BankAccount` a `Transaction`. Pokud je nemáte k dispozici, použijte jako základ [tento kód](https://github.com/hakenr/Programiste.CSharp/blob/master/BankingOop/BankingOop/Program.cs), který si zkopírujte do nového projektu. ## Úkol Úkolem je zavést do modelu bankovnictví nové typy účtů: * `InterestEarningAccount` - "Spořící účet" - Na konci každého měsíce získá vkladatel úroky. * `LineOfCreditAccount` - "Úvěrový účet" - Může mít záporný zůstatek, z kterého se platí měsíční úroky. Transakce do záporu jsou zpoplatněny. * `GiftCardAccount` - "Předplacený účet dárkového poukazu" - Začíná s určitým vkladem a lze ho jenom čerpat. Jednou za měsíc (na začátku) může být znovu nabit. ## `InterestEarningAccount` - "Spořící účet" * Na konci každého měsíce získá úrok 2% ze zůstatku. * Jinak se chová jako běžný účet. ## `LineOfCreditAccount` - "Úvěrový účet" * Může mít záporný zůstatek, ale neměl by být větší než na začátku přidělený limit - výši úvěru (`creditLimit`). * Na konci každého měsíce, pokud je zůstatek menší než 0, je nutné zaplatit úrok z úvěru (v procentech ze zůstatku). * Pokud výjimečně dojde k přečerpání přiděleného úvěrového limitu, je nutné zaplatit mimořádný poplatek `$20`. ## `GiftCardAccount` - "Předplacený účet dárkového poukazu" * Na konci každého měsíce se automaticky připíše nový měsíční vklad v předem dané výši, něco jako pravidelné kapesné. *Poznámka: Model bankovnictvím je zde pro výukové účely značně zjednodušen. Ve skutečném bankovnictvím má například každá transakce dvě strany - dva účty, mezi kterými se transakce provádí.* ![Screenshot2](screenshot2.png) ## Challenges (volitelná rozšíření zadání) 1. U spořícího účtu implementujte úrokovou tabulku. Pokud je zůstatek menší než X, neúročí se, zůstatek v rozmezí Y..Z se úročí sazbou A, zůstatek vetší než Z se úroční nízkou sazbou B. 2. U spořícího účtu implementujte "termínovost" - dovolte výběry pouze v určité periodě - např. jen v první den v měsíci. 3. U úvěrového účtu implementujte vyšší úrokovou sazbu za čerpání přes limit. 4. U předplaceného účtu dárkového poukazu implementujte počet období, po které se bude automaticky obnovovat, potom skončí. 5. Přidejte na všechny účty poplatky dle vlastního uvážení - pravidelný poplatek za vedení účtu, poplatek za každou transakci, atp. 5. Implementujte model samostatného transakčního deníku, kdy každá transakce bude mít dvě strany - `From` a `To`. Vytvořte účet pro banku, z kterého bude banka klientům připisovat úroky a naopak na něj bude dostávat bankovní poplatky. ## Inspirace Kromě Microsoft dokumentace najdete možné řešení i zde (třídy jsou v samostatných souborech): https://github.com/hakenr/Programiste.CSharp/tree/master/BankingOop2/BankingOop2<file_sep>using System.Diagnostics; long dim1size = 1024 * 1024; long dim2size = 3 * 1024; //ulong[] obj = new ulong[size]; var obj = Array.CreateInstance(typeof(Int64), dim1size, dim2size); Console.WriteLine($"{dim1size * dim2size * 8:n0} bytes"); /* 8 = Int64 */ Console.WriteLine("Writing..."); for (int d = 0; d < dim2size; d++) { for (long i = 0; i < dim1size; i++) obj.SetValue(i, i, d); } Console .WriteLine(obj.GetValue(153, 0)); Console.WriteLine(obj.GetLongLength(0)); Console.ReadLine(); obj.SetValue(100, 123, 0); <file_sep># Duplicate Encoder Vytvořte miniaplikaci, která zpracuje vstupní text. Znaky, které se v něm opakují, převede na jednu značku (např. `)`), ostatní na jinou značku (např. `(`). Implementaci zapouzdřete do třídy a jako vedlejší produkt ji naučte i vypsat statistiku četnosti znaků ve vstupním textu. ![Screenshot](img/screenshot.png) ## Implementační instrukce (nezávazné) 1. Vytvořte třídu (`class DuplicateEncoder`), která bude mít konstruktor s jedním parametrem (vstupní text). 1. Konsturktor uloží vstupní text do privátního fieldu třídy a zároveň rovnou spočítá statistiku znaků v textu. Statistiku reprezentujte vhodnou datovou strukturou (např. `Dictionary<char, int>`) a uložte ji jako privátní field třídy. 1. Přidejte metodu `Encode`, která použije data z privátních fieldů a provede sestavení výstupního kódování. 1. Přidejte metodu `PrintStatistics`, která použije data třídy a vypíše statistiku četnosti znaků. ## Challenges 1. Udělejte kódování parametrizovatelné, např. nastavitelné znaky pro reprezentaci unikátního a duplicitního znaku, 2. nebo mez pro duplicitu (počet opakování znaku, od kterého se má považovat za signifikantně duplicitní). 3. Zamyslete se nad problémem: Pokud máme k dispozici statistiku (viz screenshot), jsme schopni z ní zpětně zrekonstruovat původní text? Za jakých podmínek je to možné? ## Inspirace ```csharp while (true) { Console.WriteLine("Your input?"); var input = Console.ReadLine(); var encoder = new DuplicateEncoder(input); Console.WriteLine(encoder.Encode()); Console.WriteLine(encoder.Encode('_', '+')); Console.WriteLine(encoder.Encode('_', '!', 3)); encoder.PrintStatistics(); } public class DuplicateEncoder { private string normalizedInput; private Dictionary<char, int> statistics; public DuplicateEncoder(string input) { this.normalizedInput = input.ToLower(); BuildStatistics(); } private void BuildStatistics() { statistics = new Dictionary<char, int>(); foreach (var character in normalizedInput) { if (statistics.TryGetValue(character, out int count)) { statistics[character] = count + 1; } else { statistics[character] = 1; } } } public string Encode(char uniqueSymbol = '(', char duplicateSymbol = ')', int duplicateThreshold = 2) { string encodedResult = null; foreach (var character in normalizedInput) { if (statistics.TryGetValue(character, out int count) && (count >= duplicateThreshold)) { encodedResult = encodedResult + duplicateSymbol; } else { encodedResult = encodedResult + uniqueSymbol; } } return encodedResult; } public void PrintStatistics() { Console.WriteLine("Statistics:"); foreach (var dictionaryItem in statistics) { Console.WriteLine($"{dictionaryItem.Key}: {dictionaryItem.Value}"); } } } ``` <file_sep>using System; namespace Prvocisla { class Program { static void Main(string[] args) { Console.WriteLine("<NAME>"); int cislo = Convert.ToInt32(Console.ReadLine()); int delitel = 2; while (true) { if (cislo % delitel == 0) { if (cislo == delitel) { Console.WriteLine("Toto je prvočíslo."); } if (delitel < cislo) { Console.WriteLine("Toto není prvočíslo."); } break; } delitel = delitel + 1; } } } } <file_sep>namespace CloveceNezlobSe { public class Policko { HashSet<Figurka> figurkyNaPolicku = new(); bool dovolitViceFigurek; public bool JeDomecek { get; init; } public Policko(bool jeDomecek = false, bool dovolitViceFigurek = false) { this.dovolitViceFigurek = dovolitViceFigurek; this.JeDomecek = jeDomecek; } public virtual void PolozFigurku(Figurka figurka) { if (JeObsazeno()) { throw new InvalidOperationException("Na políčku je již figurka a políčko nedovoluje více figurek."); } figurkyNaPolicku.Add(figurka); figurka.NastavPolicko(this); } public Figurka ZvedniJedinouFigurku() { if (figurkyNaPolicku.Count != 1) { throw new InvalidOperationException("Na políčku není jediná figurka."); } var figurka = figurkyNaPolicku.First(); ZvedniFigurku(figurka); return figurka; } public void ZvedniFigurku(Figurka figurka) { if (!figurkyNaPolicku.Contains(figurka)) { throw new InvalidOperationException("Na políčku figurka není."); } figurkyNaPolicku.Remove(figurka); figurka.NastavPolicko(null); } public IEnumerable<Figurka> ZjistiFigurkyHrace(Hrac hrac) { return figurkyNaPolicku.Where(figurka => figurka.Hrac == hrac); } public IEnumerable<Figurka> ZjistiFigurkyProtihracu(Hrac hrac) { return figurkyNaPolicku.Where(figurka => figurka.Hrac != hrac); } public bool JeObsazeno() { return !dovolitViceFigurek && (figurkyNaPolicku.Count != 0); } public void Vykresli() { Console.Write("["); foreach (var figurka in figurkyNaPolicku) { Console.Write(figurka.OznaceniFigurky); } Console.Write("]"); } } }<file_sep># Vigenerova šifra ## Zadání Vytvořte jednoduchou miniaplikaci v C#, která bude umět šifrovat a dešifrovat zadané zprávy textové zprávy pomocí [Vigenerova šifrovacího algoritmu](https://cs.wikipedia.org/wiki/Vigen%C3%A8rova_%C5%A1ifra). ![Screenshot](screenshot.png) ## Vigenerova šifra ve zkratce VŠ je založena na posunu písmen v abecedě. 1. Heslo `a` (první písmeno abecedy) znaky nikam neposouvá. 1. Pokud by bylo heslo `b` (druhé písmeno abecedy), posunu každý znak vstupu o jedno písmeno, např. z písmene `e` by se stalo písmeno `f`. Poslední písmeno `z` by se cyklicky změnilo na `a`. Ze vstupu `ahoj` by se stalo `bipk`. 1. Pokud by bylo heslo `c` (třetí písmeno abecedy), posunu každý znak vstupu o tolik písmen, kolik znaků je heslo vzdáleno od základního písmene `a`, tedy o dva znaky. Ze vstupu `ahoj` by se stalo `cjql`. 1. Pokud má heslo více znaků, každý znak hesla použiju postupně pro jedno písmeno vstupního řetězce. Např. šifruji slovo `wikipedie` s heslem `bagr`, tak `w` posouvám o 1 znak (vzdálenost `b` od `a`), písmeno `i` neposouvám (druhým písmenem v `bagr` je `a`), písmeno `k` posouvám o 6 znaků (vzdálenost `g` od `a`). Když je vstupní řetězec delší než heslo, vracím se v hesle na začátek a používám ho stále dokola. Jako kdyby heslo bylo `bagrbagrbagrbagr...`. 1. Ručně se šifra řeší obvykle prostřednictvím tzv. Vigenerova čtverce. Příklad pro slovo `informatika` a heslo `skola`: ![Vigenere Square](VigenereSquare.png) ## Bude se vám hodit Získání znaku z konkrétní pozice textového řetězce (zero-based indexing): ```csharp var znak = test[pozice]; ``` Získání číselného [ASCII kódu](https://en.wikipedia.org/wiki/ASCII) znaku: ```csharp int kod = (int)znak; int kod2 = (int)'A'; // 65 ``` Získání vzdálenosti dvou písmen v abecedě: ```csharp int posun = znak1 - znak2; int posun2 = 'C' - 'A'; // 2 ``` Převod čísla na znak (z jeho [ASCII kódu](https://en.wikipedia.org/wiki/ASCII)) ```csharp char pismeno = (char)asciiKod; char pismeno2 = (char)65; // A ``` Převod textového řetězce na pole znaků a zpět: ```csharp char[] pole = retezec.ToCharArray(); // z textu na pole znaků string vystup = new string(pole); // z pole znaků na text ``` ## Inspirace ```csharp string heslo = "SKOLA"; string vstup = "INFORMATIKA"; Console.WriteLine(Vigenere(vstup, heslo, true)); // false = decrypt string Vigenere(string vstup, string heslo, bool encrypt) { char[] vystup = new char[vstup.Length]; for (int i = 0; i < vstup.Length; i++) { int posun = heslo[i % heslo.Length] - 'A'; if (!encrypt) { posun = -posun; } int znak = (vstup[i] - 'A' + posun) % 26; if (znak < 0) // decrypt { znak = znak + 26; } vystup[i] = (char)('A' + znak); } return new string(vystup); } ```<file_sep># Člověče, nezlob se! (OOP) Vytvořte simulátor hry *Člověče, nezlob se!* pomocí objektově orientovaného programování (OOP). Hru zná asi každý, najdete ji i ve [Wikipedii](https://cs.wikipedia.org/wiki/%C4%8Clov%C4%9B%C4%8De,_nezlob_se!). Naším cílem bude naprogramovat simulátor, který bude generovat hody kostkou jako náhodná čísla a bude zaznamenávat postup hry od začátku až do konce. 1. Analyzujte, jaké objekty, resp. jejich třídy, budete pro reprezentaci hry potřebovat. 1. Jaké vlastnosti a operace budou objekty mít? 1. Vytvořte třídy, které budou jednotlivé objekty popisovat. 1. Naprogramujte chování jednotlivých objektů. 1. Sestavte z objektů kompletní simulátor s jednoduchým uživatelským rozhraním (konzolová aplikace, která hru spustí a bude vypisovat údaje z jejího průběhu). 1. Hru si můžete libovolně zjednodušit, dle svých dovedností a časových možností. Např. nemusíte řešit "nasazování" figurek šestkou na začátku, cílový domeček udělat jako poslední políčko (bez nutnosti trefit ho přesně), nebo neřešit vzájemné vyhazování mezi hráči. ## Výzvy 1. Existují různé variace hry, např. různé herní plány (různý maximální počet hráčů, různé tvary, velikosti, atp.) Navrhněte (a naprogramujte) způsob, jak v simulátoru umožnit volbu herního plánu pro konkrétní simulaci. 1. Variace může být i v pravidlech, např. pokud hodím kostkou 2x za sebou šestku, vracím se o tři pole nazpět. Navrhněte (a naprogramujte) způsob, jak v simulátoru reprezentovat pravidla a umožnit volbu konkrétních pravidel pro jednotlivé simulace. 1. Hráči mohou uplatňovat různé strategie. Např. táhnout vždy figurkou, která je nejblíže k cíli, táhnout náhodnou figurkou, nebo brát v úvahu pozici figurek ostatních hráčů. Zkuste navrhnout objektově orientovaný princip, jak umožnit jednotlivým hráčům nastavit různé strategie (popř. vyzkoušejte, které strategie jsou nejúspěšnější). <file_sep>Test("10 1 +", 11); Test("10 1 -", 9); Test("10 10 *", 100); Test("3 2 /", 1.5); Test("2 3 4 + *", 14); Test("5 1 2 + 4 * + 3 -", 14); void Test(string expression, double expectedResult) { var actualResult = Calculate(expression); Console.Write($"{expression} = {actualResult}"); if (actualResult == expectedResult) { Console.WriteLine(" (OK)"); } else { Console.WriteLine(" (FAIL)"); } } double Calculate(string expression) { var stack = new Stack<double>(); var tokens = expression.Split(' '); double operand1, operand2; foreach (string token in tokens) { switch (token) { case "+": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand1 + operand2); break; case "-": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand2 - operand1); break; case "*": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand1 * operand2); break; case "/": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand2 / operand1); break; default: stack.Push(double.Parse(token)); break; } } return stack.Pop(); }<file_sep>Console.WriteLine("Kolik prvků mám seřadit?"); int size = Convert.ToInt32(Console.ReadLine()); // generate input data int[] inputData = new int[size]; for (int i = 0; i < size; i++) { inputData[i] = Random.Shared.Next(size * 2); } PrintArray(inputData); BubbleSort(inputData); PrintArray(inputData); void BubbleSort(int[] data) { int temp; for (int j = 0; j <= data.Length - 2; j++) { for (int i = 0; i <= data.Length - 2; i++) { if (data[i] > data[i + 1]) { temp = data[i + 1]; data[i + 1] = data[i]; data[i] = temp; } PrintArray(data); } } } void PrintArray(int[] inputData) { for (int i = 0; i < inputData.Length; i++) { Console.Write($"{inputData[i]}".PadLeft(4)); } Console.WriteLine(); }<file_sep>long counter = 0; void MyMethod() { // increase stack-frame size //Int64 a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p; counter++; Console.WriteLine(counter.ToString()); MyMethod(); } MyMethod(); // increase stack size //var thread = new Thread(MyMethod, int.MaxValue); //thread.Start(); //thread.Join();<file_sep>namespace Banking; public class LineOfCreditAccount : BankAccount { public LineOfCreditAccount(string name, decimal initialBalance, decimal creditLimit) : base(name, initialBalance, -creditLimit) { } public override void PerformMonthEndTransactions() { if (Balance < 0) { // Negate the balance to get a positive interest charge: var interest = -Balance * 0.07m; MakeWithdrawal(interest, DateTime.Now, "Charge monthly interest"); } } protected override Transaction CheckWithdrawalLimit(bool isOverdrawn) { if (isOverdrawn) { return new Transaction(-20, DateTime.Now, "Apply overdraft fee"); } return null; } } <file_sep>namespace CloveceNezlobSe { public abstract class HerniPlan { public abstract int MaximalniPocetHracu { get; } public abstract void DejFigurkuNaStartovniPolicko(Figurka figurka); public abstract Policko? ZjistiCilovePolicko(Figurka figurka, int hod); public abstract void PosunFigurku(Figurka figurka, int pocetPolicek); public abstract bool MuzuTahnout(Figurka figurka, int hod); public abstract void Vykresli(); } }<file_sep># Bankovní účet (třídy) Procvičíme si základní práci s třídami (`class`) - jejich definicí a použitím. Definujte objektový model (třídy), který bude reprezentovat základní bankovnictví: * Bankovní účet má vlastníka (jméno) a počáteční vklad (částku). * Bankovní účet má číslo účtu, které je mu automaticky přiděleno při založení. * Změny zůstatku bankovního účtu provádíme prostřednictvím transakcí na něm. Každý účet si pamatuje seznam transakcí, které se s ním prováděly. * Každá transakce má datum, popis a částku (kladnou/zápornou). * Bankovní účet podporuje několik operací * Vklad na účet - Musí být kladný, vytvoří transakci zvyšující zůstatek. * Výběr z účtu - Musí být kladný, vytvoří transakci snižující zůstatek. Nelze provést, pokud zůstatek účtu nepostačuje na požadovanou částku. * Počáteční vklad - Vzniká při založení účtu a je v podstatě první transakcí na účtu. * Výpis z účtu - Vrátí textovou reprezentaci seznamu všech transakcí s účtem. *Poznámka: Model bankovnictvím je zde pro výukové účely značně zjednodušen. Ve skutečném bankovnictvím má například každá transakce dvě strany - dva účty, mezi kterými se transakce provádí.* ![Screenshot](screenshot.png) ## Challenges (volitelná rozšíření zadání) 1. Reprezentujte transakce jako operace mezi dvěma účty. 2. Přidejte podporu převodu peněz mezi dvěma účty. Hlídejte podmínky, které musí účty splňovat, aby bylo možné transakci provést. 3. Přidejte podporu termínovaných spořících účtů. Takový účet nedovolí provádět transakce mimo zvolené periodické datum - např. jen v jeden konkrétní den v týdnu (týdenní fixace), nebo měsíci (měsíční fixace). 4. Přidejte podporu úročení účtů. Na každém účtu bude evidována úroková sazba a nějakou centrální úlohu spouštěnou jednou měsíčně připište na účty získané úroky. ## Inspirace Obdobnou úlohu s podrobným popisem řešení a zdrojovými kódy najdete v souvisejícím kurzu: https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/tutorials/classes<file_sep># Vyhledávání souborů Napište konzolovou miniaplikaci, která projde zvolenou složku a její podsložky, najde v nich C# soubory (s příponou `.cs`) a vypíše z nich řádky, které pracují s třídou `Console` (pro zjednodušení - obsahují text "`Console.`"). Výstup zapište do souboru `output.txt` a na konci programu obsah výsledného souboru vypište na obrazovku. ## Příklad ![File Read Write Result](FileReadWriteResult.png) ## Bude se vám hodit * třída `System.IO.Directory` - https://docs.microsoft.com/en-us/dotnet/api/system.io.directory * `System.IO.File` - https://docs.microsoft.com/en-us/dotnet/api/system.io.file * `System.IO.Path` - https://docs.microsoft.com/en-us/dotnet/api/system.io.path ## Challenges pro pokročilejší 1. Optimalizujte kód, aby pracoval efektivně se soubory (prozkoumejte možnosti `FileStream`) 1. Optimalizujte kód, aby pracoval efektivně s textovými řetězci (prozkoumejte možnosti třídy `StringBuilder`) 1. Umožněte prohledávat více typů souborů najednou, např. `.cs` a `.md`. 1. Umožněte prohledávání celého disku. Bude potřeba se vypořádat např. s nepřístupnými systémovými složkami (přeskočit) a podobnými záludnostmi. ## Inspirace Příklad kódu bez optimalizací ```csharp using System; using System.IO; var outputFile = "output.txt"; if (File.Exists(outputFile)) { File.Delete(outputFile); } var searchDirectory = "D:\\Development\\Programiste.CSharp"; var files = Directory.EnumerateFiles(searchDirectory, "*.cs", SearchOption.AllDirectories); string directory = null; foreach (var fileName in files) { var fileExtension = Path.GetExtension(fileName); if (Path.GetDirectoryName(fileName) != directory) { directory = Path.GetDirectoryName(fileName); File.AppendAllText(outputFile, Environment.NewLine + directory + Environment.NewLine); } if (fileExtension == ".cs") { var fileContents = File.ReadAllText(fileName); var fileOutput = String.Empty; var lines = fileContents.Split(Environment.NewLine); for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++) { if (lines[lineNumber].Contains("Console.")) { fileOutput += $"\t Line {lineNumber + 1}: {lines[lineNumber].Trim()}" + Environment.NewLine; } } if (!String.IsNullOrWhiteSpace(fileOutput)) { File.AppendAllText(outputFile, Path.GetFileName(fileName) + Environment.NewLine); File.AppendAllText(outputFile, fileOutput); } } } Console.OutputEncoding = System.Text.Encoding.Unicode; Console.Write(File.ReadAllText(outputFile)); ``` <file_sep># Spojový seznam (LinkedList) [Spojový (lineární) seznam](https://cs.wikipedia.org/wiki/Line%C3%A1rn%C3%AD_seznam) je datová struktura pro uložení množiny prvků, přičemž datové položky jsou navzájem provázány vzájemnými odkazy (reference, pointery): * *jednosměrný* spojový seznam - každá datová položka se odkazuje na položku následující, ![](https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Singly-linked-list.svg/612px-Singly-linked-list.svg.png) * *obousměrný* spojový seznam - každá datový položka se odkazuje na položku předcházející a položku následující, ![](https://media.geeksforgeeks.org/wp-content/uploads/20190326091540/Untitled-Diagram11.jpg) * *kruhový* spojový seznam - "první" a "poslední" položka jsou navzájem provázány - seznam se uzavírá do kruhu, V .NET je připravena hotová třída `LinkedList<T>`, my si však zkusíme **obousměrný** spojový seznam implementovat vlastními silami. Dávejme do něj třeba textové řetězce. Spojový seznam chceme naučit následující operace: 1. `AddStart(string item)` - přidání prvku na začátek 1. `Print()` - vypsání seznamu prvků 1. `AddEnd(string item)` - přidání prvku na konec 1. `AddBefore(string itemToAdd, string beforeItem)` - přidání prvku před existující prvek 1. `RemoveFirst()` - odebrání prvního prvku 1. `RemoveLast()` - odebrání posledního prvku 1. `Remove(string item)` - odebrání konkrétního prvku 1. `bool Contains(string item)` - ověření existence prvku 1. `int IndexOf(string item)` - zjištění (první) pozice prvku 1. `InsertAt(string item, int index)` - vložení prvku na konkrétní pozici 1. `int Count()` - vrátí počet prvků v seznamu ...implementujte, co během hodiny stihnete. ## Challenges 1. `Exchange(string item1, string item2)` - výměna prvků v seznamu 1. `Sort()` - seřazení prvků v seznamu ## Inspirace ```csharp var linkedList = new LinkedList(); linkedList.AddEnd("Marek"); linkedList.AddStart("Ahoj"); linkedList.AddStart("Nazdar"); linkedList.AddStart("Hello"); linkedList.AddEnd("Marek"); linkedList.Print(); public class Node { public string Value { get; set; } public Node PreviousNode { get; set; } public Node NextNode { get; set; } } public class LinkedList { private Node firstNode; private Node lastNode; public void AddStart(string item) { var newNode = new Node(); newNode.Value = item; newNode.PreviousNode = null; newNode.NextNode = this.firstNode; // dosavadní první uzel musí ukazovat na nový předchozí uzel if (this.firstNode != null) { this.firstNode.PreviousNode = newNode; } this.firstNode = newNode; // pokud vkládámé první uzel, je zároveň posledním if (lastNode == null) { this.lastNode = newNode; } } public void Print() { var currentNode = this.firstNode; while (currentNode != null) { Console.WriteLine(currentNode.Value); currentNode = currentNode.NextNode; } } public void AddEnd(string item) { var newNode = new Node(); newNode.Value = item; newNode.PreviousNode = this.lastNode; newNode.NextNode = null; // dosavadní poslední uzel musí ukazovat na nový následující uzel if (this.lastNode != null) { this.lastNode.NextNode = newNode; } this.lastNode = newNode; // pokud vkládámé první uzel, je zároveň prvním vůbec if (firstNode == null) { this.firstNode = newNode; } } } ```<file_sep>var data = new int[20]; var random = new Random(); // generování vstupního pole for (int i = 0; i < data.Length; i++) { data[i] = random.Next(i * 10, i * 10 + 10); Console.WriteLine(data[i]); } // hledání v poli while (true) { Console.WriteLine("Jakou hodnotu mám v poli hledat?"); var x = Convert.ToInt32(Console.ReadLine()); var found = false; for (int i = 0; i < data.Length; i++) { if (data[i] == x) { Console.WriteLine("Je tam!"); found = true; } } if (!found) { Console.WriteLine("Není tam!"); } }<file_sep>using System.Diagnostics; using CloveceNezlobSe; static Hrac HrajPartii() { HerniPlan herniPlan = new LinearniHerniPlan(15); Hra hra = new Hra(herniPlan); HerniStrategie herniStrategieTahniPrvniFigurkou = new HerniStrategieTahniPrvniMoznouFigurkou(hra); HerniStrategie herniStrategiePreferujVyhazovaniJinakPrvniMoznou = new HerniStrategiePreferujVyhazovaniJinakPrvniMoznou(hra); Hrac hrac1 = new Hrac("Karel:PrvniFigurkou", herniStrategieTahniPrvniFigurkou); Hrac hrac2 = new Hrac("Robert:PreferujVyhazovaniJinakPrvniFigurkou", herniStrategiePreferujVyhazovaniJinakPrvniMoznou); //Hrac hracN = new Hrac("Martin", herniStrategiePreferujVyhazovaniJinakPrvniMoznou); hra.PridejHrace(hrac1); hra.PridejHrace(hrac2); //hra.PridejHrace(hracN); hra.NastavNahodnePoradiHracu(); hra.Start(); return hra.Vitezove[0]; // vrátíme vítěze } // MĚŘENÍ var vysledkyHer = new Dictionary<string, int>(); // Key: hráč, Value: počet vítěztví // vypneme výstup do konzole, abychom urychlili průběh var originalConsoleOut = Console.Out; Console.SetOut(TextWriter.Null); var sw = Stopwatch.StartNew(); for (int i = 0; i < 50000; i++) { Hrac vitez = HrajPartii(); vysledkyHer[vitez.Jmeno] = vysledkyHer.GetValueOrDefault(vitez.Jmeno, 0) + 1; } // obnovení výstupu do konzole Console.SetOut(originalConsoleOut); Console.WriteLine($"{sw.ElapsedMilliseconds:n2} ms"); foreach (var vysledek in vysledkyHer.OrderByDescending(v => v.Value)) { Console.WriteLine($"{vysledek.Key}: {vysledek.Value}"); } <file_sep>using System; namespace HadaniCisel { class Program { static void Main(string[] args) { int horniMez = 1000; Console.WriteLine($"Myslím si číslo od 0 do {horniMez}." + $" Uhádneš, které to je?"); int cislo = new Random().Next(horniMez + 1); int tipovaneCislo; int pocetTipu = 0; do { tipovaneCislo = Convert.ToInt32(Console.ReadLine()); pocetTipu = pocetTipu + 1; if (tipovaneCislo > cislo) { Console.WriteLine("To není ono! Zkus menší číslo..."); } if (tipovaneCislo < cislo) { Console.WriteLine("To není ono! Zkus větší číslo..."); } } while (tipovaneCislo != cislo); Console.WriteLine($"To je ono! Gratuluji," + $" uhádl(a) si číslo na {pocetTipu}. pokus."); } } } <file_sep>Console.WriteLine(GetUnique(new int[] { 1, 2, 2, 2 })); // 1 Console.WriteLine(GetUnique(new int[] { 1, 2, 1, 1 })); // 2 Console.WriteLine(GetUnique(new int[] { -2, 2, 2, 2 })); // -2 Console.WriteLine(GetUnique(new int[] { 2, 2, 14, 2, 2 })); // 14 Console.WriteLine(GetUnique(new int[] { 3, 3, 3, 3, 4 })); // 4 int GetUnique(IEnumerable<int> numbers) { int? prevNum = null; int? lastNum = null; bool diff = false; foreach (int n in numbers) { if (diff && (n == lastNum)) { return prevNum.Value; } if (n != lastNum) { if (lastNum != null) { diff = true; } if ((prevNum == lastNum) && lastNum.HasValue) { return n; } else if (prevNum == n) { return lastNum.Value; } else if ((lastNum == n) && prevNum.HasValue) { return prevNum.Value; } } prevNum = lastNum; lastNum = n; } return -1; } <file_sep># Binární vyhledávací strom (Binary Search Tree, BST) ![BST](bst.png) [Binární vyhledávací strom](https://cs.wikipedia.org/wiki/Bin%C3%A1rn%C3%AD_vyhled%C3%A1vac%C3%AD_strom) je datová struktura, která: * je složená z uzlů (Node), * každý uzel může mít dva potomky (pravého a levého), * uzle jsou uspořádány podle své hodnoty (klíče) * levý podstrom uzlu obsahuje pouze hodnoty (klíče) menší (nebo shodné) než je hodnota (klíč) tohoto uzlu, * pravý podstraom uzlu obsahuje pouze hodnoty (klíče) větší (nebo shodné) než je hodnota (klíč) tohoto uzlu, ## Úloha Naprogramujte vlastní BST, který bude umět minimálně následující operace: 1. `Insert(int value)` - vložení nového prvku, 1. `bool Contains(int value)` - ověření existence prvku, 1. `List<int> GetValues()` - výpis všech hodnot ve stromu (vyzkoušejte si různé podoby navštěvování uzlů - pre-order, in-order, post-order) ![Screenshot](screenshot.png) ### Challenges Naučte svůj strom další operace: 1. `Print()` - vykreslení stromu na obrazovku v jakkoliv srozumitelné podobě 1. `Delete(int value)` - odebrání prvku ze stromu, 1. `Invert()` - převrátí pořadí prvků ve stromu Pokuste se implementovat nějakou formu vyvažování stromu (viz např. [AVL stromy](https://cs.wikipedia.org/wiki/AVL-strom). ## Inspirace ```csharp var tree = new BinarySearchTree(); tree.Insert(7); tree.Insert(5); tree.Insert(6); tree.Insert(3); tree.Insert(4); tree.Insert(1); tree.Insert(2); tree.Insert(8); tree.Insert(9); foreach (var value in tree.GetValues()) { Console.WriteLine(value); } tree.Print(); Console.WriteLine(tree.Contains(2)); Console.WriteLine(tree.Contains(23)); public class Node { public Node(int value) { this.Value = value; } public int Value { get; set; } public Node Left { get; set; } public Node Right { get; set; } } public class BinarySearchTree { public Node Root { get; set; } public void Insert(int value) { Insert(value, Root); } private void Insert(int value, Node node) { if (node == null) { Root = new Node(value); return; } if (value < node.Value) { if (node.Left == null) { node.Left = new Node(value); } else { Insert(value, node.Left); } } else { if (node.Right == null) { node.Right = new Node(value); } else { Insert(value, node.Right); } } } public bool Contains(int value) { return Contains(value, Root); } private bool Contains(int value, Node node) { if (node == null) { return false; } if (value == node.Value) { return true; } if (value < node.Value) { return Contains(value, node.Left); } else { return Contains(value, node.Right); } } public List<int> GetValues() { return GetValues(Root); } private List<int> GetValues(Node node) { if (node == null) { return new List<int>(); } var values = new List<int>(); values.AddRange(GetValues(node.Left)); values.Add(node.Value); values.AddRange(GetValues(node.Right)); return values; } public void Print() { Print(Root, 0, String.Empty); } private void Print(Node node, int level, string direction) { if (node == null) { return; } Print(node.Left, level + 1, "/"); Console.WriteLine(direction.PadLeft(level * 4) + " " + node.Value.ToString().PadRight(4)); Print(node.Right, level + 1, "\\"); } } ```<file_sep>Test(new int[] { 5, 3, 4 }, 1, 12); Test(new int[] { 10, 2, 3, 3 }, 2, 10); Test(new int[] { 2, 3, 10 }, 2, 12); Test(new int[] { 1, 2, 3, 4 }, 1, 10); Test(new int[] { 1, 2, 3, 4, 5 }, 100, 5); Test(new int[] { 2, 2, 3, 3, 4, 4 }, 2, 9); Test(new int[0], 2, 0); // empty queue void Test(int[] customersProcessingTimes, int selfserviceCountersCount, int expectedTimeToVerify) { var supermarket = new Supermarket(selfserviceCountersCount); var computedTime = supermarket.ProcessCustomers(customersProcessingTimes); Console.Write($"Customers: {String.Join(" ", customersProcessingTimes)}, Counters: {selfserviceCountersCount}, Time: {computedTime}"); if (computedTime == expectedTimeToVerify) { Console.WriteLine(" ==> OK"); } else { Console.WriteLine(" ==> FAILED"); } } public class Supermarket { private Queue<Customer> customersQueue; private List<SelfserviceCounter> selfserviceCountersList; private int timer = 0; public Supermarket(int selfserviceCountersCount) { // create counters selfserviceCountersList = new List<SelfserviceCounter>(); for (int i = 0; i < selfserviceCountersCount; i++) { selfserviceCountersList.Add(new SelfserviceCounter()); } } public int ProcessCustomers(int[] customersProcessingTimes) { customersQueue = new Queue<Customer>(); foreach (var customerTime in customersProcessingTimes) { customersQueue.Enqueue(new Customer(customerTime)); } timer = 0; while (true) { if (customersQueue.Count == 0) { bool allCountersFree = true; foreach (var counter in selfserviceCountersList) { if (!counter.IsFree()) { allCountersFree = false; break; // occupied counter found, exit foreach loop } } if (allCountersFree) { break; // work done, exit main while loop } } TimerTick(); } return timer; } private void TimerTick() { foreach (var selfserviceCounter in selfserviceCountersList) { if (selfserviceCounter.IsFree()) { if (customersQueue.TryDequeue(out var customer)) { selfserviceCounter.AssignCustomer(customer); } } selfserviceCounter.TimerTick(); } timer++; } } public class SelfserviceCounter { private int timeToFinishCurrentCustomer; private Customer currentCustomer; public void TimerTick() { if (timeToFinishCurrentCustomer > 0) { timeToFinishCurrentCustomer--; // current customer completed? if (timeToFinishCurrentCustomer == 0) { currentCustomer = null; } } } public bool IsFree() { return (currentCustomer == null); } public void AssignCustomer(Customer customer) { if (currentCustomer != null) { throw new InvalidOperationException("Counter is occupied!"); } currentCustomer = customer; timeToFinishCurrentCustomer = customer.ProcessingTimeNeeded; } } public class Customer { public Customer(int processingTimeNeeded) { ProcessingTimeNeeded = processingTimeNeeded; } public int ProcessingTimeNeeded { get; init; } }<file_sep>Console.OutputEncoding = System.Text.Encoding.Unicode; const string url = "https://www.cnb.cz/cs/financni-trhy/devizovy-trh/kurzy-devizoveho-trhu/kurzy-devizoveho-trhu/denni_kurz.txt"; using var httpClient = new HttpClient(); string cnbWebContent = await httpClient.GetStringAsync(url); var lines = cnbWebContent.Split('\n'); for (int i = 2; i < lines.Length; i++) { var line = lines[i]; if (!line.Contains("|")) { continue; } var segments = line.Split('|'); var country = segments[0]; var currencyName = segments[1]; var amount = Convert.ToDecimal(segments[2]); var currencyCode = segments[3]; var exchangeRate = segments[4]; Console.Write(country.PadRight(25)); Console.Write(currencyName.PadRight(15)); Console.Write(String.Format("{0:n2} ", exchangeRate).PadLeft(10)); Console.Write($"CZK / {amount} {currencyCode}"); Console.WriteLine(); }<file_sep>namespace CloveceNezlobSe { public class Hrac { public string Jmeno { get; private set; } public List<Figurka> Figurky { get; } private HerniStrategie herniStrategie; public Hrac(string jmeno, HerniStrategie herniStrategie) { this.Jmeno = jmeno; this.herniStrategie = herniStrategie; Figurky = new(); for (int i = 0; i < 4; i++) { Figurky.Add(new Figurka(this, $"{this.Jmeno.Substring(0,1)}{(i + 1)}")); } } public bool MaVsechnyFigurkyVDomecku() { return Figurky.All(figurka => figurka.JeVDomecku()); } public Figurka? DejFigurkuKterouHrat(int hod) { return herniStrategie.DejFigurkuKterouHrat(this, hod); } } } <file_sep># k-NN: k-nejbližších sousedů (k-NN) ## Cíl: Seznámit se s algoritmem "k-NN" (k-nejbližších sousedů) a implementovat jej v jazyce C# pro klasifikaci bodů ve dvoudimenzionálním prostoru. ## Pokyny: 1. Vytvořte třídu `KNN`, která bude obsahovat metody pro trénování a predikci modelu k-NN. 2. Implementujte metodu `Train`, která přijímá trénovací data ve formě seznamu bodů a jejich příslušných tříd (např. jako `List<Tuple<double, double, string>>`, kde první dvě hodnoty představují souřadnice bodu a třetí hodnota je název třídy). 3. Implementujte metodu `Predict`, která přijímá testovací bod (např. `Tuple<double, double>`) a počet nejbližších sousedů k jako parametry. Metoda vrátí predikovanou třídu testovacího bodu. 4. V metodě `Predict` vypočítejte vzdálenosti mezi testovacím bodem a všemi trénovacími body (Euklidovská vzdálenost je nejčastější volbou). 5. Seřaďte trénovací body podle vzdálenosti od testovacího bodu a vyberte `k` nejbližších sousedů. 6. Určete nejčastější třídu mezi `k` nejbližšími sousedy a vrátte ji jako predikci pro testovací bod. 7. Otestujte svůj k-NN model na nějakém datasetu. Například můžete vytvořit umělý dataset s dvěma třídami bodů, které jsou rozmístěny ve dvou klastrech. Rozdělte dataset na trénovací a testovací část a vyhodnoťte úspěšnost vašeho modelu. Příklad použití vaší implementace k-NN v kódu: ```csharp // Příprava trénovacích dat List<Tuple<double, double, string>> trainingData = new List<Tuple<double, double, string>> { Tuple.Create(1.0, 2.0, "ClassA"), Tuple.Create(3.0, 4.0, "ClassB"), // ...další body... }; // Příprava testovacího bodu Tuple<double, double> testPoint = Tuple.Create(2.5, 3.5); // Inicializace a trénování k-NN modelu KNN knn = new KNN(); knn.Train(trainingData); // Predikce třídy pro testovací bod int k = 3; string predictedClass = knn.Predict(testPoint, k); // Výpis výsledku Console.WriteLine($"Predikovaná třída pro bod ({testPoint.Item1}, {testPoint.Item2}) je: {predictedClass}"); ``` ## Inspirace Vzorové řešení úlohy může vypadat takto: ```csharp using System; using System.Collections.Generic; using System.Linq; public class KNN { private List<Tuple<double, double, string>> _trainingData; public void Train(List<Tuple<double, double, string>> trainingData) { _trainingData = trainingData; } public string Predict(Tuple<double, double> testPoint, int k) { var sortedNeighbors = _trainingData.Select(point => new { Distance = EuclideanDistance(testPoint, Tuple.Create(point.Item1, point.Item2)), Class = point.Item3 }) .OrderBy(point => point.Distance) .Take(k) .ToList(); string predictedClass = sortedNeighbors.GroupBy(x => x.Class) .OrderByDescending(g => g.Count()) .First() .Key; return predictedClass; } private double EuclideanDistance(Tuple<double, double> point1, Tuple<double, double> point2) { double distance = Math.Sqrt(Math.Pow(point1.Item1 - point2.Item1, 2) + Math.Pow(point1.Item2 - point2.Item2, 2)); return distance; } } class Program { static void Main(string[] args) { List<Tuple<double, double, string>> trainingData = new List<Tuple<double, double, string>> { Tuple.Create(1.0, 2.0, "ClassA"), Tuple.Create(3.0, 4.0, "ClassB"), // ...další body... }; Tuple<double, double> testPoint = Tuple.Create(2.5, 3.5); KNN knn = new KNN(); knn.Train(trainingData); int k = 3; string predictedClass = knn.Predict(testPoint, k); Console.WriteLine($"Predikovaná třída pro bod ({testPoint.Item1}, {testPoint.Item2}) je: {predictedClass}"); } } ``` # Závěr Algoritmus k-nejbližších sousedů (k-NN) je univerzální a jednoduchý algoritmus, který se dá použít v mnoha praktických příkladech. Zde jsou některé z nich: 1. Rozpoznávání ručně psaných číslic: Souřadnice mohou představovat pixely z obrázku ručně psané číslice (předzpracované do vektoru), zatímco třída klasifikace odpovídá číselné hodnotě číslice (0-9). 2. Klasifikace novinových článků: Souřadnice mohou být reprezentace článků, například vektor TF-IDF nebo jiné metody výpočtu slovních vah. Třída klasifikace pak odpovídá kategoriím článků, jako např. politika, sport, kultura atd. 3. Diagnóza nemocí: Souřadnice mohou být hodnoty různých biomedicínských měření, jako jsou krevní testy, krevní tlak, tělesná hmotnost atd. Třída klasifikace by pak odpovídala diagnóze nemoci nebo stavu pacienta. 4. Doporučování filmů: Souřadnice mohou být vlastnosti filmů, jako je žánr, délka, hodnocení, obsazení atd. Třída klasifikace by pak mohla odpovídat preferencím uživatele (např. "líbí se" nebo "nelíbí se"). 5. Detekce spamu: Souřadnice mohou být slovní vektor zprávy, např. frekvence klíčových slov, délka zprávy nebo další textové rysy. Třída klasifikace by pak odpovídala označení zprávy jako "spam" nebo "ne-spam". V praxi je důležité správně předzpracovat data a zvolit vhodnou metriku vzdálenosti, která bude fungovat dobře pro konkrétní případ použití. K-NN algoritmus může být citlivý na škálování dat a výběr správného parametru k, což může ovlivnit jeho výkon a přesnost. # Další příklady ## Iris Jednoduchý příklad použití k-NN algoritmu, který vyžaduje minimální předzpracování dat, je klasifikace květů irisů na základě jejich délky a šířky okvětních lístků. Tento dataset je známý jako Iris dataset a je populární v oblasti strojového učení pro testování algoritmů. Dataset obsahuje 150 vzorků, každý s čtyřmi atributy (délka a šířka okvětních lístků a délka a šířka kališních lístků) a třemi třídami (setosa, versicolor, virginica). V tomto případě by souřadnice byly hodnoty délky a šířky okvětních lístků, které jsou běžně dostupné v reálném světě a nevyžadují značné předzpracování. Třída klasifikace by pak byl druh irisu (setosa, versicolor nebo virginica). Příklad použití k-NN algoritmu pro klasifikaci květů irisů v C#: ```csharp List<Tuple<double, double, string>> trainingData = new List<Tuple<double, double, string>> { Tuple.Create(5.1, 3.5, "setosa"), Tuple.Create(4.9, 3.0, "setosa"), Tuple.Create(7.0, 3.2, "versicolor"), Tuple.Create(6.4, 3.2, "versicolor"), Tuple.Create(6.3, 3.3, "virginica"), Tuple.Create(5.8, 2.7, "virginica"), // ...další vzorky... }; Tuple<double, double> testPoint = Tuple.Create(5.9, 3.0); KNN knn = new KNN(); knn.Train(trainingData); int k = 3; string predictedClass = knn.Predict(testPoint, k); Console.WriteLine($"Predikovaná třída pro bod ({testPoint.Item1}, {testPoint.Item2}) je: {predictedClass}"); ``` V tomto příkladě je použití k-NN algoritmu jednoduché a přímočaré, protože vstupní data jsou již v jednoduchém formátu, který je snadno srozumitelný a nevyžaduje složité předzpracování. ## Víno Další jednoduchý příklad použití k-NN algoritmu je klasifikace vína na základě jejich chemických vlastností. Představme si, že máme dataset obsahující informace o různých typech vín, jako je obsah alkoholu, kyselost, hustota, cukr atd. Naším cílem je klasifikovat vína do tříd jako červené, bílé nebo růžové. V tomto případě by souřadnice byly chemické vlastnosti vína, které jsou běžně dostupné v reálném světě a nevyžadují značné předzpracování. Třída klasifikace by pak byl druh vína (červené, bílé nebo růžové). Příklad použití k-NN algoritmu pro klasifikaci vín v C#: ```csharp List<Tuple<double, double, string>> trainingData = new List<Tuple<double, double, string>> { Tuple.Create(13.2, 3.4, "red"), Tuple.Create(12.8, 3.1, "red"), Tuple.Create(9.8, 3.3, "white"), Tuple.Create(10.2, 3.2, "white"), Tuple.Create(11.6, 3.2, "rose"), Tuple.Create(11.0, 3.0, "rose"), // ...další vzorky... }; // Testovací bod: obsah alkoholu a kyselost Tuple<double, double> testPoint = Tuple.Create(10.5, 3.1); KNN knn = new KNN(); knn.Train(trainingData); int k = 3; string predictedClass = knn.Predict(testPoint, k); Console.WriteLine($"Predikovaná třída pro bod ({testPoint.Item1}, {testPoint.Item2}) je: {predictedClass}"); ``` ## Studijní výsledky Jednoduchý příklad použití k-NN algoritmu, který by byl tematicky ze studentského prostředí, je klasifikace studentů do skupin podle jejich studijních návyků a dosažených výsledků. Představme si, že máme dataset obsahující informace o studentech, jako je počet hodin studia týdně, účast na přednáškách a průměrné známky. V tomto případě by souřadnice byly studijní návyky a dosažené výsledky studentů, které jsou běžně dostupné v reálném světě a nevyžadují značné předzpracování. Třída klasifikace by pak byla skupina studentů (například "úspěšní", "průměrní" nebo "potřebují zlepšit"). Příklad použití k-NN algoritmu pro klasifikaci studentů v C#: ```csharp List<Tuple<double, double, string>> trainingData = new List<Tuple<double, double, string>> { // Formát: (počet hodin studia týdně, účast na přednáškách, skupina) Tuple.Create(25.0, 90.0, "successful"), Tuple.Create(20.0, 85.0, "successful"), Tuple.Create(15.0, 75.0, "average"), Tuple.Create(10.0, 70.0, "average"), Tuple.Create(5.0, 50.0, "needs_improvement"), Tuple.Create(3.0, 40.0, "needs_improvement"), // ...další vzorky... }; // Testovací bod: počet hodin studia týdně a účast na přednáškách Tuple<double, double> testPoint = Tuple.Create(12.0, 60.0); KNN knn = new KNN(); knn.Train(trainingData); int k = 3; string predictedClass = knn.Predict(testPoint, k); Console.WriteLine($"Predikovaná třída pro bod ({testPoint.Item1}, {testPoint.Item2}) je: {predictedClass}"); ``` V tomto případě je použití k-NN algoritmu jednoduché a přímočaré, protože vstupní data jsou v jednoduchém formátu a nevyžadují složité předzpracování.<file_sep>namespace CloveceNezlobSe { public abstract class HerniStrategie { public abstract Figurka? DejFigurkuKterouHrat(Hrac hrac, int hod); } }<file_sep># Základní řazení (ordering, sorting) *Řazení* je úloha, kdy je cílem vytvořit uspořádanou posloupnost prvků. (Doporučuji nezaměňovat s pojmem *třídění*, který se používá pro kategorizaci prvků do určitých skupin dle podobných vlastností.) Dnešním úkolem bude prozkoumat situaci kolem základních algoritmů řazení a jeden z nich (dle vlastního výběru) implementovat. Snažte se najít odpověď na otázky: 1. Jaký je rozdíl mezi *stabilním* a *nestabilním* řazením? Kdy této vlastnosti můžete využít? 2. Co znamená, když je řadící algoritmus označovaný jako *přirozený*? Kdy této vlastnosti můžete využít? 3. Jak fungují základní běžné algoritmy? * insertion-sort (řazení vkládáním) * selection-sort (řazení výběrem) * bubble-sort (bublikové řazení) * VOLITELNĚ: quick-sort (rychlé řazení) 4. Proč jsou některé algoritmy řádově rychlejší než ostatní? ### Doporučené zdroje: * [Wikipedia: Řadící algoritmus](https://cs.wikipedia.org/wiki/%C5%98adic%C3%AD_algoritmus) * [Wikipedia: Řazení výběrem](https://cs.wikipedia.org/wiki/%C5%98azen%C3%AD_v%C3%BDb%C4%9Brem) * [Wikipedia: Řazení vkládáním](https://cs.wikipedia.org/wiki/%C5%98azen%C3%AD_vkl%C3%A1d%C3%A1n%C3%ADm) * [Wikipedia: Bublinkové řazení](https://cs.wikipedia.org/wiki/Bublinkov%C3%A9_%C5%99azen%C3%AD) * [Algoritmy.net - Bubble sort](https://www.algoritmy.net/article/3/Bubble-sort) * [Algoritmy.net - Selection sort](https://www.algoritmy.net/article/4/Selection-sort) * [Algoritmy.net - Insertion sort](https://www.algoritmy.net/article/8/Insertion-sort) * ([Algoritmy.net - Quick sort](https://www.algoritmy.net/article/10/Quicksort)) * [Algoritmy.net - Porovnání řadících algoritmů](https://www.algoritmy.net/article/75/Porovnani-algoritmu) ## Úkol Napište jednoduchou miniaplikaci v C#, která si vygeneruje pole náhodných prvků zadané velikosti a ty následně seřadí. Implementujte klidně dle vlastní fantazie, na konci se však podívejte, jestli vaše implementace odpovídá některému z běžných řadících algoritmů. ![Screenshot](screenshot.png) ### Challenges 1. Zkuste dle výpisu průběhu algoritmu najít možné optimalizace algoritmu. Nešlo by řazení ukončit dříve? Nějaké jiné zkratky? 1. Implementujte více řadících algoritmů. Porovnejte jejich rychlost nad stejnou vstupní množinou. 1. Prozkoumejte a implementujte QuickSort. Proč je řádově rychlejší než základní algoritmy zmiňované výše? ## Inspirace ```csharp Console.WriteLine("Kolik prvků mám seřadit?"); int size = Convert.ToInt32(Console.ReadLine()); // generate input data int[] inputData = new int[size]; for (int i = 0; i < size; i++) { inputData[i] = Random.Shared.Next(size * 2); } PrintArray(inputData); BubbleSort(inputData); PrintArray(inputData); void BubbleSort(int[] data) { int temp; for (int j = 0; j <= data.Length - 2; j++) { for (int i = 0; i <= data.Length - 2; i++) { if (data[i] > data[i + 1]) { temp = data[i + 1]; data[i + 1] = data[i]; data[i] = temp; } PrintArray(data); } } } void PrintArray(int[] inputData) { for (int i = 0; i < inputData.Length; i++) { Console.Write($"{inputData[i]}".PadLeft(4)); } Console.WriteLine(); } ```<file_sep>var linkedList = new LinkedList(); linkedList.AddEnd("Marek"); linkedList.AddStart("Ahoj"); linkedList.AddStart("Nazdar"); linkedList.AddStart("Hello"); linkedList.AddEnd("Marek"); linkedList.Print(); public class Node { public string Value { get; set; } public Node PreviousNode { get; set; } public Node NextNode { get; set; } } public class LinkedList { private Node firstNode; private Node lastNode; public void AddStart(string item) { var newNode = new Node(); newNode.Value = item; newNode.PreviousNode = null; newNode.NextNode = this.firstNode; // dosavadní první uzel musí ukazovat na nový předchozí uzel if (this.firstNode != null) { this.firstNode.PreviousNode = newNode; } this.firstNode = newNode; // pokud vkládámé první uzel, je zároveň posledním if (lastNode == null) { this.lastNode = newNode; } } public void Print() { var currentNode = this.firstNode; while (currentNode != null) { Console.WriteLine(currentNode.Value); currentNode = currentNode.NextNode; } } public void AddEnd(string item) { var newNode = new Node(); newNode.Value = item; newNode.PreviousNode = this.lastNode; newNode.NextNode = null; // dosavadní poslední uzel musí ukazovat na nový následující uzel if (this.lastNode != null) { this.lastNode.NextNode = newNode; } this.lastNode = newNode; // pokud vkládámé první uzel, je zároveň prvním vůbec if (firstNode == null) { this.firstNode = newNode; } } } <file_sep># ExceptionHandlingCalculator - Kalkulátor se zpracováním výjimek ## Výjimky *Výjimky* (**exceptions**) slouží v .NET i dalších programovacích platformách k signalizaci a zpracování chybových či jinak výjimečných stavů. Říkáme, že program *vyhazuje výjimku* (**throws** exception), pokud v nějaké jeho části nastává situace, která je výjimkou signalizována (např. dělení nulou, nesprávný formát čísel, nedostatek paměti, atp.). Výjimky můžeme zpracovávat ("ošetřovat") pomocí konstrukce `try-catch`. Blokem `try` obalíme část kódu, kde může výjimka nastat, nasleduje blok `catch`, v kterém můžeme na výjimku reagovat, tzv. ji zpracovat: ```csharp try { result = num1 / num2; } catch (DivideByZeroException ex) { Console.WriteLine("Dělení nulou není dovoleno."); } ``` Pokud výjimku nezpracujeme, program je ukončen s chybovým výpisem. Bloků `catch` můžeme mít za sebou více a zachytávat tak více různých výjimek. ### Vlastní výjimky Můžeme též vytvářet a vyhazovat vlastní výjimky. Dědíme z třídy `Exception` a používáme klíčové slovo `throw`: ```csharp public class MyException : Exception { ... } if (some_error_conditions) { throw new MyException("Exception message"); } ``` Více o výjimkách si nastudujte v dokumentaci .NET (celkem ~13min čtení): * [Přehled](https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/exceptions/) * [Použití výjimek](https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/exceptions/using-exceptions) * [Ošetření výjimek](https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/exceptions/exception-handling) * [Vytváření a vyvolání výjimek](https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/exceptions/creating-and-throwing-exceptions) * [Výjimky generované kompilátorem](https://docs.microsoft.com/cs-cz/dotnet/csharp/fundamentals/exceptions/compiler-generated-exceptions) ## Zadání Vytvořte miniaplikaci, která bude jednoduchým kalkulátorem se základními operacemi (+, -, *, /) nad dvěma čísly (vstupem bude např. textový řetězec `3 + 2`). Smyslem však tentokrát není vytvořit dokonalý výpočet, ale **ošetřit co nejvíce chybových stavů**, vysvětlit uživateli chybu a vyžádat od něj korekci, například: * dělení nulou `3 / 0` * nesprávný formát čísla `3 / jedna` * nesprávný formát vstupu `31 21`, `31 + 23 12` * nezpracovatelné číslo (rozsahem) `123456789012345678901234567890 - 10` * výsledek mimo rozsah `2147483647 * 2147483647` * prázdný vstup * atp. Pokuste se alespoň jeden z chybových stavů detekovat vlastní kontrolou a signalizovat vlastní výjimkou, např. nesprávný formát vstupu. ![Screenshot](screenshot.png) ## Inspirace ```csharp while (true) { Console.Write("Zadejte výraz k výpočtu: "); string input = Console.ReadLine(); try { int result = Calculate(input); Console.WriteLine($"Výsledek: {result}"); } catch (DivideByZeroException) { Console.WriteLine("Chyba: Nelze dělit nulou!"); } catch (FormatException) { Console.WriteLine("Chyba: Nespravný formát vstupu!"); } catch (OverflowException) { Console.WriteLine("Chyba: Vstup nebo výsledek je mimo rozsah typu Int32!"); } catch (MyMissingOperatorException ex) { Console.WriteLine($"Chyba: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Chyba: {ex.Message}"); } } int Calculate(string input) { if (input.Contains("/")) { string[] parts = input.Split('/'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left / right; } else if (input.Contains("*")) { string[] parts = input.Split('*'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left * right; } else if (input.Contains("+")) { string[] parts = input.Split('+'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left + right; } else if (input.Contains("-")) { string[] parts = input.Split('-'); int left = int.Parse(parts[0]); int right = int.Parse(parts[1]); return left - right; } throw new MyMissingOperatorException("Chybí operátor!"); } public class MyMissingOperatorException : Exception { public MyMissingOperatorException() : base() { } public MyMissingOperatorException(string message) : base(message) { } } ``` ## Rozšíření Další informace a cvičení si můžete projít například v CodinGame: * https://www.codingame.com/playgrounds/12322/c-professional---basics-oop---exercises/exception-handling * https://www.codingame.com/playgrounds/12322/c-professional---basics-oop---exercises/exception-handling---exercises <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CloveceNezlobSe { public class Figurka { public string OznaceniFigurky { get; private set; } public Hrac Hrac { get; private set; } public Policko? Policko { get; private set; } public Figurka(Hrac hrac, string oznaceniFigurky) { this.Hrac = hrac; this.OznaceniFigurky = oznaceniFigurky; } public void NastavPolicko(Policko? policko) { this.Policko = policko; } public bool JeVDomecku() { return (this.Policko != null) && (this.Policko.JeDomecek); } } } <file_sep>namespace CloveceNezlobSe { /// <summary> /// Herní plán je tvořen rovnou řadou políček. Všichni hráči začínají na stejném startovním políčku. /// </summary> public class LinearniHerniPlan : HerniPlan { List<Policko> policka; public override int MaximalniPocetHracu => int.MaxValue; public LinearniHerniPlan(int pocetPolicek) { policka = new(); // startovní políčko policka.Add(new Policko(dovolitViceFigurek: true)); // ostatní políčka for (int i = 1; i < pocetPolicek - 1; i++) { policka.Add(new Policko()); } // cílové políčko policka.Add(new Policko(jeDomecek: true, dovolitViceFigurek: true)); } public override void DejFigurkuNaStartovniPolicko(Figurka figurka) { policka[0].PolozFigurku(figurka); } public override void PosunFigurku(Figurka figurka, int pocetPolicek) { Policko stavajiciPolicko = figurka.Policko; int indexStavajicihoPolicka = policka.IndexOf(stavajiciPolicko); int indexCile = (indexStavajicihoPolicka + pocetPolicek); if (indexCile < 0) { // figurka se vrací na začátek indexCile = 0; } if (indexCile >= policka.Count) { Console.WriteLine($"Figurka {figurka.OznaceniFigurky} vyjela z herní plochy, cíl je potřeba trefit přesně."); return; } Policko cilovePolicko = policka[indexCile]; // posun figurky na novou pozici stavajiciPolicko.ZvedniFigurku(figurka); Console.WriteLine($"Posouvám figurku {figurka.OznaceniFigurky} z pozice {indexStavajicihoPolicka} na pozici {indexCile}."); if (cilovePolicko.JeObsazeno()) { Figurka vyhozenaFigurka = cilovePolicko.ZvedniJedinouFigurku(); Console.WriteLine($"Vyhazuji figurku {vyhozenaFigurka.OznaceniFigurky} hráče: {vyhozenaFigurka.Hrac.Jmeno}"); policka[0].PolozFigurku(vyhozenaFigurka); } cilovePolicko.PolozFigurku(figurka); } public override Policko? ZjistiCilovePolicko(Figurka figurka, int hod) { if (figurka.Policko == null) { return null; // figurka není na herní ploše } int indexStavajicihoPolicka = policka.IndexOf(figurka.Policko); int indexCile = (indexStavajicihoPolicka + hod); if (indexCile < 0) { // figurka se vrací na začátek indexCile = 0; } if (indexCile >= policka.Count) { return null; } return policka[indexCile]; } public override bool MuzuTahnout(Figurka figurka, int hod) { if (figurka.Policko == null) { return false; // figurka není na herní ploše } int indexStavajicihoPolicka = policka.IndexOf(figurka.Policko); if (indexStavajicihoPolicka > policka.Count - hod - 1) { return false; // figurka by vyjela z herní plochy } return true; } public override void Vykresli() { foreach (var policko in policka) { policko.Vykresli(); } Console.WriteLine(); } } } <file_sep>var calculator = new RomanNumeralsCalculator(); Console.WriteLine(calculator.RomanToArabic("I")); // 1 Console.WriteLine(calculator.RomanToArabic("VIII")); // 8 Console.WriteLine(calculator.RomanToArabic("XXI")); // 21 Console.WriteLine(calculator.RomanToArabic("CLXXIII")); // 173 Console.WriteLine(calculator.RomanToArabic("MDCLXVI")); // 1666 Console.WriteLine(calculator.RomanToArabic("MDCCCXXII")); // 1822 Console.WriteLine(calculator.RomanToArabic("MCMLIV")); // 1954 Console.WriteLine(calculator.RomanToArabic("MCMXC")); // 1990 Console.WriteLine(calculator.RomanToArabic("MMVIII")); // 2008 Console.WriteLine(calculator.RomanToArabic("MMXIV")); // 2014 public class RomanNumeralsCalculator { private Dictionary<char, int> charValues; public RomanNumeralsCalculator() { charValues = new Dictionary<char, int>(); charValues.Add('I', 1); charValues.Add('V', 5); charValues.Add('X', 10); charValues.Add('L', 50); charValues.Add('C', 100); charValues.Add('D', 500); charValues.Add('M', 1000); } public int RomanToArabic(string roman) { if (roman.Length == 0) return 0; roman = roman.ToUpper(); int total = 0; int lastValue = 0; for (int i = roman.Length - 1; i >= 0; i--) { int new_value = charValues[roman[i]]; // přičítáme nebo odečítáme? if (new_value < lastValue) { total -= new_value; } else { total += new_value; lastValue = new_value; } } return total; } }<file_sep>using System; using System.Threading; namespace JackpotGame { class Program { static void Main(string[] args) { Console.Clear(); int score = 0; int pokus = 0; while (true) { int cislo1 = new Random().Next(10); Console.SetCursorPosition(10, 10); Console.Write(cislo1); int cislo2 = new Random().Next(10); Console.SetCursorPosition(20, 10); Console.Write(cislo2); int cislo3 = new Random().Next(10); Console.SetCursorPosition(30, 10); Console.Write(cislo3); if (Console.KeyAvailable) { Console.ReadKey(); pokus = pokus + 1; if (cislo1 == cislo2) { score = score + 1; } if (cislo2 == cislo3) { score = score + 1; } if (cislo1 == cislo3) { score = score + 1; } Console.SetCursorPosition(1, 1); Console.Write($"{score}/{pokus}"); Console.Beep(); Thread.Sleep(1000); // 1s } } } } } <file_sep>using System; using System.IO; using System.Net.Http; using System.Text.RegularExpressions; namespace WebDownloader { public class Program { public static void Main(string[] args) { HttpClient client = new HttpClient(); string stranka = client.GetStringAsync("https://www.mensagymnazium.cz/cs/kontakty").Result; Regex re = new Regex(@"<span class=""name"">(?<jmeno>.*)</span>"); foreach (Match match in re.Matches(stranka)) { Console.WriteLine(match.Groups["jmeno"]); } //Console.WriteLine(stranka); } } } // HttpRequestMessage request = new HttpRequestMessage(); // request.Method = HttpMethod.Get; // request.Headers.Add("User-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.44"); // request.RequestUri = new Uri("https://www.mensagymnazium.cz/cs/kontakty"); // using var response2 = client.SendAsync(request).Result; // var statusCode = response2.StatusCode; //// var header = response2.Headers.GetValues("Content-Type"); // var stranka = response2.Content.ReadAsStringAsync().Result;<file_sep>Test("{[()]}", true); Test("{(})", false); Test("{[(])}", false); Test("{{[[(())]]}}", true); Test("(){}[]", true); Test("(]", false); Test("[(])", false); Test("[({})](]", false); Test("", true); Test("pepa", true); Test("(pepa)", true); Test("10 * [123 + 7 (6 + 2)]", true); Test("10 * [123 + 7 (6 + 2))", false); void Test(string input, bool expected) { var actual = BracesValidator.IsValid(input); Console.WriteLine($"'{input}' - {actual} {(actual == expected ? String.Empty : "TEST FAILED")}"); } public class BracesValidator { public static bool IsValid(string braces) { var stack = new Stack<char>(); foreach (var c in braces) { if (c == '(' || c == '{' || c == '[') { stack.Push(c); } else if (c == ')' || c == '}' || c == ']') { if (stack.Count == 0) { return false; } var top = stack.Pop(); if (c == ')' && top != '(') { return false; } if (c == '}' && top != '{') { return false; } if (c == ']' && top != '[') { return false; } } } return stack.Count == 0; } }<file_sep>using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace StringLetterCount { class Program { // https://www.codewars.com/kata/59e19a747905df23cb000024/ // Spočítej počet výskytů jednotlivých písmen a-z ve vstupním textu // Výsledek vrať v podobě "1a2b1c" (1x A, 2x B, 1xC) pro vstup "babc". public static string StringLetterCount3(string str) { return str .Select(c1 => Char.ToLower(c1)) .Where(c2 => c2 >= 'a' && c2 <= 'z') .GroupBy(c3 => c3) .OrderBy(g => g.Key) .Aggregate("", (output, next) => output += next.Count().ToString() + next.Key); } public static string StringLetterCount(string str) { string returnStr = ""; int[] poctyVyskytuPismen = new int[26]; foreach (char c in str) { char x = Char.ToLower(c); if (x >= 'a' && x <= 'z') { poctyVyskytuPismen[x - 'a']++; } } for (int i = 0; i < 26; i++) { if (poctyVyskytuPismen[i] > 0) { returnStr += poctyVyskytuPismen[i].ToString() + (char)(i + 'a'); } } return returnStr; } public static string StringLetterCount2(string str) { string returnStr = ""; Dictionary<char, int> poctyVyskytuPismen = new Dictionary<char, int>(); foreach (char c in str) { char x = Char.ToLower(c); if (x >= 'a' && x <= 'z') { if (poctyVyskytuPismen.TryGetValue(x, out int dosavadniPocet)) { poctyVyskytuPismen[x] = dosavadniPocet + 1; } else { poctyVyskytuPismen[x] = 1; } } } foreach (var item in poctyVyskytuPismen.OrderBy(i => i.Key)) { returnStr += item.Value.ToString() + item.Key; } return returnStr; } public static string StringLetterCount1(string str) { str = str.ToLower(); string alphabet = "abcdefghijklmnopqrstuvwxyz"; string returnStr = ""; foreach (char c in alphabet) { int count = str.Count(x => x == c); if (count > 0) { returnStr += count.ToString() + c.ToString(); } } return returnStr; } static void Main(string[] args) { Assert.AreEqual("1a1b1c1d3e1f1g2h1i1j1k1l1m1n4o1p1q2r1s2t2u1v1w1x1y1z", StringLetterCount("The quick brown fox jumps over the lazy dog.")); Assert.AreEqual("2a1d5e1g1h4i1j2m3n3o3s6t1u2w2y", StringLetterCount("The time you enjoy wasting is not wasted time.")); Assert.AreEqual("", StringLetterCount("./4592#{}()")); Console.WriteLine("Testy OK! ...gratuluji."); } } } <file_sep>// https://www.codewars.com/kata/54b42f9314d9229fd6000d9c while (true) { Console.WriteLine("Your input?"); var input = Console.ReadLine(); var encoder = new DuplicateEncoder(input); Console.WriteLine(encoder.Encode()); Console.WriteLine(encoder.Encode('_', '+')); Console.WriteLine(encoder.Encode('_', '!', 3)); encoder.PrintStatistics(); } public class DuplicateEncoder { private string normalizedInput; private Dictionary<char, int> statistics; public DuplicateEncoder(string input) { this.normalizedInput = input.ToLower(); BuildStatistics(); } private void BuildStatistics() { statistics = new Dictionary<char, int>(); foreach (var character in normalizedInput) { if (statistics.TryGetValue(character, out int count)) { statistics[character] = count + 1; } else { statistics[character] = 1; } } } public string Encode(char uniqueSymbol = '(', char duplicateSymbol = ')', int duplicateThreshold = 2) { string encodedResult = null; foreach (var character in normalizedInput) { if (statistics.TryGetValue(character, out int count) && (count >= duplicateThreshold)) { encodedResult = encodedResult + duplicateSymbol; } else { encodedResult = encodedResult + uniqueSymbol; } } return encodedResult; } public void PrintStatistics() { Console.WriteLine("Statistics:"); foreach (var dictionaryItem in statistics) { Console.WriteLine($"{dictionaryItem.Key}: {dictionaryItem.Value}"); } } }<file_sep># Fronta u samoobslužných pokladen Máme supermarket a v něm samoobslužné podkladny. Známe počet pokladen, všechny fungují stejně. K pokladnám vede jediná společná fronta zákazníků a u každého zákazníka víme, kolik času bude u pokladny potřebovat k odbavení svého nákupu. Sestavte aplikaci, která bude počítat, za jak dlouho bude odbaven poslední zákazník. Příklady: Zákazníci (potřebné časy) | Počet pokladen | Potřebná doba ------------------------------|-----------------|---------------- 5, 3, 4 | 1 | 12 10, 2, 3, 3 | 2 | 10 2, 3, 10 | 2 | 12 1, 2, 3, 4 | 1 | 10 1, 2, 3, 4, 5 | 100 | 5 2, 2, 3, 3, 4, 4 | 2 | 9 žádný | 2 | 0 ![Screenshot](screenshot.png) Na vstupu předpokládejte: * potřebné časy jednotlivých zákazníků, např. ve formě pole `int[]` * počet pokladen - `int` ## Implementační typy * prozkoumejte datovou strukturu typu FIFO (First-In, First-Out), může se vám hodit * s výhodou lze využít uspořádání problému do tříd, kdy každá třída řeší svojí část problému * alternativně lze využít několika prostých polí ## Challenges * Upravte uspořádání, aby bylo možné v průběhu času zákazníky do fronty přidávat (např. "po deseti jednotkách času přijde do fronty další zákazník, který potřebuje na odbavení u pokladny 7 jednotek času) ## Inspirace Neoptimalizovaný základní postup algoritmu "v časových taktech": ```csharp Test(new int[] { 5, 3, 4 }, 1, 12); Test(new int[] { 10, 2, 3, 3 }, 2, 10); Test(new int[] { 2, 3, 10 }, 2, 12); Test(new int[] { 1, 2, 3, 4 }, 1, 10); Test(new int[] { 1, 2, 3, 4, 5 }, 100, 5); Test(new int[] { 2, 2, 3, 3, 4, 4 }, 2, 9); Test(new int[0], 2, 0); // empty queue void Test(int[] customersProcessingTimes, int selfserviceCountersCount, int expectedTimeToVerify) { var supermarket = new Supermarket(selfserviceCountersCount); var computedTime = supermarket.ProcessCustomers(customersProcessingTimes); Console.Write($"Customers: {String.Join(" ", customersProcessingTimes)}, Counters: {selfserviceCountersCount}, Time: {computedTime}"); if (computedTime == expectedTimeToVerify) { Console.WriteLine(" ==> OK"); } else { Console.WriteLine(" ==> FAILED"); } } public class Supermarket { private Queue<Customer> customersQueue; private List<SelfserviceCounter> selfserviceCountersList; private int timer = 0; public Supermarket(int selfserviceCountersCount) { // create counters selfserviceCountersList = new List<SelfserviceCounter>(); for (int i = 0; i < selfserviceCountersCount; i++) { selfserviceCountersList.Add(new SelfserviceCounter()); } } public int ProcessCustomers(int[] customersProcessingTimes) { customersQueue = new Queue<Customer>(); foreach (var customerTime in customersProcessingTimes) { customersQueue.Enqueue(new Customer(customerTime)); } timer = 0; while (true) { if (customersQueue.Count == 0) { bool allCountersFree = true; foreach (var counter in selfserviceCountersList) { if (!counter.IsFree()) { allCountersFree = false; break; // occupied counter found, exit foreach loop } } if (allCountersFree) { break; // work done, exit main while loop } } TimerTick(); } return timer; } private void TimerTick() { foreach (var selfserviceCounter in selfserviceCountersList) { if (selfserviceCounter.IsFree()) { if (customersQueue.TryDequeue(out var customer)) { selfserviceCounter.AssignCustomer(customer); } } selfserviceCounter.TimerTick(); } timer++; } } public class SelfserviceCounter { private int timeToFinishCurrentCustomer; private Customer currentCustomer; public void TimerTick() { if (timeToFinishCurrentCustomer > 0) { timeToFinishCurrentCustomer--; // current customer completed? if (timeToFinishCurrentCustomer == 0) { currentCustomer = null; } } } public bool IsFree() { return (currentCustomer == null); } public void AssignCustomer(Customer customer) { if (currentCustomer != null) { throw new InvalidOperationException("Counter is occupied!"); } currentCustomer = customer; timeToFinishCurrentCustomer = customer.ProcessingTimeNeeded; } } public class Customer { public Customer(int processingTimeNeeded) { ProcessingTimeNeeded = processingTimeNeeded; } public int ProcessingTimeNeeded { get; init; } } ``` --- Original kata: https://www.codewars.com/kata/57b06f90e298a7b53d000a86 <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileReadWrite { public class TestFile { public void DoSomething() { Console.WriteLine("Najdeš mě?"); } } } <file_sep># Hledání hodnoty v poli (sekvenční, neoptimalizované) seřazené pole => vyhledávání půlením intervalu (binary search)<file_sep>#pragma warning disable IDE1006 // Naming Styles - CodeWars nedodržuje konvence pojmenování pro C# namespace DirReduction { public class DirReduction { public static string[] dirReduc(string[] arr) { // TODO Your code goes here. return null; } } } <file_sep># Regresní přímka metodou nejmenších čtverců (LSRL - Least Squares Regression Line) ## Úvod AI. Umělá inteligence. Machine Learning. Jak fungují? Postupně se pokusíme na jednoduchých příkladech vyzkoušet, co stojí za umělou inteligencí, jak funguje. Dnes začneme úplným základem - predikcí hodnot na základě regresní analýzy. ### Regresní analýza **Regresní analýza** hledá funkci, která co nejlépe popisuje vztah mezi proměnnými (pro jednoduchost pracujme se dvěma proměnnými). Představ si graf s body, kde na ose x je nezávislá proměnná (např. věk auta) a na ose y je závislá proměnná (např. cena auta). Hledáme jakoukoli funkci (může to být přímka, parabola, křivka nebo složitější tvar), která co nejlépe prochází těmito body. Tato funkce nám pak umožňuje **předpovědět** cenu auta na základě jeho věku. Tímto způsobem se snažíme najít nejlepší možný vztah mezi proměnnými, aby naše předpovědi byly co nejpřesnější. ![Regression analysis](https://static.javatpoint.com/tutorial/machine-learning/images/machine-learning-polynomial-regression.png) **Lineární regresní analýza** je jednoduchý příklad regresní analýzy, kde se snažíme najít nejlepší přímku, která popisuje vztah mezi dvěma proměnnými. Představ si graf s body, kde na ose x je nezávislá proměnná (např. počet pokojů v domě) a na ose y je závislá proměnná (např. cena domu). Lineární regrese hledá takovou přímku, která co nejlépe prochází těmito body, a výsledná přímka nám umožňuje předpovědět cenu domu na základě počtu pokojů. ### Metoda nejmenších čtverců Metoda nejmenších čtverců (least squares method) je základní technika používaná při lineární regresní analýze, jejímž cílem je najít nejlepší přímku, která popisuje vztah mezi dvěma proměnnými. Tato metoda funguje tak, že minimalizuje součet čtverců rozdílů mezi skutečnými hodnotami závislé proměnné (např. cena domu) a hodnotami předpovězenými lineární funkcí (přímka na grafu). [![LSRL](image1.png)](https://phet.colorado.edu/sims/html/least-squares-regression/latest/least-squares-regression_all.html) Při použití metody nejmenších čtverců se snažíme najít koeficienty lineární funkce (`y = ax + b`), které minimalizují součet čtverců těchto rozdílů. Když nalezneme tyto koeficienty, získáme lineární funkci, která nejlépe prochází našimi daty, a můžeme ji použít k předpovídání hodnot závislé proměnné na základě hodnot nezávislé proměnné. Metoda nejmenších čtverců je široce používána pro odhad vztahů mezi proměnnými v různých oborech, jako jsou ekonomie, biologie nebo sociální vědy. Modelaci si můžete vyzkoušet zde: https://phet.colorado.edu/sims/html/least-squares-regression/latest/least-squares-regression_all.html # Úloha 1. Prozkoumej metodu nejmenších čtverců a její princip. 2. Vytvoř jednoduchý program v C#, který pomocí této metody předpoví hodnoty, které dosud neznáme. * vstupem programu (Console nebo soubor) bude * učící sada dvojic `[x, y]` * dotazovací sada hodnot `x` * výstupem programu bude * predikce hodnot `y` pro dotazovací sadu `x` (Good to know: Existuje vzorec pro výpočet hledaných koeficientů. Zvládneš ho najít a aplikovat[?](http://physics.ujep.cz/~ehejnova/UTM/materialy_studium/linearni_regrese.pdf)) # Inspirace Jedno z možných řešení nalezneš jako obvykle v tomto repozitáři.<file_sep># Digital Root - Číslicový kořen (suma číslic) ## Úloha Mějme na vstupu číslo *n*. Vytvoříme součet jeho číslic. Pokud je tento součet víceciferný, opakujeme celý proces a opět sečteme číslice. Pokračujeme takto sčítáním číslic, dokud výsledek není jednociferný. Příklady: ``` 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2 ``` ## Rekurze *Rekurzivní algoritmy* jsou takové algoritmy, v jejichž postupu je podprogram, který volá sám sebe dříve, než je dokončeho jeho předchozí volání. Každý rekurzivní algoritmus potřebuje kromě volání sama sebe i nějakou "zarážku" - podmínku, za které se další volání sama sebe neprovede a další rekurze se zastaví. Každý rekurzivní algoritmus lze převést do iterativní podoby (cyklus), rekurzivní algoritmy bývají však oblíbené pro jejich přehlednost. ## Challenges (volitelné) 1. Umožněte volbu číselní soustavy (desítková, šestnáctková, dvojková, atp.) 2. Přemýšlejte nad podobou, která zvládne na vstupu velmi vysoké číslo, např. 100 číslic. 2. Pokud jste algoritmus implementovali cyklem, vyzkoušete vytvořit jeho rekurzivní variantu a porovnejte je. A naopak, pokud jste pro implementaci použili rekurzi, implementujte algoritmus cyklem. 3. Zjistěte, jestli existuje nějaký matematický postup (vzorec), nebo jiná možnost, jak celý výpočet zefektivnit. ## Inspirace ```csharp Console.WriteLine("Zadejte číslo:"); var input = Console.ReadLine(); var output = DigitalRoot1_StringBased(input); Console.WriteLine($"Digital root: {output}"); var output2 = DigitalRoot2_Numeric(Convert.ToInt64(input)); Console.WriteLine($"Digital root: {output2}"); string DigitalRoot1_StringBased(string number) { if (number.Length == 1) { return number; } long sum = 0; foreach (char digit in number) { if (Char.IsDigit(digit)) { sum = sum + (int)Char.GetNumericValue(digit); } } return DigitalRoot1_StringBased(sum.ToString()); } long DigitalRoot2_Numeric(long number) { if (number < 10) { return number; } long sum = 0; do { sum = sum + number % 10; number = number / 10; } while (number > 1); sum = sum + number; return DigitalRoot2_Numeric(sum); } ``` <file_sep>using Microsoft.VisualBasic.CompilerServices; using System; using System.Data.SqlClient; namespace SqlInjectionDemo { class Program { static void Main(string[] args) { Console.WriteLine("Username:"); var username = Console.ReadLine(); Console.WriteLine("Password:"); var password = Console.ReadLine(); // SELECT UserID FROM User WHERE Username='pepa' AND Password = '<PASSWORD>' string cmdText = "SELECT UserId FROM [User] WHERE Username=@username AND Password=@password"; Console.WriteLine(cmdText); using var conn = new SqlConnection("Server=rhdemosql.database.windows.net;Database=AdventureWorksLT;User Id=PrgStudent;Password=<PASSWORD>.;"); conn.Open(); using var cmd = new SqlCommand(cmdText, conn); cmd.Parameters.AddWithValue("username", username); cmd.Parameters.AddWithValue("password", <PASSWORD>); var userID = cmd.ExecuteScalar(); Console.Write("ID přihlášeného uživatele:"); Console.WriteLine(userID); } } } <file_sep>using System; using System.IO; var outputFile = "output.txt"; if (File.Exists(outputFile)) { File.Delete(outputFile); } var searchDirectory = "D:\\Development\\Programiste.CSharp"; var files = Directory.EnumerateFiles(searchDirectory, "*.cs", SearchOption.AllDirectories); string directory = null; foreach (var fileName in files) { var fileExtension = Path.GetExtension(fileName); if (Path.GetDirectoryName(fileName) != directory) { directory = Path.GetDirectoryName(fileName); File.AppendAllText(outputFile, Environment.NewLine + directory + Environment.NewLine); } if (fileExtension == ".cs") { var fileContents = File.ReadAllText(fileName); var fileOutput = String.Empty; var lines = fileContents.Split(Environment.NewLine); for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++) { if (lines[lineNumber].Contains("Console.")) { fileOutput += $"\t Line {lineNumber + 1}: {lines[lineNumber].Trim()}" + Environment.NewLine; } } if (!String.IsNullOrWhiteSpace(fileOutput)) { File.AppendAllText(outputFile, Path.GetFileName(fileName) + Environment.NewLine); File.AppendAllText(outputFile, fileOutput); } } } Console.OutputEncoding = System.Text.Encoding.Unicode; Console.Write(File.ReadAllText(outputFile));<file_sep># Collatzův problém Viz [Collatzův problém na Wikipedii](https://cs.wikipedia.org/wiki/Collatz%C5%AFv_probl%C3%A9m). ## Úkol Vytvořte program, který ze zadaného celého kladného čísla generuje posloupnost čísel následujícím postupem: * Je-li číslo sudé, vyděl ho dvěma. * Je-li naopak číslo liché, vynásob ho třemi a přičti jedničku. * Tento postup opakuj tak dlouho, až se dostaneš k hodnotě 1. Dále vypíše, kolik výpočtů bylo třeba učinit, než se k číslu 1 dostane. Zadá-li tedy uživatel např. číslo 8, vznikne posloupnost 8, 4, 2, 1, tj. budou třeba 3 výpočty (z 8 na 4, ze 4 na 2 a z 2 na 1). Zadá-li uživatel např. číslo 9, vznikne posloupnost 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, která ke svému vygenerování potřebuje 19 kroků. ### Rozšíření 1. Zjistěte, pro které z čísel v rozmezí 2 až 1000 je vygenerovaná posloupnost nejdelší (tj. je třeba učinit nejvíc kroků). 2. Zjistěte nejmenší číslo, pro které je potřeba k vygenerování posloupnosti učinit alespoň 500 kroků. 3. Jak je z ilustračního příkladu v zadání vidět, pro zadané číslo 9 je ve vygenerované posloupnosti největší hodnotou 52. Najděte, které z čísel 2 až 100000 má ve své posloupnosti absolutně nejvyšší hodnotu ze všech a jaká hodnota to je. 4. Najděte nejmenší tři bezprostředně po sobě jdoucí čísla taková, že k vygenerování posloupností z nich je zapotřebí stejný počet kroků. ## Inspirace ```csharp int number = 9; Console.WriteLine(number); int step = 0; while (number != 1) { if (number % 2 == 0) { number = number / 2; } else { number = number * 3 + 1; } Console.WriteLine(number); step++; } Console.WriteLine("Number of steps: " + step); ```<file_sep>using System; using System.Threading; namespace Vlnky { class Program { static void Main(string[] args) { int posun = 1; int smer = 1; while (true) { if ((posun > 0) && (posun < 11)) { posun = posun + smer; } for (int i = 0; i < posun; i++) { Console.Write(" "); } Console.WriteLine("O"); Thread.Sleep(100); if (posun == 10) { smer = -1; } if (posun == 1) { smer = 1; } } } } } <file_sep>using System; Console.WriteLine("Zadejte vstupní text, najdu v něm palindromy."); var input = Console.ReadLine(); Console.WriteLine("\nNalezené palindromy:"); var words = input.Split(' '); foreach (var word in words) { string wordTrimmed = word.Trim(',', '.', '?', '!', ':'); char[] chars = wordTrimmed.ToCharArray(); Array.Reverse(chars); string reversedWord = new string(chars); if (String.Equals(wordTrimmed, reversedWord, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(wordTrimmed); } } <file_sep>namespace CloveceNezlobSe { public class HerniStrategieTahniPrvniMoznouFigurkou : HerniStrategie { protected readonly Hra hra; public HerniStrategieTahniPrvniMoznouFigurkou(Hra hra) { this.hra = hra; } public override Figurka? DejFigurkuKterouHrat(Hrac hrac, int hod) { var figurkyNaCeste = hrac.Figurky.Where(figurka => !figurka.JeVDomecku()).ToList(); var figurkyKtereMuzuHrat = figurkyNaCeste.Where(figurka => hra.HerniPlan.MuzuTahnout(figurka, hod)); if (figurkyKtereMuzuHrat.Any()) { return figurkyKtereMuzuHrat.First(); } return null; } } } <file_sep>using Banking; Console.WriteLine("GiftCardAccount:"); var giftCard = new GiftCardAccount("gift card", 100, 50); giftCard.MakeWithdrawal(20, DateTime.Now, "get expensive coffee"); giftCard.MakeWithdrawal(50, DateTime.Now, "buy groceries"); giftCard.PerformMonthEndTransactions(); // can make additional deposits: giftCard.MakeDeposit(27.50m, DateTime.Now, "add some additional spending money"); Console.WriteLine(giftCard.GetAccountHistory()); Console.WriteLine("InterestEarningAccount:"); var savings = new InterestEarningAccount("savings account", 10000); savings.MakeDeposit(750, DateTime.Now, "save some money"); savings.MakeDeposit(1250, DateTime.Now, "Add more savings"); savings.MakeWithdrawal(250, DateTime.Now, "Needed to pay monthly bills"); savings.PerformMonthEndTransactions(); Console.WriteLine(savings.GetAccountHistory()); Console.WriteLine("LineOfCreditAccount:"); var lineOfCredit = new LineOfCreditAccount("line of credit", initialBalance: 0, creditLimit: 2000); // How much is too much to borrow? lineOfCredit.MakeWithdrawal(1000m, DateTime.Now, "Take out monthly advance"); lineOfCredit.MakeDeposit(50m, DateTime.Now, "Pay back small amount"); lineOfCredit.MakeWithdrawal(5000m, DateTime.Now, "Emergency funds for repairs"); lineOfCredit.MakeDeposit(150m, DateTime.Now, "Partial restoration on repairs"); lineOfCredit.PerformMonthEndTransactions(); Console.WriteLine(lineOfCredit.GetAccountHistory());<file_sep>// Vstupní data (double x, double y)[] uciciVzorek = { (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) }; // Výpočet koeficientů (double alpha, double beta) = CalculateCoefficients(uciciVzorek); // Výpis výsledků Console.WriteLine($"Nalezená aproximační lineární funkce: y = {alpha} + {beta} * x"); // Testování aproximace Console.WriteLine("Aproximace pro jednotlivé body učícího vzorku:"); for (int i = 0; i < uciciVzorek.Length; i++) { double approximatedY = alpha + beta * uciciVzorek[i].x; Console.WriteLine($"x = {uciciVzorek[i].x}, y (skutečné) = {uciciVzorek[i].y}, y (aproximované) = {approximatedY}"); } // Predikce Console.WriteLine("\nPredikce hodnot:"); while (true) { Console.Write("> "); if (double.TryParse(Console.ReadLine(), out var x)) { double y = alpha + beta * x; Console.WriteLine($"Pro x = {x} predikuji y = {y}.\n"); } else { break; } } // Metoda pro výpočet koeficientů alfa a beta static (double alpha, double beta) CalculateCoefficients((double x, double y)[] values) { int n = values.Length; double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0; for (int i = 0; i < n; i++) { sumX += values[i].x; sumY += values[i].y; sumXY += values[i].x * values[i].y; sumX2 += values[i].x * values[i].x; } double beta = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX); double alpha = (sumY - beta * sumX) / n; return (alpha, beta); }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CloveceNezlobSe { public class Kostka { int pocetSten; public Kostka(int pocetSten) { this.pocetSten = pocetSten; } public int Hod() { var x = Random.Shared.Next(1, pocetSten + 1); Console.WriteLine($"Kostka hodila {x}."); return x; } } } <file_sep>using System; namespace Nasobky { class Program { static void Main(string[] args) { Console.WriteLine($"Vypíšu násobky A, které jsou zároveň násobky B."); Console.WriteLine("Zadejte celé číslo A:"); int a = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Zadejte celé číslo B:"); int b = Convert.ToInt32(Console.ReadLine()); Console.WriteLine($"Násobky {a}, které jsou zároveň násobky {b}:"); int nasobek = 0; for (int poradi = 0; poradi < 10; poradi++) { do { nasobek = nasobek + a; } while ((nasobek % b) != 0); // % vypočte zbytek po dělení Console.WriteLine(nasobek); } } } } <file_sep># Kalkulačka s reverzní polskou notací (postfixová notace) [RPN](https://cs.wikipedia.org/wiki/Postfixov%C3%A1_notace) je způsob zápisu matematického výrazu, kde operátor následuje své operandy, přičemž je odstraněna nutnost používat závorky (priorita operátorů se vyjadřuje samotným zápisem výrazu). Běžné operátory jsou binární, tj. mají dva operandy. Lze tedy říct, že kdykoliv narazíme na operátor, předchozí dvě hodnoty jsou jeho operandy. Jednotlivé složky (tokeny) oddělujme mezerníkem. Např. * `3 4 +` odpovídá výrazu `3 + 4`. * `2 3 4 + *` odpovídá výrazu `2 * (3 + 4)` * `5 1 2 + 4 * + 3 -` odpovídá výrazu `5 + ((1 + 2) * 4) - 3` ## Úloha Napište miniaplikaci, která bude přijímat výraz zapsaný reverzní polskou notací a vypočte numerický výsledek. ![Screenshot](screenshot.png) ## Inspirace ```csharp Test("10 1 +", 11); Test("10 1 -", 9); Test("10 10 *", 100); Test("3 2 /", 1.5); Test("2 3 4 + *", 14); Test("5 1 2 + 4 * + 3 -", 14); void Test(string expression, double expectedResult) { var actualResult = Calculate(expression); Console.Write($"{expression} = {actualResult}"); if (actualResult == expectedResult) { Console.WriteLine(" (OK)"); } else { Console.WriteLine(" (FAIL)"); } } double Calculate(string expression) { var stack = new Stack<double>(); var tokens = expression.Split(' '); double operand1, operand2; foreach (string token in tokens) { switch (token) { case "+": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand1 + operand2); break; case "-": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand2 - operand1); break; case "*": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand1 * operand2); break; case "/": operand1 = stack.Pop(); operand2 = stack.Pop(); stack.Push(operand2 / operand1); break; default: stack.Push(double.Parse(token)); break; } } return stack.Pop(); } ``` <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CloveceNezlobSe { public class HerniStrategiePreferujVyhazovaniJinakPrvniMoznou : HerniStrategieTahniPrvniMoznouFigurkou { public HerniStrategiePreferujVyhazovaniJinakPrvniMoznou(Hra hra) : base(hra) { } public override Figurka? DejFigurkuKterouHrat(Hrac hrac, int hod) { foreach (var figurka in hrac.Figurky) { var cilovePolicko = hra.HerniPlan.ZjistiCilovePolicko(figurka, hod); if (cilovePolicko != null) { if (!cilovePolicko.JeDomecek && cilovePolicko.ZjistiFigurkyProtihracu(hrac).Any()) { // na cílovém políčku je figurka protihráče, která by se dala vyhodit // proto vyberu příslušnou svoji figurku return figurka; } } } return base.DejFigurkuKterouHrat(hrac, hod); } } } <file_sep>namespace CloveceNezlobSe { public class Hra { public HerniPlan HerniPlan { get; private set; } public List<Hrac> Vitezove { get; } = new(); List<Hrac> hraci = new(); public Hra(HerniPlan herniPlan) { this.HerniPlan = herniPlan; } public void PridejHrace(Hrac hrac) { if (hraci.Count == HerniPlan.MaximalniPocetHracu) { throw new Exception("Hra je plná, maximální počet hráčů herního plánu byl překročen."); } hraci.Add(hrac); } public void NastavNahodnePoradiHracu() { hraci = hraci.OrderBy(hrac => Guid.NewGuid()).ToList(); } public void Start() { // TODO Kontrola vstupních podmínek pro zahájení hry. foreach (var hrac in hraci) { foreach (var figurka in hrac.Figurky) { HerniPlan.DejFigurkuNaStartovniPolicko(figurka); } } Kostka kostka = new Kostka(pocetSten: 6); while (true) { foreach (var hrac in hraci) { if (Vitezove.Contains(hrac)) { continue; } HerniPlan.Vykresli(); Console.WriteLine($"Hraje hráč {hrac.Jmeno}."); var hod = kostka.Hod(); var figurka = hrac.DejFigurkuKterouHrat(hod); if (figurka == null) { Console.WriteLine($"Hráč {hrac.Jmeno} nemůže tahnout."); continue; } HerniPlan.PosunFigurku(figurka, hod); if (figurka.Policko.JeDomecek) { Console.WriteLine($"Figurka {figurka.OznaceniFigurky} hráče {figurka.Hrac.Jmeno} došla do cíle."); if (hrac.MaVsechnyFigurkyVDomecku()) { Vitezove.Add(hrac); } } } if (Vitezove.Count == hraci.Count) { Console.WriteLine("Hra skončila."); break; } } Console.WriteLine("Výsledky hry:"); for (int i = 0; i < Vitezove.Count; i++) { Console.WriteLine($"{i + 1}. {Vitezove[i].Jmeno}"); } } } } <file_sep>Console.WriteLine("Zadejte zprávu:"); var vstup = Console.ReadLine(); Console.WriteLine("Zadejte heslo:"); var heslo = Console.ReadLine(); var encrypted = Vigenere(vstup, heslo, true); // false = decrypt Console.WriteLine("Zašifrovaná zpráva: " + encrypted); var message = Vigenere(encrypted, heslo, false); // false = decrypt Console.WriteLine("Rozšifrovaná zpráva: " + message); string Vigenere(string vstup, string heslo, bool encrypt) { char[] vystup = new char[vstup.Length]; for (int i = 0; i < vstup.Length; i++) { int posun = heslo[i % heslo.Length] - 'A'; if (!encrypt) { posun = -posun; } int znak = (vstup[i] - 'A' + posun) % 26; if (znak < 0) // decrypt { znak = znak + 26; } vystup[i] = (char)('A' + znak); } return new string(vystup); } <file_sep># Validace závorek (BracesValidator) Napište funkci/třídu, která bude kontrolovat ve vstupním textovém řetězci správné závorkování: * jako závorky berme `()`, `[]` a `{}`, * každá otevírací závorka musí mít svou protější zavírací závorku, * závorky se nesmí křížit. ![Screenshot](images/Screenshot.png) ## Tip Prozkoumejte datové struktury využívající princip LIFO (Last-In First-Out). Najděte v .NET vhodnou připravenou třídu, která vám při implementaci úlohy pomůže. ## Challenges * Omezte se na implementaci, která nepoužívá žádné pokročilejší datové struktury než je prosté pole. ## Inspirace ```csharp Test("{[()]}", true); Test("{(})", false); Test("{[(])}", false); Test("{{[[(())]]}}", true); Test("(){}[]", true); Test("(]", false); Test("[(])", false); Test("[({})](]", false); Test("", true); Test("pepa", true); Test("(pepa)", true); Test("10 * [123 + 7 (6 + 2)]", true); Test("10 * [123 + 7 (6 + 2))", false); void Test(string input, bool expected) { var actual = BracesValidator.IsValid(input); Console.WriteLine($"'{input}' - {actual} {(actual == expected ? String.Empty : "TEST FAILED")}"); } public class BracesValidator { public static bool IsValid(string braces) { var stack = new Stack<char>(); foreach (var c in braces) { if (c == '(' || c == '{' || c == '[') { stack.Push(c); } else if (c == ')' || c == '}' || c == ']') { if (stack.Count == 0) { return false; } var top = stack.Pop(); if (c == ')' && top != '(') { return false; } if (c == '}' && top != '{') { return false; } if (c == ']' && top != '[') { return false; } } } return stack.Count == 0; } } ``` <file_sep>int number = 9; Console.WriteLine(number); int step = 0; while (number != 1) { if (number % 2 == 0) { number = number / 2; } else { number = number * 3 + 1; } Console.WriteLine(number); step++; } Console.WriteLine("Number of steps: " + step);<file_sep>var tree = new BinarySearchTree(); tree.Insert(7); tree.Insert(5); tree.Insert(6); tree.Insert(3); tree.Insert(4); tree.Insert(1); tree.Insert(2); tree.Insert(8); tree.Insert(9); foreach (var value in tree.GetValues()) { Console.WriteLine(value); } tree.Print(); Console.WriteLine(tree.Contains(2)); Console.WriteLine(tree.Contains(23)); public class Node { public Node(int value) { this.Value = value; } public int Value { get; set; } public Node Left { get; set; } public Node Right { get; set; } } public class BinarySearchTree { public Node Root { get; set; } public void Insert(int value) { Insert(value, Root); } private void Insert(int value, Node node) { if (node == null) { Root = new Node(value); return; } if (value < node.Value) { if (node.Left == null) { node.Left = new Node(value); } else { Insert(value, node.Left); } } else { if (node.Right == null) { node.Right = new Node(value); } else { Insert(value, node.Right); } } } public bool Contains(int value) { return Contains(value, Root); } private bool Contains(int value, Node node) { if (node == null) { return false; } if (value == node.Value) { return true; } if (value < node.Value) { return Contains(value, node.Left); } else { return Contains(value, node.Right); } } public List<int> GetValues() { return GetValues(Root); } private List<int> GetValues(Node node) { if (node == null) { return new List<int>(); } var values = new List<int>(); values.AddRange(GetValues(node.Left)); values.Add(node.Value); values.AddRange(GetValues(node.Right)); return values; } public void Print() { Print(Root, 0, String.Empty); } private void Print(Node node, int level, string direction) { if (node == null) { return; } Print(node.Left, level + 1, "/"); Console.WriteLine(direction.PadLeft(level * 4) + " " + node.Value.ToString().PadRight(4)); Print(node.Right, level + 1, "\\"); } }
ee075182e29d05ef2e5b47179ee4bec4f02f1a93
[ "Markdown", "C#" ]
68
Markdown
hakenr/Programiste.CSharp
ace0fbb32e3484c4212f9fbd6a1ff863e2f3df6f
b0aab68da6356c58c5157aabcbf210280b2611d0
refs/heads/master
<repo_name>TeamChad/Resume-Template<file_sep>/src/components/Role/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import './styles.css' export default class Role extends Component { render() { const { title, company, date, summary, showSummary, duties } = this.props, dutiesList = duties.join('; ') + '.' return ( <div className="resume-role"> <h4>{title} | {company}</h4> <h5 className="resume-role__date"><em>{date}</em></h5> { showSummary ? (<div dangerouslySetInnerHTML={{__html: summary}}></div>) : null } <p><strong>Duties:</strong> {dutiesList}</p> </div> ) } } Role.defaultProps = { showSummary: true, duties: [] } Role.propTypes = { title: PropTypes.string.isRequired, company: PropTypes.string.isRequired, date: PropTypes.string.isRequired, summary: PropTypes.string.isRequired, showSummary: PropTypes.bool.isRequired, duties: PropTypes.array.isRequired, }<file_sep>/src/components/AsideTwo/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import './styles.css' export default class AsideTwo extends Component { render() { const { social, contact } = this.props, { mobile, email } = contact return ( <aside className="resume-aside-two"> <div className="resume-aside-two__body"> <div className="resume-aside-two__section"> <h2>Contact.</h2> <address> <strong>Mobile:</strong> {mobile} <br /> <strong>Email:</strong> {email} <br /> <strong>LinkedIn:</strong> <a href={social.linkedin}>{social.linkedin}</a> </address> </div> </div> </aside> ) } } AsideTwo.propTypes = { contact: PropTypes.string.isRequired, social: PropTypes.string.isRequired }<file_sep>/src/components/PageTwo/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import Project from '../Project/' import './styles.css' export default class PageTwo extends Component { _renderProjects() { return this.props.projects.map((project, i) => { return ( <Project key={i} name={project.name} client={project.client} summary={project.summary} duties={project.duties} technologies={project.technologies} /> ) }) } render() { const projects = this._renderProjects() return ( <div className="resume-main-two"> <div className="resume-main-two__body"> <div className="resume-main-two__section"> <h3>Recent Projects.</h3> {projects} </div> </div> </div> ) } } PageTwo.propTypes = { projects: PropTypes.array.isRequired }<file_sep>/src/components/Project/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import './styles.css' export default class Project extends Component { render() { const { name, client, summary, duties, technologies } = this.props, dutiesList = duties.join('; ') + '.', techList = technologies.join('; ') + '.' return ( <div className="resume-project"> <h4>{name}</h4> <h5><em>{client}</em></h5> <div dangerouslySetInnerHTML={{__html: summary}}></div> <p><strong>Duties:</strong> {dutiesList}</p> <p><strong>Technologies:</strong> {techList}</p> </div> ) } } Project.defaultProps = { duties: [], technologies: [] } Project.propTypes = { name: PropTypes.string.isRequired, client: PropTypes.string.isRequired, summary: PropTypes.string.isRequired, duties: PropTypes.array.isRequired, technologies: PropTypes.array.isRequired }<file_sep>/src/components/PageOne/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import Role from '../Role/' import Award from '../Award/' import './styles.css' export default class PageOne extends Component { _renderRoles() { return this.props.roles.map((role, i) => { return ( <Role key={i} title={role.title} company={role.company} date={role.date} summary={role.summary} showSummary={role.showSummary} duties={role.duties} /> ) }) } _renderAwards() { return this.props.awards.map((award, i) => { return ( <Award key={i} name={award.name} date={award.date} /> ) }) } render() { const { name, job } = this.props, roles = this._renderRoles(), awards = this._renderAwards() return ( <div className="resume-main-one"> <h1>{name}</h1> <h2>{job}</h2> <div className="resume-main-one__body"> <div className="resume-main-one__section"> <h3>Work Experience.</h3> {roles} </div> <div className="resume-main-one__section"> <h3>Awards.</h3> {awards} </div> </div> </div> ) } } PageOne.propTypes = { name: PropTypes.string.isRequired, job: PropTypes.string.isRequired, roles: PropTypes.array.isRequired, awards: PropTypes.array.isRequired }<file_sep>/src/reducers/Resume.js import * as types from '../constants/' export const initialState = { appReady: false, contact: { firstname: '', lastname: '', email: '', mobile: '', home: '' }, job: '', photo: '', summary: '', // accepts HTML social: { linkedin: '' }, roles: [ // component { title: 'Role 1', company: '', date: '', summary: '', // accepts HTML showSummary: true, // Set to false for short version of role duties: [ // lists duties in ';' separated string 'duty 1', 'duty 2', 'duty 3 ...' ] }, { title: 'Role 2', company: '', date: '', summary: '', // accepts HTML showSummary: true, // Set to false for short version of role duties: [ // lists roles in ';' separated string 'duty 1', 'duty 2', 'duty 3 ...' ] } ], skills: [ { name: 'Skill 1', rating: 9 // 0 - 10 }, { name: 'Skill 2', rating: 4 // 0 - 10 }, { name: 'Skill 3', rating: 7 // 0 - 10 } ], interests: [ // Prints as '<li>' in an '<ul>' 'interest 1', 'interest 2', 'interest 3 ... ' ], awards: [ // component { name: 'Award 1', date: '2017' }, { name: 'Award 2', date: '2016' } ], projects: [ // component { name: 'Project 1', client: '', summary: '', // accepts HTML duties: [ // lists duties in ';' separated string 'duty 1', 'duty 2', 'duty 3 ...' ], technologies: [ // lists technologies in ';' separated string 'tech 1', 'tech 2', 'tech 3 ...' ] }, { name: 'Project 2', client: '', summary: '', // accepts HTML duties: [ // lists duties in ';' separated string 'duty 1', 'duty 2', 'duty 3 ...' ], technologies: [ // lists technologies in ';' separated string 'tech 1', 'tech 2', 'tech 3 ...' ] } ], referees: [] } export default function resume(state = initialState, action) { switch(action.type) { case types.APP_READY: return {...state, appReady: true } default: return state; } }<file_sep>/src/components/AsideOne/index.js import React, { Component } from 'react' import PropTypes from 'prop-types' import Skill from '../Skill/' import './styles.css' export default class AsideOne extends Component { _renderSkills() { const { appReady, skills } = this.props return skills.map((skill, i) => { return ( <Skill key={i} appReady={appReady} name={skill.name} rating={skill.rating} /> ) }) } _renderInterests() { const { interests } = this.props, interestsList = interests.map((interest, i) => { return ( <li key={i}>{interest}</li> ) }) if (interests.length) { return ( <ul>{interestsList}</ul> ) } return null } render() { const { name, photo, summary } = this.props, skillsList = this._renderSkills(), interestsList = this._renderInterests() return ( <aside className="resume-aside-one"> <header> <img src={photo} alt={`${name} profile. `} /> </header> <div className="resume-aside-one__body"> <div className="resume-aside-one__section"> <h2>About Me.</h2> <div dangerouslySetInnerHTML={{__html: summary}}></div> </div> <div className="resume-aside-one__section"> <h2>Skills.</h2> {skillsList} </div> <div className="resume-aside-one__section"> <h2>Interests.</h2> {interestsList} </div> </div> </aside> ) } } AsideOne.propTypes = { appReady: PropTypes.bool.isRequired, name: PropTypes.string.isRequired, photo: PropTypes.string.isRequired, summary: PropTypes.string.isRequired, skills: PropTypes.array.isRequired, interests: PropTypes.array.isRequired }
5eef41d3cc6b482ce5a9be7af5c8c9965fe60c8d
[ "JavaScript" ]
7
JavaScript
TeamChad/Resume-Template
3ecfee9383612b55e0fc1b05890d6b3be35d1e99
167b25b28ce9adce65893681117c78d4b0529c92
refs/heads/main
<file_sep>// // MacroPlanGenerator.swift // Udemy05-SuperSenha // // Created by <NAME> on 16/10/21. // import Foundation class MacroGenerator{ var weight : Int var height : Int var age : Int var activityLevel : ActivityLevel var gender : Gender var optSwitch : Bool init(weight : Int, height : Int, age : Int, activityLevel : ActivityLevel, gender : Gender, optSwitch : Bool) { self.weight = weight self.height = height self.age = age self.activityLevel = activityLevel self.gender = gender self.optSwitch = optSwitch } func BMRGenerate() -> Double{ switch gender { case .MAN: return calcMan() default: return calcWoman() } } private func calcWoman() -> Double{ var tmb = 665.1 + (9.56 * Double(weight)) + (1.8 * Double(height)) - (4.7 * Double(age)) tmb = activityLevel.addActivityBurn(tmb: tmb) return tmb } private func calcMan() -> Double{ var tmb = 66.5 + (13.75 * Double(weight)) + (5.0 * Double(height)) - (6.8 * Double(age)) tmb = activityLevel.addActivityBurn(tmb: tmb) return tmb } func highProtRecompDiet() -> String{ var kcalBase = BMRGenerate() let threeGramsProtByKilo = weight * 3 let threeGramsProtByKiloTotalKcal = threeGramsProtByKilo * 4 kcalBase -= Double(threeGramsProtByKiloTotalKcal) let twoGramsCarbByKilo = weight * 2 let twoGramsCarbByKiloTotalKcal = twoGramsCarbByKilo * 4 kcalBase -= Double(twoGramsCarbByKiloTotalKcal) let remaingWithFat = kcalBase / 9 let remaingWithFatTotalKcal = remaingWithFat * 9 print(Int(threeGramsProtByKilo)) print(Int(twoGramsCarbByKilo)) print(Int(remaingWithFat)) return """ High-Protein Recomp Diet Prot: \(Int(threeGramsProtByKilo)) grams Carb: \(Int(twoGramsCarbByKilo)) grams Gord: \(Int(remaingWithFat)) grams """ } func highCarbGenerator(){ } func fiftyGenerator() -> String{ var kcalBase = BMRGenerate() let fiftyCarb = kcalBase * 0.4 let fiftyProt = kcalBase * 0.4 let remaingFat = kcalBase * 0.2 return """ 50-50 Clean Bulk Diet Prot: \(Int(fiftyProt)/4) grams Carb: \(Int(fiftyCarb)/4) grams Gord: \(Int(remaingFat)/9) grams """ } } <file_sep>// // MacroViewController.swift // Udemy05-SuperSenha // // Created by <NAME> on 16/10/21. // import UIKit //Duvida pro mentor //No curso ele usa o ! force para receber os dados e passar para a classe geradora // Qual é a forma correta? class MacroViewController: UIViewController { @IBOutlet weak var tvGeneratedMacro: UITextView! var weight : Int? var height : Int? var age : Int! var activityLevel : ActivityLevel! var gender : Gender! var showKcal : Bool! var macroGenerator : MacroGenerator! override func viewDidLoad() { super.viewDidLoad() if let validWeight = weight, let validHeight = height, let validAge = age { macroGenerator = MacroGenerator(weight: validWeight , height: validHeight , age: validAge, activityLevel: activityLevel, gender: gender, optSwitch: showKcal) let highProt = macroGenerator.highProtRecompDiet() let fiftyfifty = macroGenerator.fiftyGenerator() title = "Total de calorias: " + String( Int(macroGenerator.BMRGenerate())) tvGeneratedMacro.text.append(highProt + "\n\n") tvGeneratedMacro.text.append(fiftyfifty + "\n\n") } else { print("Erro ao preencher os dados") } } } enum Gender : Int { case MAN = 0 case WOMAN } enum ActivityLevel : Int { case LOW = 0 case MED = 1 case HIGH = 2 func addActivityBurn(tmb : Double) -> Double { switch self { case .LOW: return tmb * 1.1 case .MED: return tmb * 1.2 case .HIGH: return tmb * 1.3 } } } <file_sep>// // ViewController.swift // Udemy05-SuperSenha // // Created by <NAME> on 16/10/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tfWeight: UITextField! @IBOutlet weak var tfHeight: UITextField! @IBOutlet weak var segActivityLevel: UISegmentedControl! @IBOutlet weak var segGender: UISegmentedControl! @IBOutlet weak var optShowKcal: UISwitch! @IBOutlet weak var tfAge: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func btnGenerateMacro(_ sender: UIButton) { if let unWrapWeight = tfWeight.text, let safeWeight = Int(unWrapWeight), safeWeight > 40, safeWeight < 200, let unWrapHeight = tfHeight.text, let safeHeight = Int(unWrapHeight), safeHeight > 100, Int(unWrapHeight)! < 220, let unWrapAge = tfAge.text , let safeAge = Int(unWrapAge), safeAge > 15, safeAge < 100 { performSegue(withIdentifier: "nextSegue", sender: nil) } else { let alert = UIAlertController(title: "Erro", message: "Você deve preencher os campos corretamente", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let next = segue.destination as! MacroViewController if let weight = Int(tfWeight.text!), let height = Int(tfHeight.text!), let age = Int(tfAge.text!) { next.weight = weight next.height = height next.age = age } next.showKcal = optShowKcal.isOn next.activityLevel = ActivityLevel.init(rawValue: segActivityLevel.selectedSegmentIndex) next.gender = Gender.init(rawValue: segGender.selectedSegmentIndex) next.showKcal = optShowKcal.isOn view.endEditing(true) } }
8c5cbe27bb5c7387e8550a2400dc214a1a1cf142
[ "Swift" ]
3
Swift
WilliamMoraesZup/UdemySection5-MacroGeneratorAPP
53357af7ca161824418b601a7bf2ee6a0a1c36c7
5e8510f5a80697a60cd9988f16df31190e97c79a
refs/heads/master
<repo_name>techwebspot/InstagramBot<file_sep>/main.py #! /usr/bin/python3 from chatterbot import ChatBot from chatterbot.trainers import ListTrainer from chatterbot.trainers import ChatterBotCorpusTrainer from selenium import webdriver import time from selenium.common.exceptions import NoSuchElementException print( """ \t\t\t\t\t\t██  ██████  ██████  ██████  ████████  \t\t\t\t\t\t██ ██       ██   ██ ██    ██    ██     \t\t\t\t\t\t██ ██  ███  ██████  ██  ██  ██  \t\t\t\t\t\t██ ██  ██  ██   ██ ██  ██  ██  \t\t\t\t\t\t██  ██████   ██████   ██████   ██  - By Mansi                                 """ ) def printGreen(text): print("\033[92m{}\033[00m" .format(text)) def printPurple(text): print("\033[95m{}\033[00m" .format(text)) def printRed(text): print("\033[91m{}\033[00m" .format(text)) try: chatbot = ChatBot("Mansi's chatbot", storage_adapter='chatterbot.storage.SQLStorageAdapter', logic_adapters=[ 'chatterbot.logic.MathematicalEvaluation', #'chatterbot.logic.TimeLogicAdapter', 'chatterbot.logic.BestMatch', { 'import_path': 'chatterbot.logic.SpecificResponseAdapter', 'input_text': 'help', 'output_text': 'here is a link: http://chatterbot.rtfd.org' } ], database_uri='sqlite:///database.db' ) conversation = [ "Hello", "Hi there!", "How are you doing?", "I'm doing great.", "That is good to hear", "Thank you.", "You're welcome.", "who made you?", "Mansi made me under Jeet's guidance", ] printGreen("Loading Corpus...\n") trainer = ListTrainer(chatbot) trainer.train(conversation) trainer = ChatterBotCorpusTrainer(chatbot) trainer.train( "chatterbot.corpus.hindi" ) def finding_path(xpath): flag = False while (flag == False): try: driver.find_element_by_xpath(xpath) flag = True except NoSuchElementException: #print("Finding path...") pass return flag printGreen("\nEnter Instagram Credentials - \n") username_id = input("\033[95mUsername: \033[00m") username_password = input("\<PASSWORD>") driver = webdriver.Firefox() driver.get("https://www.instagram.com/") username = "html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[2]/div/label/input" password = "/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[3]/div/label/input" login = "/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div[4]" save = "/html/body/div[1]/section/main/div/div/div/div/button" notnowbutton = "/html/body/div[4]/div/div/div/div[3]/button[2]" signmsg = "/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[2]/div/div/div/div/div[1]/a/div/div[3]/div" user1 = "/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[2]/div/div/div/div/div[1]/a/div" userpath = "/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[2]/div/div/div/div/div[1]/a/div/div[2]/div[1]/div/div/div/div" msg_to_send = "/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea" send_button = "/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[3]/button" check_user = finding_path(username) try: if check_user: driver.find_element_by_xpath(username).send_keys(username_id) driver.find_element_by_xpath(password).send_keys(<PASSWORD>_<PASSWORD>) driver.find_element_by_xpath(login).click() check_save_popup = finding_path(save) if check_save_popup: printGreen("\nLogin Successfully! \n\nBot is running....") driver.find_element_by_xpath(save).click() check_notnow = finding_path(notnowbutton) if check_notnow: driver.find_element_by_xpath(notnowbutton).click() while True: driver.get("https://www.instagram.com/direct/inbox/") check_msg = finding_path(signmsg) if check_msg: #print("new msg") print("\n") firstuser = driver.find_element_by_xpath(userpath).text driver.find_element_by_xpath(user1).click() counter = 1 while True: """ a = driver.find_element_by_xpath("/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[6]/div[2]/div").text print(a) """ try: finding_last_msg_xpath = "/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[" + str(counter) + "]/div[2]/div" last_message = driver.find_element_by_xpath(finding_last_msg_xpath).text #print(last_message) counter = counter + 1 except NoSuchElementException: #print("There's no message with ID: " + str(counter)) counter = counter + 1 if counter > 50: print(firstuser + ": " + last_message) counter = 1 break bot_response = chatbot.get_response(last_message) driver.find_element_by_xpath(msg_to_send).send_keys(str(bot_response)) driver.find_element_by_xpath(send_button).click() print("Bot: " + str(bot_response)) except (KeyboardInterrupt, EOFError, SystemExit): printRed("\n\nUser Requested An Interrupt") printRed("Apllication Shutting Down") printRed("Closing Instagram Bot") driver.quit() except KeyboardInterrupt: printRed("\n\nUser Requested An Interrupt") printRed("Application Shutting Down") <file_sep>/requirements.txt blis==0.2.4 certifi==2020.4.5.1 chardet==3.0.4 ChatterBot==1.1.0 chatterbot-corpus==1.2.0 click==7.1.2 cymem==2.0.3 en-core-web-sm==2.1.0 idna==2.9 joblib==0.15.1 mathparse==0.1.2 murmurhash==1.0.2 nltk==3.5 numpy==1.18.4 Pint==0.11 pkg-resources==0.0.0 plac==0.9.6 preshed==2.0.1 python-dateutil==2.8.1 pytz==2020.1 PyYAML==3.13 regex==2020.5.14 requests==2.23.0 selenium==3.141.0 six==1.15.0 spacy==2.1.9 SQLAlchemy==1.3.17 srsly==1.0.2 thinc==7.0.8 tqdm==4.46.0 urllib3==1.25.9 wasabi==0.6.0 <file_sep>/README.md # InstagramBot *This Instagram Bot is designed to convincingly simulate the way a human would behave as a conversational partner.* ## Requirements : 1. Python3 2. Selenium - Setup selenium in your system for firefox which requires geckodrivers. 3. Chatterbot 4. Mozilla Firefox ## How to run the script: ###### Installing from web browser 1. Download the zip file using the "Clone or download" button. 2. Navigate to the download directory and unzip the archive. 3. Open a terminal and navigate to the target directory. `cd ~/Downloads/InstagramBot-master` 4. To install requirement modules. `pip3 install -r requirements.txt` 5. Give permission to the script. `chmod +x main.py` 6. Execute the script. `./main.py` ###### Installing from command line ``` cd ~/Downloads git clonehttps://github.com/mansisharma0510/InstagramBot.git cd InstagramBot pip3 install -r requirements.txt chmod +x main.py ./main.py ```
fe5c398eb716044e4c461929bf3b4551dec50511
[ "Markdown", "Python", "Text" ]
3
Python
techwebspot/InstagramBot
123a61ed7abc75abdc67b613f956b3115307b953
ab96751c6607f650db327d559ec190a6042303e0
refs/heads/master
<file_sep># -------------------------------- # <NAME> # 5/23/18 # Dialogue between computer and user # -------------------------------- import datetime import time import sys def slow_text(word): # Add a parameter 'speed' to control speeds of different things # Makes the text type letter by letter slowly. for l in word: sys.stdout.write(l) sys.stdout.flush() time.sleep(0.2) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st + " Sean >> ") slow_text("Hey Denise \n\n") ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st + " Denise >> ") slow_text("Hey Sean \n\n") ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st + " Sean >> ") slow_text("I'm just chillin wbu? \n\n") ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st + " Denise >> ") slow_text("Venmo'ing you a ton of money \n\n") ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(st + " Sean >> ") slow_text("Oh heck ya! \n\n")
bec8e8310efb02eed9d347b7e6e582c9cb5eeb71
[ "Python" ]
1
Python
seanconrad1/robot_dialogue
6558358365e751a907bec1f88f5b0e4610c6fd76
f68bd96c9c35a0276c32b4038c08e064c9f9380b
refs/heads/main
<file_sep># nat-res-map Simple web app showing some of Armenia's natural resources. <file_sep>import folium import pandas map = folium.Map(location=[40.0691, 45.0382], zoom_start=8, tiles="Stamen Terrain") def generate_colors(arg): if arg == 'CALCITE': color = 'red' elif arg == 'TUFF': color = 'yellow' elif arg == 'COPPER': color = 'black' elif arg == 'MULTI-METAL ORE': color = 'grey' elif arg == 'BASALT': color = 'green' elif arg == 'SALT': color = 'brown' elif arg == "CHROME": color = 'orange' return color data = pandas.read_csv('natres.txt', sep=';') natural_resources = list(data['NATRES']) lon = list(data['LON']) lat = list(data['LAT']) print(natural_resources) fg_calcite = folium.FeatureGroup(name='կրաքար') fg_tuff = folium.FeatureGroup(name='տուֆ') fg_copper = folium.FeatureGroup(name='պղինձ') fg_basalt = folium.FeatureGroup(name='բազալտ') fg_salt = folium.FeatureGroup(name='կերակրի աղ') fg_chrome = folium.FeatureGroup(name='քրոմիտ') fg_mmore = folium.FeatureGroup(name='բազմամետաղային հանքաքար') for i in range(len(natural_resources)): if 'CALCITE' == natural_resources[i]: fg_calcite.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('CALCITE'), color=generate_colors('CALCITE'), fill_opacity=0.7)) elif 'TUFF' == natural_resources[i]: fg_tuff.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('TUFF'), color=generate_colors('TUFF'), fill_opacity=0.7)) elif 'COPPER' == natural_resources[i]: fg_copper.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('COPPER'), color=generate_colors('COPPER'), fill_opacity=0.7)) elif 'BASALT' == natural_resources[i]: fg_basalt.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('BASALT'), color=generate_colors('BASALT'), fill_opacity=0.7)) elif 'SALT' == natural_resources[i]: fg_salt.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('SALT'), color=generate_colors('SALT'), fill_opacity=0.7)) elif 'CHROME' == natural_resources[i]: fg_chrome.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('CHROME'), color=generate_colors('CHROME'), fill_opacity=0.7)) elif 'MULTI-METAL ORE' == natural_resources[i]: fg_mmore.add_child(folium.CircleMarker(location=[lon[i], lat[i]], popup=str(lon[i])+' '+str(lat[i]), radius=6, fill_color=generate_colors('MULTI-METAL ORE'), color=generate_colors('MULTI-METAL ORE'), fill_opacity=0.7)) map.add_child(fg_calcite) map.add_child(fg_tuff) map.add_child(fg_copper) map.add_child(fg_basalt) map.add_child(fg_salt) map.add_child(fg_chrome) map.add_child(fg_mmore) map.add_child(folium.LayerControl()) map.save('new_map.html')
1c7b218a0d691d77f04a9dafcd69e8ce7f830682
[ "Markdown", "Python" ]
2
Markdown
koryun23/nat-res-map
a66f7e777243ba5543da500cac03fb9ff1b67d47
101e3c281e4436ec9f0b96c8c9654a014c820262
refs/heads/master
<file_sep>#include <Servo.h> #include <math.h> # define button_pin 2 # define led_pin 6 # define servo_pin 9 # define angle_max 90 # define angle_min 33 Servo myservo; int button_to_fade = 0; // variable for reading the pushbutton status int brightness = 0; // how bright the LED is int fadeAmount = 2; // how many points to fade the LED int servo_pos = 0; bool to_fade = false; // to_fade or not to_fade void setup() { pinMode(led_pin, OUTPUT); pinMode(button_pin, INPUT); pinMode(LED_BUILTIN, OUTPUT); myservo.attach(servo_pin); myservo.write(angle_min); Serial.begin(9600); } void loop() { button_to_fade = digitalRead(button_pin); if (to_fade) { LED_fade(); servo_turn(); delay(50); } else { if (button_to_fade == HIGH) { to_fade = true; // digitalWrite(LED_BUILTIN, HIGH); // Serial.println("to_fade = "); Serial.print(to_fade); } else { // digitalWrite(LED_BUILTIN, LOW); // To see result } if (brightness <= 0){ digitalWrite(led_pin, LOW); // } else if (brightness >= 255){ // digitalWrite(led_pin, HIGH); } } // Serial.print("to_fade = "); Serial.println(to_fade); } void LED_fade(){ // analogWrite(led_pin, fading_brightness(brightness)); analogWrite(led_pin, brightness); // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness <= 0 || brightness >= 255) { fadeAmount = -fadeAmount; to_fade = false; // if (brightness < 0){ // brightness = 0; // digitalWrite(led_pin, LOW); // } } // Serial.print("Brightness = "); Serial.print(brightness); Serial.print(" | new_brightness = "); Serial.println(fading_brightness(brightness)); // Serial.print("Brightness = "); Serial.println(brightness); } //int fading_brightness (int old_brightness){ // return exp(old_brightness / 46); // return old_brightness; //} void servo_turn(){ servo_pos = map(brightness, 0, 255, angle_min, angle_max); // servo_pos = servo_pos + servo_step; // servo_pos = constrain(servo_pos, 5, 175) myservo.write(servo_pos); } <file_sep># Flower Simple code for Blooming Mechanical Flower [project](https://www.instructables.com/id/Ever-Blooming-Mechanical-Tulip/, "Project link").
c15e6ff9a8339a67917f4910d8ceeaf48a90409a
[ "Markdown", "C++" ]
2
C++
Aquarious02/Flower
12287a925b84ff12d9e83bdc351bc46654e997cf
9edf3e68e1ce15315b619a49a63455364c79806c
refs/heads/master
<file_sep>package test; import java.util.concurrent.TimeUnit; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import common.*; import pageobject.CreateScholarshipObject; public class CreateScholarship { @BeforeTest @Parameters("browser") public void setUp(String browser) throws Exception { OpenBrowser.multi_browser(browser); //Common.driver.manage().window().maximize(); Common.driver.manage().timeouts().implicitlyWait(Common.TIMEOUTS,TimeUnit.SECONDS); } @Test public void CreateSchoolarship() throws InterruptedException { Common.driver.get(Common.URL); // Select obj = Common.driver.findElement(); // obj.selectByIndex(3); // obj.selectByValue("VN"); // obj.selectByVisibleText("Viet Nam"); Common.driver.findElement(CreateScholarshipObject.mnuHocduong).click(); // Common.driver.findElement(CreateScholarshipObject.txtuseradmin).sendKeys("<EMAIL>"); // Common.driver.findElement(CreateScholarshipObject.txtpassadmin).sendKeys("<PASSWORD>"); // Common.driver.findElement(CreateScholarshipObject.btnLoginadmin).click(); // Common.driver.findElement(CreateScholarshipObject.menuScholarship).click(); // Common.driver.findElement(CreateScholarshipObject.submenuCreate).click(); // Common.driver.findElement(CreateScholarshipObject.optNonrefundable).click(); // Common.driver.findElement(CreateScholarshipObject.txtNameScholarship).sendKeys("HUBT"); // Common.driver.findElement(CreateScholarshipObject.txtNameOranization).sendKeys("Shoppie VN1"); // Common.driver.findElement(CreateScholarshipObject.cboTypeOranization).click(); // Common.driver.findElement(CreateScholarshipObject.cboTypeOranization).sendKeys("companies"); // Common.driver.findElement(CreateScholarshipObject.cboOrigin).click(); // Common.driver.findElement(CreateScholarshipObject.cboOrigin).sendKeys("Australia"); // Common.driver.findElement(CreateScholarshipObject.cbxSchool).click(); // Common.driver.findElement(CreateScholarshipObject.cboCurrency).sendKeys("USD"); // Common.driver.findElement(CreateScholarshipObject.txtMinimum).sendKeys("8000000"); // Common.driver.findElement(CreateScholarshipObject.cboBenifitMonth).click(); // Common.driver.findElement(CreateScholarshipObject.cboBenifitMonth).sendKeys("6 Month"); // Common.driver.findElement(CreateScholarshipObject.cboBenifitYear).click(); // Common.driver.findElement(CreateScholarshipObject.cboBenifitYear).sendKeys("4 Year"); // Common.driver.findElement(CreateScholarshipObject.cboAppStartMonth).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppStartMonth).sendKeys("6 Month"); // Common.driver.findElement(CreateScholarshipObject.cboAppStartDay).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppStartDay).sendKeys("1"); // Common.driver.findElement(CreateScholarshipObject.cboAppStartYear).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppStartYear).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppStartYear).sendKeys("2016"); // Common.driver.findElement(CreateScholarshipObject.cboAppEndMonth).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppEndMonth).sendKeys("12 Month"); // Common.driver.findElement(CreateScholarshipObject.cboAppEndDay).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppEndDay).sendKeys("28"); // Common.driver.findElement(CreateScholarshipObject.cboAppEndYear).click(); // Common.driver.findElement(CreateScholarshipObject.cboAppEndYear).sendKeys("2016"); // Common.driver.findElement(CreateScholarshipObject.cbxDocument).click(); // } @AfterTest public void tearDown() throws Exception { //Common.driver.quit(); } }
c46c8ebee4d335f68524438009a2b7e510e027e8
[ "Java" ]
1
Java
duongth9x/Schoolynk
b64edbb1fa98aac988f3097dd8662e63535b309d
0505bfeafa74bc71e00ad00daa328ebd35a29dba
refs/heads/master
<file_sep>trantor-almanac =============== An almanac for the friendly neighborhoods on Trantor! The Trantor Almanac is an essential tool for the peaceful people living on Trantor. Every bookstore or library has copies of the almanac. <file_sep>#include <stdio.h> #include <time.h> #include <stdlib.h> #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" int date_seed() { // generates a random seed based on system date return 3; } int main(int argc, char const *argv[]) { // Try out the colors printf("%sred\n", KRED); printf("%sgreen\n", KGRN); printf("%syellow\n", KYEL); printf("%sblue\n", KBLU); printf("%smagenta\n", KMAG); printf("%scyan\n", KCYN); printf("%swhite\n", KWHT); printf("%snormal\n", KNRM); time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); printf ("Current local time and date: %s", asctime(timeinfo)); return 0; } <file_sep># # Makefile for trantor-almanac # CC = gcc CFLAGS = -Wall DFLAGS = -Wall -O0 -g almanac: almanac.c $(CC) $(DFLAGS) almanac.c -o almanac clean: rm *.o ./almanac
c65e7f73f0da9fa7c0ab18334dc8243a66d3b5ac
[ "Markdown", "C", "Makefile" ]
3
Markdown
shimmy1996/trantor-almanac
7bb630a734416390418373df4444259edd85efc1
4db4bfa8d557f32320469f80737935a678d1027a
refs/heads/master
<file_sep>from fastapi import FastAPI, HTTPException from pydantic import BaseModel import requests import os import json ip = os.getenv("redirect_ip") addr = 'http://' + ip + ':5000' app = FastAPI() dict_tasks = dict() class Tasks(BaseModel): name: str priority: int @app.get("/") async def read_root(): redirect = requests.get(url = addr + '/') return redirect.json() @app.get("/task") async def list_tasks(): print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa') redirect = requests.get(url = addr + '/task') return redirect.json() @app.post("/task") async def add_task(task: Tasks): data = { "name": task.name, "priority": task.priority } requests.post(url = addr + '/task', data = json.dumps(data)) <file_sep># Cloud_APS1 Webserver for cloud <file_sep>from fastapi import FastAPI, HTTPException from pydantic import BaseModel import pymongo import os ip = os.getenv("mongodb_ip") addr = "mongodb://" + ip + ":27017/" mongo_client = pymongo.MongoClient(addr) db = mongo_client['cloud_database'] tasks = db['tasks'] app = FastAPI() class Tasks(BaseModel): name: str priority: int @app.get("/") async def read_root(): return {"hello": "world"} @app.get("/task") async def list_tasks(): ret = {} ret['Values'] = [] for i in tasks.find(): # .sort( {'priority': 1} ): ret['Values'].append( { 'id': str(i["_id"]), 'name': i["name"], 'priority': i["priority"] } ) return ret @app.post("/task") async def add_task(task: Tasks): ret = { 'name': task.name, 'priority': task.priority, } tasks.insert(ret)
63219c0c555718634db2f492a44912255e36bd72
[ "Markdown", "Python" ]
3
Python
vadlachary2002/Cloud_APS1
1a45723482095b7686a4025260759d7141a68f50
f6e636bcd93ea5e42c18f35606e2c4f49d7f4c01
refs/heads/master
<repo_name>362663496/yk_friend_yao<file_sep>/runtime/temp/7088ef9512d8119035ff9e1ff86b1662.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:69:"D:\phpStudy\WWW\yk_friend/application/index\view\questions\index.html";i:1551321476;}*/ ?> <!DOCTYPE html> <html> <head> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css?v=4.1.0" rel="stylesheet"> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> <link href="css/plugins/cropper/cropper.min.css" rel="stylesheet"> <link href="css/plugins/datapicker/datepicker3.css" rel="stylesheet"> </head> <body class="gray-bg"> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-sm-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>常见问题&nbsp; <a class="btn btn-info btn-xs" onclick="confirmAdd()">新增常见问题</a></h5> </div> <div class="ibox-content"> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>ID</th> <th>标题</th> <th>内容</th> <th>发布时间</th> </tr> </thead> <tbody> <?php if(is_array($data) || $data instanceof \think\Collection || $data instanceof \think\Paginator): $i = 0; $__LIST__ = $data;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$questions): $mod = ($i % 2 );++$i;?> <tr> <td style="width: 5%;"><?php echo $questions['id']; ?></td> <td style="width: 15%;"><?php echo $questions['title']; ?></td> <td style="width:50%;"><?php echo $questions['content']; ?></td> <td style="width: 20%;"><?php echo date("Y-m-d H:i:s",$questions['addtime']); ?></td> </tr> <?php endforeach; endif; else: echo "" ;endif; ?> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="modal fade in" id="add" tabindex="-1" role="dialog" aria-labelledby="exampleModal" style="display: none; padding-right: 17px;"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="exampleModal" style="text-align: center">新增系统消息</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="addTitle" class="control-label">标题:</label> <input type="text" class="form-control" id="addTitle" placeholder="标题"> </div> <div class="form-group"> <label for=addContent class="control-label">内容:</label> <textarea id="addContent" class="form-control" rows="4"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" onclick="sendAdd()">确定</button> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> </div> </div> </div> </div> <!-- 全局js --> <script src="js/jquery.min.js?v=2.1.4"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- 自定义js --> <script src="js/content.js?v=1.0.0"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <!-- Image cropper --> <script src="js/plugins/cropper/cropper.min.js"></script> <!-- Data picker --> <script src="js/plugins/datapicker/bootstrap-datepicker.js"></script> <script src="js/demo/form-advanced-demo.js"></script> <script> //新增系统消息 function confirmAdd() { $('#add').modal("show"); } function sendAdd() { var addTitle = $('#addTitle').val(); var addContent = $('#addContent').val(); if (addTitle == '' || addContent == ''){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error("不能为空"); return false; } $.post("<?php echo url('questions/addQuestions'); ?>",{title:addTitle,content:addContent},function (res) { if (res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },1500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); } },'json') } </script> </body> </html><file_sep>/application/index/controller/Activity.php <?php namespace app\index\controller; use app\index\model\Activities; use think\Db; use think\Request; class Activity extends Base { /** * 文章列表 * * @return \think\response\View */ public function index() { //搜索框条件 $activity_name = empty(input('activity_name')) ? '' : trim(input('activity_name')); //获取文章列表 $list = Activities::getActivity($activity_name); //赋值 $this->assign('activity_name',$activity_name); $this->assign('list',$list); //列表数据 //渲染视图 return view(); } /** * 文章新增 * * @param Request $request * @return \think\response\View */ public function activity_add(Request $request) { if ($request->isPost()) { //接值 $post['activity_name'] = input('activity_name'); $post['desc'] = input('desc'); $post['pid'] = input('type'); $insertRs = Db::name('activity')->insert($post); if ($insertRs) ajaxReturn(1,'新增分类成功',''); ajaxReturn(0,'新增分类失败',''); } else { //获取分类列表 $typeList = Activities::getType(); $this->assign('typeList', $typeList); return view(); } } /** * 文章类型 * * @return \think\response\View */ public function type() { //搜索框条件 $type_name = empty(input('type_name')) ? '' : trim(input('type_name')); //获取分类列表 $articleList = Articles::getArticleType($type_name); //赋值 $this->assign('type_name',$type_name); $this->assign('list',$articleList); //列表数据 //渲染视图 return view(); } } <file_sep>/application/common/controller/Image.php <?php namespace app\common\controller; class Image { public function createQRcode($save_path,$qr_data='PHP QR Code :)',$qr_level='H',$qr_size=10,$save_prefix='qrcode') { if(!isset($save_path)) return ''; //设置生成png图片的路径 $PNG_TEMP_DIR = & $save_path; //导入二维码核心程序 vendor('phpqrcode.phpqrcode'); //注意这里的大小写哦,不然会出现找不到类,PHPQRcode是文件夹名字,class#phpqrcode就代表class.phpqrcode.php文件名 //检测并创建生成文件夹 if (!file_exists($PNG_TEMP_DIR)){ mkdir($PNG_TEMP_DIR); } $filename = $PNG_TEMP_DIR.md5($qr_data).'.png'; $errorCorrectionLevel = 'L'; if (isset($qr_level) && in_array($qr_level, array('L','M','Q','H'))){ $errorCorrectionLevel = & $qr_level; } $matrixPointSize = 10; if (isset($qr_size)){ $matrixPointSize = min(max((int)$qr_size, 1), 10); } if (!isset($qr_data)) { if (trim($qr_data) == ''){ die('data cannot be empty!'); } //生成文件名 文件路径+图片名字前缀+md5(名称)+.png $filename = $PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png'; //开始生成 \QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2); } else { //默认生成 \QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2); } // p($filename,1); if(file_exists($PNG_TEMP_DIR.basename($filename))) return basename($filename); else return FALSE; } }<file_sep>/application/index/model/AdminRole.php <?php namespace app\index\model; use think\Model; class AdminRole extends Model { /** * 获取角色列表 * * @return false|\PDOStatement|string|\think\Collection */ public static function getRoleList() { return self::field('id,role_name,addtime,pri')->paginate(15); } /** * 判断角色名称是否存在 * * @param $roleName * @return array|false|\PDOStatement|string|Model */ public static function checkName($roleName) { return self::field('id')->where(['role_name'=>$roleName])->find(); } } ?><file_sep>/application/common.php <?php // 应用公共文件 /** * 自定义打印函数p * * @param $data * @param int $status */ function p($data,$status=0) { if (is_array($data)) { echo '<pre>'; print_r($data); echo '<hr>'; } else { echo '<pre>'; var_dump($data); echo '<hr>'; } if ($status==1) die; } /** * 定义后台统一返回数据格式 * * @param $status * @param $msg * @param $data */ function ajaxReturn($status,$msg,$data) { exit(json_encode(['status'=>$status,'msg'=>$msg,'data'=>$data])); } /** * qpi统一返回数据 * * @param $code * @param string $msg_zh * @param array $data */ function apiReturn($code, $msg_zh = '', $data = array("k" => "")) { header('Content-type: application/json'); exit(json_encode(['code' => $code, 'msg' => $msg_zh, 'data' => $data])); } /** * web端同一返回数据 * * @param $code * @param string $msg_zh * @param array $data */ function webReturn($code, $msg_zh = '', $data = array("k" => "")) { header('Access-Control-Allow-Origin:*'); header('Content-Type:text/html;charset=utf-8'); header('Content-type: application/json'); exit(json_encode(['code' => $code, 'msg' => $msg_zh, 'data' => $data])); } /** * 对象 转 数组 * * @param object $obj 对象 * @return array */ function object_to_array($obj) { $obj = (array)$obj; foreach ($obj as $k => $v) { if (gettype($v) == 'resource') { return; } if (gettype($v) == 'object' || gettype($v) == 'array') { $obj[$k] = (array)object_to_array($v); } } return $obj; } /** * 自定义MD5加密 * * @param $str * @return bool|string */ function myMd5($str) { if(!$str){ return false; } $md5 = md5($str); $md5 = md5('chejishi'.$md5); return $md5; } /** * php获取中文字符拼音首字母 * * @param $str * @return null|string */ function getFirstCharter($str) { if (empty($str)) { return ''; } $fchar = ord($str{0}); if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0}); $s1 = iconv('UTF-8', 'gb2312', $str); $s2 = iconv('gb2312', 'UTF-8', $s1); $s = $s2 == $str ? $s1 : $str; $asc = ord($s{0}) * 256 + ord($s{1}) - 65536; if ($asc >= -20319 && $asc <= -20284) return 'A'; if ($asc >= -20283 && $asc <= -19776) return 'B'; if ($asc >= -19775 && $asc <= -19219) return 'C'; if ($asc >= -19218 && $asc <= -18711) return 'D'; if ($asc >= -18710 && $asc <= -18527) return 'E'; if ($asc >= -18526 && $asc <= -18240) return 'F'; if ($asc >= -18239 && $asc <= -17923) return 'G'; if ($asc >= -17922 && $asc <= -17418) return 'H'; if ($asc >= -17417 && $asc <= -16475) return 'J'; if ($asc >= -16474 && $asc <= -16213) return 'K'; if ($asc >= -16212 && $asc <= -15641) return 'L'; if ($asc >= -15640 && $asc <= -15166) return 'M'; if ($asc >= -15165 && $asc <= -14923) return 'N'; if ($asc >= -14922 && $asc <= -14915) return 'O'; if ($asc >= -14914 && $asc <= -14631) return 'P'; if ($asc >= -14630 && $asc <= -14150) return 'Q'; if ($asc >= -14149 && $asc <= -14091) return 'R'; if ($asc >= -14090 && $asc <= -13319) return 'S'; if ($asc >= -13318 && $asc <= -12839) return 'T'; if ($asc >= -12838 && $asc <= -12557) return 'W'; if ($asc >= -12556 && $asc <= -11848) return 'X'; if ($asc >= -11847 && $asc <= -11056) return 'Y'; if ($asc >= -11055 && $asc <= -10247) return 'Z'; return null; } /** * 过滤客户端类型和版本 * * @param $data * @return bool|array */ function flitApiParam($data) { if (!is_array($data)) return false; unset($data['client_type']); unset($data['client_version']); unset($data['timestamp']); return $data; } /** * 处理图片数据类型 * * @param $str * @return array */ function dealAppImgStructure($str) { $str = str_replace('[','',$str); $str = str_replace(']','',$str); return explode(',',$str); } /** * curl form-data 请求 * * @param $url * @param $data_string * @return mixed */ function http_post($url, $data) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt ( $ch, CURLOPT_POST, 1 );//请求方式为post curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); //不打印header信息 curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );//返回结果转成字符串 curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data);//post传输的数据。 $return = curl_exec($ch); curl_close($ch); return $return; } /** * 去除12张车图片--空白图片 * * @param $data * @return array */ function dealBannerImg($string) { $imgArr = dealAppImgStructure(trim($string)); $newImg = []; $i = 0; foreach ($imgArr as $k => $v){ if (strpos($v,'ttp://')){ $newImg[$i] = trim($imgArr[$k]) . QINIU_HANDLE_IMG; $i++; } } return $newImg; } /** * 处理图片最多为9张 * * @param $arr * @return mixed */ function dealShareImg($arr) { while (count($arr) > 9){ array_pop($arr); } return $arr; } /** * 获取ip * * @return string */ function ip() { if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { $ip = getenv('HTTP_CLIENT_IP'); } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { $ip = getenv('REMOTE_ADDR'); } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { $ip = $_SERVER['REMOTE_ADDR']; } $res = preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : ''; return $res; } /** * 计算两天之间相隔天数(带正负号) * * @param $day1 * @param $day2 * @return float|int */ function diffBetweenTwoDays($day1, $day2) { $second1 = strtotime($day1); $second2 = strtotime($day2); // if ($second1 < $second2) { // $tmp = $second2; // $second2 = $second1; // $second1 = $tmp; // } return ($second1 - $second2) / 86400; } /** * 根据ip地址获取城市信息 * * @param string $ip * @return bool|string */ function getCity($ip = '') { if($ip == ''){ $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json"; $ip=json_decode(file_get_contents($url),true); $data = $ip; }else{ $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip; $ip=json_decode(file_get_contents($url)); if((string)$ip->code=='1'){ return false; } $data = (array)$ip->data; } $list = $data['region'].'-'.$data['city']; return $list; } /** * 获取完整的二维码链接 * * @param $str * @return string */ function completeQrUrl($str) { return \think\Request::instance()->domain()."/public/qrcode/".$str; }<file_sep>/application/web/controller/Base.php <?php namespace app\web\controller; use think\Controller; use think\Db; use think\Request; class Base extends Controller { private $post; private $get; public function __construct(Request $request = null) { parent::__construct($request); $this->post = input('post.'); $this->get = input('get.'); } /** * 接收post值 * * @return array|mixed */ public function webPostData() { return $this->post; } /** * 接收get值 * * @return array|mixed */ public function webGetData() { return $this->get; } }<file_sep>/runtime/temp/d44df0e2c835cbb942763df760f0534c.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:66:"D:\phpStudy\WWW\yk_friend/application/index\view\index\appear.html";i:1551253342;}*/ ?> <!doctype html> <html lang="en"> <head> <base href="/public/backend/"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <title>Document</title> </head> <body> <div class="jumbotron"> <h1>Hello, world!</h1> <p>...</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p> </div> </body> </html><file_sep>/runtime/temp/9c07970bce71c2984873935761bc0598.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:68:"D:\phpStudy\WWW\yk_friend/application/index\view\activity\index.html";i:1551333768;}*/ ?> <!DOCTYPE html> <html> <head> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css?v=4.1.0" rel="stylesheet"> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> <link href="layui/css/layui.css" rel="stylesheet" > <link rel="stylesheet" href="/public/backend/css/boxImg.css?v=2018"> </head> <body class="gray-bg"> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-sm-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>活动列表 &nbsp;&nbsp;&nbsp;<a class="btn btn-info btn-xs" href="<?php echo url('activity/activity_add'); ?>">新增活动</a></h5> </div> <div class="ibox-content"> <div class="row" > <form action="<?php echo url('activity/index'); ?>" method="post"> <div class="col-sm-7" style="margin-left: -15px;margin-bottom: 15px;"> <span class="col-sm-3"> <input type="text" placeholder="标题" class="input-sm form-control" name="activity_name" value="<?php echo $activity_name; ?>"> </span> <span class="col-sm-1"> <button type="submit" class="btn btn-sm btn-primary"> 搜索</button> </span> </div> </form> </div> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>序号</th> <th>活动标题</th> <th>活动logo</th> <th>所属分类</th> </tr> </thead> <tbody> <?php if(is_array($list) || $list instanceof \think\Collection || $list instanceof \think\Paginator): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$activity): $mod = ($i % 2 );++$i;?> <tr> <td><?php echo $activity['id']; ?></td> <td><?php echo $activity['activity_name']; ?></td> <td><img src="<?php echo $activity['activity_logo']; ?>" width="120px;" height="60px;" ></td> <td><button class="btn btn-sm btn-info">ceshi</button></td> </tr> <?php endforeach; endif; else: echo "" ;endif; ?> </tbody> </table> <div> <span>共 <?php echo $list->total(); ?>条</span>&nbsp;<span><?php echo $list->currentPage(); ?>/<?php echo $list->lastPage(); ?>页</span> <span style="float: right;margin-top: -23px;"> <?php echo $list->appends(['activity_name'=>$activity_name])->render(); ?> </span> </div> </div> </div> </div> </div> </div> </div> <!-- 全局js --> <script src="js/jquery.min.js?v=2.1.4"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- 自定义js --> <script src="js/content.js?v=1.0.0"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <!-- layui --> <script src="layui/layui.all.js"></script> <script src="/public/backend/js/jquery.boxImg.js?v=1.8"></script> <script> function delBanner(id) { var bool = confirm('确认删除?'); if (bool == true){ if (id == ''){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success('参数不能为空'); return false; } $.post("<?php echo url('overall/banner_del'); ?>",{id:id},function (res) { if (res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },1500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function () { location.reload(); },2000); } },'json') } } </script> </body> </html><file_sep>/application/index/controller/Auth.php <?php namespace app\index\controller; use app\index\model\AppMem; use app\index\model\Admin; use app\index\model\AdminPri; use app\index\model\AdminRole; use app\index\model\PdaAccount; use think\Request; use think\Session; use think\Db; class Auth extends Base { /** * 管理员权限 * * @param Request $request * @return \think\response\View */ public function admin_pri(Request $request) { if ($request->isPost()){ //接值 $id = empty(input('id')) ? '' : trim(input('id')); $pri = empty(input('pri')) ? '' : trim(input('pri')); if (empty($id)) ajaxReturn(0,'非法请求',''); //处理$pri最后的 , if (!empty($pri)){ $pri = substr($pri,0,-1); } //跟新数据 $updateRes = Db::name('admin_role')->update(['id'=>$id,'pri'=>$pri]); if ($updateRes !== false) ajaxReturn(1,'修改管理员权限成功',''); ajaxReturn(0,'修改失败,请稍后尝试',''); }else{ //接值 $id = input('id'); $name = input('name'); $rolePri = Db::name('admin_role')->where(['id'=>$id])->find(); // dump($adminPri);die; $priArr = AdminPri::getPriArr($rolePri['pri']); //用户权限数组(将pri字段处理成一维数组) // dump($priArr);die; //所有权限 $priAll = Db::name('admin_pri')->where(['pid'=>0,'isdel'=>0])->select(); //处理是否选中 foreach ($priAll as $key => $value){ //标记父级节点是否被选中 if (in_array($value['id'],$priArr)){ $priAll[$key]['curr'] = 1; }else{ $priAll[$key]['curr'] = 0; } //找到父级之后查询对应的子级 $tmp = Db::name('admin_pri')->where(['pid'=>$value['id'],'isdel'=>0])->select(); foreach ($tmp as $k => $v){ //标记子级节点是否被选中 if (in_array($v['id'],$priArr)){ $tmp[$k]['curr'] = 1; }else{ $tmp[$k]['curr'] = 0; } } $priAll[$key]['son'] = $tmp; } $this->assign('id',$id); $this->assign('name',$name); $this->assign('priAll',$priAll); return view(); } } /* * 管理员列表 * * @return \think\response\View */ public function administrators() { //搜索框条件 $adminName = empty(input('name')) ? '' : trim(input('name')); //获取管理员信息 $adminList = Admin::getAdmin($adminName); //赋值 $menu = Db::name('admin_pri')->select(); $str = ''; foreach ($menu as $v){ $str .= $v['id'] . ','; } $count = strlen($str) - 1; $roleNameList = Db::name('admin_role')->field('id,role_name')->select(); $this->assign('roleNameList',$roleNameList); $this->assign('admin_name',$adminName); $this->assign('list',$adminList); //列表数据 $this->assign('count',$count); //渲染视图 return view(); } /** * 更新角色名称 * */ public function update_role() { $id = input('id'); $role_name = input('role_name'); if ( empty($id) || empty($role_name)) ajaxReturn(0,'不能为空',''); //判断角色名称是否存在 if(AdminRole::checkName($role_name)) ajaxReturn(0,'该名称已存在',''); //更新数据 $roleModel = new AdminRole(); $role = $roleModel->where(['id'=>$id])->find(); $role->role_name = $role_name; if($role->save() !== false ) ajaxReturn(1,'修改成功',''); ajaxReturn(0,'修改失败',''); } /** * 更新角色名称 * */ public function update_admin_role() { $id = input('id'); $role_name = input('role_name'); if ( empty($id) || empty($role_name)) ajaxReturn(0,'不能为空',''); //更新数据 $Admin = new Admin(); $role = $Admin->where(['id'=>$id])->find(); $role->role = $role_name; if($role->save() !== false ) ajaxReturn(1,'修改成功',''); ajaxReturn(0,'修改失败',''); } /** * 修改管理员用户登录权限 * * @return \think\response\View */ public function editAdmin() { $val = empty(input('val')) ? '0' : input('val'); $id = empty(input('id')) ? '' : input('id'); if (empty($id)) ajaxReturn(0,'非法操作',''); $return = Admin::editIsDel($id,$val); //返回给ajax if ($return) ajaxReturn(1,'修改成功',''); ajaxReturn(0,'修改失败',''); } /** * 管理员修改密码 * * @param Request $request * @return \think\response\View */ public function password(Request $request) { if ($request->isPost()) { $adminInfo = Session::get('adminInfo'); //接值 $ori = input('ori'); $pwd = input('pwd'); if ($ori == $pwd) ajaxReturn(0,'旧密码与新密码相同',''); if (myMd5($ori) !== $adminInfo->admin_pwd) ajaxReturn(0,'旧密码不正确',''); $return = Admin::editPwd($adminInfo->id,myMd5(trim($pwd))); if ($return) { Session::delete('adminInfo'); ajaxReturn(1,'修改密码成功,正在退出',''); } ajaxReturn(0,'修改密码失败',''); } else { return view(); } } /** * 新增管理员 * * @param Request $request * @return \think\response\View */ public function addAdmin(Request $request) { if ($request->isPost()) { //接值 $adminName = input('admin_name'); $role = input('role'); $pwd = input('<PASSWORD>'); $confirm_pwd = input('confirm'); if ($confirm_pwd != $pwd) ajaxReturn(0,'两次密码不一致',''); //查询此账号在数据库中是否存在 $one = Db::name('admin')->where(['admin_name'=>$adminName])->find(); if($one) ajaxReturn(0,'此帐号已存在,请勿重复添加',''); //新增 $return = Admin::addAdmin($adminName,<PASSWORD>($pwd),$role); if ($return) ajaxReturn(1,'新增管理员成功',''); ajaxReturn(0,'新增失败,请重新添加',''); } else { $roleList = AdminRole::getRoleList(); $this->assign('roleList',$roleList); return view('auth/addadmin'); } } /** * 添加角色 * * @param Request $request * @return \think\response\View */ public function addRole(Request $request) { if ($request->isPost()){ $data['role_name'] = input('role_name'); if (empty($data['role_name'])) ajaxReturn(0,'不能为空',''); //判断角色名称是否已存在 if (AdminRole::checkName($data['role_name'])) ajaxReturn(0,'该角色已存在,请勿重复添加',''); //添加数据 $data['addtime'] = time(); $addRes =Db::name('admin_role')->insert($data); if ($addRes > 0) ajaxReturn(1,'新增成功',''); ajaxReturn(0,'新增失败',''); }else{ return view('auth/addrole'); } } /** * 角色列表 * * @return \think\response\View */ public function role() { //查询权限 $menu = Db::name('admin_pri')->select(); $str = ''; foreach ($menu as $v){ $str .= $v['id'] . ','; } $count = strlen($str) - 1; $this->assign('count',$count); $roleList = AdminRole::getRoleList(); $this->assign('list',$roleList); return view(); } /** * 删除角色 * */ public function role_del() { $id = input('id'); if (empty($id) || !@is_numeric($id)) ajaxReturn(0,'参数不正确',''); //查询此角色下有没有管理员 $data = Db::name('admin') ->where(['role'=>$id]) ->select(); if(empty($data)) { $bool = Db::name('admin_role')->where(['id'=>$id])->delete(); if ($bool !== false) ajaxReturn(1,'删除成功',''); } else{ ajaxReturn(0,'此角色正在被使用,不能删除',''); } } /** * pda人员列表 * * @return \think\response\View */ public function pda_admin() { //搜索框条件 $account = empty(input('account')) ? '' : trim(input('account')); //获取管理员信息 $accountList = PdaAccount::getAccount($account); $this->assign('account',$account); $this->assign('list',$accountList); return view(); } /** * 新增pda人员 * * @param Request $request * @return \think\response\View */ public function addPdaAdmin(Request $request) { if ($request->isPost()){ $data = input('post.'); //两次密码是否一致 if ($data['confirm'] <> $data['password']) ajaxReturn(0,'两次密码不一致,请重新输入',''); //查询此账号在数据库中是否存在 $one = Db::name('pda_account')->where(['pda_account'=>$data['pda_account']])->find(); if($one) ajaxReturn(0,'此帐号已存在,请勿重复添加',''); //新增数据 $res = PdaAccount::addAccount($data); if ($res > 0) ajaxReturn(1,'新增成功,请返回给该人员赋予权限',''); ajaxReturn(0,'新增失败',''); }else{ return view(); } } /** * 删除PDA账户 * */ public function delPdaAdmin() { $padId = input('pda_id'); $delRs = PdaAccount::delAccount($padId); if ($delRs) ajaxReturn(1,'删除成功,该账户将不能登录PDA设备',''); ajaxReturn(0,'删除失败,请稍后再试',''); } /** * pda权限 * * @param Request $request * @return \think\response\View */ public function pda_pri(Request $request) { if ($request->isPost()){ //接值 $id = empty(input('id')) ? '' : trim(input('id')); $pri = empty(input('pri')) ? '' : trim(input('pri')); if (empty($id)) ajaxReturn(0,'非法请求',''); //处理$pri最后的 , if (!empty($pri)){ $pri = substr($pri,0,-1); } $updateRes = Db::name('pda_account')->update(['pda_id'=>$id,'pda_pri'=>$pri]); if ($updateRes !== false) ajaxReturn(1,'成功赋权给PDA人员',''); ajaxReturn(0,'赋权失败,请稍后尝试',''); }else{ $id = input('id'); $name = input('name'); //所有权限 $priAll = Db::name('pda_pri')->select(); //查询单个用户权限 $userPri = Db::name('pda_account')->where(['pda_id'=>$id])->value('pda_pri'); //已有权重选中 foreach ($priAll as $k => $v) { if (strpos($userPri,(string)$v['id']) !== false){ $priAll[$k]['curr'] = 1; }else{ $priAll[$k]['curr'] = 0; } } return view('',['id'=>$id,'name'=>$name,'priAll'=>$priAll]); } } /** * APP用户列表 * * @return \think\response\View */ public function app_user() { //搜索框条件 $appMobile = empty(input('mobile')) ? '' : trim(input('mobile')); //获取APP用户信息 $appList = AppMem::getAccount($appMobile); $this->assign('appMobile',$appMobile); $this->assign('list',$appList); //渲染视图 return view(); } /** * 修改app用户登录权限 * */ public function editApp() { $id = empty(input('id')) ? '' : input('id'); $val = empty(input('val')) ? '0' : input('val'); if (empty($id)) ajaxReturn(0,'非法操作',''); $return = AppMem::editIsDel($id,$val); //返回给ajax if ($return) ajaxReturn(1,'修改成功',''); ajaxReturn(0,'修改失败',''); } /** * 口令 * * @return \think\response\View */ public function command() { $list = Db::name('command')->paginate(15); $this->assign('list',$list); return view(); } /** * 更新口令 * */ public function update_command() { $command = input('command'); $id = input('id'); if (empty($command) || empty($id)) ajaxReturn(0,'不能为空',''); //更新数据 $updateRs = Db::name('command')->where(['id'=>$id])->update(['command'=>$command,'updatetime'=>time()]); if($updateRs !== false ) ajaxReturn(1,'修改成功',''); ajaxReturn(0,'修改失败',''); } } <file_sep>/application/index/controller/Base.php <?php namespace app\index\controller; use think\Controller; use think\Session; class Base extends Controller { public function __construct() { parent::__construct(); $loginInfo = Session::get('adminInfo'); if(!$loginInfo) { $this->redirect('/index/login/index.html', array(), 0, '登录失效,请重新登录'); } } } <file_sep>/README.md 约个小伙伴系统 =============== > 运行环境要求PHP5.4以上。 详细开发文档参考 [ThinkPHP5完全开发手册](http://www.kancloud.cn/manual/thinkphp5) ## 命名规范 遵循PSR-2命名规范和PSR-4自动加载规范,并且注意如下规范: ### 目录和文件 * 目录不强制规范,驼峰和小写+下划线模式均支持; * 类库、函数文件统一以`.php`为后缀; * 类的文件名均以命名空间定义,并且命名空间的路径和类库文件所在路径一致; * 类名和类文件名保持一致,统一采用驼峰法命名(首字母大写); ### 函数和类、属性命名 * 类的命名采用驼峰法,并且首字母大写,例如 `User`、`UserType`,默认不需要添加后缀,例如`UserController`应该直接命名为`User`; * 函数的命名使用小写字母和下划线(小写字母开头)的方式,例如 `get_client_ip`; * 方法的命名使用驼峰法,并且首字母小写,例如 `getUserName`; * 属性的命名使用驼峰法,并且首字母小写,例如 `tableName`、`instance`; * 以双下划线“__”打头的函数或方法作为魔法方法,例如 `__call` 和 `__autoload`; ### 常量和配置 * 常量以大写字母和下划线命名,例如 `APP_PATH`和 `THINK_PATH`; * 配置参数以小写字母和下划线命名,例如 `url_route_on` 和`url_convert`; ### 数据表和字段 * 数据表和字段采用小写加下划线方式命名,并注意字段名不要以下划线开头,例如 `think_user` 表和 `user_name`字段 ### 页面跳转提示 * 失败提示 ```$xslt toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error('请进行人机验证'); return false; ``` * 成功提示 ```$xslt toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success('成功'); return false; ``` * 配合setTimeOut()使用 <file_sep>/runtime/temp/7adb949ed30a37002e42df42370a68ba.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:73:"D:\phpStudy\WWW\yk_friend/application/index\view\auth\administrators.html";i:1551232115;}*/ ?> <!DOCTYPE html> <html> <head> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css?v=4.1.0" rel="stylesheet"> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> </head> <body class="gray-bg"> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-sm-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>管理员列表 &nbsp; <a class="btn btn-info btn-xs" href="<?php echo url('auth/addAdmin'); ?>">新增管理员</a></h5> </div> <div class="ibox-content"> <div class="row" > <form action="<?php echo url('auth/administrators'); ?>" method="post"> <div class="col-sm-7" style="margin-left: -15px;margin-bottom: 15px;"> <span class="col-sm-3"> <input type="text" placeholder="账号" class="input-sm form-control" name="name" value="<?php echo $admin_name; ?>"> </span> <span class="col-sm-1"> <button type="submit" class="btn btn-sm btn-primary"> 搜索</button> </span> </div> </form> </div> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>ID</th> <th>账号</th> <th>角色</th> <th>登录权限</th> <th>最后登录时间</th> <th>最后登录ip</th> <th>最后登录城市</th> <th>操作</th> </tr> </thead> <tbody> <?php if(is_array($list) || $list instanceof \think\Collection || $list instanceof \think\Paginator): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$admin): $mod = ($i % 2 );++$i;?> <tr> <td><?php echo $admin['id']; ?></td> <td><?php echo $admin['admin_name']; ?></td> <td><?php echo $admin['role_name']; ?></td> <td align="center"> <span onclick="changeStatus(<?php echo $admin['isdel']; ?>,<?php echo $admin['id']; ?>)"> <?php echo !empty($admin['isdel'])?'<button class="btn btn-danger btn-circle">✖</button>' : '<button class="btn btn-primary btn-circle">✔</button>'; ?> </span> </td> <td><?php echo date("Y-m-d H:i:s",$admin['lasttime']); ?></td> <td><?php echo $admin['lastip']; ?></td> <td><?php echo $admin['city']; ?></td> <td><button class="btn btn-sm btn-warning" onclick='confirmUpdate("<?php echo $admin['id']; ?>","<?php echo $admin['role_name']; ?>")'>修改</button></td> </tr> <?php endforeach; endif; else: echo "" ;endif; ?> </tbody> </table> <!--分页--> <div> <span>共 <?php echo $list->total(); ?>条</span>&nbsp;<span><?php echo $list->currentPage(); ?>/<?php echo $list->lastPage(); ?>页</span> <span style="float: right;margin-top: -23px;"> <?php echo $list->appends(['name'=>$admin_name])->render(); ?> </span> </div> </div> </div> </div> </div> </div> </div> <!--修改角色--> <div class="modal fade in" id="modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: none; padding-right: 17px;"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="exampleModalLabel" style="text-align: center">修改管理员角色</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="role_name" class="control-label">更换角色:</label> <select id="role_name" class="form-control"> <?php if(is_array($roleNameList) || $roleNameList instanceof \think\Collection || $roleNameList instanceof \think\Paginator): $i = 0; $__LIST__ = $roleNameList;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$role): $mod = ($i % 2 );++$i;?> <option value="<?php echo $role['id']; ?>"><?php echo $role['role_name']; ?></option> <?php endforeach; endif; else: echo "" ;endif; ?> </select> <input type="hidden" id="id"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" onclick="updateRoleName()">确定</button> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> </div> </div> </div> </div> <!-- 全局js --> <script src="js/jquery.min.js?v=2.1.4"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- 自定义js --> <script src="js/content.js?v=1.0.0"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <script> function confirmUpdate(id,role_name) { $('#modal').modal("show"); $('#id').val(id); $('#role_name').val(role_name); } function updateRoleName() { var id = $('#id').val(); var role_name = $('#role_name').val(); $.post("<?php echo url('Auth/update_admin_role'); ?>",{id:id,role_name:role_name},function (res) { if (res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },1500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function () { location.reload(); },2000); } },'json') } function changeStatus(val,id) { $.post("<?php echo url('auth/editAdmin'); ?>",{val:val,id:id},function (res) { if(res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function () { location.reload(); },2000); } },'json') } </script> </body> </html><file_sep>/application/index/model/Admin.php <?php namespace app\index\model; use think\Db; use think\Model; class Admin extends Model { const OK = 0; const NO = 1; /** * 检测登录 * * @param $data * @return */ public function checkLogin($data) { if (count($data) > 0) { $data['isdel'] = 0; return $this->where($data)->find(); } return false; } /** * 获取管理员信息 * * @param $name * @return \think\Paginator */ public static function getAdmin($name) { $admin = Db::name('admin')->alias('a') ->join('admin_role r','a.role = r.id') ->where(function ($query) use($name) { if(!empty($name)){ $query->where('admin_name','like','%'.$name.'%'); }else{ } }) ->field('r.role_name,a.*') ->order("a.id desc") ->paginate(10); return $admin; } /** * 修改管理员登录权限 * * @param $id * @param $val * @return bool|int|string */ public static function editIsDel($id,$val) { if (empty($id)) return false; $newVal = empty($val) ? self::NO : self::OK; return self::update(['id'=>$id,'isdel'=>$newVal]); } /** * 修改管理员密码 * * @param $id * @param $pwd * @return bool|int|string */ public static function editPwd($id,$pwd) { if (empty($id) || empty($pwd)) return false; return self::update(['id'=>$id,'admin_pwd'=>$pwd]); } /** * 新增管理员账号 * * @param $admin_name * @param $pwd * @param $name * @return bool|int|string */ public static function addAdmin($admin_name,$pwd,$role) { if (empty($role) || empty($pwd) || empty($admin_name)) return false; $data['admin_name'] = $admin_name; $data['admin_pwd'] = <PASSWORD>; $data['addtime'] = time(); $data['addip'] = ''; $data['isdel'] = 0; $data['role'] = $role; $data['lasttime'] = ''; $data['lastip'] = ''; return self::insert($data); } } ?><file_sep>/application/index/controller/Index.php <?php namespace app\index\controller; use app\index\model\AdminPri; use think\Session; use think\Db; class Index extends Base { /** * 后台首页 * * @return \think\response\View */ public function index() { //获取session信息 $adminInfo = Session::get('adminInfo'); $this -> assign('adminInfo',$adminInfo); //查询用户角色 $adminRole = Db::name('admin_role')->where(['id'=>$adminInfo['role']])->find(); $menuList = $this->getMenu(AdminPri::getPriDetail($adminRole['pri'])); $this->assign('menuList',$menuList); //后台标题 $config = Db::name('config')->where(['id'=>1])->find(); $this->assign('config',$config); return view(); } /** * 首页内容 * * @return \think\response\View */ public function appear() { return view(); } /** * 简单权限,查询管理员拥有权限(树状菜单形状) * * @param $data * @param int $pid * @return array */ public function getMenu($data,$pid = 0) { $menu = []; if (is_array($data) && count($data) > 0){ foreach ($data as $k => $v){ if ($v['pid'] == $pid){ $menu[$k] = $v; $menu[$k]['son'] = $this->getMenu($data,$v['id']); } } } return $menu; } } <file_sep>/application/web/controller/Index.php <?php namespace app\web\controller; use think\Db; class Index extends Base { /** * 常见问题 * */ public function questions() { $data = Db::name('questions')->select(); if ($data){ webReturn(200,'请求成功',$data); } webReturn(400,'请求失败'); } public function activity() { $data = Db::name('activity')->select(); if ($data){ webReturn(200,'请求成功',$data); } webReturn(400,'请求失败'); } }<file_sep>/public/backend/js/clock.js /** * Created by when on 2018/3/28. */ (function(w){ function Relogio(container){ this.container = container; this.initialize(); } Relogio.prototype.initialize = function(){ this.clockdata = { h: 0, m: 0, s: 0, ms: 0 }; this.canvas = createCanvas(this.container); this.ctx = this.canvas.getContext("2d"); this.size = this.canvas.width; this.beginLoop(); }; function deg2rad(deg){ return deg * Math.PI / 180; } function rotate(point, deg, center){ var ang = deg2rad(deg); point = { x: point.x - center.x, y: point.y - center.y }; var rotatedPoint = { x: ( point.x * Math.cos(ang) ) - (point.y * Math.sin(ang) ) + center.x, y: ( point.x * Math.sin(ang) ) + (point.y * Math.cos(ang) ) + center.y, }; return rotatedPoint; } function draw(){ drawClock.call(this); drawPointers.call(this); }; function drawPointers(){ var ctx = this.ctx; var size = this.size; var sizeBlock = size * .05; var center = { x: size / 2, y: size / 2 }; var positions = { seconds: { x: size / 2 , y: sizeBlock + sizeBlock / 4 }, minutes: { x: size / 2 , y: sizeBlock + sizeBlock }, hours: { x: size / 2 , y: sizeBlock + sizeBlock * 3.5 } } var angles = { seconds: (this.clockdata.s / 60) * 360, minutes: (this.clockdata.m / 60) * 360, hours: (this.clockdata.h / 12) * 360 }; positions.seconds = rotate(positions.seconds, angles.seconds, center); positions.minutes = rotate(positions.minutes, angles.minutes, center); positions.hours = rotate(positions.hours, angles.hours, center); var conterMinutes = { x: ( 2 * center.x + ( center.x + (center.x - positions.minutes.x) ) ) / 3, y: ( 2 * center.y + ( center.y + (center.y - positions.minutes.y) ) ) / 3 }; var conterSeconds = { x: center.x + (conterMinutes.x - positions.seconds.x) , y: center.y + (conterMinutes.y - positions.seconds.y) }; ctx.strokeStyle = "#777"; ctx.lineWidth = 6; ctx.beginPath(); ctx.moveTo(positions.minutes.x, positions.minutes.y); ctx.quadraticCurveTo(conterMinutes.x, conterMinutes.y, positions.hours.x, positions.hours.y); ctx.stroke(); ctx.closePath(); ctx.strokeStyle = "#A35EED"; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(positions.seconds.x, positions.seconds.y, 20, 0, Math.PI * 2); ctx.stroke(); ctx.closePath(); var jointPosition = { x: positions.seconds.x, y: positions.seconds.y + (sizeBlock / 4 * 3) }; jointPosition = rotate(jointPosition, angles.seconds, positions.seconds); ctx.beginPath(); ctx.moveTo(jointPosition.x, jointPosition.y ); ctx.quadraticCurveTo(conterSeconds.x, conterSeconds.y, positions.minutes.x, positions.minutes.y); ctx.stroke(); ctx.closePath(); } function drawClock(){ var ctx = this.ctx; var size = this.size; var sizeBlock = size * .05; var center = size / 2; ctx.clearRect(0, 0, size, size); ctx.strokeStyle = "black"; ctx.shadowBlur=2; ctx.shadowColor="black"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.font = "14pt sans-serif"; var position = { x: size / 2 , y: sizeBlock }; for(var i = 0; i < 60; i++){ var angle = i * 6; ctx.save(); ctx.translate(center, center); ctx.rotate(deg2rad(angle)); ctx.translate(-center, -center); if( i % 5 == 0){ var reverseAngle = ( 360 * 3 ) - (angle ); reverseAngle %= 360; ctx.save() ctx.translate(position.x, position.y + sizeBlock / 5); ctx.rotate(deg2rad(reverseAngle)); ctx.translate(-position.x, -(position.y + sizeBlock / 5)); var hora = (( i / 5 ) || 12); ctx.beginPath(); ctx.fillText( hora , position.x, position.y + sizeBlock / 5); ctx.fill(); ctx.closePath(); ctx.restore(); } ctx.beginPath(); if( i % 5 ){ ctx.moveTo(position.x, position.y ); ctx.lineTo(position.x, position.y + sizeBlock /2); ctx.stroke(); }else{ } ctx.closePath(); ctx.restore(); } } function update(){ var time = new Date(); this.clockdata.h = time.getHours(); this.clockdata.m = time.getMinutes(); this.clockdata.s = time.getSeconds(); this.clockdata.ms = time.getMilliseconds(); this.clockdata.h += (this.clockdata.m / 60); this.clockdata.m += (this.clockdata.s / 60); this.clockdata.s += (this.clockdata.ms / 1000); }; function loop(){ update.call(this); draw.call(this); requestAnimationFrame(loop.bind(this)); }; Relogio.prototype.beginLoop = function(){ loop.call(this); }; function createCanvas(cont){ var size = Math.min(cont.offsetWidth, cont.offsetHeight); var canvas = document.createElement("canvas"); canvas.width = size; canvas.height = size; cont.appendChild(canvas); return canvas; } w.Relogio = Relogio; }(window)) var relogio = new Relogio(document.querySelector(".relogio")); <file_sep>/application/index/model/AdminPri.php <?php namespace app\index\model; use think\Db; use think\Model; class AdminPri extends Model { /** * 查询用户拥有权限(用于菜单遍历) * * @param string $pri * @return false|\PDOStatement|string|\think\Collection */ public static function getPriDetail($pri) { if ($pri == null){ //拥有全部权限 // $priDetail = Db::name('admin_pri')->field('id,pid,menu_name,menu_icon,menu_url')->where(['isdel'=>0])->order('sort asc')->select(); //无权限 $priDetail = []; }else{ $priArr = array_values(explode(',',$pri)); $priDetail = Db::name('admin_pri')->field('id,pid,menu_name,menu_icon,menu_url')->where('id','in',$priArr)->where(['isdel'=>0])->order('sort asc')->select(); } return $priDetail; } /** * 获取管理员权限数组 * * @param $pri * @return array|false|\PDOStatement|string|\think\Collection */ public static function getPriArr($pri) { if ($pri == null){ //权限为空默认全部权限 // $priArr = Db::name('admin_pri')->field('id')->where(['isdel'=>0])->order('sort asc')->select(); // $priArr = array_column($priArr,'id'); //权限为空默认没有权限 $priArr = []; }else{ $priArr = array_values(explode(',',$pri)); } return $priArr; } } ?><file_sep>/application/index/controller/Login.php <?php namespace app\index\controller; use app\index\model\Admin; use think\Controller; use think\Request; use think\Session; class Login extends Controller { /** * 用户登录 * * @param Request $request * @return \think\response\View */ public function index(Request $request) { if ($request->isPost()) { //接值处理 $data['admin_name'] = empty(input('admin_name')) ? '' : trim(input('admin_name')) ; $data['admin_pwd'] = empty(input('admin_pwd')) ? '' : myMd5(input('admin_pwd')) ; //检测用户密码 $admin = new Admin(); $adminInfo = $admin->checkLogin($data); if ($adminInfo) { //session Session::set('adminInfo',$adminInfo); //更改登录信息 //获取ip $ip = ip(); // $city = getCity($ip); $city = ''; $admin ->save(['lasttime' => time(),'lastip'=>$ip,'city'=>$city] , ['id' => $adminInfo['id']]) ; //返回登录状态 ajaxReturn(1,'登录成功,正在跳转……',''); } ajaxReturn(0,'用户名或密码错误,请重新登录',''); } else { return view(); } } /** * 退出登录 * */ public function loginout() { Session::delete('adminInfo'); $this->redirect('/index/login/index.html'); } }<file_sep>/application/index/model/Activities.php <?php namespace app\index\model; use think\Db; use think\Model; class Activities extends Model { /** * 获取活动列表 * * @param $activity_name * @return \think\Paginator * @throws \think\exception\DbException */ public static function getActivity($activity_name) { $list = Db::name('activity') ->where(function ($query) use($activity_name) { if(!empty($activity_name)){ $query->where('activity_name','like','%'.$activity_name.'%'); }else{} }) ->paginate(); return $list; } /** * 获取分类 * * @return false|\PDOStatement|string|\think\Collection */ public static function getType() { return Db::name('activity') ->field('id,activity_name') ->where(['pid'=>0]) ->select(); } } <file_sep>/runtime/temp/91c1aa3bd9d12d3cb35e73c97bae8ad4.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:75:"D:\phpStudy\WWW\yk_friend/application/index\view\activity\activity_add.html";i:1551334528;}*/ ?> <!DOCTYPE html> <html> <head> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css?v=4.1.0" rel="stylesheet"> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> <link href="layui/css/layui.css" rel="stylesheet" > <link href="css/plugins/chosen/chosen.css?v=12" rel="stylesheet"> </head> <body class="gray-bg"> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-sm-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>新增活动</h5> </div> <div class="ibox-content"> <div class="form-horizontal m-t" id="signupForm"> <div class="form-group"> <label class="col-sm-3 control-label">请选择分类:</label> <div class="col-sm-6"> <select name="type" id="type_id" class="form-control m-b" > <option value="0">请选择分类</option> <?php if(is_array($typeList) || $typeList instanceof \think\Collection || $typeList instanceof \think\Paginator): $i = 0; $__LIST__ = $typeList;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$type): $mod = ($i % 2 );++$i;?> <option value="<?php echo $type['id']; ?>"><?php echo $type['activity_name']; ?></option> <?php endforeach; endif; else: echo "" ;endif; ?> </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">活动标题:</label> <div class="col-sm-6"> <input name="activity_name" class="form-control" type="text" placeholder="请输入活动标题"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">描述:</label> <div class="col-sm-6"> <textarea name="desc" id="desc" class="form-control" rows="5"></textarea> </div> </div> <div class="form-group"> <div class="col-sm-6 col-sm-offset-3"> <button class="btn btn-primary" onclick="save()">提交</button> <a class="btn btn-default" href="<?php echo url('activity/index'); ?>">返回</a> </div> </div> </div> </div> </div> </div> </div> </div> <!-- 全局js --> <script src="js/jquery.min.js?v=2.1.4"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- 自定义js --> <script src="js/content.js?v=1.0.0"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <!-- layui --> <script src="layui/layui.all.js"></script> <script src="js/plugins/chosen/chosen.jquery.js"></script> <script type="text/javascript" src="js/ueditor/ueditor.config.js"></script> <!-- 编辑器源码文件 --> <script type="text/javascript" src="js/ueditor/ueditor.all.js"></script> <script type="text/javascript" src="js/ueditor/lang/zh-cn/zh-cn.js"></script> <!-- 实例化编辑器 --> <script type="text/javascript"> // 百度编辑器 var ue = UE.getEditor('content',{ initialFrameHeight: 400 }); //数据上传 function save() { var activity_name = $('input[name="activity_name"]').val(); var type =$("#type_id").find("option:selected").val(); var desc = $('#desc').val(); if (activity_name == '' || type == '' ){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error('不能为空'); return false; } $.post("<?php echo url('activity/activity_add'); ?>",{activity_name:activity_name,type:type,desc:desc},function (res) { if(res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.href='<?php echo url("activity/index"); ?>'; },2000); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); } },'json') } </script> </body> </html> <file_sep>/runtime/temp/5a577f0a304060c158df90e8b7d8c529.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:63:"D:\phpStudy\WWW\yk_friend/application/index\view\auth\role.html";i:1551232115;}*/ ?> <!DOCTYPE html> <html> <head> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css?v=4.1.0" rel="stylesheet"> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> </head> <body class="gray-bg"> <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col-sm-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>角色列表 &nbsp; <a class="btn btn-info btn-xs" href="<?php echo url('auth/addRole'); ?>">新增角色</a></h5> </div> <div class="ibox-content"> <div class="table-responsive"> <table class="table table-striped table-bordered"> <thead> <tr> <th>ID</th> <th>角色名称</th> <th>添加时间</th> <th>菜单权限/操作</th> </tr> </thead> <tbody> <?php if(is_array($list) || $list instanceof \think\Collection || $list instanceof \think\Paginator): $i = 0; $__LIST__ = $list;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$role): $mod = ($i % 2 );++$i;?> <tr> <td><?php echo $role['id']; ?></td> <td><?php echo $role['role_name']; ?></td> <td><?php echo date("Y-m-d H:i:s",$role['addtime']); ?></td> <td> <?php if((strlen($role['pri']) == $count)): ?> <button class="btn btn-sm btn-danger" disabled>全部权限</button> <?php elseif(($role['pri'] == null)): ?> <button class="btn btn-sm btn-default" disabled>暂无权限</button> <?php else: ?> <button class="btn btn-sm btn-primary" disabled>部分权限</button> <?php endif; ?> <a href="<?php echo url('auth/admin_pri',['id'=>$role['id'],'name'=>$role['role_name']]); ?>" class="btn btn-sm btn-primary">赋权</a> <button class="btn btn-sm btn-warning" onclick='confirmUpdate("<?php echo $role['id']; ?>","<?php echo $role['role_name']; ?>")'>修改</button> <button class="btn btn-sm btn-danger" onclick="delRole(<?php echo $role['id']; ?>)">删除</button> </td> </tr> <?php endforeach; endif; else: echo "" ;endif; ?> </tbody> </table> <!--分页--> <div> <span>共 <?php echo $list->total(); ?>条</span>&nbsp;<span><?php echo $list->currentPage(); ?>/<?php echo $list->lastPage(); ?>页</span> <span style="float: right;margin-top: -23px;"> <?php echo $list->render(); ?> </span> </div> </div> </div> </div> </div> </div> </div> <!--修改管理员名称--> <div class="modal fade in" id="modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display: none; padding-right: 17px;"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="exampleModalLabel" style="text-align: center">修改列表信息</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="role_name" class="control-label">角色名称:</label> <input type="text" class="form-control" id="role_name" > <input type="hidden" id="id"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" onclick="updateRoleName()">确定</button> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> </div> </div> </div> </div> <!-- 全局js --> <script src="js/jquery.min.js?v=2.1.4"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- 自定义js --> <script src="js/content.js?v=1.0.0"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <script> function delRole(id) { var bool = confirm('确认删除?'); if (bool == true){ if (id == ''){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success('参数不能为空'); return false; } $.post("<?php echo url('Auth/role_del'); ?>",{id:id},function (res) { if (res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },1500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); } },'json') } } function confirmUpdate(id,role_name) { $('#modal').modal("show"); $('#id').val(id); $('#role_name').val(role_name); } function updateRoleName() { var id = $('#id').val(); var role_name = $('#role_name').val(); $.post("<?php echo url('Auth/update_role'); ?>",{id:id,role_name:role_name},function (res) { if (res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },1500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function () { location.reload(); },2000); } },'json') } function changeStatus(val,id) { $.post("<?php echo url('overall/editAdmin'); ?>",{val:val,id:id},function (res) { if(res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function () { location.reload(); },2000); } },'json') } </script> </body> </html><file_sep>/application/index/controller/Questions.php <?php namespace app\index\controller; use app\index\model\QuestionsNews; use think\Db; use think\Request; class Questions extends Base { /** * 常见问题 * */ public function index() { //系统消息列表 $data = Db::name('questions')->select(); //赋值 $this->assign('data',$data); //view return view(); } /** * 新增常见问题 * * @param Request $request * @return \think\response\View */ public function addQuestions(Request $request) { if ($request->isPost()) { //接值 $post['title'] = input('title'); $post['content'] = input('content'); $post['addtime'] = time(); $insertRs = Db::name('questions')->insert($post); if ($insertRs) ajaxReturn(1,'新增常见问题成功',''); ajaxReturn(0,'新增失败',''); } else { return view(); } } } <file_sep>/runtime/temp/d0cc4a6b66b47b015a809784254f6781.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:65:"D:\phpStudy\WWW\yk_friend/application/index\view\login\index.html";i:1551317286;}*/ ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>赢开网络·约个小伙伴后台登陆</title> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <!-- Toastr style --> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <!--[if lt IE 9]> <meta http-equiv="refresh" content="0;ie.html" /> <![endif]--> <script> if (window.top !== window.self) { window.top.location = window.location; } </script> <style> .bgimg{ background: url(images/bg2.png); /*background: grey;*/ /*background-repeat: no-repeat;*/ background-size: 100% 100%; } </style> </head> <body class="bgimg"> <div class="middle-box text-center loginscreen animated fadeInDown"> <div> <div> <h1 class="logo-name" style="margin-top: 200px;font-size: 60px;color:#ffffff;letter-spacing: 0px;">约个小伙伴</h1> <br> </div> <form class="m-t" role="form" autocomplete="off"> <div class="form-group"> <input type="text" class="form-control" autocomplete="off" placeholder="用户名" required name="admin_name" > </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control" placeholder="密码" name="admin_pwd" required> </div> <br><br> <button type="button" class="btn btn-primary block full-width m-b" onclick="checkLogin()">登 录</button> </form> </div> </div> <!-- 全局js --> <script src="js/jquery.min.js?v=2.1.4"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <script> //登录 function checkLogin() { //非空验证 var name = $('input[name="admin_name"]').val(); var pwd = $('input[name="<PASSWORD>_pwd"]').val(); // var value = $('input[name="luotest_response"]').val(); var value = $('#lc-captcha-response').val(); // console.log(value); if(name == '' || pwd == '') { toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error('用户名或密码不能为空'); return false; } //判断登录 var url = '/index/login/index'; $.post(url,{admin_name:name,admin_pwd:pwd},function (res) { if (res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { window.location.href = "/index.html"; },3000); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function() { location.reload(); }, 2000); } },'json') } </script> </body> </html><file_sep>/runtime/temp/132e830284284aa8ce4c9a85ae2b128e.php <?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:68:"D:\phpStudy\WWW\yk_friend/application/index\view\auth\admin_pri.html";i:1551232115;}*/ ?> <!DOCTYPE html> <html> <head> <base href="/public/backend/"> <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet"> <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet"> <link href="css/plugins/iCheck/custom.css" rel="stylesheet"> <link href="css/animate.css" rel="stylesheet"> <link href="css/style.css?v=4.1.0" rel="stylesheet"> <link href="css/plugins/toastr/toastr.min.css" rel="stylesheet"> </head> <body> <div class="ibox float-e-margins"> <div class="ibox-title"> <center> <h3>赋权分配权限给[<?php echo $name; ?>]</h3> </center> </div> </div> <!--<form action="<?php echo url('overall/admin_pri'); ?>" method="post">--> <center> <table class="table table-hover table-bordered" style="width:auto"> <?php foreach($priAll as $value): ?> <tr> <td> <span > <input type="checkbox" parent="<?php echo $value['pid']; ?>" class="check firstLevel" value="<?php echo $value['id']; ?>" name="id" <?php if($value['curr']==1): ?>checked<?php endif; ?>> <span style="padding-left:5px;"><?php echo $value['menu_name']; ?></span> </span> </td> <td> <?php foreach($value['son'] as $val): ?> <span style="width:25%;padding-right:50px;"> <input type="checkbox" parent="<?php echo $val['pid']; ?>" class="check secondLevel" value="<?php echo $val['id']; ?>" name="id" <?php if($val['curr']==1): ?>checked<?php endif; ?> > <span style="margin-right:50px;"><?php echo $val['menu_name']; ?></span> </span> <?php endforeach; ?> </td> </tr> <?php endforeach; ?> <tr> <td colspan="2" align="center"><input type="checkbox" id="checkAll">全选</td> </tr> </table> </center> <div class="form-group"> <div class="col-sm-4 col-sm-offset-5"> <button class="btn btn-primary" onclick="savePri(<?php echo $id; ?>)">确定</button> <a href="<?php echo url('auth/role'); ?>" class="btn btn-white">返回</a> </div> </div> <!--</form>--> </body> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js?v=3.3.6"></script> <!-- 自定义js --> <script src="js/content.js?v=1.0.0"></script> <!-- Toastr --> <script src="js/plugins/toastr/toastr.min.js"></script> <script> $(function () { //全选 $("#checkAll").click(function () { var state = $(this).prop("checked"); var inputList = $(".check"); $(inputList).each(function (key, val) { inputList.eq(key).prop("checked", state); }) }); //选择父级 子级跟随被选中 $(".firstLevel").click(function () { var state = $(this).prop("checked"); var pri_id = $(this).val(); var secondLevel = $(".secondLevel"); $(secondLevel).each(function (k, v) { if ($(secondLevel).eq(k).attr("parent") == pri_id) { $(secondLevel).eq(k).prop("checked", state); } }) }); //选择子级 父级跟随被选中 $(".secondLevel").click(function () { var pri_id = $(this).attr("parent"); var firstLevel = $(".firstLevel"); $(firstLevel).each(function (k, v) { if ($(firstLevel).eq(k).val() == pri_id) { $(firstLevel).eq(k).prop("checked", true); } }) }); }) //提交权限 function savePri(id) { var pri = ''; $("input[name='id']").each(function () { if($(this).prop('checked') == true){ pri = pri+$(this).val()+','; } }); $.post("<?php echo url('auth/admin_pri'); ?>",{id:id,pri:pri},function (res) { if(res.status == 1){ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success(res.msg); setTimeout(function () { location.reload(); },500); }else{ toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.error(res.msg); setTimeout(function () { location.reload(); },2000); } },'json') } </script> </html>
802e5e7aeedb057de480bfae0ddfa840999c72d6
[ "Markdown", "JavaScript", "PHP" ]
24
PHP
362663496/yk_friend_yao
f85a4a368a0c5c0ef1c638236d42dacb5b209d2e
73deee0b8ea50ea2c8da8f5db44f7a19b48653c1
refs/heads/master
<repo_name>disposedtrolley/smartcitieshack-hyperledger<file_sep>/README.md # org.stashit <file_sep>/lib/logic.js 'use strict'; function onCreateStorageRequest(createStorageRequest) { var assetRegistry var ns = 'org.stashit' var factory = getFactory() var totalCost = createStorageRequest.lendingPeriod * createStorageRequest.storageLocation.costPerPeriod var enoughFunds = createStorageRequest.requester.fundsAvailable >= totalCost var minPeriodReached = createStorageRequest.lendingPeriod >= createStorageRequest.storageLocation.minLendingPeriod if (enoughFunds && minPeriodReached) { getAssetRegistry(ns + '.ItemStorageRequest') .then(function(ar) { assetRegistry = ar var storageRequest = factory.newResource(ns, 'ItemStorageRequest', '1234') storageRequest.requester = createStorageRequest.requester storageRequest.provider = createStorageRequest.provider storageRequest.storageLocation = createStorageRequest.storageLocation storageRequest.itemsToStore = createStorageRequest.itemsToStore storageRequest.totalCost = createStorageRequest.storageLocation.costPerPeriod * createStorageRequest.lendingPeriod storageRequest.startDate = createStorageRequest.startDate storageRequest.lendingPeriod = createStorageRequest.lendingPeriod storageRequest.status = 'PENDING' return assetRegistry.add(storageRequest) }) } else { throw new Error('Requester does not have enough funds or the request does not meet the minimum period.'); } } function onApproveStorageRequest(approveStorageRequest) { var assetRegistry var ns = 'org.stashit' var factory = getFactory() // vertify the current request is still pending and the requester has enough funds var requestStatus = approveStorageRequest.requestToApprove.status var enoughFunds = approveStorageRequest.requestToApprove.requester.fundsAvailable >= approveStorageRequest.requestToApprove.totalCost if (requestStatus === 'PENDING' && enoughFunds) { getParticipantRegistry(ns + '.User') .then(function(ar) { assetRegistry = ar var totalCost = approveStorageRequest.requestToApprove.totalCost // charge the requester approveStorageRequest.requestToApprove.requester.fundsAvailable = approveStorageRequest.requestToApprove.requester.fundsAvailable - totalCost // credit the owner approveStorageRequest.requestToApprove.provider.fundsAvailable = approveStorageRequest.requestToApprove.provider.fundsAvailable + totalCost assetRegistry.update(approveStorageRequest.requestToApprove.requester) assetRegistry.update(approveStorageRequest.requestToApprove.provider) }) // update status of ItemStorageRequest getAssetRegistry(ns + '.ItemStorageRequest') .then(function(ar) { assetRegistry = ar approveStorageRequest.requestToApprove.status = 'APPROVED' return assetRegistry.update(approveStorageRequest.requestToApprove) }) // create ItemStorageContract getAssetRegistry(ns + '.ItemStorageContract') .then(function(ar) { assetRegistry = ar var storageContract = factory.newResource(ns, 'ItemStorageContract', approveStorageRequest.requestToApprove.$identifier + '_contract') storageContract.approvedRequest = approveStorageRequest.requestToApprove storageContract.fulfillmentDate = new Date() return assetRegistry.add(storageContract) }) } else { throw new Error('The request status is not PENDING or the requester does not have enough funds.') } } function onDeclineStorageRequest(declineStorageRequest) { var assetRegistry var ns = 'org.stashit' var factory = getFactory() if (declineStorageRequest.requestToDecline.status === 'PENDING') { getAssetRegistry(ns + '.ItemStorageRequest') .then(function(ar) { assetRegistry = ar declineStorageRequest.requestToDecline.status = 'DECLINED' return assetRegistry.update(declineStorageRequest.requestToDecline) }) } else { throw new Error('The request status is not PENDING.') } } function onCancelStorageRequest(cancelStorageRequest) { var assetRegistry var ns = 'org.stashit' var factory = getFactory() if (cancelStorageRequest.requestToCancel.status === 'PENDING') { getAssetRegistry(ns + '.ItemStorageRequest') .then(function(ar) { assetRegistry = ar cancelStorageRequest.requestToCancel.status = 'CANCELLED' return assetRegistry.update(cancelStorageRequest.requestToCancel) }) } else { throw new Error('The request status is not PENDING.') } }
fe5303baf41de3f885b279567a37436ecc0ccd68
[ "Markdown", "JavaScript" ]
2
Markdown
disposedtrolley/smartcitieshack-hyperledger
6ec7bf4b15c9537ad6e37be7b242cfc0edabca34
3f0d6d5a447ffd417441572dd9154f33de70fc6f
refs/heads/master
<repo_name>YouAppi/git-cherry-picker<file_sep>/docker_build.sh #!/usr/bin/env bash docker build -t 434766423903.dkr.ecr.us-west-2.amazonaws.com/ya_cherry_picker \ -t 434766423903.dkr.ecr.eu-central-1.amazonaws.com/ya_cherry_picker . <file_sep>/README.md ### local run * **AutoCherryPicksPR** `./run_cherry_picker.sh [args]` * **GitGreenMergerMain** `./run_gitk_merger.sh [args]` --- ### docker build `./docker_build.sh` ### docker exec * **AutoCherryPicksPR** `./docker_exec_cherry_picker.sh [args]` * **GitGreenMergerMain** `./docker_exec_gitk_merger.sh [args]`<file_sep>/gitk/build.gradle plugins { id 'com.github.johnrengelman.shadow' } shadowJar { archiveFileName = "gitk-$version-fat.jar" manifest.attributes("Main-Class": 'com.jacky.git.GitGreenMergerMain') zip64 true } jar { manifest.attributes("Main-Class": 'com.jacky.git.GitGreenMergerMain') } artifacts { archives jar, shadowJar } dependencies { compile library.jackson_yaml compile library.jackson_databind testCompile library.mockito }<file_sep>/build.gradle plugins { id 'com.github.johnrengelman.shadow' version '4.0.4' } ext.library = [ groovy: 'org.codehaus.groovy:groovy-all:2.3.4', cli: 'commons-cli:commons-cli:1.2', github: 'org.eclipse.mylyn.github:org.eclipse.egit.github.core:2.1.5', jackson_yaml: 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.8.6', jackson_databind: 'com.fasterxml.jackson.core:jackson-databind:2.8.6', mail: 'javax.mail:mail:1.4.5', junit: 'junit:junit-dep:4.10', hamcrest: 'org.hamcrest:hamcrest-all:1.3', mockito: 'org.mockito:mockito-core:2.7.7', ] def BUILD_NUMBER = project.hasProperty('BUILD_NUMBER')? "$BUILD_NUMBER" : '0' version = "1.0.$BUILD_NUMBER" subprojects { apply plugin: 'groovy' apply plugin: 'jacoco' group = 'com.jacky' version = "1.0.$BUILD_NUMBER" sourceCompatibility = 1.8 targetCompatibility = 1.8 gradle.startParameter.continueOnFailure = true sourceSets.main.java.srcDirs = [] sourceSets.test.java.srcDirs = [] repositories { jcenter() } dependencies { compile library.groovy compile library.cli compile library.github testCompile library.junit testCompile library.hamcrest } }
4b1db658fec66b1f7f95e25bf555fa47e8dfeeb0
[ "Markdown", "Shell", "Gradle" ]
4
Shell
YouAppi/git-cherry-picker
bc27257242d87f2375bd8f4f778b0042cc3b46f8
e49ab034408b297f190d4a90e97bcaa0c4141c4d
refs/heads/master
<repo_name>Skooled/Magenta-Elephants<file_sep>/IOS_client/main/index.js import React, { Component } from 'react' import { Provider } from 'react-redux' import Navigator from './navigation' import { applyMiddleware, createStore } from 'redux' function loginReducer(state, action) { console.log('initial state', state); switch (action.type) { case 'LOGIN': return {...state, login: action.payload, userInfo: action.userInfo} case 'SIGNUP': return {...state, login: false, signUp: action.payload} case 'LOGOUT': return {...state, login: false, signUp: false} default: return state } } const middleware = applyMiddleware(logger); const logger = (store) => (next) => (action) => { console.log('action fired', action); next(action); }; const store = createStore(loginReducer, { login: false }); store.subscribe(()=> { console.log('store changed', store.getState()); }); export default class Root extends Component { constructor() { super() this.state = { store } } render() { return ( <Provider store={this.state.store}> <Navigator /> </Provider> ) } }<file_sep>/IOS_client/main/components/Stream.js import React from 'react'; import { View, ScrollView, StyleSheet } from 'react-native'; import Question from './Question.js'; class Stream extends React.Component { constructor(props) { super(props) } render() { return ( <ScrollView style={styles.container} > {this.props.questions.map((question, index) => <Question q={question} key={index} navigation={this.props.navigation}/>)} </ScrollView> ) } } const styles = StyleSheet.create({ container: { flex: 1 }, scrollView: { backgroundColor: '#eeeeee', height: 300, }, horizontalScrollView: { height: 106, }, text: { fontSize: 16, fontWeight: 'bold', margin: 5, }, button: { margin: 5, padding: 5, alignItems: 'center', backgroundColor: '#cccccc', borderRadius: 3, }, thumb: { margin: 5, padding: 5, backgroundColor: '#cccccc', borderRadius: 3, minWidth: 96, }, img: { width: 64, height: 64, } }); export default Stream;<file_sep>/IOS_client/main/navigation/index.js import React, { Component } from 'react' import { connect } from 'react-redux' import OnboardingNavigator from './navigationOnboarding' import MainNavigator from './navigationMain' import SigningUpNavigator from './navigationSigning' class Navigator extends Component { render() { console.log('GIVE ME THE PROPS', this.props); if (this.props.login) { return <MainNavigator/> } else if (this.props.signUp) { return <SigningUpNavigator/> } else { return <OnboardingNavigator/> } } } const mapStateToProps = state => (state) export default connect(mapStateToProps, {})(Navigator)<file_sep>/server/index.js const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const Promise = require('bluebird'); const db = Promise.promisifyAll(require('../models/index')); const sessionParser = require('../middleware/sessionParser.js'); const request = require('request'); const config = require('../config/vars.js'); const login = require('../middleware/onLogin.js'); const port = process.env.PORT || 80; const app = express(); process.env.PWD = process.cwd(); app.use(cookieParser()); var jsonParser = bodyParser.json(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/testing', function(req, res, next) { res.end('this is a test'); }); // app.get('/', function(req, res, next) { // console.log('got to index!'); // // res.redirect('/dashboard'); // }); app.get('/dashboard', sessionParser, function(req, res, next) { res.sendFile(process.env.PWD + '/client/index.html'); }); app.get('/callback', function(req, res, next) { var code = req.query.code; var url = `https://github.com/login/oauth/access_token?client_id=${config.clientID}&redirect_uri=https://fast-forest-86732.herokuapp.com/callback&client_secret=${config.clientSecret}&code=${code}`; console.log('do we at least get here????\n\n\n\n\n\n\n\n\n\n\n'); request.post(url, function(err, httpResponse, body) { var accessToken = body.substring(13); var options = { url: `https://api.github.com/user?access_token=${accessToken}`, headers: { 'User-Agent': '4um' } }; console.log('this is the access token', accessToken); request.get(options, function(err, httpResponse, body) { login(req, res, next, body); }); }); }); app.get('/expertRating', function(req, res) { db.User.getRating('expert', req.body.username) .then((result) => { res.end(result); }); }); app.get('/noviceRating', function(req, res) { db.User.getRating('novice', req.body.username) .then((result) => { res.end(result); }) }); app.get('/questions/*', function(req, res) { var slashIndex = req.url.lastIndexOf('/') + 1; var tag = req.url.substring(slashIndex).toLowerCase(); db.Tag.getQuestionsFromTag(tag, questions => res.end(JSON.stringify(questions))); }); app.get('/questions', function (req, res) { db.Question.getQuestions('', arr => res.send(arr)); }); // { '{"tags":"ios","username":"Pa87901","title":"Why is Tom so cheap?","body":"","price":"10","minExpertRating":"10"}': '' } app.post('/questions', function(req, res) { console.log('client request from IOS!!', req.headers); // req.body.tags = JSON.parse(req.body.tags); db.Question.createNewQuestion(req.body.username, req.body.title, req.body.body, Number(req.body.price), req.body.tags, req.body.minExpertRating ); // db.User.updateCurrency(req.body.username, Number(req.body.price)); res.end(); }); app.put('/questions', function(req, res) { var questionId = req.body.questionId; delete req.body.questionId; db.Question.updateQuestion(questionId, req.body) .then((result) => { res.end(JSON.stringify(result)); }); }); app.post('/messages', function(req, res) { db.Message.createMessage(req.body.questionId, req.body.userId, req.body.body); res.end(); }); app.post('/messages/*', function(req, res) { var slashIndex = req.url.lastIndexOf('/') + 1; var destination = req.url.substring(slashIndex); if (!namespaces.includes(destination)) { namespaces.push(destination); createNamespace(destination); } }) app.get('/github', (req, res) => { console.log(req.headers); const githubusername = req.headers.githubusername; const email = req.headers.email; var options = { method: 'GET', url: `https://api.github.com/users/${githubusername}`, headers: { 'User-Agent': 'pa87901', 'authorization': 'Basic c<KEY>=', 'email': email }, }; request(options, (error, response, fields) => { if(error) { console.error('Error getting Github profile.'); res.sendStatus(500); } else { console.log('github profile', response.body, 'options', options); let JSONresponse = JSON.parse(response.body) if (JSONresponse.login === 'undefined') { res.sendStatus(500); } else { // Save this in database. let username = githubusername; let email = options.headers.email; let avatar_url = JSONresponse.avatar_url; let bio = JSONresponse.bio; let name = JSONresponse.name; // console.log('EMAIL', email); db.User.createUser(username, email, avatar_url, bio, name) .then(response => { console.log('User saved in db!', response.dataValues); res.json(response.dataValues); }); } } }); }); app.use(express.static(process.env.PWD + '/client')); app.get('/users*', function(req, res) { var slashIndex = req.url.lastIndexOf('/') + 1; var user = req.url.substring(slashIndex); console.log('this is the user', user); console.log('this is the url', req.url); db.User.getUserInfo(user, userInfo => res.end(JSON.stringify(userInfo))); }); app.get('/user', (req, res) => { console.log('email', req.headers.email); db.User.getUserInfoByEmail(req.headers.email) .then(response => { console.log('userinfo', response); res.json(response); }) .catch(error => { res.sendStatus(500); }); }); app.get('*', function(req, res) { // res.redirect('/dashboard'); }); var server = app.listen(port, function() { console.log('Listening on port 3000 the dirname is', process.env.PWD + '/../client'); }); // Socket-support for React Native Apps: const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); var chats = {}; var ChatRoom = function () { this.users = []; } ChatRoom.prototype.addUser = function (chatClient) { if(this.users.indexOf(chatClient) === -1) { this.users.push(chatClient); console.log('new user'); } }; ChatRoom.prototype.broadCast = function (data, broadcastingUser) { this.users.forEach(function(user, index, array) { // The message should not be broadcasted to the user who sent it: if (user !== broadcastingUser) { user.send(JSON.stringify(data), function(error) { console.log(error); }); } }); }; wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: ', JSON.parse(message).msg[0].text); var newMessage = JSON.parse(message); db.Message.createMessage(newMessage.questionId, newMessage.msg[0].user._id, newMessage.msg[0].text, newMessage.msg[0].user.avatar); // Create Room if it doesn't exist: if (!(newMessage.questionId in chats)) { var createdRoom = new ChatRoom(); createdRoom.addUser(ws); chats[newMessage.questionId] = createdRoom; // Broadcast message if there are other users in the same room: } else { chats[newMessage.questionId].broadCast(newMessage, ws); // Add user/client to room: chats[newMessage.questionId].addUser(ws); } }); }); // End of Socket-support for React Native Apps const io = require('socket.io')(server); var namespaces = [] connections = []; users = []; var createNamespace = function(destination) { var nsp = io.of(`/${destination}`); nsp.on('connection', function(socket) { connections.push(socket); console.log(`someone connected`); socket.on('disconnect', function() { console.log('user disconnected'); }) socket.on('new user', function(data, callback) { callback(true); socket.username = data; users.push(socket.username); updateUsernames(); }); socket.on('new message', function(msg){ console.log('message: ' + msg); nsp.emit('new message', msg); }); socket.on('finish', function(msg) { db.Question.finishQuestion(destination); nsp.emit('finish'); }); }); var updateUsernames = function() { nsp.emit('get users', users); }; };<file_sep>/IOS_client/main/navigation/screen/screenOverview.js import React from 'react' import { Text, View, Button, StyleSheet } from 'react-native' import { connect } from 'react-redux' import AppChatNavigator from '../navigationAppChat' class Overview extends React.Component { static navigationOptions = { drawer: () => ({ label: 'My Overview', logout: () => dispatch({type:'LOGOUT'}), }) }; render() { const {navigate} = this.props.navigation; return ( <View style={styles.mainContainer}> <AppChatNavigator style={styles.contentContainer}/> <View style={styles.footerContainer}> <Button onPress={() => navigate('DrawerOpen')} title="Menu" /> </View> </View> ); } } const styles = StyleSheet.create({ mainContainer: { flex: 1, backgroundColor: '#F5FCFF', height: 24 }, footerContainer: { flex: 0.5, flexDirection: "row", backgroundColor: "#FFFFFF", justifyContent: "center", alignItems:"center", paddingRight: 5 }, contentContainer: { flex: 7, }, }); function bindActions(dispatch) { return { dispatch, } } const mapStateToProps = state => (state) export default connect(mapStateToProps, bindActions)(Overview)<file_sep>/IOS_client/index.ios.js import React from 'react' import { AppRegistry } from 'react-native' import forumApp from './main' console.disableYellowBox = true; AppRegistry.registerComponent('AwesomeProject', () => forumApp);<file_sep>/IOS_client/main/components/App.js import React, { Component } from 'react'; import axios from 'axios'; import { AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; import Stream from './Stream.js'; import testData from './TestData.js'; import QuestionInput from './QuestionInput.js'; import { connect } from 'react-redux'; import t from 'tcomb-form-native'; var serverURL = 'http://172.16.17.32'; const Form = t.form.Form; const Question = t.struct({ question: t.String }); const options = {}; class App extends Component { constructor(props) { super(props); this.state = { questions: [], questionInput: '' } this.onButtonPress = this.onButtonPress.bind(this); this.handleInput = this.handleInput.bind(this); } componentWillMount () { // console.log('this.props in App', this.props); // Get feed from server using http GET request. axios.get(serverURL + '/questions') .then(questions => { console.log('Received question from server.', questions); this.setState({ questions: questions.data }); }) .catch(error => { console.error('Unable to receive response from server GET /questions.'); }) } handleInput (text) { this.setState({ questionInput: text }); } onButtonPress () { console.log('The user asked for: ' + this.state.questionInput); console.log('this.props in App.js', this.props.userInfo); var headers = { tags: 'ios', username: this.props.userInfo.username, title: this.state.questionInput, body: '', price: '10', minExpertRating: '10' } axios.post(serverURL + '/questions', headers) .then(response => { console.log(response); this.componentWillMount(); }) .catch(error => { console.log('error: ', error) }); } render() { return ( <View style={styles.container} > <QuestionInput handleInput={this.handleInput}/> <Button onPress={this.onButtonPress} title="Post" color="#000066" /> <Stream questions={this.state.questions} navigation={this.props.navigation}/> </View> ) } // render() { // return ( // <View style={styles.container} > // <Form // ref="qform" // type={Question} // value={{questionInput: this.state.questionInput}} // onChange={this.handleInput} // options={options} // /> // <TouchableHighlight style={styles.postButton} onPress={this.onButtonPress} > // <Text style={styles.postButtonText}>Post</Text> // </TouchableHighlight> // <Stream questions={this.state.questions} navigation={this.props.navigation}/> // </View> // ) // } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF' }, quesitonInput: { height: 40, borderColor: 'gray', borderWidth: 1, marginLeft: 10, marginRight: 10, marginTop: 20 }, postButtonText: { fontSize: 18, color: 'white', alignSelf: 'center' }, postButton: { height: 20, backgroundColor: '#228B22', borderColor: '#48BBEC', borderWidth: 1, borderRadius: 8, marginBottom: 10, alignSelf: 'stretch', justifyContent: 'center' } }); // No dispatch methods for App component for now so return empty dispatch. function bindActions(dispatch) { return { dispatch } } const mapStateToProps = state => (state); export default connect(mapStateToProps, bindActions)(App);<file_sep>/IOS_client/main/navigation/screen/screenLogin.js 'use strict'; import React from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; import t from 'tcomb-form-native'; import { connect } from 'react-redux'; import { firebaseApp } from './config/config.js'; import axios from 'axios'; var serverURL = 'http://192.168.127.12'; const Form = t.form.Form; const Person = t.struct({ email: t.String, // githubUsername: t.String, password: t.String, rememberMe: t.Boolean }); // These options are to make the password hidden when you type. const options = { fields: { password: { password: <PASSWORD>, secureTextEntry: true } } }; class Login extends React.Component { constructor (props) { super(props); this.state = { value: { email: '', password: '' } } this.onChange = this.onChange.bind(this); this.login = this.login.bind(this); } onChange(value) { this.setState({value}); } login() { let value = this.refs.form.getValue(); if (value) { firebaseApp.auth().signInWithEmailAndPassword(this.state.value.email, this.state.value.password) .then(response => { console.log('User authenticated!'); const config = { headers: { 'email': this.state.value.email } }; axios.get(`${serverURL}/user`, config) .then(response => { console.log('User info retrieved!', response.data); this.props.login(response.data); }) .catch(error => { this.props.relogin(); window.alert('We are sorry but there are issues with fetching your Github profile. Please try again later.') }) }) .catch(error => { this.props.relogin(); window.alert('Incorrect username or password. Please retry.') }); } } render() { return ( <View style={styles.container}> <Form ref="form" type={Person} value={this.state.value} onChange={this.onChange} options={options} /> <TouchableHighlight style={styles.loginButton} onPress={this.login} underlayColor='#99d9f4'> <Text style={styles.buttonText}>Login</Text> </TouchableHighlight> <TouchableHighlight style={styles.signUpButton} onPress={this.props.signUp}> <Text style={styles.buttonText}>Sign Up</Text> </TouchableHighlight> </View> ); } } const styles = StyleSheet.create({ container: { justifyContent: 'center', marginTop: 50, padding: 20, backgroundColor: '#ffffff', }, title: { fontSize: 30, alignSelf: 'center', marginBottom: 30 }, buttonText: { fontSize: 18, color: 'white', alignSelf: 'center' }, loginButton: { height: 36, backgroundColor: '#6495ED', borderColor: '#48BBEC', borderWidth: 1, borderRadius: 8, marginBottom: 10, alignSelf: 'stretch', justifyContent: 'center' }, signUpButton: { height: 36, backgroundColor: '#32CD32', borderColor: '#48BBEC', borderWidth: 1, borderRadius: 8, marginBottom: 10, alignSelf: 'stretch', justifyContent: 'center' } }); function bindActions(dispatch) { return { login: (data) => dispatch({type:'LOGIN', payload: true, userInfo: data}), signUp: () => dispatch({type: 'SIGNUP', payload: true}), relogin: () => dispatch({type: 'LOGIN', payload: false}) } }; const mapStateToProps = state => ({}) export default connect(mapStateToProps, bindActions)(Login)<file_sep>/database/schema.sql DROP DATABASE IF EXISTS `test`; CREATE DATABASE test; USE test; -- DROP DATABASE IF EXISTS `4um`; -- CREATE DATABASE 4um; -- USE 4um; <file_sep>/IOS_client/main/navigation/navigationSigning.js import { StackNavigator } from 'react-navigation'; // import SignUp from '../components/SignUp.js'; import SignUp from './screen/screenSignUp'; const SigningNavigator = StackNavigator({ SignUp: { screen: SignUp }, }, { initialRouteName: 'SignUp' }) export default SigningNavigator;<file_sep>/IOS_client/main/components/AnsweredStatus.js import React from 'react'; import { Text } from 'react-native'; const AnsweredStatus = (props) => { if (props.answeredStatus) { return ( <Text>✅</Text> ) } else { return ( <Text>✍</Text> ) } } export default AnsweredStatus;<file_sep>/README.md # 4.um > Personalized, interactive forum for software developers. ## Team - <NAME> - <NAME> - <NAME> ## Table of Contents 1. [Git Workflow](#git-workflow) 1. [Usage](#usage) 1. [Requirements](#requirements) 1. [Contributing](#contributing) ## Git Workflow 1. Type: git remote add upstream https://github.com/skooled/Magenta-Elephants 2. (ensure you are on master branch) type: git checkout master 3. (Sync local master with org’s master) type: git pull --rebase upstream master 4. Create a feature branch, type: git checkout -b <name_of_branch> 5. BEFORE SUBMITTING YOUR NEW CHANGES: 1. git add . 2. git commit 3. git pull --rebase upstream master 6. git push origin <name_of_branch> 7. PULL REQUEST WITH GITHUB 8. Team member reviews code and decides whether to merge or not 9. IF ACCEPTED/MERGED 10. (Switch back to master) type: git checkout master 11. (Delete local branch) type: git branch -D <name_of_branch> 12. type: git pull --rebase upstream master 13. git push origin master ## Usage > Where software developers of all skill levels and specialties can come together for trustworthy guidance and positive contributions to their community's growth. ## Requirements - Android/iOS - Express - Firebase - MySql - React Native - Redux - Socket ### Getting Started - From the root directory run 'npm install' - Open a new terminal and run 'npm run server-dev' - Open a new terminal from the spec directory run 'RUN=true node populateDB.js' - Open a new terminal from the IOS_client directory run 'npm install' - Launch emulator/simulator for the respective device you wish to emulate - From the IOS_client directory run either 'react-native run-ios' or 'react-native run-android' - Use a Mac/Linux to implement this repository (no bat file included for Windows) ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines. <file_sep>/IOS_client/main/navigation/screen/screenSignUpOLD.js import React from 'react' import { Text, View, Button } from 'react-native' import { connect } from 'react-redux' class SignUp extends React.Component { render() { return ( <View> <Text>Name, Password</Text> <Button onPress={() => this.props.signUp()} title="SignUp" /> </View> ) } } function bindActions(dispatch) { return { signUp: () => dispatch({type:'SIGNUP'}), } } const mapStateToProps = state => ({}) export default connect(mapStateToProps, bindActions)(SignUp)<file_sep>/IOS_client/main/navigation/screen/screenLogout.js import React from 'react' import { Text, View, Button } from 'react-native' import { connect } from 'react-redux' class Logout extends React.Component { render() { this.props.logout(); return ( <Text /> ) } } function bindActions(dispatch) { return { logout: () => dispatch({type:'LOGOUT'}), } } const mapStateToProps = state => ({}) export default connect(mapStateToProps, bindActions)(Logout)<file_sep>/IOS_client/main/navigation/navigationOnboarding.js import { StackNavigator } from 'react-navigation'; // import Register from './screenRegister' import Login from './screen/screenLogin'; // import Login from '../components/Login.js'; // import PwdForget from './screenPwdforget' // import Tour from './screenTour' import SignUp from './screen/screenSignUp'; const OnboardingNavigator = StackNavigator({ Login: { screen: Login }, SignUp: { screen: SignUp }, // PwdForgot: { screen: PwdForgot }, }, { initialRouteName: 'Login' // initialRouteName: 'SignUp' }) export default OnboardingNavigator;
665591300fefa9de3ec8032eea1ec0375ab9f1f9
[ "JavaScript", "SQL", "Markdown" ]
15
JavaScript
Skooled/Magenta-Elephants
f06d2310c155a476c5880d99c69d9afb54d1f121
102bb916412d194a92eb4086194ac3123fc5bd2d
refs/heads/master
<repo_name>L4D15/Game_of_Thrones_FG<file_sep>/campaign/scripts/char_labelframetop.lua local widget = nil; function onInit() if icons and icons[1] then setIcon(icons[1]); end end function setIcon(sIcon) if widget then widget.destroy(); end if sIcon then widget = addBitmapWidget(sIcon); widget.setPosition("topleft", 2, 8); end end function onHover(state) if highlight then if state then setColor("494340"); else setColor("FFF1CC"); end end end function onClickDown(button, x, y) if (class and class[1]) then return true; end end function onClickRelease(button, x, y) if (class and class[1]) then if button == 1 then local node = window.getDatabaseNode(); local w = Interface.findWindow(class[1], node); if w then w.bringToFront(); else Interface.openWindow(class[1], node); end end end return true; end function onDragStart(button, x, y, dragdata) if (class and class[1]) then local nodeChar = window.getDatabaseNode(); local sDescription = nodeChar.getChild("name").getValue(); local sWindowType = StringManager.capitalize(getValue():lower()); sDescription = sWindowType .. " - " .. sDescription:match("%a+"); dragdata.setType("shortcut"); dragdata.setDescription(sDescription); if icons and icons[1] then dragdata.setIcon(icons[1]); else dragdata.setIcon("button_link") end dragdata.setShortcutData(class[1], nodeChar.getNodeName()); return true; end end
d6abc2b4d6681c43903aa4689398dbb4423b1733
[ "Lua" ]
1
Lua
L4D15/Game_of_Thrones_FG
077017a6a4bbf0410024f7eff55d7770e3edc5d1
2c0414550c9d02c1a69b4e8b2b1d155be88b2297
refs/heads/master
<file_sep>// // PhotoBucketTableViewController.swift // PhotoBucket // // Created by FengYizhi on 2018/4/13. // Copyright © 2018年 FengYizhi. All rights reserved. // import UIKit import CoreData class PhotoBucketTableViewController: UITableViewController { var context = (UIApplication.shared.delegate as! AppDelegate) .persistentContainer.viewContext let photoCellIdentifier = "PhotoCell" let noPhotoCellIdentifier = "NoPhotoCell" let showDetailSegueIdentifier = "ShowDetailSegue" var photos = [Photo]() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = self.editButtonItem navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showAddDialog)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.updatePhotoArray() tableView.reloadData() } @objc func showAddDialog() { let alertController = UIAlertController(title: "Create a new Weatherpic", message: "", preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Caption" } alertController.addTextField { (textField) in textField.placeholder = "Image URL (or blank)" } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let createAction = UIAlertAction(title: "Create", style: .default) { (action) in let captionTextField = alertController.textFields![0] let imageUrlTextField = alertController.textFields![1] let newPhoto = Photo(context: self.context) newPhoto.caption = captionTextField.text newPhoto.imageUrl = (imageUrlTextField.text?.isEmpty)! ? self.getRandomImageUrl() : imageUrlTextField.text newPhoto.created = Date() self.save() self.updatePhotoArray() if self.photos.count == 1 { self.tableView.reloadData() self.setEditing(false, animated: true) } else { self.tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .top) } } alertController.addAction(cancelAction) alertController.addAction(createAction) present(alertController, animated: true, completion: nil) } func getRandomImageUrl() -> String { let testImages = ["https://upload.wikimedia.org/wikipedia/commons/0/04/Hurricane_Isabel_from_ISS.jpg", "https://upload.wikimedia.org/wikipedia/commons/0/00/Flood102405.JPG", "https://upload.wikimedia.org/wikipedia/commons/6/6b/Mount_Carmel_forest_fire14.jpg"] let randomIndex = Int(arc4random_uniform(UInt32(testImages.count))) return testImages[randomIndex]; } func save() { (UIApplication.shared.delegate as! AppDelegate).saveContext() } func updatePhotoArray() { let request: NSFetchRequest<Photo> = Photo.fetchRequest() request.sortDescriptors = [NSSortDescriptor(key: "created", ascending: false)] do { photos = try context.fetch(request) } catch { fatalError("Unresolve Core Data error \(error)") } } override func setEditing(_ editing: Bool, animated: Bool) { if photos.count == 0 { super.setEditing(false, animated: animated) } else { super.setEditing(editing, animated: animated) } } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return max(photos.count, 1) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell if photos.count == 0 { cell = tableView.dequeueReusableCell(withIdentifier: noPhotoCellIdentifier, for: indexPath) } else { cell = tableView.dequeueReusableCell(withIdentifier: photoCellIdentifier, for: indexPath) cell.textLabel?.text = photos[indexPath.row].caption } return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return photos.count > 0 } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { context.delete(photos[indexPath.row]) save() updatePhotoArray() if photos.count == 0 { tableView.reloadData() } else { tableView.deleteRows(at: [indexPath], with: .fade)} } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == showDetailSegueIdentifier { if let indexPath = tableView.indexPathForSelectedRow { (segue.destination as! PhotoBucketDetailViewController).photo = photos[indexPath.row] } } } }
f9de81704563aa90824752a3ae500c8c13c46a86
[ "Swift" ]
1
Swift
CSSE484-IOS/PhotoBucket
5ae933e909484b9d07999992a370b21798d5aa5f
3b890e9f1031a1b79089d6da1196f07dbd300299
refs/heads/master
<file_sep>export const printTime = function(t) { const prependZero = function(x){ return ('0' + x).slice(-2); }; t = Math.round(t); var h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60; if (h === 0) { return [m, prependZero(s)].join(':') } return [h, prependZero(m), prependZero(s)].join(':'); }; <file_sep># React Nickelodeon ![screenshot](https://cdn.rphlo.com/humppakone-screenshot.png) A frontend for the django-nickelodeon API https://github.com/rphlo/django-nickelodeon Hosted at https://humppakone.com <file_sep> import React from "react"; import Tooltip from '@material-ui/core/Tooltip'; export default class SearchResultItem extends React.PureComponent { render() { const { audio, queue, username, isSuperuser } = this.props; const queueIndex = queue.findIndex(el => el.id === audio.id); return ( <div className="searchResultItem" > <span className="link" title={audio.filename} onClick={()=>this.props.onQueueAudio(audio)} > <img className="cover" src="/vinyl.jpg" alt="cover" /> { (queueIndex !== -1) && (<div className="queueNumber">{(queueIndex+1).toString()}</div>)} </span> <Tooltip arrow placement="bottom" title={audio.filename}> <span className="link" onClick={()=>this.props.onRandomAudioLoaded(audio)}>{ audio.filename.split('/').pop() }</span> </Tooltip> { (username === audio.owner || isSuperuser) && <span className="searchResultActions"> <span className="link" onClick={()=>this.props.editAudioFilename(audio)} > <i className="fas fa-edit"></i> </span> <span className="link" onClick={()=>this.props.deleteAudio(audio)} > <i className="fas fa-trash"></i> </span> </span>} </div>); } }
1cf2f8956b4ddf4ce812d73c939b26d708933866
[ "JavaScript", "Markdown" ]
3
JavaScript
rphlo/react-nickelodeon
e482f35575c90fb64cd9c8e69fb844e959b21603
fcae437f1261701d04df10613c647f476f86884d
refs/heads/master
<file_sep>using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Services { public interface IUserService { User Create(string currentUsername, string username, string password); User Update(string currentUsername, int userId, string username); User Validate(string username, string password); List<User> ListUsersForManagement(string currentUsername); User GetUserForEdit(string currentUsername, int id); User ResetPassword(string currentUsername, int userId, string password); List<User> ListUsersForProject(string currentUsername, int projectId); } } <file_sep>using BugNet.Domain.Infrastructure.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BugNet.Domain.ApplicationModels; using BugNet.Domain; namespace BugNet.Application.Services { public class ReportService : IReportService { public Dictionary<string, double> GetProjectStatusStatistics(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Where(x => x.ProjectId == projectId && x.Status != null); return issues.GroupBy(x => x.Status).ToDictionary(x => x.Key.Name, x => (double)x.Count() / (double)issues.Count() * (double)100); } } public Dictionary<string, double> GetProjectPriorityStatistics(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Where(x => x.ProjectId == projectId && !x.Status.IsClosedState && x.Priority != null); return issues.GroupBy(x => x.Priority).ToDictionary(x => x.Key.Name, x => (double)x.Count() / (double)issues.Count() * (double)100); } } public double TotalLoggedHoursInPastWeek() { using (var ctx = new BugNetContext()) { DateTime startDate = DateTime.Now.AddDays(-7); DateTime endDate = DateTime.Now; return ctx.WorkReports.Where(x => x.Timestamp >= startDate && x.Timestamp <= endDate).Sum(x => x.Duration); } } public double TotalHoursLoggedInBeforePastWeek() { using (var ctx = new BugNetContext()) { DateTime startDate = DateTime.Now.AddDays(-14); DateTime endDate = DateTime.Now.AddDays(-7); return ctx.WorkReports.Where(x => x.Timestamp >= startDate && x.Timestamp <= endDate).Sum(x => x.Duration); } } public Dictionary<string, double> GetProjectMilestoneStatistics(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Where(x => x.ProjectId == projectId && !x.Status.IsClosedState && x.Milestone != null); return issues.GroupBy(x => x.Milestone).ToDictionary(x => x.Key.Name, x => (double)x.Count() / (double)issues.Count() * (double)100); } } public Dictionary<string, double> GetProjectTypeStatistics(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Where(x => x.ProjectId == projectId && !x.Status.IsClosedState && x.Type != null); return issues.GroupBy(x => x.Type).ToDictionary(x => x.Key.Name, x => (double)x.Count() / (double)issues.Count() * (double)100); } } public Dictionary<string, double> GetProjectCategoryStatistics(string username, int projectId) { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Where(x => x.ProjectId == projectId && !x.Status.IsClosedState && x.Category != null); return issues.GroupBy(x => x.Category).ToDictionary(x => x.Key.Name, x => (double)x.Count() / (double)issues.Count() * (double)100); } } public Dictionary<string, List<LoggedHoursPerDay>> GetLoggedHoursPerDayOnProjects(string username) { using (var ctx = new BugNetContext()) { Dictionary<string, List<LoggedHoursPerDay>> result = new Dictionary<string, List<LoggedHoursPerDay>>(); var projects = ctx.Projects.Where(x => x.UserProjects.Count(y => y.User.Username == username) > 0 || x.ManagerUser.Username == username || x.CreatorUser.Username == username).ToList(); foreach (var project in projects) { var workReports = project.Issues.SelectMany (x => x.WorkReports).ToList(); var groupedHoursPerDay = workReports.GroupBy(x => x.Timestamp.ToString("yyyy-MM-dd")); var data = groupedHoursPerDay.Select(x => new LoggedHoursPerDay() { Timestamp = Convert.ToDateTime(x.Key), Hours = x.Sum(y => y.Duration) }).ToList(); result.Add(project.Name, data.OrderBy(x => x.Timestamp).ToList()); } return result; } } public double Velocity() { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Include("Status").Include("WorkReports").Where(x => x.Status != null && x.Status.IsClosedState && x.StoryPoints.HasValue &&x.StoryPoints > 0).ToList(); return (double)issues.Sum(x => x.StoryPoints) / (double)issues.Sum(x => x.WorkReports.Sum(y => y.Duration)); } } public double OpenVsClosedIssuesInPastWeek() { using (var ctx = new BugNetContext()) {; var issues = ctx.Issues.Include("Status").Where(x => x.Status != null).ToList(); return (double)issues.Count(x => !x.Status.IsClosedState) / (double)issues.Count(x => x.Status.IsClosedState) * 100; } } public double OpenVsClosedIssuesInBeforePastWeek() { using (var ctx = new BugNetContext()) { var issues = ctx.Issues.Include("Status").Where(x => x.Status != null).ToList(); return (double)issues.Count(x => !x.Status.IsClosedState) / (double)issues.Count(x => x.Status.IsClosedState) * 100; } } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectMailBoxes { [Key] public int ProjectMailboxId { get; set; } [Required] [StringLength(100)] public string MailBox { get; set; } public int ProjectId { get; set; } public Guid? AssignToUserId { get; set; } public int? IssueTypeId { get; set; } public int? CategoryId { get; set; } public virtual BugNet_ProjectCategories BugNet_ProjectCategories { get; set; } public virtual BugNet_ProjectIssueTypes BugNet_ProjectIssueTypes { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } public virtual User User { get; set; } } } <file_sep>using BugNet.WebApplication.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Controllers { public class HomeController : Controller { [HttpGet] [Base] [Authorize] public ActionResult Index() { return View(); } } }<file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_IssueVotes { [Key] public int IssueVoteId { get; set; } public int IssueId { get; set; } public Guid UserId { get; set; } public DateTime DateCreated { get; set; } public virtual BugNet_Issues BugNet_Issues { get; set; } public virtual User User { get; set; } } } <file_sep>using BugNet.Domain.Infrastructure.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Application.Services { public class ApplicationService : IApplicationService { public string GetApplicationName() { return "BugNet Demo"; } public string AssemblyVersion { get { return typeof(ApplicationService).Assembly.GetName().Version.ToString(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Services { public interface IApplicationService { string GetApplicationName(); string AssemblyVersion { get;} } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectIssueTypes { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_ProjectIssueTypes() { BugNet_Issues = new HashSet<BugNet_Issues>(); BugNet_ProjectMailBoxes = new HashSet<BugNet_ProjectMailBoxes>(); } [Key] public int IssueTypeId { get; set; } public int ProjectId { get; set; } [Required] [StringLength(50)] public string IssueTypeName { get; set; } [Required] [StringLength(50)] public string IssueTypeImageUrl { get; set; } public int SortOrder { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectMailBoxes> BugNet_ProjectMailBoxes { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models.Graph { public class C3SplineGraph { public List<object[]> Data { get; set; } } }<file_sep># BugNet An open source issue tracking &amp; project management application using MVC and Domain Driven Development # Setup <ol> <li>Clone project in your workspace or download zip</li> <li>Open project in Visual Studio</li> <li>Restore nuget packages</li> <li>Build BugNet.WebApplication in DomainDrivenDevelopment folder</li> </ol> <h5>Login with 'admin' and 'admin'</h5> <h4>Notes!</h4> <ul> <li>Make sure connection string is correct in web config</li> </ul> # Another version of BugNet? Developer's Workspace has taken BugNet a step further. We have transformed BugNet into a Neat, Admin Themed, Domain Driven site. Have a look at http://dev.bugnet.developersworkspace.co.za for a preview. Please note that this project is still in it's development phase and daily updates will be made on the site mentioned above. <file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using BugNet.WebApplication.Models.Chart; using BugNet.WebApplication.Models.Graph; using BugNet.WebApplication.Models.Widget; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Controllers { public class AjaxController : Controller { private Random random = new Random(); private IReportService ReportService; private IProjectService ProjectService; public AjaxController() { this.ReportService = Dependencies.ReportService; this.ProjectService = Dependencies.ProjectService; } [Authorize] public ActionResult MenuItemProjects() { return View(this.ProjectService.ListProjectsForUser(this.User.Identity.Name)); } [Authorize] public ActionResult WidgetDataLoggedHours() { double value1 = this.ReportService.TotalHoursLoggedInBeforePastWeek(); double value2 = this.ReportService.TotalLoggedHoursInPastWeek(); return View(new LoggedHours() { StatsValue = value1 / value2 * 100, Up = value1 < value2, Value = value2 }); } [Authorize] public ActionResult WidgetDataGeneralVelocity() { double value = this.ReportService.Velocity(); return View(value); } [Authorize] public ActionResult WidgetDataOpenVsClosed() { double value1 = this.ReportService.OpenVsClosedIssuesInBeforePastWeek(); double value2 = this.ReportService.OpenVsClosedIssuesInPastWeek(); return View(new OpenVsClosed() { StatsValue = value1 / value2 * 100, Up = value1 < value2, Value = value2 }); } [Authorize] public JsonResult ChartDataProjectTypes(int projectId) { var model = new C3DonutChart(); model.Data = new List<object[]>() { }; var data = this.ReportService.GetProjectTypeStatistics(this.User.Identity.Name, projectId); foreach (var item in data) { List<object> status = new List<object>() { (object)item.Key }; status.Add(item.Value); model.Data.Add(status.ToArray()); } return Json(model, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult ChartDataProjectCategories(int projectId) { var model = new C3DonutChart(); model.Data = new List<object[]>() { }; var data = this.ReportService.GetProjectCategoryStatistics(this.User.Identity.Name, projectId); foreach (var item in data) { List<object> status = new List<object>() { (object)item.Key }; status.Add(item.Value); model.Data.Add(status.ToArray()); } return Json(model, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult ChartDataProjectPriorities(int projectId) { var model = new C3DonutChart(); model.Data = new List<object[]>() { }; var data = this.ReportService.GetProjectPriorityStatistics(this.User.Identity.Name, projectId); foreach (var item in data) { List<object> status = new List<object>() { (object)item.Key }; status.Add(item.Value); model.Data.Add(status.ToArray()); } return Json(model, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult ChartDataProjectMilestones(int projectId) { var model = new C3DonutChart(); model.Data = new List<object[]>() { }; var data = this.ReportService.GetProjectMilestoneStatistics(this.User.Identity.Name, projectId); foreach (var item in data) { List<object> status = new List<object>() { (object)item.Key }; status.Add(item.Value); model.Data.Add(status.ToArray()); } return Json(model, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult ChartDataProjectStatuses(int projectId) { var model = new C3DonutChart(); model.Data = new List<object[]>() { }; var data = this.ReportService.GetProjectStatusStatistics(this.User.Identity.Name, projectId); foreach (var item in data) { List<object> status = new List<object>() { (object)item.Key }; status.Add(item.Value); model.Data.Add(status.ToArray()); } return Json(model, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult GraphDataLoggedHours() { var model = new C3SplineGraph(); var data = this.ReportService.GetLoggedHoursPerDayOnProjects(this.User.Identity.Name); var timestamps = data.SelectMany(x => x.Value.Select(y => y.Timestamp)).OrderBy(x => x).Distinct().ToList(); List<object> xAxis = new List<object>() { "x" }; xAxis.AddRange(timestamps.Select(x => x.ToString("yyyy-MM-dd")).Select(x => (object)x)); model.Data = new List<object[]>() { xAxis.ToArray(), }; foreach (var item in data) { List<object> project = new List<object>() { (object)item.Key }; foreach (var timestamp in timestamps) { double? value = item.Value.Count(x => x.Timestamp <= timestamp) == 0 ? (double?)null : item.Value.Where(x => x.Timestamp <= timestamp).Sum(x => x.Hours); project.Add(value); } model.Data.Add(project.ToArray()); } return Json(model, JsonRequestBehavior.AllowGet); } private int[] getRandomNumbers() { int[] ints = Enumerable.Repeat(0, 10).Select(i => random.Next(10, 120)).ToArray(); return ints; } private List<DateTime> getRandomDates() { List<DateTime> result = new List<DateTime>(); while (result.Count() < 10) { DateTime dateTime = DateTime.UtcNow.AddDays(-random.Next(90)); dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day); if (!result.Contains(dateTime)) result.Add(dateTime); } return result.OrderBy(x => x).ToList(); } } }<file_sep>namespace BugNet.Domain.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Comment")] public partial class Comment : BaseEntity { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Comment() { WorkReports = new HashSet<WorkReport>(); } public Comment(int userId,int issueId, string comment) { Content = comment; UserId = userId; IssueId = issueId; } public int Id { get; set; } public int IssueId { get; set; } [Required] public string Content { get; set; } public int UserId { get; set; } public virtual Issue Issue { get; set; } public virtual User User { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<WorkReport> WorkReports { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_UserCustomFields { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_UserCustomFields() { BugNet_UserCustomFieldSelections = new HashSet<BugNet_UserCustomFieldSelections>(); BugNet_UserCustomFieldValues = new HashSet<BugNet_UserCustomFieldValues>(); } [Key] public int CustomFieldId { get; set; } [Required] [StringLength(50)] public string CustomFieldName { get; set; } public bool CustomFieldRequired { get; set; } public int CustomFieldDataType { get; set; } public int CustomFieldTypeId { get; set; } public virtual BugNet_UserCustomFieldTypes BugNet_UserCustomFieldTypes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_UserCustomFieldSelections> BugNet_UserCustomFieldSelections { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_UserCustomFieldValues> BugNet_UserCustomFieldValues { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Repositories { public class Repository { protected IQueryable<T> addIncludes<T>(IQueryable<T> query, string[] includes) { if (includes != null) { foreach (var include in includes) { query = query.Include(include); } } return query.Cast<T>(); } } } <file_sep>using BugNet.Domain.ApplicationModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Services { public interface IReportService { Dictionary<string, double> GetProjectStatusStatistics(string currentUsername, int projectId); Dictionary<string, List<LoggedHoursPerDay>> GetLoggedHoursPerDayOnProjects(string currentUsername); Dictionary<string, double> GetProjectMilestoneStatistics(string currentUsername, int projectId); Dictionary<string, double> GetProjectTypeStatistics(string currentUsername, int projectId); Dictionary<string, double> GetProjectCategoryStatistics(string currentUsername, int projectId); Dictionary<string, double> GetProjectPriorityStatistics(string currentUsername, int projectId); double TotalLoggedHoursInPastWeek(); double TotalHoursLoggedInBeforePastWeek(); double OpenVsClosedIssuesInPastWeek(); double OpenVsClosedIssuesInBeforePastWeek(); double Velocity(); } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_Roles { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_Roles() { BugNet_Permissions = new HashSet<BugNet_Permissions>(); Users = new HashSet<User>(); } [Key] public int RoleId { get; set; } public int? ProjectId { get; set; } [Required] [StringLength(256)] public string RoleName { get; set; } [Required] [StringLength(256)] public string RoleDescription { get; set; } public bool AutoAssign { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Permissions> BugNet_Permissions { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<User> Users { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_Issues { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_Issues() { BugNet_IssueAttachments = new HashSet<BugNet_IssueAttachments>(); BugNet_IssueComments = new HashSet<BugNet_IssueComments>(); BugNet_IssueHistory = new HashSet<BugNet_IssueHistory>(); BugNet_IssueNotifications = new HashSet<BugNet_IssueNotifications>(); BugNet_IssueRevisions = new HashSet<BugNet_IssueRevisions>(); BugNet_IssueVotes = new HashSet<BugNet_IssueVotes>(); BugNet_IssueWorkReports = new HashSet<BugNet_IssueWorkReports>(); BugNet_ProjectCustomFieldValues = new HashSet<BugNet_ProjectCustomFieldValues>(); BugNet_RelatedIssues = new HashSet<BugNet_RelatedIssues>(); BugNet_RelatedIssues1 = new HashSet<BugNet_RelatedIssues>(); } [Key] public int IssueId { get; set; } [Required] [StringLength(500)] public string IssueTitle { get; set; } [Required] public string IssueDescription { get; set; } public int? IssueStatusId { get; set; } public int? IssuePriorityId { get; set; } public int? IssueTypeId { get; set; } public int? IssueCategoryId { get; set; } public int ProjectId { get; set; } public int? IssueAffectedMilestoneId { get; set; } public int? IssueResolutionId { get; set; } public Guid IssueCreatorUserId { get; set; } public Guid? IssueAssignedUserId { get; set; } public Guid? IssueOwnerUserId { get; set; } public DateTime? IssueDueDate { get; set; } public int? IssueMilestoneId { get; set; } public int IssueVisibility { get; set; } public decimal IssueEstimation { get; set; } public int IssueProgress { get; set; } public DateTime DateCreated { get; set; } public DateTime LastUpdate { get; set; } public Guid LastUpdateUserId { get; set; } public bool Disabled { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueAttachments> BugNet_IssueAttachments { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueComments> BugNet_IssueComments { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueHistory> BugNet_IssueHistory { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueNotifications> BugNet_IssueNotifications { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueRevisions> BugNet_IssueRevisions { get; set; } public virtual BugNet_ProjectCategories BugNet_ProjectCategories { get; set; } public virtual BugNet_ProjectIssueTypes BugNet_ProjectIssueTypes { get; set; } public virtual BugNet_ProjectMilestones BugNet_ProjectMilestones { get; set; } public virtual BugNet_ProjectMilestones BugNet_ProjectMilestones1 { get; set; } public virtual BugNet_ProjectPriorities BugNet_ProjectPriorities { get; set; } public virtual BugNet_ProjectResolutions BugNet_ProjectResolutions { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } public virtual BugNet_ProjectStatus BugNet_ProjectStatus { get; set; } public virtual User User { get; set; } public virtual User User1 { get; set; } public virtual User User2 { get; set; } public virtual User User3 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueVotes> BugNet_IssueVotes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueWorkReports> BugNet_IssueWorkReports { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectCustomFieldValues> BugNet_ProjectCustomFieldValues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_RelatedIssues> BugNet_RelatedIssues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_RelatedIssues> BugNet_RelatedIssues1 { get; set; } } } <file_sep>namespace BugNet.Domain.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("User")] public partial class User : BaseEntity { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public User() { Comments = new HashSet<Comment>(); AssignedIssues = new HashSet<Issue>(); CreatedIssues = new HashSet<Issue>(); OwnedIssues = new HashSet<Issue>(); CreatedProjects = new HashSet<Project>(); ManagedProjects = new HashSet<Project>(); UserProjects = new HashSet<UserProject>(); WorkReports = new HashSet<WorkReport>(); } public User(string username, string password) { Username = username; Password = <PASSWORD>; } public int Id { get; set; } [Required] [StringLength(255)] public string Username { get; set; } [Required] [StringLength(255)] public string Password { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Comment> Comments { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Issue> AssignedIssues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Issue> CreatedIssues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Issue> OwnedIssues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Project> CreatedProjects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Project> ManagedProjects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<UserProject> UserProjects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<WorkReport> WorkReports { get; set; } public virtual ICollection<Audit> Audits { get; set; } } } <file_sep>namespace BugNet.Domain.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("WorkReport")] public partial class WorkReport : BaseEntity { public WorkReport() { } public WorkReport(int userId, int issueId, double duration) { Duration = duration; Timestamp = DateTime.Now; IssueId = issueId; UserId = userId; } public int Id { get; set; } public int IssueId { get; set; } public DateTime Timestamp { get; set; } public double Duration { get; set; } public int? CommentId { get; set; } public int UserId { get; set; } public virtual Comment Comment { get; set; } public virtual Issue Issue { get; set; } public virtual User User { get; set; } public void AttachComment(Comment c) { this.Comment = c; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_IssueAttachments { [Key] public int IssueAttachmentId { get; set; } public int IssueId { get; set; } [Required] [StringLength(250)] public string FileName { get; set; } [Required] [StringLength(80)] public string Description { get; set; } public int FileSize { get; set; } [Required] [StringLength(50)] public string ContentType { get; set; } public DateTime DateCreated { get; set; } public Guid UserId { get; set; } public byte[] Attachment { get; set; } public virtual BugNet_Issues BugNet_Issues { get; set; } public virtual User User { get; set; } } } <file_sep>using BugNet.Domain; using BugNet.Domain.Infrastructure.Services; using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Application.Services { public class ProjectService : IProjectService { public Project Create(string currentUsername, string name, string description, string code, int managerUserId, int creatorUserId, byte[] icon) { using (var ctx = new BugNetContext()) { Project project = new Project(name, description, code, managerUserId, creatorUserId, icon); ctx.Projects.Add(project); ctx.SaveChanges(currentUsername); return project; } } public List<Project> ListProjectsForManagement(string currentUsername) { return null; } public List<Project> ListProjectsForUser(string currentUsername) { using (var ctx = new BugNetContext()) { return ctx.Projects.Where(x => x.UserProjects.Count(y => y.User.Username == currentUsername) > 0 || x.ManagerUser.Username == currentUsername || x.CreatorUser.Username == currentUsername).ToList(); } } public Project GetProjectForDashboad(string currentUsername, int id) { using (var ctx = new BugNetContext()) { return ctx.Projects.SingleOrDefault(x => x.Id == id); } } public Project GetProjectForEdit(string currentUsername, int id) { using (var ctx = new BugNetContext()) { return ctx.Projects.SingleOrDefault(x => x.Id == id); } } public Project Edit(string currentUsername, int id, string name, string description, string code, int managerUserId, int creatorUserId, byte[] icon) { using (var ctx = new BugNetContext()) { Project project = ctx.Projects.Single(x => x.Id == id); project.Description = description.Trim(); project.Code = code; project.CreatorUserId = creatorUserId; project.Icon = icon; project.ManagerUserId = managerUserId; project.Name = name; ctx.SaveChanges(currentUsername); return project; } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class Project { public int ProjectId { get; set; } [Required] [StringLength(255)] public string Name { get; set; } [Required] [StringLength(255)] public string Code { get; set; } public string Description { get; set; } [Required] public int ManagerUserId { get; set; } [Required] public int CreatorUserId { get; set; } public string Icon { get; set; } public List<UserView> Users { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class ResetPassword { public int UserId { get; set; } [Display(Name = "Password")] [Required(ErrorMessage = "Please enter a password.")] [DataType(DataType.Password)] [StringLength(255, ErrorMessage = "Please enter a password long than 5 characters.", MinimumLength = 5)] public string Password { get; set; } [Display(Name = "Confirm Password")] [DataType(DataType.Password)] [Compare("Password")] public string ConfirmPassword { get; set; } } }<file_sep>using BugNet.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace BugNet.WebApplication { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //Migrator migrator = new Migrator(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath); //migrator.Execute(); BugNetContext context = new BugNetContext(); context.Database.Initialize(true); context.SaveChanges(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models.Chart { public class C3DonutChart { public List<object[]> Data { get; set; } } }<file_sep>namespace BugNet.Domain { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Models; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; public partial class BugNetContext : DbContext { public BugNetContext() : base("name=BugNetContext") { Database.SetInitializer<BugNetContext>(new Initailizer()); } public virtual DbSet<Category> Categories { get; set; } public virtual DbSet<Comment> Comments { get; set; } public virtual DbSet<Issue> Issues { get; set; } public virtual DbSet<Milestone> Milestones { get; set; } public virtual DbSet<Priority> Priorities { get; set; } public virtual DbSet<Project> Projects { get; set; } public virtual DbSet<Resolution> Resolutions { get; set; } public virtual DbSet<Status> Status { get; set; } public virtual DbSet<Models.Type> Types { get; set; } public virtual DbSet<User> Users { get; set; } public virtual DbSet<UserProject> UserProjects { get; set; } public virtual DbSet<WorkReport> WorkReports { get; set; } public virtual DbSet<Audit> Audits { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Category>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<Comment>() .Property(e => e.Content) .IsUnicode(false); modelBuilder.Entity<Issue>() .Property(e => e.Title) .IsUnicode(false); modelBuilder.Entity<Issue>() .Property(e => e.Description) .IsUnicode(false); modelBuilder.Entity<Issue>() .HasMany(e => e.Comments) .WithRequired(e => e.Issue) .WillCascadeOnDelete(false); modelBuilder.Entity<Issue>() .HasMany(e => e.WorkReports) .WithRequired(e => e.Issue) .WillCascadeOnDelete(false); modelBuilder.Entity<Milestone>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<Priority>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<Project>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<Project>() .Property(e => e.Code) .IsUnicode(false); modelBuilder.Entity<Project>() .Property(e => e.Description) .IsUnicode(false); modelBuilder.Entity<Project>() .HasMany(e => e.Categories) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.Issues) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.Milestones) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.Priorities) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.Resolutions) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.Status) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.Types) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Project>() .HasMany(e => e.UserProjects) .WithRequired(e => e.Project) .WillCascadeOnDelete(false); modelBuilder.Entity<Resolution>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<Status>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<Models.Type>() .Property(e => e.Name) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.Username) .IsUnicode(false); modelBuilder.Entity<User>() .Property(e => e.Password) .IsUnicode(false); modelBuilder.Entity<User>() .HasMany(e => e.Comments) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.AssignedIssues) .WithOptional(e => e.AssignedUser) .HasForeignKey(e => e.AssignedUserId); modelBuilder.Entity<User>() .HasMany(e => e.CreatedIssues) .WithRequired(e => e.CreatorUser) .HasForeignKey(e => e.CreatorUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.OwnedIssues) .WithRequired(e => e.OwnerUser) .HasForeignKey(e => e.OwnerUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.CreatedProjects) .WithRequired(e => e.CreatorUser) .HasForeignKey(e => e.CreatorUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.ManagedProjects) .WithRequired(e => e.ManagerUser) .HasForeignKey(e => e.ManagerUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.UserProjects) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.WorkReports) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.Audits) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<Audit>() .Property(e => e.EntityName) .IsUnicode(false); modelBuilder.Entity<Audit>() .Property(e => e.PrimaryKeyValue) .IsUnicode(false); modelBuilder.Entity<Audit>() .Property(e => e.PropertyName) .IsUnicode(false); modelBuilder.Entity<Audit>() .Property(e => e.OldValue) .IsUnicode(false); modelBuilder.Entity<Audit>() .Property(e => e.NewValue) .IsUnicode(false); } public int SaveChangesAndUpdateTimestamps() { var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified)); foreach (var entity in entities) { if (entity.State == EntityState.Added) { ((BaseEntity)entity.Entity).DateCreated = DateTime.Now; } ((BaseEntity)entity.Entity).DateModified = DateTime.Now; } return base.SaveChanges(); } public int SaveChanges(string currentUsername) { var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified)); foreach (var entity in entities) { if (entity.State == EntityState.Added) { ((BaseEntity)entity.Entity).DateCreated = DateTime.Now; } if (entity.State == EntityState.Modified) { var tableAttribute = (TableAttribute)entity.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), true).SingleOrDefault(); if (tableAttribute == null) continue; var entityName = tableAttribute.Name; var primaryKey = GetPrimaryKeyValue(entity); foreach (var prop in entity.OriginalValues.PropertyNames) { var originalValue = entity.OriginalValues[prop] == null ? null : entity.OriginalValues[prop].ToString(); var currentValue = entity.CurrentValues[prop] == null? null : entity.CurrentValues[prop].ToString(); if (originalValue != currentValue) //Only create a log if the value changes { Audit audit = new Audit() { EntityName = entityName, PrimaryKeyValue = primaryKey.ToString(), PropertyName = prop, OldValue = originalValue, NewValue = currentValue, Timestamp = DateTime.Now, UserId = Users.Single(x => x.Username == currentUsername).Id }; Audits.Add(audit); } } } ((BaseEntity)entity.Entity).DateModified = DateTime.Now; } try { return base.SaveChanges(); }catch (DbEntityValidationException ex) { throw ex; } } object GetPrimaryKeyValue(DbEntityEntry entry) { var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity); return objectStateEntry.EntityKey.EntityKeyValues[0].Value; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_Projects { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_Projects() { BugNet_Issues = new HashSet<BugNet_Issues>(); BugNet_ProjectCategories = new HashSet<BugNet_ProjectCategories>(); BugNet_ProjectCustomFields = new HashSet<BugNet_ProjectCustomFields>(); BugNet_ProjectIssueTypes = new HashSet<BugNet_ProjectIssueTypes>(); BugNet_ProjectMailBoxes = new HashSet<BugNet_ProjectMailBoxes>(); BugNet_ProjectMilestones = new HashSet<BugNet_ProjectMilestones>(); BugNet_ProjectNotifications = new HashSet<BugNet_ProjectNotifications>(); BugNet_ProjectPriorities = new HashSet<BugNet_ProjectPriorities>(); BugNet_ProjectResolutions = new HashSet<BugNet_ProjectResolutions>(); BugNet_ProjectStatus = new HashSet<BugNet_ProjectStatus>(); BugNet_Queries = new HashSet<BugNet_Queries>(); BugNet_Roles = new HashSet<BugNet_Roles>(); BugNet_UserProjects = new HashSet<BugNet_UserProjects>(); } [Key] public int ProjectId { get; set; } [Required] [StringLength(50)] public string ProjectName { get; set; } [Required] [StringLength(50)] public string ProjectCode { get; set; } [Required] public string ProjectDescription { get; set; } [Required] [StringLength(256)] public string AttachmentUploadPath { get; set; } public DateTime DateCreated { get; set; } public bool ProjectDisabled { get; set; } public int ProjectAccessType { get; set; } public Guid ProjectManagerUserId { get; set; } public Guid ProjectCreatorUserId { get; set; } public bool AllowAttachments { get; set; } [StringLength(255)] public string SvnRepositoryUrl { get; set; } public bool AllowIssueVoting { get; set; } public byte[] ProjectImageFileContent { get; set; } [StringLength(150)] public string ProjectImageFileName { get; set; } [StringLength(50)] public string ProjectImageContentType { get; set; } public long? ProjectImageFileSize { get; set; } public virtual BugNet_DefaultValues BugNet_DefaultValues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectCategories> BugNet_ProjectCategories { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectCustomFields> BugNet_ProjectCustomFields { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectIssueTypes> BugNet_ProjectIssueTypes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectMailBoxes> BugNet_ProjectMailBoxes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectMilestones> BugNet_ProjectMilestones { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectNotifications> BugNet_ProjectNotifications { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectPriorities> BugNet_ProjectPriorities { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectResolutions> BugNet_ProjectResolutions { get; set; } public virtual User User { get; set; } public virtual User User1 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectStatus> BugNet_ProjectStatus { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Queries> BugNet_Queries { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Roles> BugNet_Roles { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_UserProjects> BugNet_UserProjects { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_IssueNotifications { [Key] public int IssueNotificationId { get; set; } public int IssueId { get; set; } public Guid UserId { get; set; } public virtual BugNet_Issues BugNet_Issues { get; set; } public virtual User User { get; set; } } } <file_sep>BEGIN TRAN COMMIT TRAN<file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using BugNet.WebApplication.Attributes; using BugNet.WebApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Controllers { public class IssueController : Controller { private IIssueService IssueService; private IListService ListService; private IUserService UserService; private IProjectService ProjectService; public IssueController() { this.IssueService = Dependencies.IssueService; this.ListService = Dependencies.ListService; this.UserService = Dependencies.UserService; this.ProjectService = Dependencies.ProjectService; } [HttpPost] [Base] [Authorize] public ActionResult NewSave(Issue model) { if (!ModelState.IsValid) { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, model.ProjectId); return View(new Issue() { ProjectName = project.Name, Statuses = this.ListService.ListIssueStatuses(this.User.Identity.Name, model.ProjectId).Select(x => new StatusView() { Name = x.Name, StatusId = x.Id }).ToList(), Priorities = this.ListService.ListIssuePriorities(this.User.Identity.Name, model.ProjectId).Select(x => new PriorityView() { Name = x.Name, PriorityId = x.Id }).ToList(), Users = this.UserService.ListUsersForProject(this.User.Identity.Name, model.ProjectId).Select(x => new UserView() { UserId = x.Id, Username = x.Username }).ToList(), Resolutions = this.ListService.ListIssueResolutions(this.User.Identity.Name, model.ProjectId).Select(x => new ResolutionView() { Name = x.Name, ResolutionId = x.Id }).ToList(), Types = this.ListService.ListIssueTypes(this.User.Identity.Name, model.ProjectId).Select(x => new TypeView() { Name = x.Name, TypeId = x.Id }).ToList(), Categories = this.ListService.ListIssueCategories(this.User.Identity.Name, model.ProjectId).Select(x => new CategoryView() { Name = x.Name, CategoryId = x.Id }).ToList(), Milestones = this.ListService.ListIssueMilestones(this.User.Identity.Name, model.ProjectId).Select(x => new MilestoneView() { Name = x.Name, MilestoneId = x.Id }).ToList() }); } var issue = this.IssueService.Create( this.User.Identity.Name, model.ProjectId, model.Title, model.StatusId, model.PriorityId, model.TypeId, model.CategoryId, model.MilestoneId, model.ResolutionId, model.AssignedUserId, model.StoryPoints, model.CreatorUserId, model.OwnerUserId, model.Description ); return RedirectToAction("List", "Issue", new { id = model.ProjectId }); } [HttpPost] [Base] [Authorize] public ActionResult SaveWorkLog(Issue model) { Domain.Models.WorkReport workLog = this.IssueService.LogWork(this.User.Identity.Name,model.IssueId, model.Duration, model.Comment); return RedirectToAction("Edit", "Issue", new { id = model.IssueId}); } [HttpPost] [Base] [Authorize] public ActionResult EditSave(Issue model) { if (!ModelState.IsValid) { var issueView = this.IssueService.GetIssueForEdit(this.User.Identity.Name, model.IssueId); var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, model.ProjectId); return View("Edit",new Issue(issueView) { ProjectName = project.Name, Statuses = this.ListService.ListIssueStatuses(this.User.Identity.Name, model.ProjectId).Select(x => new StatusView() { Name = x.Name, StatusId = x.Id }).ToList(), Priorities = this.ListService.ListIssuePriorities(this.User.Identity.Name, model.ProjectId).Select(x => new PriorityView() { Name = x.Name, PriorityId = x.Id }).ToList(), Users = this.UserService.ListUsersForProject(this.User.Identity.Name, model.ProjectId).Select(x => new UserView() { UserId = x.Id, Username = x.Username }).ToList(), Resolutions = this.ListService.ListIssueResolutions(this.User.Identity.Name, model.ProjectId).Select(x => new ResolutionView() { Name = x.Name, ResolutionId = x.Id }).ToList(), Types = this.ListService.ListIssueTypes(this.User.Identity.Name, model.ProjectId).Select(x => new TypeView() { Name = x.Name, TypeId = x.Id }).ToList(), Categories = this.ListService.ListIssueCategories(this.User.Identity.Name, model.ProjectId).Select(x => new CategoryView() { Name = x.Name, CategoryId = x.Id }).ToList(), Milestones = this.ListService.ListIssueMilestones(this.User.Identity.Name, model.ProjectId).Select(x => new MilestoneView() { Name = x.Name, MilestoneId = x.Id }).ToList() }); } var issue = this.IssueService.Edit( this.User.Identity.Name, model.IssueId, model.ProjectId, model.Title, model.StatusId, model.PriorityId, model.TypeId, model.CategoryId, model.MilestoneId, model.ResolutionId, model.AssignedUserId, model.StoryPoints, model.CreatorUserId, model.OwnerUserId, model.Description ); return RedirectToAction("List", "Issue", new { id = model.ProjectId }); } [HttpGet] [Base] [Route("Issue/New/{projectId}")] [Authorize] public ActionResult New(int projectId) { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, projectId); return View(new Issue() { ProjectName = project.Name, ProjectId = projectId, Statuses = this.ListService.ListIssueStatuses(this.User.Identity.Name, projectId).Select(x => new StatusView() { Name = x.Name, StatusId = x.Id }).ToList(), Priorities = this.ListService.ListIssuePriorities(this.User.Identity.Name, projectId).Select(x => new PriorityView() { Name = x.Name, PriorityId = x.Id }).ToList(), Users = this.UserService.ListUsersForProject(this.User.Identity.Name, projectId).Select(x => new UserView() { UserId = x.Id, Username = x.Username }).ToList(), Resolutions = this.ListService.ListIssueResolutions(this.User.Identity.Name, projectId).Select(x => new ResolutionView() { Name = x.Name, ResolutionId = x.Id }).ToList(), Types = this.ListService.ListIssueTypes(this.User.Identity.Name, projectId).Select(x => new TypeView() { Name = x.Name, TypeId = x.Id }).ToList(), Categories = this.ListService.ListIssueCategories(this.User.Identity.Name, projectId).Select(x => new CategoryView() { Name = x.Name, CategoryId = x.Id }).ToList(), Milestones = this.ListService.ListIssueMilestones(this.User.Identity.Name, projectId).Select(x => new MilestoneView() { Name = x.Name, MilestoneId = x.Id }).ToList() }); } [HttpGet] [Base] [Authorize] public ActionResult Edit(int id) { var issue = this.IssueService.GetIssueForEdit(this.User.Identity.Name, id); var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, issue.ProjectId); return View(new Issue(issue) { ProjectName = project.Name, Statuses = this.ListService.ListIssueStatuses(this.User.Identity.Name, issue.ProjectId).Select(x => new StatusView() { Name = x.Name, StatusId = x.Id }).ToList(), Priorities = this.ListService.ListIssuePriorities(this.User.Identity.Name, issue.ProjectId).Select(x => new PriorityView() { Name = x.Name, PriorityId = x.Id }).ToList(), Users = this.UserService.ListUsersForProject(this.User.Identity.Name, issue.ProjectId).Select(x => new UserView() { UserId = x.Id, Username = x.Username }).ToList(), Resolutions = this.ListService.ListIssueResolutions(this.User.Identity.Name, issue.ProjectId).Select(x => new ResolutionView() { Name = x.Name, ResolutionId = x.Id }).ToList(), Types = this.ListService.ListIssueTypes(this.User.Identity.Name, issue.ProjectId).Select(x => new TypeView() { Name = x.Name, TypeId = x.Id }).ToList(), Categories = this.ListService.ListIssueCategories(this.User.Identity.Name, issue.ProjectId).Select(x => new CategoryView() { Name = x.Name, CategoryId = x.Id }).ToList(), Milestones = this.ListService.ListIssueMilestones(this.User.Identity.Name, issue.ProjectId).Select(x => new MilestoneView() { Name = x.Name, MilestoneId = x.Id }).ToList() }); } [HttpGet] [Base] [Route("Issue/List/{id}/{status?}")] [Authorize] public ActionResult List(int id, string status = "Open") { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, id); return View(new IssueList() { ProjectName = project.Name, Issues = this.IssueService.ListIssuesForProject(this.User.Identity.Name, id).Select(x => new IssueView(x)).ToList().Where(x => x.Status == status || x.Status == null).ToList(), Statuses = this.ListService.ListIssueStatuses(this.User.Identity.Name, id).Select(x => new StatusView() { Name = x.Name, StatusId = x.Id }).ToList(), Status = status, ProjectId = id }); } [HttpGet] [Base] [Authorize] public ActionResult MyIssues() { return View(new IssueList() { Issues = this.IssueService.ListMyIssues(this.User.Identity.Name).Select(x => new IssueView(x)).ToList(), }); } } }<file_sep>using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Services { public interface IListService { List<Status> ListIssueStatuses(string currentUsername, int projectId); List<Category> ListIssueCategories(string currentUsername, int projectId); List<Priority> ListIssuePriorities(string currentUsername, int projectId); List<Milestone> ListIssueMilestones(string currentUsername, int projectId); List<Models.Type> ListIssueTypes(string currentUsername, int projectId); List<Resolution> ListIssueResolutions(string currentUsername, int projectId); Status CreateStatus(string currentUsername, int projectId, string name, bool isClosedState); Status GetStatusForEdit(int id); Status UpdateStatus(string currentUsername, int statusId, string name, bool isClosedState); } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectMilestones { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_ProjectMilestones() { BugNet_Issues = new HashSet<BugNet_Issues>(); BugNet_Issues1 = new HashSet<BugNet_Issues>(); } [Key] public int MilestoneId { get; set; } public int ProjectId { get; set; } [Required] [StringLength(50)] public string MilestoneName { get; set; } [Required] [StringLength(50)] public string MilestoneImageUrl { get; set; } public int SortOrder { get; set; } public DateTime DateCreated { get; set; } public DateTime? MilestoneDueDate { get; set; } public DateTime? MilestoneReleaseDate { get; set; } public string MilestoneNotes { get; set; } public bool MilestoneCompleted { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues1 { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } } } <file_sep>using BugNet.Domain.Infrastructure.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BugNet.Domain.Models; using System.Security.Cryptography; using BugNet.Domain.Infrastructure.Repositories; using BugNet.Domain; namespace BugNet.Application.Services { public class UserService : Repository, IUserService { public User ResetPassword(string currentUsername, int userId, string password) { using (var ctx = new BugNetContext()) { User currentUser = ctx.Users.SingleOrDefault(x => x.Username == currentUsername); User user = ctx.Users.SingleOrDefault(x => x.Id == userId); string passwordSalt = <PASSWORD>(user.Username.ToLower()); password = sha1(passwordSalt + password + password<PASSWORD>); user.Password = <PASSWORD>; ctx.SaveChanges(currentUsername); return user; } } public User Create(string currentUsername, string username, string password) { using (var ctx = new BugNetContext()) { username = username.ToLower(); currentUsername = currentUsername.ToLower(); User currentUser = ctx.Users.SingleOrDefault(x => x.Username == currentUsername); string passwordSalt = <PASSWORD>(username); password = <PASSWORD>(passwordSalt + password + <PASSWORD>); User user = new User(username, password); ctx.Users.Add(user); ctx.SaveChanges(currentUsername); return user; } } public User GetUserForEdit(string currentUsername, int id) { using (var ctx = new BugNetContext()) { return ctx.Users.SingleOrDefault(x => x.Id == id); } } public List<User> ListUsersForManagement(string currentUsername) { using (var ctx = new BugNetContext()) { User currentUser = ctx.Users.SingleOrDefault(x => x.Username == currentUsername); return ctx.Users.ToList(); } } public List<User> ListUsersForProject(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { User currentUser = ctx.Users.SingleOrDefault(x => x.Username == currentUsername); return ctx.Users.Where(x => x.UserProjects.Count(y => y.ProjectId == projectId) > 0 || x.ManagedProjects.Count(y => y.Id == projectId) > 0 || x.CreatedProjects.Count(y => y.Id == projectId) > 0).ToList(); } } public User Update(string currentUsername, int userId, string username) { using (var ctx = new BugNetContext()) { User currentUser = ctx.Users.SingleOrDefault(x => x.Username == currentUsername); User user = ctx.Users.SingleOrDefault(x => x.Id == userId); user.Username = username; ctx.SaveChanges(currentUsername); return user; } } public User Validate(string username, string password) { using (var ctx = new BugNetContext()) { username = username.ToLower(); password = <PASSWORD>(<PASSWORD>(username) + password + <PASSWORD>(username)); User user = ctx.Users.SingleOrDefault(x => x.Username == username); if (user == null) { return null; } if (user.Password == <PASSWORD>) { return user; } return null; } } private string sha1(string input) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); var sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) { sb.Append(b.ToString("X2")); } return sb.ToString(); } } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_IssueWorkReports { [Key] public int IssueWorkReportId { get; set; } public int IssueId { get; set; } public DateTime WorkDate { get; set; } public decimal Duration { get; set; } public int IssueCommentId { get; set; } public Guid UserId { get; set; } public virtual BugNet_Issues BugNet_Issues { get; set; } public virtual User User { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Extensions { public static class HtmlExtension { public static string Controller(this HtmlHelper htmlHelper) { var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values; if (routeValues.ContainsKey("controller")) return (string)routeValues["controller"]; return string.Empty; } public static string Action(this HtmlHelper htmlHelper) { var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values; if (routeValues.ContainsKey("action")) return (string)routeValues["action"]; return string.Empty; } public static bool IsActive(this HtmlHelper helper, string controller, string action = null) { string currentAction = helper.Action(); string currentController = helper.Controller(); if (controller == currentController) { if (action == null) return true; return action == currentAction; } else return false; } public static List<SelectListItem> AddPlaceholder(this IEnumerable<SelectListItem> list, string placeholder) { var result = list.ToList(); result.Insert(0, new SelectListItem() { Text = placeholder, Value = "" }); return result; } public static string GetClass(this HtmlHelper helper, string controller, string action = null) { return helper.IsActive(controller, action) ? "active" : string.Empty; } } }<file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using BugNet.WebApplication.Attributes; using BugNet.WebApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace BugNet.WebApplication.Controllers { public class AccountController : Controller { private IUserService UserService; public AccountController() { this.UserService = Dependencies.UserService; } [HttpGet] [Base] public ActionResult Login() { FormsAuthentication.SignOut(); return View(); } [HttpPost] [Base] public ActionResult Login(Login model) { if (!ModelState.IsValid) return View(model); var user = this.UserService.Validate(model.Username, model.Password); if (user != null) { FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe); return RedirectToAction("", ""); } model.Message = "Invalid login credentials."; return View(model); } } }<file_sep>using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Services { public interface IIssueService { List<Issue> ListMyIssues(string currentUsername); List<Issue> ListIssuesForProject(string currentUsername, int projectId); Issue GetIssueForEdit(string currentUsername, int id); Issue Create(string currentUsername, int projectId, string title, int? statusId, int? priorityId, int? typeId, int? categoryId, int? milestoneId, int? resolutionId, int? assignedUserId, int? storyPoints, int creatorUserId, int ownerUserId, string description); Issue Edit(string currentUsername, int id, int projectId, string title, int? statusId, int? priorityId, int? typeId, int? categoryId, int? milestoneId, int? resolutionId, int? assignedUserId, int? storyPoints, int creatorUserId, int ownerUserId, string description); WorkReport LogWork(string currentUsername, int issueId, double duration, string comment); } } <file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using BugNet.WebApplication.Attributes; using BugNet.WebApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Controllers { public class StatusController : Controller { private IListService ListService; private IProjectService ProjectService; public StatusController() { this.ListService = Dependencies.ListService; this.ProjectService = Dependencies.ProjectService; } [HttpGet] [Base] [Route("Status/New/{projectId}")] [Authorize] public ActionResult New(int projectId) { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, projectId); return View(new Status() { ProjectName = project.Name, ProjectId = projectId }); } [HttpGet] [Base] [Route("Status/Edit/{statusId}")] [Authorize] public ActionResult Edit(int statusId) { var status = this.ListService.GetStatusForEdit(statusId); return View(new Status(status) { ProjectName = status.Project.Name, ProjectId = status.ProjectId }); } [HttpPost] [Base] [Authorize] public ActionResult NewSave(Status model) { if (!ModelState.IsValid) { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, model.ProjectId); return View(new Status() { ProjectName = project.Name, ProjectId = model.ProjectId }); } var status = this.ListService.CreateStatus( this.User.Identity.Name, model.ProjectId, model.Name, model.IsClosedState ); return RedirectToAction("List", "Status", new { id = model.ProjectId }); } [HttpPost] [Base] [Authorize] public ActionResult EditSave(Status model) { if (!ModelState.IsValid) { var s = this.ListService.GetStatusForEdit(model.StatusId); return View("Edit" ,new Status(s) { ProjectName = s.Project.Name, ProjectId = s.ProjectId }); } var status = this.ListService.UpdateStatus( this.User.Identity.Name, model.StatusId, model.Name, model.IsClosedState ); return RedirectToAction("List", "Status", new { id = model.ProjectId }); } [HttpGet] [Base] [Authorize] public ActionResult List(int id) { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, id); return View(new StatusList() { ProjectId = id, ProjectName = project.Name, Statuses = this.ListService.ListIssueStatuses(this.User.Identity.Name, id).Select(x => new StatusView() { IsClosedState = x.IsClosedState ? "Yes" : "No", Name = x.Name, StatusId = x.Id }).ToList() }); } } }<file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using BugNet.WebApplication.Attributes; using BugNet.WebApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Controllers { public class ProjectController : Controller { private IUserService UserService; private IProjectService ProjectService; public ProjectController() { this.UserService = Dependencies.UserService; this.ProjectService = Dependencies.ProjectService; } [HttpGet] [Base] [Authorize] public ActionResult List() { var projectList = this.ProjectService.ListProjectsForUser(this.User.Identity.Name); return View(new ProjectList() { Projects = projectList.Select(x => new ProjectView() { Code = x.Code, Name = x.Name, ProjectId = x.Id }).ToList() }); } [HttpGet] [Base] [Authorize] public ActionResult New() { return View(new Project() { Users = this.UserService.ListUsersForManagement(this.User.Identity.Name).Select(x => new UserView() { UserId = x.Id, Username = x.Username }).ToList() }); } [HttpPost] [Base] [Authorize] public ActionResult New(Project model) { if (!ModelState.IsValid) { return View(model); } var project = this.ProjectService.Create(this.User.Identity.Name, model.Name,model.Description, model.Code, model.ManagerUserId, model.CreatorUserId,null); return RedirectToAction("List", "Project"); } [HttpGet] [Base] [Authorize] public ActionResult Edit(int id) { var project = this.ProjectService.GetProjectForEdit(this.User.Identity.Name, id); return View(new Project() { Code = project.Code, CreatorUserId = project.CreatorUserId, Description = project.Description, Icon = null, ManagerUserId = project.ManagerUserId, Name = project.Name, ProjectId = project.Id, Users = this.UserService.ListUsersForManagement(this.User.Identity.Name).Select(x => new UserView() { UserId = x.Id, Username = x.Username }).ToList() }); } [HttpPost] [Base] [Authorize] public ActionResult Edit(Project model) { if (!ModelState.IsValid) { return View(model); } var project = this.ProjectService.Edit(this.User.Identity.Name,model.ProjectId, model.Name, model.Description, model.Code, model.ManagerUserId, model.CreatorUserId, null); return RedirectToAction("List", "Project"); } [HttpGet] [Base] [Authorize] public ActionResult Dashboard(int id) { var project = this.ProjectService.GetProjectForDashboad(this.User.Identity.Name,id); return View(new Project() { Name = project.Name, ProjectId = id }); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class ProjectList { public List<ProjectView> Projects { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class StatusView { public int StatusId { get; set; } public string Name { get; set; } public string IsClosedState { get; set; } } }<file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("UsersOpenAuthData")] public partial class UsersOpenAuthData { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public UsersOpenAuthData() { UsersOpenAuthAccounts = new HashSet<UsersOpenAuthAccount>(); } [Key] [Column(Order = 0)] public string ApplicationName { get; set; } [Key] [Column(Order = 1)] public string MembershipUserName { get; set; } public bool HasLocalPassword { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<UsersOpenAuthAccount> UsersOpenAuthAccounts { get; set; } } } <file_sep>namespace BugNet.Domain.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Audit")] public partial class Audit { public int Id { get; set; } [Required] [StringLength(255)] public string EntityName { get; set; } [Required] [StringLength(255)] public string PrimaryKeyValue { get; set; } [Required] [StringLength(255)] public string PropertyName { get; set; } [StringLength(255)] public string OldValue { get; set; } [StringLength(255)] public string NewValue { get; set; } public DateTime Timestamp { get; set; } public int UserId { get; set; } public virtual User User { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectStatus { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_ProjectStatus() { BugNet_Issues = new HashSet<BugNet_Issues>(); } [Key] public int StatusId { get; set; } public int ProjectId { get; set; } [Required] [StringLength(50)] public string StatusName { get; set; } [Required] [StringLength(50)] public string StatusImageUrl { get; set; } public int SortOrder { get; set; } public bool IsClosedState { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class FromContext : DbContext { public FromContext() : base("name=FromContext.Production") { } public virtual DbSet<Application> Applications { get; set; } public virtual DbSet<BugNet_ApplicationLog> BugNet_ApplicationLog { get; set; } public virtual DbSet<BugNet_DefaultValues> BugNet_DefaultValues { get; set; } public virtual DbSet<BugNet_DefaultValuesVisibility> BugNet_DefaultValuesVisibility { get; set; } public virtual DbSet<BugNet_HostSettings> BugNet_HostSettings { get; set; } public virtual DbSet<BugNet_IssueAttachments> BugNet_IssueAttachments { get; set; } public virtual DbSet<BugNet_IssueComments> BugNet_IssueComments { get; set; } public virtual DbSet<BugNet_IssueHistory> BugNet_IssueHistory { get; set; } public virtual DbSet<BugNet_IssueNotifications> BugNet_IssueNotifications { get; set; } public virtual DbSet<BugNet_IssueRevisions> BugNet_IssueRevisions { get; set; } public virtual DbSet<BugNet_Issues> BugNet_Issues { get; set; } public virtual DbSet<BugNet_IssueVotes> BugNet_IssueVotes { get; set; } public virtual DbSet<BugNet_IssueWorkReports> BugNet_IssueWorkReports { get; set; } public virtual DbSet<BugNet_Languages> BugNet_Languages { get; set; } public virtual DbSet<BugNet_Permissions> BugNet_Permissions { get; set; } public virtual DbSet<BugNet_ProjectCategories> BugNet_ProjectCategories { get; set; } public virtual DbSet<BugNet_ProjectCustomFields> BugNet_ProjectCustomFields { get; set; } public virtual DbSet<BugNet_ProjectCustomFieldSelections> BugNet_ProjectCustomFieldSelections { get; set; } public virtual DbSet<BugNet_ProjectCustomFieldTypes> BugNet_ProjectCustomFieldTypes { get; set; } public virtual DbSet<BugNet_ProjectCustomFieldValues> BugNet_ProjectCustomFieldValues { get; set; } public virtual DbSet<BugNet_ProjectIssueTypes> BugNet_ProjectIssueTypes { get; set; } public virtual DbSet<BugNet_ProjectMailBoxes> BugNet_ProjectMailBoxes { get; set; } public virtual DbSet<BugNet_ProjectMilestones> BugNet_ProjectMilestones { get; set; } public virtual DbSet<BugNet_ProjectNotifications> BugNet_ProjectNotifications { get; set; } public virtual DbSet<BugNet_ProjectPriorities> BugNet_ProjectPriorities { get; set; } public virtual DbSet<BugNet_ProjectResolutions> BugNet_ProjectResolutions { get; set; } public virtual DbSet<BugNet_Projects> BugNet_Projects { get; set; } public virtual DbSet<BugNet_ProjectStatus> BugNet_ProjectStatus { get; set; } public virtual DbSet<BugNet_Queries> BugNet_Queries { get; set; } public virtual DbSet<BugNet_QueryClauses> BugNet_QueryClauses { get; set; } public virtual DbSet<BugNet_RelatedIssues> BugNet_RelatedIssues { get; set; } public virtual DbSet<BugNet_RequiredFieldList> BugNet_RequiredFieldList { get; set; } public virtual DbSet<BugNet_Roles> BugNet_Roles { get; set; } public virtual DbSet<BugNet_UserCustomFields> BugNet_UserCustomFields { get; set; } public virtual DbSet<BugNet_UserCustomFieldSelections> BugNet_UserCustomFieldSelections { get; set; } public virtual DbSet<BugNet_UserCustomFieldTypes> BugNet_UserCustomFieldTypes { get; set; } public virtual DbSet<BugNet_UserCustomFieldValues> BugNet_UserCustomFieldValues { get; set; } public virtual DbSet<BugNet_UserProfiles> BugNet_UserProfiles { get; set; } public virtual DbSet<BugNet_UserProjects> BugNet_UserProjects { get; set; } public virtual DbSet<Membership> Memberships { get; set; } public virtual DbSet<Profile> Profiles { get; set; } public virtual DbSet<Role> Roles { get; set; } public virtual DbSet<User> Users { get; set; } public virtual DbSet<UsersOpenAuthAccount> UsersOpenAuthAccounts { get; set; } public virtual DbSet<UsersOpenAuthData> UsersOpenAuthDatas { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Application>() .HasMany(e => e.Memberships) .WithRequired(e => e.Application) .WillCascadeOnDelete(false); modelBuilder.Entity<Application>() .HasMany(e => e.Roles) .WithRequired(e => e.Application) .WillCascadeOnDelete(false); modelBuilder.Entity<Application>() .HasMany(e => e.Users) .WithRequired(e => e.Application) .WillCascadeOnDelete(false); modelBuilder.Entity<BugNet_ApplicationLog>() .Property(e => e.Thread) .IsUnicode(false); modelBuilder.Entity<BugNet_ApplicationLog>() .Property(e => e.Level) .IsUnicode(false); modelBuilder.Entity<BugNet_ApplicationLog>() .Property(e => e.Logger) .IsUnicode(false); modelBuilder.Entity<BugNet_ApplicationLog>() .Property(e => e.Message) .IsUnicode(false); modelBuilder.Entity<BugNet_ApplicationLog>() .Property(e => e.Exception) .IsUnicode(false); modelBuilder.Entity<BugNet_DefaultValues>() .Property(e => e.IssueEstimation) .HasPrecision(5, 2); modelBuilder.Entity<BugNet_Issues>() .Property(e => e.IssueEstimation) .HasPrecision(5, 2); modelBuilder.Entity<BugNet_Issues>() .HasMany(e => e.BugNet_IssueVotes) .WithRequired(e => e.BugNet_Issues) .WillCascadeOnDelete(false); modelBuilder.Entity<BugNet_Issues>() .HasMany(e => e.BugNet_RelatedIssues) .WithRequired(e => e.BugNet_Issues) .HasForeignKey(e => e.PrimaryIssueId); modelBuilder.Entity<BugNet_Issues>() .HasMany(e => e.BugNet_RelatedIssues1) .WithRequired(e => e.BugNet_Issues1) .HasForeignKey(e => e.SecondaryIssueId) .WillCascadeOnDelete(false); modelBuilder.Entity<BugNet_IssueWorkReports>() .Property(e => e.Duration) .HasPrecision(4, 2); modelBuilder.Entity<BugNet_Permissions>() .HasMany(e => e.BugNet_Roles) .WithMany(e => e.BugNet_Permissions) .Map(m => m.ToTable("BugNet_RolePermissions").MapLeftKey("PermissionId").MapRightKey("RoleId")); modelBuilder.Entity<BugNet_ProjectCategories>() .HasMany(e => e.BugNet_Issues) .WithOptional(e => e.BugNet_ProjectCategories) .HasForeignKey(e => e.IssueCategoryId); modelBuilder.Entity<BugNet_ProjectCustomFields>() .HasMany(e => e.BugNet_ProjectCustomFieldValues) .WithRequired(e => e.BugNet_ProjectCustomFields) .WillCascadeOnDelete(false); modelBuilder.Entity<BugNet_ProjectMilestones>() .HasMany(e => e.BugNet_Issues) .WithOptional(e => e.BugNet_ProjectMilestones) .HasForeignKey(e => e.IssueMilestoneId); modelBuilder.Entity<BugNet_ProjectMilestones>() .HasMany(e => e.BugNet_Issues1) .WithOptional(e => e.BugNet_ProjectMilestones1) .HasForeignKey(e => e.IssueAffectedMilestoneId); modelBuilder.Entity<BugNet_ProjectPriorities>() .HasMany(e => e.BugNet_Issues) .WithOptional(e => e.BugNet_ProjectPriorities) .HasForeignKey(e => e.IssuePriorityId); modelBuilder.Entity<BugNet_ProjectResolutions>() .HasMany(e => e.BugNet_Issues) .WithOptional(e => e.BugNet_ProjectResolutions) .HasForeignKey(e => e.IssueResolutionId); modelBuilder.Entity<BugNet_Projects>() .HasOptional(e => e.BugNet_DefaultValues) .WithRequired(e => e.BugNet_Projects) .WillCascadeOnDelete(); modelBuilder.Entity<BugNet_Projects>() .HasMany(e => e.BugNet_Roles) .WithOptional(e => e.BugNet_Projects) .WillCascadeOnDelete(); modelBuilder.Entity<BugNet_ProjectStatus>() .HasMany(e => e.BugNet_Issues) .WithOptional(e => e.BugNet_ProjectStatus) .HasForeignKey(e => e.IssueStatusId); modelBuilder.Entity<BugNet_Roles>() .HasMany(e => e.Users) .WithMany(e => e.BugNet_Roles) .Map(m => m.ToTable("BugNet_UserRoles").MapLeftKey("RoleId").MapRightKey("UserId")); modelBuilder.Entity<BugNet_UserCustomFields>() .HasMany(e => e.BugNet_UserCustomFieldValues) .WithRequired(e => e.BugNet_UserCustomFields) .WillCascadeOnDelete(false); modelBuilder.Entity<BugNet_UserProfiles>() .HasMany(e => e.Users) .WithRequired(e => e.BugNet_UserProfiles) .WillCascadeOnDelete(false); modelBuilder.Entity<Role>() .HasMany(e => e.Users) .WithMany(e => e.Roles) .Map(m => m.ToTable("UsersInRoles").MapLeftKey("RoleId").MapRightKey("UserId")); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_DefaultValues) .WithOptional(e => e.User) .HasForeignKey(e => e.IssueOwnerUserId) .WillCascadeOnDelete(); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_DefaultValues1) .WithOptional(e => e.User1) .HasForeignKey(e => e.IssueAssignedUserId); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_IssueAttachments) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Issues) .WithOptional(e => e.User) .HasForeignKey(e => e.IssueAssignedUserId); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Issues1) .WithOptional(e => e.User1) .HasForeignKey(e => e.IssueOwnerUserId); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Issues2) .WithRequired(e => e.User2) .HasForeignKey(e => e.LastUpdateUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Issues3) .WithRequired(e => e.User3) .HasForeignKey(e => e.IssueCreatorUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_IssueVotes) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_IssueWorkReports) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_ProjectMailBoxes) .WithOptional(e => e.User) .HasForeignKey(e => e.AssignToUserId); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Projects) .WithRequired(e => e.User) .HasForeignKey(e => e.ProjectCreatorUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Projects1) .WithRequired(e => e.User1) .HasForeignKey(e => e.ProjectManagerUserId) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasMany(e => e.BugNet_Queries) .WithRequired(e => e.User) .WillCascadeOnDelete(false); modelBuilder.Entity<User>() .HasOptional(e => e.Membership) .WithRequired(e => e.User); modelBuilder.Entity<User>() .HasOptional(e => e.Profile) .WithRequired(e => e.User); modelBuilder.Entity<UsersOpenAuthData>() .HasMany(e => e.UsersOpenAuthAccounts) .WithRequired(e => e.UsersOpenAuthData) .HasForeignKey(e => new { e.ApplicationName, e.MembershipUserName }); } } } <file_sep>using BugNet.Domain; using BugNet.Domain.Infrastructure.Repositories; using BugNet.Domain.Infrastructure.Services; using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Application.Services { public class IssueService : Repository, IIssueService { public Issue GetIssueForEdit(string currentUsername, int id) { using (var ctx = new BugNetContext()) { return ctx.Issues.SingleOrDefault(x => x.Id == id); } } public List<Issue> ListMyIssues(string currentUsername) { using (var ctx = new BugNetContext()) { var result = ctx.Issues.Include("AssignedUser") .Include("CreatorUser") .Include("Category") .Include("Project.UserProjects.User") .Include("Project.CreatorUser") .Include("Project.ManagerUser") .Include("Milestone") .Include("OwnerUser") .Include("Priority") .Include("Resolution") .Include("Status") .Include("Type") .Include("WorkReports") .Where(x => !x.Status.IsClosedState && (x.AssignedUser.Username == currentUsername || x.CreatorUser.Username == currentUsername || x.OwnerUser.Username == currentUsername)) .ToList(); return result; } } public List<Issue> ListIssuesForProject(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { var result = ctx.Issues.Include("AssignedUser") .Include("CreatorUser") .Include("Category") .Include("Project.UserProjects.User") .Include("Project.CreatorUser") .Include("Project.ManagerUser") .Include("Milestone") .Include("OwnerUser") .Include("Priority") .Include("Resolution") .Include("Status") .Include("Type") .Include("WorkReports") .Where(x => x.Project.Id == projectId && (x.Project.UserProjects.Count(y => y.User.Username == currentUsername) > 0 || x.Project.ManagerUser.Username == currentUsername || x.Project.CreatorUser.Username == currentUsername)) .ToList(); return result; } } public Issue Create(string currentUsername, int projectId, string title, int? statusId, int? priorityId, int? typeId, int? categoryId, int? milestoneId, int? resolutionId, int? assignedUserId, int? storyPoints, int creatorUserId, int ownerUserId, string description) { using (var ctx = new BugNetContext()) { Issue issue = new Issue(projectId, title, statusId, priorityId, typeId, categoryId, milestoneId, resolutionId, assignedUserId, storyPoints, creatorUserId, ownerUserId, description); ctx.Issues.Add(issue); ctx.SaveChanges(currentUsername); return issue; }; } public Issue Edit(string currentUsername, int id, int projectId, string title, int? statusId, int? priorityId, int? typeId, int? categoryId, int? milestoneId, int? resolutionId, int? assignedUserId, int? storyPoints, int creatorUserId, int ownerUserId, string description) { using (var ctx = new BugNetContext()) { Issue issue = ctx.Issues.Single(x => x.Id == id); issue.AssignedUserId = assignedUserId; issue.CategoryId = categoryId; issue.CreatorUserId = creatorUserId; issue.Description = description; issue.MilestoneId = milestoneId; issue.OwnerUserId = ownerUserId; issue.PriorityId = priorityId; issue.ProjectId = projectId; issue.ResolutionId = resolutionId; issue.StatusId = statusId; issue.StoryPoints = storyPoints; issue.Title = title; issue.TypeId = typeId; ctx.SaveChanges(currentUsername); return issue; }; } public WorkReport LogWork(string currentUsername, int issueId, double duration, string comment) { using (var ctx = new BugNetContext()) { User user = ctx.Users.Single(x => x.Username == currentUsername); WorkReport workReport = new WorkReport(user.Id, issueId, duration); Comment c = new Comment(user.Id, issueId, comment); workReport.AttachComment(c); ctx.WorkReports.Add(workReport); ctx.SaveChanges(currentUsername); return workReport; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class StatusList { public List<StatusView> Statuses { get; set; } public string ProjectName { get; set; } public int ProjectId { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class IssueView { public IssueView() { } public IssueView(Domain.Models.Issue model) { AssignedUser = model.AssignedUser == null ? null : model.AssignedUser.Username; Category = model.Category == null ? null : model.Category.Name; CreatorUser = model.CreatorUser == null ? null : model.CreatorUser.Username; ProjectCode = model.Project.Code; IssueId = model.Id; Milestone = model.Milestone == null ? null : model.Milestone.Name; OwnerUser = model.OwnerUser == null ? null : model.OwnerUser.Username; Priority = model.Priority == null ? null : model.Priority.Name; Project = model.Project == null ? null : model.Project.Name; Resolution = model.Resolution == null ? null : model.Resolution.Name; Status = model.Status == null ? null : model.Status.Name; Title = model.Title; Type = model.Type == null ? null : model.Type.Name; TimeLogged = model.WorkReports.Sum(y => y.Duration); Created = model.DateCreated; StoryPoints = model.StoryPoints; } public int IssueId { get; set; } public string ProjectCode { get; set; } public string Title { get; set; } public string Category { get; set; } public string AssignedUser { get; set; } public string Type { get; set; } public string Milestone { get; set; } public string Priority { get; set; } public string Status { get; set; } public string Project { get; set; } public string CreatorUser { get; set; } public DateTime Created { get; set; } public string LastUpdateUser { get; set; } public DateTime LastUpdate { get; set; } public string OwnerUser { get; set; } public int? StoryPoints { get; set; } public string Resolution { get; set; } public double TimeLogged { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Validation; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain { public class Initailizer : DropCreateDatabaseIfModelChanges<BugNetContext> { protected override void Seed(BugNetContext context) { try { //context.Users.Add(new Models.User("Admin", "<PASSWORD>")); //context.SaveChangesAndUpdateTimestamps(); }catch(DbEntityValidationException ex) { throw ex; } base.Seed(context); } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_DefaultValuesVisibility { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ProjectId { get; set; } public bool StatusVisibility { get; set; } public bool OwnedByVisibility { get; set; } public bool PriorityVisibility { get; set; } public bool AssignedToVisibility { get; set; } public bool PrivateVisibility { get; set; } public bool CategoryVisibility { get; set; } public bool DueDateVisibility { get; set; } public bool TypeVisibility { get; set; } public bool PercentCompleteVisibility { get; set; } public bool MilestoneVisibility { get; set; } public bool EstimationVisibility { get; set; } public bool ResolutionVisibility { get; set; } public bool AffectedMilestoneVisibility { get; set; } public bool StatusEditVisibility { get; set; } public bool OwnedByEditVisibility { get; set; } public bool PriorityEditVisibility { get; set; } public bool AssignedToEditVisibility { get; set; } public bool PrivateEditVisibility { get; set; } public bool CategoryEditVisibility { get; set; } public bool DueDateEditVisibility { get; set; } public bool TypeEditVisibility { get; set; } public bool PercentCompleteEditVisibility { get; set; } public bool MilestoneEditVisibility { get; set; } public bool EstimationEditVisibility { get; set; } public bool ResolutionEditVisibility { get; set; } public bool AffectedMilestoneEditVisibility { get; set; } } } <file_sep>using BugNet.Domain; using BugNet.Migrator.ContextFromModels; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace BugNet.Migrator { class Program { static void Main(string[] args) { using (var fromContext = new FromContext()) { using (var toContext = new BugNetContext()) { using (var dbContextTransaction = toContext.Database.BeginTransaction()) { try { DateTime startTime = DateTime.Now; Console.WriteLine("Migrating Users"); //Migrate users var users = fromContext.Users.Include("Membership").ToList().Select(x => new Domain.Models.User() { Username = x.UserName, Password = <PASSWORD>(<PASSWORD>), DateCreated = x.Membership.CreateDate }).ToList(); toContext.Users.AddRange(users); toContext.SaveChanges(); Console.WriteLine("Migrating Projects"); //Migrate projects var projects = fromContext.BugNet_Projects.ToList().Select(x => new Domain.Models.Project() { Code = x.ProjectCode, CreatorUserId = getUserId(fromContext, toContext, x.ProjectCreatorUserId), ManagerUserId = getUserId(fromContext, toContext, x.ProjectManagerUserId), Description = x.ProjectDescription, Name = x.ProjectName, DateCreated = x.DateCreated }).ToList(); toContext.Projects.AddRange(projects); toContext.SaveChanges(); Console.WriteLine("Migrating Categories"); //Migrate categories var categories = fromContext.BugNet_ProjectCategories.ToList().Select(x => new Domain.Models.Category() { Name = x.CategoryName, ProjectId = getProjectId(fromContext, toContext, x.ProjectId), DateCreated = DateTime.Now }).ToList(); toContext.Categories.AddRange(categories); toContext.SaveChanges(); Console.WriteLine("Migrating Milestones"); //Migrate milestones var milestones = fromContext.BugNet_ProjectMilestones.ToList().Select(x => new Domain.Models.Milestone() { Name = x.MilestoneName, ProjectId = getProjectId(fromContext, toContext, x.ProjectId), DateCreated = x.DateCreated }).ToList(); toContext.Milestones.AddRange(milestones); toContext.SaveChanges(); Console.WriteLine("Migrating Priorities"); //Migrate priorities var priorities = fromContext.BugNet_ProjectPriorities.ToList().Select(x => new Domain.Models.Priority() { Name = x.PriorityName, ProjectId = getProjectId(fromContext, toContext, x.ProjectId), DateCreated = DateTime.Now }).ToList(); toContext.Priorities.AddRange(priorities); toContext.SaveChanges(); Console.WriteLine("Migrating Statuses"); //Migrate statuses var statuses = fromContext.BugNet_ProjectStatus.ToList().Select(x => new Domain.Models.Status() { Name = x.StatusName, ProjectId = getProjectId(fromContext, toContext, x.ProjectId), IsClosedState = x.IsClosedState, DateCreated = DateTime.Now }).ToList(); toContext.Status.AddRange(statuses); toContext.SaveChanges(); Console.WriteLine("Migrating Types"); //Migrate types var types = fromContext.BugNet_ProjectIssueTypes.ToList().Select(x => new Domain.Models.Type() { Name = x.IssueTypeName, ProjectId = getProjectId(fromContext, toContext, x.ProjectId), DateCreated = DateTime.Now }).ToList(); toContext.Types.AddRange(types); toContext.SaveChanges(); Console.WriteLine("Migrating Issues"); //Migrate issues var issues = fromContext.BugNet_Issues.ToList().Select(x => new Domain.Models.Issue() { AssignedUserId = getUserId(fromContext, toContext, x.IssueAssignedUserId), CategoryId = getCategoryId(fromContext, toContext, x.IssueCategoryId), CreatorUserId = getUserId(fromContext, toContext, x.IssueCreatorUserId), Description = x.IssueDescription, MilestoneId = getMilestoneId(fromContext, toContext, x.IssueMilestoneId), OwnerUserId = getUserId(fromContext, toContext, x.IssueOwnerUserId), PriorityId = getPriorityId(fromContext, toContext, x.IssuePriorityId), ProjectId = getProjectId(fromContext, toContext, x.ProjectId), ResolutionId = getResolutionId(fromContext, toContext, x.IssueResolutionId), StatusId = getStatusId(fromContext, toContext, x.IssueStatusId), Title = x.IssueTitle, TypeId = getTypeId(fromContext, toContext, x.IssueTypeId), DateCreated = x.DateCreated, StoryPoints = Convert.ToInt32(x.IssueEstimation) }).ToList(); toContext.Issues.AddRange(issues); toContext.SaveChanges(); Console.WriteLine("Migrating Comments"); //Migrate comments var comments = fromContext.BugNet_IssueComments.ToList().Select(x => new Domain.Models.Comment() { Content = x.Comment, IssueId = getIssueId(fromContext, toContext, x.IssueId), UserId = getUserId(fromContext, toContext, x.UserId), DateCreated = x.DateCreated }).ToList(); toContext.Comments.AddRange(comments); toContext.SaveChanges(); Console.WriteLine("Migrating Work Reports"); //Migrate work reports var workReports = fromContext.BugNet_IssueWorkReports.ToList().Select(x => new Domain.Models.WorkReport() { Duration = (double)x.Duration, CommentId = getCommentId(fromContext, toContext, x.IssueCommentId), IssueId = getIssueId(fromContext, toContext, x.IssueId), Timestamp = x.WorkDate, UserId = getUserId(fromContext, toContext, x.UserId), DateCreated = x.WorkDate, }).ToList(); toContext.WorkReports.AddRange(workReports); toContext.SaveChanges(); Console.WriteLine("Linking all projects to admin"); //Linking all projects to admin Domain.Models.User adminUser = toContext.Users.Single(x => x.Username == "Admin"); foreach (var project in toContext.Projects) { toContext.UserProjects.Add(new Domain.Models.UserProject() { ProjectId = project.Id, UserId = adminUser.Id, DateCreated = project.DateCreated }); } toContext.SaveChanges(); dbContextTransaction.Commit(); DateTime endTime = DateTime.Now; Console.WriteLine("Migration ran for: {0} seconds", endTime.Subtract(startTime).TotalSeconds); // dbContextTransaction.Rollback(); } catch (Exception ex) { dbContextTransaction.Rollback(); throw ex; } } } } } static Dictionary<Guid, int> cache_getUserId = new Dictionary<Guid, int>(); static int getUserId(FromContext fromContext, BugNetContext toContext, Guid? id) { if (!id.HasValue) id = Guid.Empty; if (!cache_getUserId.ContainsKey(id.Value)) { var user = fromContext.Users.SingleOrDefault(x => x.UserId == id); if (user == null) { return toContext.Users.Single(y => y.Username == "Admin").Id; } string username = user.UserName; cache_getUserId.Add(id.Value, toContext.Users.Single(y => y.Username == username).Id); } return cache_getUserId[id.Value]; } static int? getMilestoneId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; var milestone = fromContext.BugNet_ProjectMilestones.Single(x => x.MilestoneId == id.Value); return toContext.Milestones.SingleOrDefault(x => x.Project.Name == milestone.BugNet_Projects.ProjectName && x.Name == milestone.MilestoneName).Id; } static int? getResolutionId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; var resolution = fromContext.BugNet_ProjectResolutions.Single(x => x.ResolutionId == id.Value); return toContext.Resolutions.SingleOrDefault(x => x.Project.Name == resolution.BugNet_Projects.ProjectName && x.Name == resolution.ResolutionName).Id; } static int? getCommentId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; if (id.Value == 0) return null; var comment = fromContext.BugNet_IssueComments.Single(x => x.IssueCommentId == id.Value); var comments = toContext.Comments.Where(x => x.Issue.Title == comment.BugNet_Issues.IssueTitle && x.Issue.Project.Name == comment.BugNet_Issues.BugNet_Projects.ProjectName); return comments.SingleOrDefault(x => x.Content == comment.Comment).Id; } static int? getTypeId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; var type = fromContext.BugNet_ProjectIssueTypes.Single(x => x.IssueTypeId == id.Value); return toContext.Types.SingleOrDefault(x => x.Project.Name == type.BugNet_Projects.ProjectName && x.Name == type.IssueTypeName).Id; } static int? getStatusId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; var status = fromContext.BugNet_ProjectStatus.Single(x => x.StatusId == id.Value); return toContext.Status.SingleOrDefault(x => x.Project.Name == status.BugNet_Projects.ProjectName && x.Name == status.StatusName).Id; } static int? getCategoryId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; var category = fromContext.BugNet_ProjectCategories.Single(x => x.CategoryId == id.Value); return toContext.Categories.SingleOrDefault(x => x.Project.Name == category.BugNet_Projects.ProjectName && x.Name == category.CategoryName).Id; } static int? getPriorityId(FromContext fromContext, BugNetContext toContext, int? id) { if (!id.HasValue) return null; var priority = fromContext.BugNet_ProjectPriorities.Single(x => x.PriorityId == id.Value); return toContext.Priorities.SingleOrDefault(x => x.Project.Name == priority.BugNet_Projects.ProjectName && x.Name == priority.PriorityName).Id; } static int getIssueId(FromContext fromContext, BugNetContext toContext, int id) { var issues = fromContext.BugNet_Issues.Single(x => x.IssueId == id); return toContext.Issues.SingleOrDefault(x => x.Project.Name == issues.BugNet_Projects.ProjectName && x.Title == issues.IssueTitle).Id; } static Dictionary<int, int> cache_getProjectId = new Dictionary<int, int>(); static int getProjectId(FromContext fromContext, BugNetContext toContext, int id) { if (!cache_getProjectId.ContainsKey(id)) { var project = fromContext.BugNet_Projects.Single(x => x.ProjectId == id); cache_getProjectId.Add(id, toContext.Projects.SingleOrDefault(x => x.Name == project.ProjectName).Id); } return cache_getProjectId[id]; } static string generatePassword(string username) { string passwordSalt = sha1(username.ToLower()); string password = <PASSWORD>(passwordSalt + "<PASSWORD>" + passwordSalt); return password; } static string sha1(string input) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); var sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) { sb.Append(b.ToString("X2")); } return sb.ToString(); } } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_DefaultValues { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ProjectId { get; set; } public int? DefaultType { get; set; } public int? StatusId { get; set; } public Guid? IssueOwnerUserId { get; set; } public int? IssuePriorityId { get; set; } public int? IssueAffectedMilestoneId { get; set; } public Guid? IssueAssignedUserId { get; set; } public int? IssueVisibility { get; set; } public int? IssueCategoryId { get; set; } public int? IssueDueDate { get; set; } public int? IssueProgress { get; set; } public int? IssueMilestoneId { get; set; } public decimal? IssueEstimation { get; set; } public int? IssueResolutionId { get; set; } public bool? OwnedByNotify { get; set; } public bool? AssignedToNotify { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } public virtual User User { get; set; } public virtual User User1 { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class ResolutionView { public int ResolutionId { get; set; } public string Name { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models.Widget { public class LoggedHours { public double Value { get; set; } public bool Up { get; set; } public double StatsValue { get; set; } } }<file_sep>using BugNet.Application.Services; using BugNet.Domain.Infrastructure.Repositories; using BugNet.Domain.Infrastructure.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Application { public static class Dependencies { public static IApplicationService ApplicationService { get { return new ApplicationService(); } } public static IProjectService ProjectService { get { return new ProjectService(); } } public static IListService ListService { get { return new ListService(); } } public static IIssueService IssueService { get { return new IssueService(); } } public static IReportService ReportService { get { return new ReportService(); } } public static IUserService UserService { get { return new UserService(); } } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectNotifications { [Key] public int ProjectNotificationId { get; set; } public int ProjectId { get; set; } public Guid UserId { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } public virtual User User { get; set; } } } <file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Attributes { public class BaseAttribute : ActionFilterAttribute { private IApplicationService ApplicationService; public BaseAttribute() { this.ApplicationService = Dependencies.ApplicationService; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (HttpContext.Current.User.Identity.IsAuthenticated) { filterContext.Controller.ViewBag.User = null; } filterContext.Controller.ViewBag.ApplicationName = this.ApplicationService.GetApplicationName(); filterContext.Controller.ViewBag.ApplicationVersion = this.ApplicationService.AssemblyVersion; base.OnActionExecuting(filterContext); } } }<file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectCustomFields { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_ProjectCustomFields() { BugNet_ProjectCustomFieldSelections = new HashSet<BugNet_ProjectCustomFieldSelections>(); BugNet_ProjectCustomFieldValues = new HashSet<BugNet_ProjectCustomFieldValues>(); } [Key] public int CustomFieldId { get; set; } public int ProjectId { get; set; } [Required] [StringLength(50)] public string CustomFieldName { get; set; } public bool CustomFieldRequired { get; set; } public int CustomFieldDataType { get; set; } public int CustomFieldTypeId { get; set; } public virtual BugNet_ProjectCustomFieldTypes BugNet_ProjectCustomFieldTypes { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectCustomFieldSelections> BugNet_ProjectCustomFieldSelections { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectCustomFieldValues> BugNet_ProjectCustomFieldValues { get; set; } } } <file_sep>using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class Issue { public Issue() { } public Issue(Domain.Models.Issue issue) { ProjectId = issue.ProjectId; AssignedUserId = issue.AssignedUserId; CategoryId = issue.CategoryId; CreatorUserId = issue.CreatorUserId; Description = issue.Description; IssueId = issue.Id; MilestoneId = issue.MilestoneId; OwnerUserId = issue.OwnerUserId; PriorityId = issue.PriorityId; ResolutionId = issue.ResolutionId; StatusId = issue.StatusId; StoryPoints = issue.StoryPoints; Title = issue.Title; TypeId = issue.TypeId; } public string ProjectName { get; set; } public int IssueId { get; set; } [Required] [StringLength(255)] public string Title { get; set; } [StringLength(255)] public string Description { get; set; } public int? StatusId { get; set; } public int? PriorityId { get; set; } public int? TypeId { get; set; } public int? CategoryId { get; set; } public int ProjectId { get; set; } public int? MilestoneId { get; set; } public int? ResolutionId { get; set; } public int CreatorUserId { get; set; } public int OwnerUserId { get; set; } public int? AssignedUserId { get; set; } public int? StoryPoints { get; set; } [Required] public double Duration { get; set; } public string Comment { get; set; } public List<StatusView> Statuses { get; set; } public List<PriorityView> Priorities { get; set; } public List<ResolutionView> Resolutions { get; set; } public List<UserView> Users { get; set; } public List<CategoryView> Categories { get; set; } public List<TypeView> Types { get; set; } public List<MilestoneView> Milestones { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class UserList { public List<UserView> Users { get; set; } } }<file_sep>namespace BugNet.Domain.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Project")] public partial class Project : BaseEntity { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Project() { Categories = new HashSet<Category>(); Issues = new HashSet<Issue>(); Milestones = new HashSet<Milestone>(); Priorities = new HashSet<Priority>(); Resolutions = new HashSet<Resolution>(); Status = new HashSet<Status>(); Types = new HashSet<Type>(); UserProjects = new HashSet<UserProject>(); } public Project(string name, string description, string code, int managerUserId, int creatorUserId, byte[] icon) { Name = name; Description = description; Code = code; ManagerUserId = managerUserId; CreatorUserId = creatorUserId; Icon = icon; } public int Id { get; set; } [Required] [StringLength(255)] public string Name { get; set; } [Required] [StringLength(255)] public string Code { get; set; } public string Description { get; set; } public int ManagerUserId { get; set; } public int CreatorUserId { get; set; } public byte[] Icon { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Category> Categories { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Issue> Issues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Milestone> Milestones { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Priority> Priorities { get; set; } public virtual User CreatorUser { get; set; } public virtual User ManagerUser { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Resolution> Resolutions { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Status> Status { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Type> Types { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<UserProject> UserProjects { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_ProjectCustomFieldSelections { [Key] public int CustomFieldSelectionId { get; set; } public int CustomFieldId { get; set; } [Required] [StringLength(255)] public string CustomFieldSelectionValue { get; set; } [Required] [StringLength(255)] public string CustomFieldSelectionName { get; set; } public int CustomFieldSelectionSortOrder { get; set; } public virtual BugNet_ProjectCustomFields BugNet_ProjectCustomFields { get; set; } } } <file_sep>(function ($) { $.fn.ajaxLoader = function () { var elements = $(this); elements.each(function () { var element = $(this); var url = element.attr('data-url'); var callback = element.attr('data-callback'); element.load(url, function () { executeCallback(callback); }); }); return this; }; function executeCallback(callback) { var x = eval(callback) if (typeof x == 'function') { x() } } }(jQuery)); $(document).ready(function () { $('div.ajax-loader').ajaxLoader(); }); <file_sep>using BugNet.Domain; using BugNet.Domain.Infrastructure.Services; using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Application.Services { public class ListService : IListService { public List<Status> ListIssueStatuses(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { return ctx.Status.Where(x => x.ProjectId == projectId).ToList(); } } public List<Resolution> ListIssueResolutions(string currentUsername, int projectId) { using (var ctx = new BugNetContext()) { return ctx.Resolutions.Where(x => x.ProjectId == projectId).ToList(); } } public List<Milestone> ListIssueMilestones(string username, int projectId) { using (var ctx = new BugNetContext()) { return ctx.Milestones.Where(x => x.ProjectId == projectId).ToList(); } } public List<Priority> ListIssuePriorities(string username, int projectId) { using (var ctx = new BugNetContext()) { return ctx.Priorities.Where(x => x.ProjectId == projectId).ToList(); } } public List<Domain.Models.Type> ListIssueTypes(string username, int projectId) { using (var ctx = new BugNetContext()) { return ctx.Types.Where(x => x.ProjectId == projectId).ToList(); } } public List<Category> ListIssueCategories(string username, int projectId) { using (var ctx = new BugNetContext()) { return ctx.Categories.Where(x => x.ProjectId == projectId).ToList(); } } public Status CreateStatus(string currentUsername, int projectId, string name, bool isClosedState) { using (var ctx = new BugNetContext()) { Status status = new Status(projectId, name, isClosedState); ctx.Status.Add(status); ctx.SaveChanges(currentUsername); return status; } } public Status GetStatusForEdit(int id) { using (var ctx = new BugNetContext()) { return ctx.Status.Include("Project").SingleOrDefault(x => x.Id == id); } } public Status UpdateStatus(string currentUsername, int statusId, string name, bool isClosedState) { using (var ctx = new BugNetContext()) { Status status = ctx.Status.Single(x => x.Id == statusId); status.Name = name; status.IsClosedState = isClosedState; ctx.SaveChanges(currentUsername); return status; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class Status { public Status() { } public Status(Domain.Models.Status model) { this.StatusId = model.Id; this.IsClosedState = model.IsClosedState; this.Name = model.Name; } public int StatusId { get; set; } public string Name { get; set; } public bool IsClosedState { get; set; } public int ProjectId { get; set; } public string ProjectName { get; internal set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.ApplicationModels { public class LoggedHoursPerDay { public DateTime Timestamp { get; set; } public double Hours { get; set; } } } <file_sep>using BugNet.Application; using BugNet.Domain.Infrastructure.Services; using BugNet.WebApplication.Attributes; using BugNet.WebApplication.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BugNet.WebApplication.Controllers { public class UserController : Controller { private IUserService UserService; public UserController() { this.UserService = Dependencies.UserService; } [HttpGet] [Base] [Authorize] public ActionResult List() { return View(new UserList() { Users = this.UserService.ListUsersForManagement(this.User.Identity.Name).Select(x => new UserView() { Created = DateTime.Now, Username = x.Username, UserId = x.Id }).ToList() }); } [HttpGet] [Base] [Authorize] public ActionResult New() { return View(); } [HttpPost] [Base] [Authorize] public ActionResult New(User model) { if (!ModelState.IsValid) { return View(model); } var user = this.UserService.Create(this.User.Identity.Name, model.Username, model.Password); return RedirectToAction("List", "User"); } [HttpGet] [Base] [Authorize] public ActionResult Edit(int id) { var user = this.UserService.GetUserForEdit(this.User.Identity.Name, id); User model = new User() { CreatedTimestamp = DateTime.Now, Username = user.Username, UserId = user.Id }; return View(model); } [HttpPost] [Base] [Authorize] public ActionResult Edit(User model) { var result = this.UserService.Update(this.User.Identity.Name, model.UserId, model.Username); if (result != null) return RedirectToAction("List", "User"); var user = this.UserService.GetUserForEdit(this.User.Identity.Name, model.UserId); model = new User() { CreatedTimestamp = DateTime.Now, Username = user.Username, UserId = user.Id, }; return View(model); } [HttpGet] [Base] [Authorize] public ActionResult Details() { return View(); } [HttpPost] [Base] [Authorize] public ActionResult ResetPassword(ResetPassword model) { if (!ModelState.IsValid) { return View(model); } var user = this.UserService.ResetPassword(this.User.Identity.Name, model.UserId, model.Password); return RedirectToAction("Edit", "User", new { id = model.UserId }); } } }<file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class User { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public User() { BugNet_DefaultValues = new HashSet<BugNet_DefaultValues>(); BugNet_DefaultValues1 = new HashSet<BugNet_DefaultValues>(); BugNet_IssueAttachments = new HashSet<BugNet_IssueAttachments>(); BugNet_IssueComments = new HashSet<BugNet_IssueComments>(); BugNet_IssueHistory = new HashSet<BugNet_IssueHistory>(); BugNet_IssueNotifications = new HashSet<BugNet_IssueNotifications>(); BugNet_Issues = new HashSet<BugNet_Issues>(); BugNet_Issues1 = new HashSet<BugNet_Issues>(); BugNet_Issues2 = new HashSet<BugNet_Issues>(); BugNet_Issues3 = new HashSet<BugNet_Issues>(); BugNet_IssueVotes = new HashSet<BugNet_IssueVotes>(); BugNet_IssueWorkReports = new HashSet<BugNet_IssueWorkReports>(); BugNet_ProjectMailBoxes = new HashSet<BugNet_ProjectMailBoxes>(); BugNet_ProjectNotifications = new HashSet<BugNet_ProjectNotifications>(); BugNet_Projects = new HashSet<BugNet_Projects>(); BugNet_Projects1 = new HashSet<BugNet_Projects>(); BugNet_Queries = new HashSet<BugNet_Queries>(); BugNet_UserCustomFieldValues = new HashSet<BugNet_UserCustomFieldValues>(); BugNet_UserProjects = new HashSet<BugNet_UserProjects>(); BugNet_Roles = new HashSet<BugNet_Roles>(); Roles = new HashSet<Role>(); } public Guid ApplicationId { get; set; } public Guid UserId { get; set; } [Required] [StringLength(50)] public string UserName { get; set; } public bool IsAnonymous { get; set; } public DateTime LastActivityDate { get; set; } public virtual Application Application { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_DefaultValues> BugNet_DefaultValues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_DefaultValues> BugNet_DefaultValues1 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueAttachments> BugNet_IssueAttachments { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueComments> BugNet_IssueComments { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueHistory> BugNet_IssueHistory { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueNotifications> BugNet_IssueNotifications { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues1 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues2 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Issues> BugNet_Issues3 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueVotes> BugNet_IssueVotes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_IssueWorkReports> BugNet_IssueWorkReports { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectMailBoxes> BugNet_ProjectMailBoxes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_ProjectNotifications> BugNet_ProjectNotifications { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Projects> BugNet_Projects { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Projects> BugNet_Projects1 { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Queries> BugNet_Queries { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_UserCustomFieldValues> BugNet_UserCustomFieldValues { get; set; } public virtual BugNet_UserProfiles BugNet_UserProfiles { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_UserProjects> BugNet_UserProjects { get; set; } public virtual Membership Membership { get; set; } public virtual Profile Profile { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_Roles> BugNet_Roles { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Role> Roles { get; set; } } } <file_sep>using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain.Infrastructure.Services { public interface IProjectService { List<Project> ListProjectsForUser(string currentUsername); Project Create(string currentUsername, string name, string description, string code, int managerUserId, int creatorUserId, byte[] icon); Project GetProjectForDashboad(string currentUsername, int id); Project GetProjectForEdit(string currentUsername, int id); Project Edit(string currentUsername, int id, string name, string description, string code, int managerUserId, int creatorUserId, byte[] icon); } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_Queries { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_Queries() { BugNet_QueryClauses = new HashSet<BugNet_QueryClauses>(); } [Key] public int QueryId { get; set; } public Guid UserId { get; set; } public int ProjectId { get; set; } [Required] [StringLength(255)] public string QueryName { get; set; } public bool IsPublic { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } public virtual User User { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_QueryClauses> BugNet_QueryClauses { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_RelatedIssues { [Key] [Column(Order = 0)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int PrimaryIssueId { get; set; } [Key] [Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int SecondaryIssueId { get; set; } [Key] [Column(Order = 2)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int RelationType { get; set; } public virtual BugNet_Issues BugNet_Issues { get; set; } public virtual BugNet_Issues BugNet_Issues1 { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_UserCustomFieldValues { [Key] public int CustomFieldValueId { get; set; } public Guid UserId { get; set; } public int CustomFieldId { get; set; } [Required] public string CustomFieldValue { get; set; } public virtual BugNet_UserCustomFields BugNet_UserCustomFields { get; set; } public virtual User User { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_UserProjects { [Key] [Column(Order = 0)] public Guid UserId { get; set; } [Key] [Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ProjectId { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int UserProjectId { get; set; } public DateTime DateCreated { get; set; } [StringLength(255)] public string SelectedIssueColumns { get; set; } public virtual BugNet_Projects BugNet_Projects { get; set; } public virtual User User { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_UserCustomFieldTypes { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public BugNet_UserCustomFieldTypes() { BugNet_UserCustomFields = new HashSet<BugNet_UserCustomFields>(); } [Key] public int CustomFieldTypeId { get; set; } [Required] [StringLength(50)] public string CustomFieldTypeName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<BugNet_UserCustomFields> BugNet_UserCustomFields { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class UsersOpenAuthAccount { [Key] [Column(Order = 0)] public string ApplicationName { get; set; } [Key] [Column(Order = 1)] public string ProviderName { get; set; } [Key] [Column(Order = 2)] public string ProviderUserId { get; set; } [Required] public string ProviderUserName { get; set; } [Required] [StringLength(128)] public string MembershipUserName { get; set; } public DateTime? LastUsedUtc { get; set; } public virtual UsersOpenAuthData UsersOpenAuthData { get; set; } } } <file_sep>namespace BugNet.Migrator.ContextFromModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class BugNet_IssueRevisions { [Key] public int IssueRevisionId { get; set; } public int Revision { get; set; } public int IssueId { get; set; } [Required] [StringLength(400)] public string Repository { get; set; } [Required] [StringLength(100)] public string RevisionAuthor { get; set; } [Required] [StringLength(100)] public string RevisionDate { get; set; } [Required] public string RevisionMessage { get; set; } public DateTime DateCreated { get; set; } [StringLength(255)] public string Branch { get; set; } [StringLength(100)] public string Changeset { get; set; } public virtual BugNet_Issues BugNet_Issues { get; set; } } } <file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace BugNet.Domain.Test { [TestClass] public class BugNetContextTest { [TestInitialize] public void Initialize () { using (var context = new BugNetContext()) { var users = context.Users.ToList(); context.Users.RemoveRange(users); context.SaveChanges(); } } [TestCleanup] public void CleanUp() { using (var context = new BugNetContext()) { var users = context.Users.ToList(); context.Users.RemoveRange(users); context.SaveChanges(); } } [TestMethod] public void Users_ShouldAddUser() { using (var context = new BugNetContext()) { context.Users.Add(new Models.User("qwerty1", "12345678")); context.SaveChanges(); } using (var context = new BugNetContext()) { context.Users.Single(x => x.Username == "qwerty1"); } } [TestMethod] public void Users_ShouldModifyUser() { Models.User user = new Models.User("qwerty2", "12345678"); using (var context = new BugNetContext()) { context.Users.Add(user); context.SaveChanges(); } using (var context = new BugNetContext()) { user = context.Users.Single(x => x.Username == "qwerty2"); } user.Username = "qwerty3"; using (var context = new BugNetContext()) { context.Entry(user).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } using (var context = new BugNetContext()) { user = context.Users.Single(x => x.Username == "qwerty3"); Assert.IsNotNull(user); } } } } <file_sep>using BugNet.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class IssueList { public string ProjectName { get; set; } public int ProjectId { get; set; } public List<IssueView> Issues { get; set; } public string Status { get; set; } public List<StatusView> Statuses { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugNet.Domain { public class Migrator { private string RelativePath; public Migrator(string relativePath) { this.RelativePath = relativePath; } public void Execute() { string connectionString = ConfigurationManager.ConnectionStrings["BugNetContext"].ToString(); if (createIfNotExists(connectionString)) { //executeScriptFile(connectionString, "0.01"); //executeScriptFile(connectionString, "0.00"); } } private bool createIfNotExists(string connectionString) { var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString); var databaseName = connectionStringBuilder.InitialCatalog; connectionStringBuilder.InitialCatalog = "master"; using (var connection = new SqlConnection(connectionStringBuilder.ToString())) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = string.Format("SELECT * FROM master.dbo.sysdatabases where [name]='{0}'", databaseName); using (var reader = command.ExecuteReader()) { if (reader.HasRows) // exists return false; } command.CommandText = string.Format("CREATE DATABASE [{0}]", databaseName); command.ExecuteNonQuery(); return true; } } } private void executeScriptFile(string connectionString, string file) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(File.ReadAllText(string.Format("{0}/Bin/Scripts/{1}.sql",this.RelativePath, file)), connection); connection.Open(); int result = command.ExecuteNonQuery(); connection.Close(); } } } } <file_sep>namespace BugNet.Domain.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Issue")] public partial class Issue : BaseEntity { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Issue() { Comments = new HashSet<Comment>(); WorkReports = new HashSet<WorkReport>(); } public Issue(int projectId, string title, int? statusId, int? priorityId, int? typeId, int? categoryId, int? milestoneId, int? resolutionId, int? assignedUserId, int? storyPoints, int creatorUserId, int ownerUserId, string description) { ProjectId = projectId; Title = title; StatusId = statusId; PriorityId = priorityId; TypeId = typeId; CategoryId = categoryId; MilestoneId = milestoneId; ResolutionId = resolutionId; AssignedUserId = assignedUserId; StoryPoints = storyPoints; CreatorUserId = creatorUserId; OwnerUserId = ownerUserId; Description = description; } public int Id { get; set; } [Required] [StringLength(255)] public string Title { get; set; } public string Description { get; set; } public int? StatusId { get; set; } public int? PriorityId { get; set; } public int? TypeId { get; set; } public int? CategoryId { get; set; } public int ProjectId { get; set; } public int? MilestoneId { get; set; } public int? ResolutionId { get; set; } public int CreatorUserId { get; set; } public int OwnerUserId { get; set; } public int? AssignedUserId { get; set; } public int? StoryPoints { get; set; } public virtual Category Category { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Comment> Comments { get; set; } public virtual User AssignedUser { get; set; } public virtual User CreatorUser { get; set; } public virtual Milestone Milestone { get; set; } public virtual User OwnerUser { get; set; } public virtual Priority Priority { get; set; } public virtual Project Project { get; set; } public virtual Resolution Resolution { get; set; } public virtual Status Status { get; set; } public virtual Type Type { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<WorkReport> WorkReports { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BugNet.WebApplication.Models { public class ProjectView { public int ProjectId { get; set; } public string Name { get; set; } public string Code { get; set; } } }<file_sep> $(document).ready(function () { $('.content-loader').each(function () { var element = $(this); element.load(element.attr('data-url'), function () { }); }); });
3d5e5c17d705bcceb3457b49262db0eeee9b6b21
[ "Markdown", "C#", "JavaScript", "SQL" ]
82
C#
developersworkspace/BugNet
fe47bada4594c09a673d090b184f2dc46795f43a
aa53fad57e7f6954b469143ef18bf4a3f218394d
refs/heads/master
<repo_name>JackBros/Milli-Piyango<file_sep>/MilliPiyango/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.Collections; namespace MilliPiyango { public partial class Form1 : Form { SqlConnection baglanti = new SqlConnection("Data Source=DESKTOP-PCOH8E6\\SQLEXPRESS;Initial Catalog=MilliPiyango;Integrated Security=True"); public Form1() { InitializeComponent(); this.Size = new Size(200, 300); //this.Size = new Size(500, 500); //tambiletsecimi(); //yarimbiletsecimi(); //ceyrekbiletsecimi(); Mlistele(); } public int Khafta = 0; private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { yeniBoyut(); mGoster(); } private void button3_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { CekilisForm frm2 = new CekilisForm(); this.Hide(); frm2.Show(); } private void biletTipi_SelectedIndexChanged(object sender, EventArgs e) { biletfiyatigoster(); biletListele(); alinmisbiletlericikart(); } void alinmisbiletlericikart() { //comboBox1.Items.Remove("Photoshop"); int[] alinanbilet = new int[50];//en fazla 50 bilet sattığım için if (baglanti.State == ConnectionState.Closed) { if (Hafta.Text !="") { baglanti.Open(); // SqlDataAdapter adtr = new SqlDataAdapter("select * from Tablo1 where hafta='" + int.Parse(Hafta.Text) + "' and bilettipi='" + biletTipi.Text + "'", baglanti); DataTable Tablo1 = new DataTable(); adtr.Fill(Tablo1); if (Tablo1.Rows.Count == 0) { baglanti.Close(); } else { for (int i = 0; i < Tablo1.Rows.Count; i++) { //Tam Bilet //Çeyrek Bilet //Yarım Bilet alinanbilet[i] = int.Parse("" + Tablo1.Rows[i][5]); if (biletTipi.Text == "Tam Bilet") { for (int j = 0; j < Mtambilet.Length; j++) { if (Mtambilet[j] == alinanbilet[i]) { int k = Mtambilet[j]; comboBox1.Items.Remove(k); } } } else if (biletTipi.Text == "Yarım Bilet") { for (int j = 0; j < Myarimbilet.Length; j++) { if (Myarimbilet[j] == alinanbilet[i]) { int t = Myarimbilet[j]; comboBox1.Items.Remove(t); } } } else if (biletTipi.Text == "Çeyrek Bilet") { for (int j = 0; j < Mceyrekbilet.Length; j++) { if (Mceyrekbilet[j] == alinanbilet[i]) { int p = Mceyrekbilet[j]; comboBox1.Items.Remove(p); } } } } baglanti.Close(); } } } for (int i = 0; i < alinanbilet.Length; i++) { alinanbilet[i] = 0; } } void biletListele() { if (biletTipi.Text == "Tam Bilet") { comboBox1.Items.Clear(); for (int i = 0; i < Mtambilet.Length; i++) { // int x = birincibasamakgetir(Mtambilet[i]), y = ikincibasamakgetir(Mtambilet[i]), z = ücüncübasamakgetir(Mtambilet[i]); //comboBox1.Items.Add(x + "-" + y + "-" + z); comboBox1.Items.Add(Mtambilet[i]); } } else if (biletTipi.Text == "Yarım Bilet") { comboBox1.Items.Clear(); for (int i = 0; i < Myarimbilet.Length; i++) { //int x = birincibasamakgetir(Myarimbilet[i]), y = ikincibasamakgetir(Myarimbilet[i]), z = ücüncübasamakgetir(Myarimbilet[i]); //comboBox1.Items.Add(x + "-" + y + "-" + z); comboBox1.Items.Add(Myarimbilet[i]); } } else if (biletTipi.Text == "Çeyrek Bilet") { comboBox1.Items.Clear(); for (int i = 0; i < Mceyrekbilet.Length; i++) { //int x = birincibasamakgetir(Mceyrekbilet[i]), y = ikincibasamakgetir(Mceyrekbilet[i]), z = ücüncübasamakgetir(Mceyrekbilet[i]); // comboBox1.Items.Add(x + "-" + y + "-" + z); comboBox1.Items.Add(Mceyrekbilet[i]); } } } void mGoster() { label2.Visible = true; label3.Visible = true; label4.Visible = true; label5.Visible = true; mAd.Visible = true; mSoyad.Visible = true; biletTipi.Visible = true; odenenFiyat.Visible = true; mEkle.Visible = true; } void yeniBoyut() { this.Size = new Size(1118, 596); } void biletfiyatigoster() { if (biletTipi.Text == "Tam Bilet") { odenenFiyat.Text = "70"; } else if (biletTipi.Text == "Yarım Bilet") { odenenFiyat.Text = "35"; } else if (biletTipi.Text == "Çeyrek Bilet") { odenenFiyat.Text = "17"; } } //int birincibasamakgetir(int A) //{ // return A / 100; //} //int ikincibasamakgetir(int A) //{ // return A % 100 / 10; //} //int ücüncübasamakgetir(int A) //{ // return (A % 100) % 10; //} int[] Mtambilet = new int[50]; int[] Myarimbilet = new int[50]; int[] Mceyrekbilet = new int[50]; //1000+Khafta*250 //2000+Khafta*250 //3000+Khafta*250 void tambiletsecimi() { Random rastgele = new Random(100+Khafta*25); int salla; int a = 0; for (int i = 0; i < Mtambilet.Length; i++) { salla = rastgele.Next(100, 999); for (int j = 0; j < Mtambilet.Length; j++) { if (Mtambilet[j] == salla) { a++; i--; break; } } if (a == 0) { Mtambilet[i] = salla; } a = 0; } } void yarimbiletsecimi() { Random rastgele2 = new Random(200+Khafta*25); int salla2; int a2 = 0; for (int i = 0; i < Myarimbilet.Length; i++) { salla2 = rastgele2.Next(100, 999); for (int j = 0; j < Myarimbilet.Length; j++) { if ((Myarimbilet[j] == salla2) || (biletlerikarsilastir(Myarimbilet, Mtambilet) )) { a2++; i--; break; } } if ((a2 == 0) || (a2 < 2)) { Myarimbilet[i] = salla2; } a2 = 0; } } void ceyrekbiletsecimi() { Random rastgele3 = new Random(300+Khafta*25); int salla3; int a3 = 0; for (int i = 0; i < Mceyrekbilet.Length; i++) { salla3 = rastgele3.Next(100,999); for (int j = 0; j < Mceyrekbilet.Length; j++) { if ((Mceyrekbilet[j] == salla3) || (biletlerikarsilastir(Mtambilet, Myarimbilet) || (biletlerikarsilastir(Mtambilet, Mceyrekbilet)) || (biletlerikarsilastir(Myarimbilet, Mceyrekbilet)))) { a3++; i--; break; } } if ((a3 == 0) || (a3 < 5)) { Mceyrekbilet[i] = salla3; } a3 = 0; } } bool biletlerikarsilastir(int[] A, int[] B) { // string sonuc = null; var sonuc= A.Intersect(B); foreach (var n in sonuc) { return true; } return false; } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if ((int)e.KeyChar >= 47 && (int)e.KeyChar <= 57) { e.Handled = false;//eğer 47 -58 arasındaysa tuşu yazdır. } else if ((int)e.KeyChar == 8) { e.Handled = false;//eğer basılan tuş backspace ise yazdır. } else { e.Handled = true;//bunların dışındaysa hiçbirisini yazdırma } if (textBox1.Text.Length > 10) { MessageBox.Show("Lütfen 11 haneli telefon numaranızı giriniz"); textBox1.Text = ""; } } private void button5_Click(object sender, EventArgs e) { } private void mEkle_Click(object sender, EventArgs e) { // havuzaParaekle(); Mkayitkontrol(); } int paraHavuz = 0; void havuzaParaekle() { int x; x=int.Parse(odenenFiyat.Text); paraHavuz = paraHavuz + x; } void Mkayitkontrol() { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlDataAdapter adtr = new SqlDataAdapter("select * from Tablo1 where isim='" + mAd.Text + "'and soyisim='" + mSoyad.Text + "' and telno='" + textBox1.Text + "'", baglanti); DataTable Tablo1 = new DataTable(); adtr.Fill(Tablo1); if (Tablo1.Rows.Count == 0) { baglanti.Close(); Mkayit(); } else { if (Tablo1.Rows[0][0] != null) { //MessageBox.Show("Sayın " + Tablo1.Rows[0][1] + " " + Tablo1.Rows[0][2] + " yeni bilet almak istiyor musunuz?"); if (MessageBox.Show("Sayın " + Tablo1.Rows[0][1] + " " + Tablo1.Rows[0][2] + " yeni bilet almak istiyor musunuz? \nEski biletleriniz:\n" + Eskibilet(), "Dikkat!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { baglanti.Close(); Mkayit(); } } } baglanti.Close(); } Mlistele(); } catch { } } string Eskibilet() { string A=""; //baglanti.Open(); try { SqlDataAdapter adtr = new SqlDataAdapter("select * from Tablo1 where isim='" + mAd.Text + "'and soyisim='" + mSoyad.Text + "' and telno='" + textBox1.Text + "'", baglanti); DataTable Tablo1 = new DataTable(); adtr.Fill(Tablo1); for (int i = 0; i < Tablo1.Rows.Count; i++) { A = A + ("" + Tablo1.Rows[i][7] + ".Hafta " + Tablo1.Rows[i][4] + " " + Tablo1.Rows[i][5] + "\n"); } return A; } catch { } return ""; } void Mkayit() { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = baglanti; cmd.CommandText = "INSERT INTO Tablo1(isim,soyisim,telno,bilettipi,biletnumarasi,odedigiucret,hafta) VALUES ('" + mAd.Text + "','" + mSoyad.Text + "','" + textBox1.Text + "','" + biletTipi.Text + "','" + int.Parse(comboBox1.Text) + "','" + int.Parse(odenenFiyat.Text) + "','" + int.Parse(Hafta.Text) + "')"; cmd.ExecuteNonQuery(); cmd.Dispose(); baglanti.Close(); MessageBox.Show("Kayıt tamamlandı"); Mlistele(); } } catch { } } void Mlistele() { try { if (baglanti.State == ConnectionState.Closed) { SqlCommand cmd2 = new SqlCommand { Connection = baglanti, CommandText = "SELECT * FROM Tablo1" }; SqlDataAdapter adptr = new SqlDataAdapter(cmd2); DataSet ds = new DataSet(); adptr.Fill(ds, "Tablo1"); dataGridView1.DataSource = ds.Tables["Tablo1"]; baglanti.Close(); } } catch { } } private void button6_Click(object sender, EventArgs e) { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = baglanti; cmd.CommandText = "update Tablo1 set isim='" + mAd.Text + "',soyisim='" + mSoyad.Text + "',telno='" + textBox1.Text + "',bilettipi='" + biletTipi.Text + "',biletnumarasi='" + int.Parse(comboBox1.Text) + "',odedigiucret='" + int.Parse(odenenFiyat.Text) + "',hafta='" + int.Parse(Hafta.Text) + "'where id=@numara"; cmd.Parameters.AddWithValue("@numara", dataGridView1.CurrentRow.Cells[0].Value.ToString()); cmd.ExecuteNonQuery(); cmd.Dispose(); baglanti.Close(); MessageBox.Show("Kayıt guncellendi"); Mlistele(); } } catch { } } private void button6_Click_1(object sender, EventArgs e) { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = baglanti; cmd.CommandText = "update Tablo1 set isim='" + mAd.Text + "',soyisim='" + mSoyad.Text + "',telno='" + textBox1.Text + "',bilettipi='" + biletTipi.Text + "',biletnumarasi='" + int.Parse(comboBox1.Text) + "',odedigiucret='" + int.Parse(odenenFiyat.Text) + "',hafta='" + int.Parse(Hafta.Text) + "'where id=@numara"; cmd.Parameters.AddWithValue("@numara", dataGridView1.CurrentRow.Cells[0].Value.ToString()); cmd.ExecuteNonQuery(); cmd.Dispose(); baglanti.Close(); MessageBox.Show("Kayıt guncellendi"); Mlistele(); } } catch { } } private void button7_Click(object sender, EventArgs e) { try { if (MessageBox.Show("Silmek istediğinizden emin misiniz?", "Dikkat!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = baglanti; cmd.CommandText = "delete from Tablo1 where id=@numara"; cmd.Parameters.AddWithValue("@numara", dataGridView1.CurrentRow.Cells[0].Value.ToString()); cmd.ExecuteNonQuery(); cmd.Dispose(); baglanti.Close(); MessageBox.Show("Kayıt silindi"); Mlistele(); } } } catch{ } } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { mAd.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString(); mSoyad.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString(); textBox1.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString(); biletTipi.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString(); comboBox1.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString(); odenenFiyat.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString(); Hafta.Text = dataGridView1.CurrentRow.Cells[7].Value.ToString(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void button8_Click(object sender, EventArgs e) { Application.Restart(); } private void button9_Click(object sender, EventArgs e) { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlCommand cmd = new SqlCommand("Select * from Tablo1 where isim like '%" + mAd.Text + "%'", baglanti); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; baglanti.Close(); } } catch { } } private void button10_Click(object sender, EventArgs e) { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlCommand cmd = new SqlCommand("Select * from Tablo1 where hafta='" + int.Parse(Hafta.Text) + "'", baglanti); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; baglanti.Close(); } } catch { } } private void Hafta_SelectedIndexChanged(object sender, EventArgs e) { Khafta = int.Parse(Hafta.Text); diziSifirla(); tambiletsecimi(); yarimbiletsecimi(); ceyrekbiletsecimi(); //alinanlariEksilt(); biletListele(); } void diziSifirla() { for (int i = 0; i < Mtambilet.Length; i++) { Mtambilet[i] = 0; Myarimbilet[i] = 0; Mceyrekbilet[i] = 0; } } //void alinanlariEksilt() //{ // if (int.Parse(Hafta.Text) == 1) // { // if(biletTipi.Text=="Tam Bilet") // { // if (baglanti.State == ConnectionState.Closed) // { // baglanti.Open(); // SqlDataAdapter adtr = new SqlDataAdapter("select * from tablo1 where bilettipi='Tam Bilet' and hafta=1", baglanti); // DataTable Tablo1 = new DataTable(); // adtr.Fill(Tablo1); // if (Tablo1.Rows.Count == 0) // { // baglanti.Close(); // Mkayit(); // } // baglanti.Close(); // } // } // else if(biletTipi.Text == "Yarım Bilet") // { // } // else if (biletTipi.Text == "Çeyrek Bilet") // { // } // } // else if(int.Parse(Hafta.Text) == 2) // { // } // else if (int.Parse(Hafta.Text) == 3) // { // } // else if (int.Parse(Hafta.Text) == 4) // { // } // else if (int.Parse(Hafta.Text) == 5) // { // } // else if (int.Parse(Hafta.Text) == 6) // { // } // else if (int.Parse(Hafta.Text) == 7) // { // } //} private void button11_Click(object sender, EventArgs e) { Mlistele(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button12_Click(object sender, EventArgs e) { //datakontrol = false; //string x, y; //x=biletTipi.Text; //y=Hafta.Text; //biletTipi.Text = "" + -1; //Hafta.Text = "" + -1; //biletTipi.Text = x; //Hafta.Text = y; //mEkle.Enabled = true; } private void hakkındaToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Bu otomasyon Mehmet Berkay tarafından hazırlanmıştır."); } private void çıkışToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } } } <file_sep>/MilliPiyango/CekilisForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace MilliPiyango { public partial class CekilisForm : Form { SqlConnection baglanti = new SqlConnection("Data Source=DESKTOP-PCOH8E6\\SQLEXPRESS;Initial Catalog=MilliPiyango;Integrated Security=True"); int ilkdegeri = 0; public CekilisForm() { InitializeComponent(); } private void çıkışToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void hakkındaToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Bu otomasyon Mehmet Berkay tarafından hazırlanmıştır."); } private void anaMenüyeDönToolStripMenuItem_Click(object sender, EventArgs e) { Form1 frm1 = new Form1(); this.Hide(); frm1.Show(); } private void button1_Click(object sender, EventArgs e) { } private void CekilisForm_Load(object sender, EventArgs e) { } private void haftaSecimi_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Clear(); listBox1.Items.Clear(); // int havuzhesabi = 0; //havuzhesabi+= havuzdakiparayihesapla(); //textBox2.Text =""+ havuzhesabi; textBox2.Text = "" +havuzdakiparayihesapla();//-kazananlar fonksiyonX(); ilkdegeri = int.Parse(textBox2.Text); } int odenecekler() { return 0; } void fonksiyonX() { //BTNcekilis.Enabled = false; //BTNonay.Enabled = false; //int haftasec = int.Parse(haftaSecimi.Text); //çekiliş yapılmış ama kazanılan olmamış olabilir if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlDataAdapter adtr = new SqlDataAdapter("select * from Tablo2 where hafta='" + int.Parse(haftaSecimi.Text) + "'", baglanti); DataTable Tablo2 = new DataTable(); adtr.Fill(Tablo2); if (Tablo2.Rows.Count == 0) { BTNcekilis.Enabled = true; BTNonay.Enabled = true; /////////////////////////////////// işlem yapılacak baglanti.Close(); } else { //kazananları gösterir for (int i = 0; i < Tablo2.Rows.Count; i++) { listBox1.Items.Add("" + Tablo2.Rows[i][1] + "---" + Tablo2.Rows[i][2] + "---" + Tablo2.Rows[i][3] + "---" + Tablo2.Rows[i][4] + "---" + Tablo2.Rows[i][8]); } } baglanti.Close(); } } private void BTNcekilis_Click(object sender, EventArgs e) { /*Random rnd = new Random(); int kazananno = rnd.Next(100, 999); textBox1.Text = "" + kazananno; */ textBox1.Text = "626" ; } int odenecekucret(string A) { int kazanansayi = int.Parse(textBox1.Text); return 0; } void kazanankontrol() { baglanti.Close(); try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); int amorti = (int.Parse(textBox1.Text))%100; string amortilike = ""; //MessageBox.Show("" + amorti); if (amorti == 0) { amortilike = "%" + amorti+""+amorti ;//'%'+'"+amorti+"' } else { amortilike = "%" + amorti;//'%'+'"+amorti+"' } SqlDataAdapter adtr = new SqlDataAdapter("select * from Tablo1 where hafta='" + int.Parse(haftaSecimi.Text) + "' and (biletnumarasi LIKE '"+amortilike+"')", baglanti); DataTable Tablo1 = new DataTable(); adtr.Fill(Tablo1); if (Tablo1.Rows.Count == 0) { //kazanan olmadı demek listBox1.Items.Add("Kazanan Yok!!"); MessageBox.Show("Kazanan Yok!"); baglanti.Close(); } else { //amorti varsa for (int i = 0; i < Tablo1.Rows.Count; i++) { int kazandigimiktar; if (int.Parse("" + Tablo1.Rows[i][5]) == (int.Parse(textBox1.Text))) { kazandigimiktar = hepsinikazandi("" + Tablo1.Rows[i][4]); listBox1.Items.Add("" + strgonder("" + Tablo1.Rows[i][1]) + "---" + strgonder("" + Tablo1.Rows[i][2]) + "---" + strgonder("" + Tablo1.Rows[i][3]) + "---" + strgonder("" + Tablo1.Rows[i][4]) + "---" + "Kazandığı="+kazandigimiktar); } else { kazandigimiktar = amorticikti("" + Tablo1.Rows[i][4]); listBox1.Items.Add("" + strgonder("" + Tablo1.Rows[i][1]) + "---" + strgonder("" + Tablo1.Rows[i][2]) + "---" + strgonder("" + Tablo1.Rows[i][3]) + "---" + strgonder("" + Tablo1.Rows[i][4]) + "---" + "Kazandığı=" + kazandigimiktar); } //düzeltcek 8. satıra kaznılan para eklenicek öyle listbox a yazılacak // bu sorgu 2. tabloya elemanları ekliyor bu yüzden Onayla butonu.... eklemeyi onaylada yap. sonra havuzu göstereni veritabanına bağlayabilirsin. //////SqlCommand cmd = new SqlCommand(); //////cmd.Connection = baglanti; //////cmd.CommandText = "INSERT INTO Tablo2(isim,soyisim,telno,bilettipi,biletnumarasi,odedigiucret,hafta,alacagiucret) VALUES ('" + "" + Tablo1.Rows[i][1] + "','" + "" + Tablo1.Rows[i][2] + "','" + "" + Tablo1.Rows[i][3] + "','" + "" + Tablo1.Rows[i][4] + "','" + int.Parse("" + Tablo1.Rows[i][5]) + "','" + int.Parse("" + Tablo1.Rows[i][6]) + "','" + int.Parse("" + Tablo1.Rows[i][7]) + "','" + odenecekucret("" + Tablo1.Rows[i][3]) + "')"; //////cmd.ExecuteNonQuery(); //////cmd.Dispose(); //SqlDataAdapter adtr2 = new SqlDataAdapter("select * from Tablo1 where hafta='" + int.Parse(haftaSecimi.Text) + "' and biletnumarasi='"+int.Parse(textBox1.Text)+"'", baglanti); } } baglanti.Close(); } } catch { } } string strgonder(string A) { A = A + ""; return A; } private void textBox1_TextChanged(object sender, EventArgs e) { kazanankontrol(); } private void BTNonay_Click(object sender, EventArgs e) { checkBox1.Checked = true; //havuzdaki paraları hesaplattır. } int amorticikti(string A) { int azalt=0; if (A == "Tam Bilet") { azalt = 70; textBox2.Text = "" + (ilkdegeri - azalt); return 70; } else if (A == "Yarım Bilet") { azalt = 35; textBox2.Text = "" + (ilkdegeri - azalt); return 35; } else if (A == "Çeyrek Bilet") { azalt = 17; textBox2.Text = "" + (ilkdegeri - azalt); return 17; } return 0; } int hepsinikazandi(string B) { int kazandigi= 0; if (B == "Tam Bilet") { kazandigi = ilkdegeri; //azalt =ilkdegeri-kazandigi; textBox2.Text = "" + (ilkdegeri-kazandigi); return kazandigi; } else if (B == "Yarım Bilet") { kazandigi = ilkdegeri/2; //azalt = ilkdegeri - kazandigi; textBox2.Text = "" + (ilkdegeri-kazandigi); return kazandigi; } else if (B == "Çeyrek Bilet") { kazandigi = ilkdegeri / 4; //azalt = ilkdegeri - kazandigi; textBox2.Text = "" + (ilkdegeri-kazandigi); return kazandigi; } return 0; } int k = 0; int havuzdakiparayihesapla() { try { if (baglanti.State == ConnectionState.Closed) { baglanti.Open(); SqlDataAdapter adtr = new SqlDataAdapter("select * from Tablo1 where hafta='" + int.Parse(haftaSecimi.Text) + "'", baglanti); DataTable Tablo1 = new DataTable(); adtr.Fill(Tablo1); for (int i = 0; i < Tablo1.Rows.Count; i++) { k += int.Parse("" + Tablo1.Rows[i][6]);// - ödenecek ücret } baglanti.Close(); } return k; } catch { } return 0; } } } <file_sep>/README.md # <NAME> <NAME>, bir otomasyon uygulamasıdır. Bu uygulamada temsili olarak, 3 rakamlı rastgele piyango biletleri oluşturulmuştur. Bilet tipine göre alacakları ücretler belirlenmiştir. ## Uygulamadan Görüntüler <br> <img src="images/1.PNG" > <p>Açılış ekranı</p><br> <img width="9000" src="images/2.PNG" height="425" > <p align="center">Bilet satış ve müşteri işlemleri</p><br> <img width="900" src="images/3.PNG" height="425" > <p align="center">Bilet satış ve müşteri işlemleri</p><br> <img width="900" src="images/6.png" height="425" > <p align="center">Bilet satış ve müşteri işlemleri</p><br> <img src="images/4.PNG" width="900" height="500" > <p align="center">Çekiliş ekranı</p><br> <img src="images/5.PNG" width="900" height="600"> <p align="center">Çekiliş ekranı</p><br>
d3ff6c48744e1a934dae0a0b39e2ab76dfe5cca1
[ "Markdown", "C#" ]
3
C#
JackBros/Milli-Piyango
6a9fb53d61a1207b44b63007fc4cfe6871541e43
4c5b4fa7f0b9c7c21e566657fe42a7d91ee3a6c3
refs/heads/master
<file_sep>angular.module('journey-planning', ['moment-picker', 'ui.select', 'ngSanitize', 'chart.js']) .controller('journeyPlanningCtrl', function($scope, $http) { // Define API endpoints const STATIC_DATA_API = "http://localhost:8080/api/"; const JOURNEY_PLANNING_API = "http://localhost:8081/route/" const ENTRY_SLIP_ROAD_API = STATIC_DATA_API + "entrySlipRoad/all"; const EXIT_SLIP_ROAD_API = STATIC_DATA_API + "exitSlipRoad/all"; const STRING_DATE_TIME_FORMAT = "HH:mm a"; const MAPBOX_ACCESS_TOKEN = '<KEY>'; // Define variables //Slip road variables $scope.entrySlipRoadMap = {}; $scope.entrySlipRoadArray = []; $scope.junctionsForSelectedFromRoadNumber = []; $scope.exitSlipRoadMap = {}; $scope.exitSlipRoadArray = []; $scope.junctionsForSelectedToRoadNumber = []; //Start & end date variables $scope.selectedStartDate = {}; $scope.selectedEndDate = {}; $scope.startDateHasChanged = false; $scope.minStartDate = moment(); $scope.minEndDate = moment(); $scope.maxEndDate = moment(); //Journey data variables $scope.returnedRoutes = null; $scope.optimalRoute = null; // Define functions $scope.onFromRoadNumberSelected = onFromRoadNumberSelected; $scope.onToRoadNumberSelected = onToRoadNumberSelected; $scope.onStartDateChanged = onStartDateChanged; $scope.isPlanJourneyButtonDisabled = isPlanJourneyButtonDisabled; $scope.getRoutes = getRoutes; //UI Variables var loadingSpinner = $('#loading-spinner'); var planJourneyButton = $('#plan-journey-button'); var entrySlipErrorText = $('#entry-slip-error-text'); var exitSlipErrorText = $('#exit-slip-error-text'); var serviceOfflineErrorText = $('#service-offline-error-text'); var unableToFindRouteErrorText = $('#route-error-text'); //Map variables var map = L.map('map'); $scope.layerGroup = {}; var southWestBounds = L.latLng(49.937457, -5.577327); var northEastBounds = L.latLng(58.989541, 2.696686); var bounds = L.latLngBounds(southWestBounds, northEastBounds); //Line graph variables $scope.labels = []; $scope.data = []; $scope.options = { scales: { yAxes: [ { scaleLabel: { display: true, labelString: 'Journey time (mins)' } } ], xAxes: [ { scaleLabel: { display: true, labelString: 'Departure time' } } ] } }; // Run functions getEntrySlipRoads(); getExitSlipRoads(); setupMap(); // Functions function setupMap() { map.setView(bounds.getCenter(), 6); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', minZoom: 6, maxZoom: 18, center: bounds.getCenter(), id: 'mapbox.streets', accessToken: MAPBOX_ACCESS_TOKEN }).addTo(map); map.setMaxBounds(bounds); } function setMapToOptimalRoute() { //remove all previous layers map.removeLayer($scope.layerGroup); if ($scope.optimalRoute == null) { return; } var pointList = []; $.each($scope.optimalRoute.route, function(index, routePoint) { var start = [routePoint.startNode.longitude, routePoint.startNode.latitude]; var end = [routePoint.endNode.longitude, routePoint.endNode.latitude]; pointList.push(start, end); }); var polylineOptions = { color: '#4286f4' }; var polyline = new L.Polyline(pointList, polylineOptions); var startMarker = new L.Marker(pointList[0]) .bindPopup($scope.selectedFromJunction.roadName); var endMarker = new L.Marker(pointList[pointList.length - 1]) .bindPopup($scope.selectedToJunction.roadName); $scope.layerGroup = L.layerGroup([polyline, startMarker, endMarker]); $scope.layerGroup.addTo(map); map.fitBounds(polyline.getBounds()); } function onStartDateChanged(newValue, oldValue) { $scope.startDateHasChanged = true; $scope.minEndDate = moment(newValue).add(15, 'minutes'); /*Functionality for 24 hour journey planning not yet implemented, therefore the max end date has been limited to 23:45pm of the same day.*/ $scope.maxEndDate = moment($scope.selectedStartDate).hour(23).minute(45); } function onFromRoadNumberSelected(selectedFromRoadNumber) { $scope.selectedFromJunction = null; $scope.junctionsForSelectedFromRoadNumber = $scope.entrySlipRoadMap[selectedFromRoadNumber.text]; } function onToRoadNumberSelected(selectedToRoadNumber) { $scope.selectedToJunction = null; $scope.junctionsForSelectedToRoadNumber = $scope.exitSlipRoadMap[selectedToRoadNumber.text]; } function setLoadingUI() { serviceOfflineErrorText.hide(); unableToFindRouteErrorText.hide(); loadingSpinner.show(); planJourneyButton.text('Loading...'); planJourneyButton.prop('disabled', true); } function removeLoadingUI() { loadingSpinner.hide(); planJourneyButton.text('Plan my journey'); planJourneyButton.prop('disabled', false); } function isPlanJourneyButtonDisabled() { return $.isEmptyObject($scope.selectedStartDate) || $.isEmptyObject($scope.selectedEndDate) || $.isEmptyObject($scope.selectedFromJunction) || $.isEmptyObject($scope.selectedToJunction); } function getEntrySlipRoads() { $http.get(ENTRY_SLIP_ROAD_API). then(function onSuccess(response) { $scope.entrySlipRoadMap = response.data; $scope.entrySlipRoadArray = $.map($scope.entrySlipRoadMap, function(value, key) { return {text: key}; }); }).catch(function onError(response) { entrySlipErrorText.show(); }); } function getExitSlipRoads() { $http.get(EXIT_SLIP_ROAD_API). then(function onSuccess(response) { $scope.exitSlipRoadMap = response.data; $scope.exitSlipRoadArray = $.map($scope.exitSlipRoadMap, function(value, key) { return {text: key}; }); }).catch(function onError(response) { exitSlipErrorText.show(); }); } function getRoutes() { setLoadingUI(); var URL = JOURNEY_PLANNING_API + $scope.selectedFromJunction.linkId + "/" + $scope.selectedToJunction.linkId + "/" + $scope.selectedStartDate + "/" + $scope.selectedEndDate; $http.get(URL). then(function onSuccess(response) { removeLoadingUI(); $scope.returnedRoutes = response.data; setOptimalRoute(); setDepartureArrivalTimeText(); setTravelTimeText(); createGraphData(); setMapToOptimalRoute(); }).catch(function onError(response) { removeLoadingUI(); $scope.optimalRoute = null; //clear the journey information setMapToOptimalRoute(); //clear the map if (response.data != null) { unableToFindRouteErrorText.show(); } else { serviceOfflineErrorText.show(); } }); } function createGraphData() { $scope.labels = []; $scope.data = []; $.each($scope.returnedRoutes, function(index, route) { $scope.labels.push(route.departureTimeText); $scope.data.push(route.minutesToTravel.toFixed(2)); }); } function setOptimalRoute() { $.each($scope.returnedRoutes, function(index, route) { if (route.optimalRoute) { $scope.optimalRoute = route; return false; } }); } function setDepartureArrivalTimeText() { $.each($scope.returnedRoutes, function(index, route) { var departureTime = moment(route.departureTimeMillis); var arrivalTime = moment(route.arrivalTimeMillis); route.departureTimeText = departureTime.format(STRING_DATE_TIME_FORMAT); route.arrivalTimeText = arrivalTime.format(STRING_DATE_TIME_FORMAT); }); } function setTravelTimeText() { $.each($scope.returnedRoutes, function(index, route) { var travelTimeText = null; var minutes = Math.round(route.minutesToTravel); var hours = Math.floor(minutes / 60); if (hours > 0) { var minutesOfTheHour = minutes - (hours * 60); if (minutesOfTheHour == 0) { if (hours == 1) { travelTimeText = hours + " hour"; } else { travelTimeText = hours + " hours"; } } else { if (hours == 1) { travelTimeText = hours + " hour, " + minutesOfTheHour + " minutes"; } else { travelTimeText = hours + " hours, " + minutesOfTheHour + " minutes"; } } } else { if (minutes == 1) { travelTimeText = minutes + " minute"; } else { travelTimeText = minutes + " minutes"; } } route.travelTimeText = travelTimeText; }); } }) .config(['momentPickerProvider', function (momentPickerProvider) { momentPickerProvider.options({ minutesStep: 15, format: "lll", locale: "en-gb", minView: "month", maxView: "hour" }); }]) ;
5337cd623285db7086e34578a0d570fbc45fa927
[ "JavaScript" ]
1
JavaScript
georgebarker/journey-planning-webapp
8d849225f552bc382afe0745de9539bca246d2f8
c80ba0dbe9b4240e880f0a1f0bec150acf1bfae6
refs/heads/master
<file_sep>#include <stdio.h> #include "curp.h" #include <stdlib.h> #include <stdlib.h> #include <time.h> #include <conio.h> #define MAX 255 #define MAXFECHA 1999999 #define ASMAMEN 65 #define ASMAMAY 90 #define ASCMINMENOS 97 #define ASCMINMAYOR 122 #define ESPACIO 32 #define UNO 49 int main (){ //Nombres y apellidos char nom[MAX]; char apat[MAX]; char amat[MAX]; char curp[17]; char continuar; while(1){ printf ("Este es un programa que genera el curp:\n \n"); printf ("Escirbe tu primer nombre: \n"); scanf ("%s",nom); fflush(stdin); printf ("\nEscirbe tu apellido paterno: \n"); fflush(stdin); scanf ("%s",apat); printf ("\nEscirbe tu apellido materno: \n"); fflush(stdin); scanf ("%s",amat); fflush(stdin); //Transformación de mayúsculas y vocales if (apat[0]>=ASMAMEN && apat[0]<=ASMAMAY) curp[0] = apat[0]; else{ curp[0] = 'A' + apat[0] - 'a';} if (amat[0]>=ASMAMEN && amat[0]<=ASMAMAY) curp[2] = amat[0]; else{ curp[2] = 'A' + amat[0] - 'a';} if (nom[0]>=ASMAMEN && nom[0]<=ASMAMAY) curp[3] = nom[0]; else{ curp[3] = 'A' + nom[0] - 'a';} //Transformación a mayúsculas y consonantes int i = 0; int j=0; int k=0; int l=0; while (i<MAX){ i++; apat[i]; if (apat[i] =='a' || apat[i] =='e' || apat[i] =='i' || apat[i] =='o' || apat[i] =='u'){ curp[1] = 'A' + apat[i] - 'a'; break; } if (apat[i] =='A' || apat[i] =='E' || apat[i] =='I' || apat[i] =='O' || apat[i] =='U'){ curp[1] = apat[i]; break; } } while (j<MAX){ j++; apat[j]; if (apat[j]>=ASMAMEN && apat[j]<=ASMAMAY){ curp[13] = apat[j]; if (apat[j] !='A' && apat[j] !='E' && apat[j] !='I' && apat[j] !='O' && apat[j] !='U'){ curp[13] = apat[j]; break; } } if (apat[j]>=ASCMINMENOS && apat[j]<=ASCMINMAYOR){ curp[13] = apat[j]; if (apat[j] !='a' && apat[j] !='e' && apat[j] !='i' && apat[j] !='o' && apat[j] !='u'){ curp[13] = 'A' + apat[j] - 'a'; break; } } } while (k<MAX){ k++; amat[k]; if(amat[k]>=ASMAMEN && amat[k]<=ASMAMAY){ curp[14] = amat[k]; if (amat[k] !='A' && amat[k] !='E' && amat[k] !='I' && amat[k] !='O' && amat[k] !='U'){ curp[14] = amat[k]; break; } } if(amat[k]>=ASCMINMENOS && amat[k]<=ASCMINMAYOR){ curp[14] = amat[k]; if (amat[k] !='a' && amat[k] !='e' && amat[k] !='i' && amat[k] !='o' && amat[k] !='u'){ curp[14] = 'A' + amat[k] - 'a'; break; } } } while (l<MAX){ l++; nom[l]; if(nom[l]>=ASMAMEN && nom[l]<=ASMAMAY){ curp[15] = nom[l]; if (nom[l] !='A' && nom[l] !='E' && nom[l] !='I' && nom[l] !='O' && nom[l] !='U'){ curp[15] = nom[l]; break; } } if(nom[l]>=ASCMINMENOS && nom[l]<=ASCMINMAYOR){ curp[15] = nom[l]; if (nom[l] !='a' && nom[l] !='e' && nom[l] !='i' && nom[l] !='o' && nom[l] !='u'){ curp[15] = 'A' + nom[l] - 'a'; break; } } } printf("Tu nombre quedo registrado asi\n %s,%s,%s presiona uno para continuar\n",nom,apat,amat); printf("\n o cualquier otra tecla para regresar\n"); scanf("%c",&continuar); if (continuar == UNO) break; } //*********************************** //Fecha de nacimiento int mes,dia; int anio; while(1) { printf ("\nIngresa el anio en que naciste \n"); scanf("%d",&anio); if (anio>2014 || anio<1800){ printf ("Error, intentalo de nuevo \n"); } if (anio>=2000 && anio<=2014){ anio = anio - 2000; break; } if (anio>=1900 && anio<=2000){ anio = anio - 1900; break; } if (anio>=1800 && anio<=1900){ anio = anio - 1800; break; } } while (1){ printf ("Ingresa el numero de mes en que naciste \n"); scanf("%d",&mes); if (mes>12 || mes==0){ printf ("Error, intentalo de nuevo \n"); } else break; } switch (mes){ case 1: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 2: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>28 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 3: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 4: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>30 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 5: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 6: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>30 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 7: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 8: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 9: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>30 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 10: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 11: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>30 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; case 12: while(1){ printf("\nIngresa el dia en que naciste\n"); scanf ("%d",&dia); if (dia>31 || dia==0) printf("\nIntentaalo de nuevo \n"); else break; } break; } //************************************ //Sexo char sexo[0]; while(1){ printf ("\nSexo: Escriba 'H' para hombre y 'M' para mujer \n"); scanf ("%s",sexo); if (sexo[0]>=ASMAMEN && sexo[0]<=ASMAMAY){ if (sexo[0] == 72 || sexo[0] == 77){ curp[10] = sexo[0]; break; } } if (sexo[0]>=ASCMINMENOS && sexo[0]<=ASCMINMAYOR){ curp[10] = 'A' + sexo[0] - 'a'; if (curp[10] == 72 || curp[10] == 77){ break; } } printf("\nIntentelo de nuevo: \n"); } //************************************ //Entidad Federativa char entidad1,entidad2; printf("\n\n ENTIDAD CLAVE\n Seleccione el numero que corresponda:\n "); printf("\nAGUASCALIENTES 1"); printf("\nBAJA CALIFORNIA 2"); printf("\nBAJA CALIFORNIA SUR 3"); printf("\nCAMPECHE 4"); printf("\nCOAHUILA 5"); printf("\nCOLIMA 6"); printf("\nCHIAPAS 7"); printf("\nCHIHUHUA 8"); printf("\nDISTRITO FEDERAL 9"); printf("\nDURANGO 10"); printf("\nGUANAJUATO 11"); printf("\nGUERRERO 12"); printf("\nHIDALGO 13"); printf("\nJALISCO 14"); printf("\nMEXICO 15"); printf("\nMICHOACAN 16"); printf("\nMORELOS 17"); printf("\nNAYARIT 18"); printf("\n<NAME> 19"); printf("\nOAXACA 20"); printf("\nPUEBLA 21"); printf("\nQUERETARO 22"); printf("\n<NAME> 23"); printf("\n<NAME> 24"); printf("\nSINALOA 25"); printf("\nSONORA 26"); printf("\nTABASCO 27"); printf("\nTAMAULIPAS 28"); printf("\nTLAXCALA 29"); printf("\nVERACRUZ 30"); printf("\nYUCATAN 31"); printf("\nZACATECAS 32"); int entidad; while(1){ printf("\n\nINGRESA LA CLAVE DE TU ENTIDAD SEGUN SEA EL CASO\n"); scanf ("%d",&entidad); if (entidad>32 || entidad ==0) printf("Solo son 32, intentalo de nuevo\n"); else break; } switch (entidad){ case 1: printf("AGUASCALIENTES\n\n"); entidad1 = 'A'; entidad2 = 'S'; curp[11] = entidad1; curp[12] = entidad2; break; case 2: printf("BAJA CALIFORNIA\n\n"); entidad1 = 'B'; entidad2 = 'C'; curp[11] = entidad1; curp[12] = entidad2; break; case 3: printf("BAJA CALIFORNIA SUR\n\n"); entidad1 = 'B'; entidad2 = 'S'; curp[11] = entidad1; curp[12] = entidad2; break; case 4: printf("CAMPECHE\n\n"); entidad1 = 'C'; entidad2 = 'C'; curp[11] = entidad1; curp[12] = entidad2; break; case 5: printf("COAHUILA\n\n"); entidad1 = 'C'; entidad2 = 'L'; curp[11] = entidad1; curp[12] = entidad2; break; case 6: printf("COLIMA\n\n"); entidad1 = 'C'; entidad2 = 'M'; curp[11] = entidad1; curp[12] = entidad2; break; case 7: printf("CHIAPAS\n\n"); entidad1 = 'C'; entidad2 = 'S'; curp[11] = entidad1; curp[12] = entidad2; break; case 8: printf("CHIHUHUA\n\n"); entidad1 = 'C'; entidad2 = 'H'; curp[11] = entidad1; curp[12] = entidad2; break; case 9: printf("DISTRITO FEDERAL\n\n"); entidad1 = 'D'; entidad2 = 'F'; curp[11] = entidad1; curp[12] = entidad2; break; case 10: printf("DURANGO\n\n"); entidad1 = 'D'; entidad2 = 'G'; curp[11] = entidad1; curp[12] = entidad2; break; case 11: printf("GUANAJUATO\n\n"); entidad1 = 'G'; entidad2 = 'T'; curp[11] = entidad1; curp[12] = entidad2; break; case 12: printf("GUERRERO\n\n"); entidad1 = 'G'; entidad2 = 'R'; curp[11] = entidad1; curp[12] = entidad2; break; case 13: printf("HIDALGO\n\n"); entidad1 = 'H'; entidad2 = 'G'; curp[11] = entidad1; curp[12] = entidad2; break; case 14: printf("JALISCO\n\n"); entidad1 = 'J'; entidad2 = 'C'; curp[11] = entidad1; curp[12] = entidad2; break; case 15: printf("MEXICO\n\n"); entidad1 = 'M'; entidad2 = 'C'; curp[11] = entidad1; curp[12] = entidad2; break; case 16: printf("MICHOACAN\n\n"); entidad1 = 'M'; entidad2 = 'N'; curp[11] = entidad1; curp[12] = entidad2; break; case 17: printf("MORELOS\n\n"); entidad1 = 'M'; entidad2 = 'S'; curp[11] = entidad1; curp[12] = entidad2; break; case 18: printf("NAYARIT\n\n"); entidad1 = 'N'; entidad2 = 'Y'; curp[11] = entidad1; curp[12] = entidad2; break; case 19: printf("<NAME>\n\n"); entidad1 = 'N'; entidad2 = 'L'; curp[11] = entidad1; curp[12] = entidad2; break; case 20: printf("OAXACA\n\n"); entidad1 = 'O'; entidad2 = 'C'; curp[11] = entidad1; curp[12] = entidad2; break; case 21: printf("PUEBLA\n\n"); entidad1 = 'P'; entidad2 = 'L'; curp[11] = entidad1; curp[12] = entidad2; break; case 22: printf("QUERETARO\n\n"); entidad1 = 'Q'; entidad2 = 'T'; curp[11] = entidad1; curp[12] = entidad2; break; case 23: printf("<NAME>\n\n"); entidad1 = 'Q'; entidad2 = 'R'; curp[11] = entidad1; curp[12] = entidad2; break; case 24: printf("<NAME>\n\n"); entidad1 = 'S'; entidad2 = 'P'; curp[11] = entidad1; curp[12] = entidad2; break; case 25: printf("SINALOA\n\n"); entidad1 = 'S'; entidad2 = 'L'; curp[11] = entidad1; curp[12] = entidad2; break; case 26: printf("SONORA\n\n"); entidad1 = 'S'; entidad2 = 'R'; curp[11] = entidad1; curp[12] = entidad2; break; case 27: printf("TABASCO\n\n"); entidad1 = 'T'; entidad2 = 'C'; curp[11] = entidad1; curp[12] = entidad2; break; case 28: printf("TAMAULIPAS\n\n"); entidad1 = 'T'; entidad2 = 'S'; curp[11] = entidad1; curp[12] = entidad2; break; case 29: printf("TLAXCALA\n\n"); entidad1 = 'T'; entidad2 = 'L'; curp[11] = entidad1; curp[12] = entidad2; break; case 30: printf("VERACRUZ\n\n"); entidad1 = 'V'; entidad2 = 'Z'; curp[11] = entidad1; curp[12] = entidad2; break; case 31: printf("YUCATAN\n\n"); entidad1 = 'Y'; entidad2 = 'N'; curp[11] = entidad1; curp[12] = entidad2; break; case 32: printf("ZACATECAS\n\n"); entidad1 = 'Z'; entidad2 = 'S'; curp[11] = entidad1; curp[12] = entidad2; break; } //*********************************** printf ("\nSu curp es :\n"); if (mes<10 && dia<10){ printf ("\n %c%c%c%c%d",curp[0],curp[1],curp[2],curp[3],anio); printf("0%d", mes); printf("0%d",dia); printf ("%c%c%c",curp[10],curp[11],curp[12]); printf ("%c%c%c",curp[13],curp[14],curp[15]); printf ("%d",homo(0,0,0)); printf ("%d",n_veri(0,0,0)); } else{ printf ("\n %c%c%c%c%d%d%d",curp[0],curp[1],curp[2],curp[3],anio,mes,dia); printf ("%c%c%c",curp[10],curp[11],curp[12]); printf ("%c%c%c",curp[13],curp[14],curp[15]); printf ("%d",homo(0,0,0)); printf ("%d",n_veri(0,0,0)); } return 0; } <file_sep>#include <stdio.h> #include "curp.h" #include <stdlib.h> #include <time.h> #include <conio.h> //números de verificacion y homoclave int n_veri(int cantidad2,int numero2, int contador2){ int hora2 = time(NULL); cantidad2 = 0; srand(hora2); for(contador2 = 0; contador2<=cantidad2; contador2++) numero2 = rand()%10; return numero2; } int homo(int cantidad,int numero, int contador){ int hora = time(NULL); cantidad = 0; srand(hora); int curp16; for(contador = 0; contador<=cantidad; contador++) { numero = rand()%100; if (numero<91 && numero>63){ curp16 = numero/10; } else{ curp16 = 0; } return curp16; } } //************************************************** <file_sep>#ifndef curp_h #define curp_h #define MAX 255 #define MAXFECHA 1999999 int n_veri(int,int,int); int homo(int,int,int); #endif <file_sep># CURPenC Ejemplo de generación del CURP en lenguaje C
ac98236647be486ef6e3cfebb4515b70219d8c86
[ "Markdown", "C" ]
4
C
ezequielbrrt/CURPenC
06c334d62af904f71146c04106eeda70a8098470
e14036a5cf4941cef37012d6dc88d28131433054
refs/heads/master
<repo_name>crevanwoo/enchilada<file_sep>/js/clever_custom_scroll.js $('.tab').on('click', function () { scrollInit() }) function addScrollListeners() { var listeners = ['wheel', 'keydown', 'touchstart', 'touchmove', 'touchend']; for (var i = 0; i < listeners.length; i++) { window.addEventListener(listeners[i], function (e) { pageScroll(e); }) } }; addScrollListeners(); var direction; function pageScroll(e) { direction = ScrollDirection.defineScrollDirection(e); console.log(direction); containerMove(); runnerMove(); } function defineContainer() { return document.querySelector(container_selector) } function defineThumb() { return defineContainer().parentElement.querySelector(runner_selector) } /* Scroll Direction */ var ScrollDirection = { getKeyCode: function (e) { if (e.keyCode == 40) { return 'down' } else if (e.keyCode == 38) { return 'up' } }, getTouchCoord: function (e) { return e.touches[0].clientY }, getSwipeDirection: function (e) { if (e.type == 'touchstart') { this.firstCoord = this.getTouchCoord(e); } else if (e.type == 'touchmove') { this.lastCoord = this.getTouchCoord(e); } else if (e.type == 'touchend') { if (this.lastCoord - this.firstCoord > 10) { return 'up'; } else if (this.lastCoord - this.firstCoord < -10) { return 'down'; } } }, getWheelDirection: function (e) { if (e.deltaY > 0) { return 'down' } else if (e.deltaY < 0) { return 'up' } }, defineScrollDirection: function (e) { if (e.type == "keydown") { return this.getKeyCode(e); } else if (e.type == "touchstart" || e.type == "touchmove" || e.type == "touchend") { return this.getSwipeDirection(e); } else if (e.type == "wheel") { return this.getWheelDirection(e); } }, } function runnerMove() { step_size = define_container_step_size(); runner_marker = runner_marker; thumb = defineThumb(); runner_step_size = define_runner_step_size(); if (direction == 'down') { //- if (runner_marker) { runner_step += runner_step_size; thumb.style.top = runner_step + "%"; } else { runner_step = (100 - parseFloat(thumb.style.height)); thumb.style.top = runner_step + "%"; } } else if (direction == 'up') { //+ if (runner_marker) { runner_step -= runner_step_size; thumb.style.top = runner_step + "%"; } else { runner_step = 0; thumb.style.top = runner_step + "%"; } } }; function containerMove() { step_size = container_step_size; container = defineContainer(); wrapper_height = define_wrapper_height(container); container_height = define_container_height(container); if (direction == 'down') { if (container_height - wrapper_height + step > step_size) { //- runner_marker = true; step -= step_size; container.style.transform = "translateY(" + step + "px)"; } else { runner_marker = false; container.style.transform = "translateY(-" + (container_height - wrapper_height) + "px)"; } } else if (direction == 'up') { if (step + step_size < 0) { runner_marker = true; step += step_size; container.style.transform = "translateY(" + step + "px)"; } else { runner_marker = false; step = 0; container.style.transform = "translateY(" + step + "px)"; } } } function scrollInit() { if (tab_index == "tab_1") { define_scroll_elems('.tab_1_content'); setRunnerSize(); } else if (tab_index == "tab_2") { define_scroll_elems('.tab_2_content'); setRunnerSize(); } else if (tab_index == "tab_3") { define_scroll_elems('.tab_3_content'); setRunnerSize(); } } scrollInit() var container_step_size = 300, /* Amount of scrolling pictures */ runner_step = 0, runner_marker = true, step = 0, direction; var wrapper_selector, container_selector, runner_selector; function define_scroll_elems(tab) { var selector = tab; wrapper_selector = selector; container_selector = selector + ' ' + '.scroll_container'; runner_selector = selector + ' ' + '.scroll_runner'; } /* Define Scroll */ function define_wrapper_height(elem) { return elem.parentElement.offsetHeight; }; function define_container_height(elem) { return elem.offsetHeight; }; function define_container_step_size() { return (100 * container_step_size / define_container_height(defineContainer())) }; function define_runner_step_size() { return define_container_step_size() }; function setRunnerSize() { container = defineContainer(); defineThumb().style.height = 100 / define_container_height(container) * define_wrapper_height(container) + "%"; console.log(define_container_height(container)); console.log(define_wrapper_height(container)); if(define_container_height(container) <= define_wrapper_height(container)) { defineThumb().parentElement.style.display = "none"} };<file_sep>/js/filter_allergens.js $('.allergens_category_block').on('click', function () { var full_block = $(this).parent().parent(); if ($(this).hasClass('marker')) { $(this).removeClass('marker'); $(this).find('.filter_delete').removeClass('active'); full_block.find('.allergens_category_title').removeClass('marker').find('.filter_delete').removeClass('active'); } else { $(this).addClass('marker'); $(this).find('.filter_delete').addClass('active'); if (full_block.find('.active').length == full_block.find('li').length) { full_block.find('.allergens_category_title').addClass('marker').find('.filter_delete').addClass('active'); } } }) $('.allergens_category_title').on('click', function () { if ($(this).hasClass('marker')) { $(this).removeClass('marker'); $(this).find('.filter_delete').removeClass('active'); $(this).parent().find('.allergens_category_block').each(function () { $(this).removeClass('marker'); $(this).find('.filter_delete').removeClass('active') }) } else { $(this).addClass('marker'); $(this).find('.filter_delete').addClass('active'); $(this).parent().find('.allergens_category_block').each(function () { $(this).addClass('marker'); $(this).find('.filter_delete').addClass('active') }) } }) $('.allergens_single').on('click', function () { if ($(this).hasClass('marker')) { $(this).removeClass('marker'); $(this).find('.filter_delete').removeClass('active'); } else { $(this).addClass('marker'); $(this).find('.filter_delete').addClass('active') } })<file_sep>/js/script.js /* !!! --- Preloader begins */ /* !!! Showing/hiding preloader begins */ /** * скрытие прелоадера */ showFirstStage(); function showFirstStage() { hidePreloader(); showMenu(); setProductHeight(); $('header').css('display', 'block') } function hidePreloader() { $('.preloader_main').animate({ opacity: 0, }, 300) setTimeout(function () { $('.preloader_main').css('display', 'none') }, 300) } /*$('.select_table_next').on('touchstart click', function () { showMenu(); hidePreloader(); setProductHeight(); $('header').css('display', 'block') })*/ /* Showing/hiding and calc sizing in preloader ends !!! */ /* !!! Langs in preloader begins */ var lang_img, lang_text; function changeLang(obj) { lang_img = $(obj).find('img').attr('src'); lang_text = $(obj).find('span').text(); $('.lang_wrapper .lang').find('img').attr('src', lang_img); $('.lang_wrapper .lang span').text(lang_text); } function hidePreloaderLangs() { $('.pop_langs').css('opacity', '0'); setTimeout(function () { $('.pop_langs').css('display', 'none') }, 500) } function showPreloaderLangs() { $('.pop_langs').css('display', 'block'); setTimeout(function () { $('.pop_langs').css('opacity', '1') }, 500) } /** * открываем модальное окно языков в прелоадере * @param {[[Type]]} '.lang_wrapper .lang').on('click' [[Description]] * @param {[[Type]]} function ( [[Description]] */ $('.lang_wrapper .lang').on('click', function () { showPreloaderLangs(); }) /** * скрываем модальное окно языков в прелоадере * @param {[[Type]]} '.internal_lang_wrapper .lang').on('click' [[Description]] * @param {[[Type]]} function ( [[Description]] */ $('.internal_lang_wrapper .lang').on('click', function () { changeLang(this); hidePreloaderLangs(); }) /* Langs in preloader ends !!! */ /* Preloader ends !!! --- */ /* !!! Menu begins */ function hideMenu() { setTimeout(function () { $('section.menu').css('display', 'none') }, 400) } function showMenu() { $('section.menu').css('display', 'block') } var cat_prod_width; /** * при скрытии прелоадера размер элементов - блюд вычисляется и ставится */ function setProductHeight() { cat_prod_width = $('.category.active .category_product').width(); $('.category_product').css('height', $('.category_product').width()) } /*$(window).on('resize', function () { // при изменении размеров окна размер элементов - блюд пересчитывается $('.category_product').css('height', $('.category.active .category_product').width()); cat_prod_width = $('.category.active .category_product').width() })*/ /** * переключение между табами меню * @param {[[Type]]} '.tab_1, .tab_2, .tab_3').on('click' [[Description]] * @param {[[Type]]} function ( [[Description]] */ $('.tab_1, .tab_2, .tab_3').on('click', function () { if (!$(this).hasClass('active')) { var prev = $(this).parent().find('>.active'); var tab_type = prev.attr('category'); var category = $(this).parent().parent().find('.category'); category.each(function () { if ($(this).attr('category') == tab_type) { $(this).css('display', 'none'); $(this).removeClass('active') } }) prev.removeClass('active'); $(this).addClass('active'); tab_type = $(this).attr('category'); category.each(function () { if ($(this).attr('category') == tab_type) { $(this).css('display', 'block'); $(this).addClass('active') } }) } }) //сворачивание категории продуктов при нажатии на заголовок $('.header_field').on('click', function () { if ($(this).hasClass('active')) { $(this).removeClass('active'); $(this).parent().find('.category_product').animate({ height: 0 }) } else { $(this).addClass('active'); $(this).parent().find('.category_product').animate({ height: cat_prod_width }) } }) //при нажатии кнопки "заказать" на продукте меняется отображение его var actual_product; $('.cat_order').on('click', function () { close_product(); actual_product = $(this).parent(); actual_product.addClass('active'); actual_product.find('.cat_calc').css('display', 'flex'); if (actual_product.find('.cat_veg')) { actual_product.find('.cat_veg').attr('hidden', '') } actual_product.find('.cat_close').removeAttr('hidden'); $(this).attr('hidden', ''); }) $('.cat_order').on('click', function () { if (actual_product.find('.cat_amount').text() < 1) { actual_product.find('.cat_amount').text('1'); } /*создание объекта*/ }) var close_product = function () { if (actual_product) { actual_product.removeClass('active'); actual_product.find('.cat_calc').css('display', 'none'); if (actual_product.find('.cat_veg')) { actual_product.find('.cat_veg').removeAttr('hidden') } actual_product.find('.cat_order').removeAttr('hidden'); actual_product.find('.cat_close').attr('hidden', ''); } } $('.cat_close').on('click', function () { close_product(); }) // работа минус плюс в товаре $('.cat_minus').on('click', function () { var amount_block = $(this).parent().find('.cat_amount'); var amount_num = amount_block.text(); if (+amount_num > 0) { amount_block.text(+amount_num - 1) } else close_product(); }) $('.cat_plus').on('click', function () { var amount_block = $(this).parent().find('.cat_amount'); var amount_num = amount_block.text(); amount_block.text(+amount_num + 1) }) /* Menu ends !!! */ /* ??? при открытии корзины, если количество в объекте = 0, то объект не выводить*/ /* !!! Cart begins */ // работа минус плюс в товаре $('.cart_minus').on('click', function () { var amount_block = $(this).parent().find('.cart_num'); var amount_num = amount_block.text(); if (+amount_num > 1) { amount_block.text(+amount_num - 1) } }) $('.cart_plus').on('click', function () { var amount_block = $(this).parent().find('.cart_num'); var amount_num = amount_block.text(); amount_block.text(+amount_num + 1) }) //open cart $('.footer_cart').on('click', function () { $('.full_cart').animate({ height: $(window).height() - $('header').innerHeight(), }) $('.full_cart_products').css('height', $(window).height() - $('header').innerHeight() - $('.full_cart_header').innerHeight() - $('.full_cart_payment').innerHeight() - $('.full_cart_footer').innerHeight()) productsTransfer(0); fixingFooterOnTop(); hideMenu(); }) function fixingFooterOnTop() { setTimeout(function () { $('footer').css('top', -($('.footer_menu').innerHeight() - $('header').innerHeight())); $('footer').css('bottom', 'auto') }, 400) } function fixingFooterOnBottom() { $('footer').css('top', 'auto'); $('footer').css('bottom', '0') } // choosing payment in cart $('.full_cart_payment >div').on('click', function () { if (!$(this).hasClass('active')) { $(this).parent().find('.active').removeClass('active'); $(this).addClass('active'); } }) // products smooth slide when cart is opening function productsTransfer(n) { var prod = document.querySelectorAll('.full_cart .full_cart_products .product'); setTimeout(function () { if (n < prod.length) { prod[n].style.left = "0"; productsTransfer(n + 1); } }, 200) } // delete product from cart $('.full_cart_products .cart_product_close').on('click', function () { $(this).parent().parent().animate({ opacity: 0, height: 0, }) }) // close cart $('.full_cart_close').on('click', function () { fixingFooterOnBottom(); $('.full_cart').animate({ height: 0, }) $('.full_cart .full_cart_products .product').css('left', '-100%'); showMenu(); }) //textarea_fill $('.product_comment textarea').on('blur', function () { checkTextarea(this) }) function checkTextarea(obj) { if ($(obj).attr('value') != 0) { $(obj).parent().find('img').css('display', 'block'); } else { $(obj).removeAttr('value'); $(obj).parent().find('img').css('display', 'none'); } } /* Cart ends !!! */ /* !!! Single product modal window begins */ //set height on custom scrolling container $('.scroll_block').css('height', $(window).height() - ($(window).width() * 0.13 * 1.3)); //set height on runner of custom scrolling container $('.menu .modal_trigger').on('click', function () { var full_list = $('.modal_single_product_ingr li').innerHeight() * $('.modal_single_product_ingr li:not(:empty)').length + parseInt($('.modal_single_product_ingr').css('padding-top')); var full_height = parseInt($('.modal_content.scroll_container').css('padding-top')) + $(".modal_single_product_title").innerHeight() + $(".modal_single_product_weight").innerHeight() + $('.scroll_container .empty').innerHeight() + full_list; var runner_height = 100 / full_height * $(window).height() + '%'; $('.scroll_runner').css('height', runner_height); }) //show allergens modal window $('.single_page_allergen').on('click', function () { $('.pop_allergens').css('display', 'block'); setTimeout(function () { $('.pop_allergens').css('opacity', '1') }, 500) }) //hide allergens modal window $('.allerg_close').on('click', function () { $('.pop_allergens').css('opacity', '0'); setTimeout(function () { $('.pop_allergens').css('display', 'none') }, 500) }) /* Single product modal window ends !!! */ /* !!! Filters begins */ /* Set value of range in special field */ $('.slider_price').parent().find('.total .total_num').text($('.slider_price').attr('value') + '.00') $('.slider_price').on('change', function () { $(this).parent().find('.total .total_num').text($(this).attr('value') + '.00') }) $('.slider_kcal').parent().find('.total .total_num').text($('.slider_kcal').attr('value')) $('.slider_kcal').on('change', function () { $(this).parent().find('.total .total_num').text($(this).attr('value')) }) $('.filter_button').on('click', showFilter); $('.filters_close').on('click', hideFilter); $('.header_logo img').on('click', hideFilter); function showFilter() { $('.filter_button').addClass('active'); $('.filters').animate({ height: $(window).innerHeight() }); hideMenu(); } function hideFilter() { showMenu(); $('.filters').animate({ height: 0 }, 400); setTimeout(function () { $('.filter_button').removeClass('active'); }, 400); $('body').removeClass('hidden') } $('.filter_button_ingr').on('click', function () { slideFilterTo('.filters_ingridients'); $('.filters_ingridients').css('height', $('.filters_ingridients').innerHeight()) }) $('.filter_button_alerg').on('click', function () { slideFilterTo('.filters_allergens'); $('.filters_allergens').css('height', $('.filters_allergens').innerHeight()) }) var filters_section_class; /** * Slide ingridients and allergens to main screen */ function slideFilterTo(classname) { filters_section_class = classname; $(filters_section_class).css('left', '0'); $('.filters_footer').css('left', '0'); } $('.filters_footer_back').on('click', slideFilterFrom) /** * Slide ingridients and allergens back */ function slideFilterFrom() { $(filters_section_class).css('left', '100%'); $('.filters_footer').css('left', '100%'); } $('.filters_title, .filters_toggle').on('click', function () { toggleList(this) }) /** * Slide down and slide up list of ingridients and allergens * @param {[[Type]]} obj [[Description]] */ function toggleList(obj) { var li = $(obj).parent().find('li'); if ($(obj).parent().find('ul').hasClass('active')) { $(obj).parent().find('ul').removeClass('active'); $(obj).parent().find('ul').animate({ height: 0, }) $(obj).parent().find('.filters_toggle img').css('transform', 'rotate(180deg)'); } else { $(obj).parent().find('ul').addClass('active'); $(obj).parent().find('ul').animate({ height: li.length * li.innerHeight(), }); $(obj).parent().find('.filters_toggle img').css('transform', 'rotate(0deg)'); } } $('.filters_allergens .filter_item_name').on('click', function () { toggleAllergens(this) }) /** * Add and remove allergens * @param {[[Type]]} obj [[Description]] */ function toggleAllergens(obj) { if ($(obj).parent().find('.filter_delete').hasClass('active')) { $(obj).parent().find('.filter_delete').animate({ opacity: 0 }) $(obj).parent().find('.filter_delete').removeClass('active') } else { $(obj).parent().find('.filter_delete').animate({ opacity: 1 }) $(obj).parent().find('.filter_delete').addClass('active') } } /* Filters ends !!! */ /* !!! Sidebar begins */ $('.menu_button').on('click', function () { console.log('dsf'); slideSidebarTo(); console.log($('.sidebar_clickable_1 + p').innerHeight()); calcSidebarParagraphsHeight(); setHeightToParagraph(0); setDefaultImg(); removeClassActiveFromLi() }) function slideSidebarTo() { // $('.sidebar_wrapper').css('display', 'block'); $('.sidebar_wrapper .shim').animate({ opacity: 1 }); $('.sidebar_wrapper .sidebar').addClass('active'); } $('.sidebar_wrapper .shim').on('click', slideSidebarFrom) function slideSidebarFrom() { $('.sidebar_wrapper .sidebar').removeClass('active'); $('.sidebar_wrapper .shim').animate({ opacity: 0 }); $('body').removeClass('hidden'); setTimeout(function () { // $('.sidebar_wrapper').css('display', 'none') }, 400) } /* Set parameters to default */ function setHeightToParagraph(height) { $('.sidebar ul li + p').css('height', height) } function setDefaultImg() { //put on sidebar open - work $('.sidebar ul li.active.sidebar_clickable_1 img').attr('src', $('.sidebar ul li.active.sidebar_clickable_1 img').attr('data-img')); $('.sidebar ul li.active.sidebar_clickable_2 img').attr('src', $('.sidebar ul li.active.sidebar_clickable_2 img').attr('data-img')); } function removeClassActiveFromLi() { if ($('.sidebar ul li.active')) { $('.sidebar ul li.active').removeClass('active') } } /*calc p height*/ var p_1_height, p_2_height; function calcSidebarParagraphsHeight() { if (!p_1_height && !p_2_height) { p_1_height = $('.sidebar_clickable_1 + p').innerHeight(); p_2_height = $('.sidebar_clickable_2 + p').innerHeight(); } } /* Toggle li */ $('.sidebar_clickable_1, .sidebar_clickable_2').on('click', function () { toggleSidebarList(this) }) function toggleSidebarList(obj) { if ($(obj).parent().find('.active')) { if ($(obj).hasClass('active')) { hideSidebarList(); removeClassActiveFromLi(); $(obj).find('img').attr('src', $(obj).find('img').attr('data-img')); } else { var img = $(obj).parent().find('.active img'); img.attr('src', img.attr('data-img')); hideSidebarList(); removeClassActiveFromLi(); openLi(obj); } } else { openLi(obj); } } function openLi(obj) { $(obj).addClass('active'); $(obj).find('img').attr('src', $(obj).find('img').attr('data-img-active')); showSidebarList(obj) } function showSidebarList(obj) { //put when li opening but after detele and add active if ($(obj).hasClass('sidebar_clickable_1')) $('.sidebar ul li.active + p').animate({ height: p_1_height }) else { $('.sidebar ul li.active + p').animate({ height: p_2_height }) } } function hideSidebarList() { $('.sidebar ul li.active + p').animate({ height: 0 }) } /* Sidebar ends !!! */ /* !!! Header begins */ var header_state = true, scroll_direction; $(window).on('scroll', function (e) { calcScrollDirection(); if (window.pageYOffset > window.innerHeight / 2) { console.log(scroll_direction) if (scroll_direction == 'to bottom' && header_state) { headerSlideUp(); header_state = false; } else if (scroll_direction == 'to top' && !header_state) { headerSlideDown(); header_state = true; } } }) var coord_1 = window.pageYOffset, coord_2 = 1; function calcScrollDirection() { coord_2 = window.pageYOffset; if ((coord_2 - coord_1 > 10)) { scroll_direction = 'to bottom'; coord_1 = coord_2 } else if ((coord_1 - coord_2 > 10)) { scroll_direction = 'to top'; coord_1 = coord_2 } /*else { console.log('something wrong' + ' ' + coord_2 + ' ' + coord_1) }*/ } var header_full_height = $('.main_header').innerHeight() + $('.main_header .header_logo img').innerHeight() / 2; function headerSlideUp() { $('.main_header').animate({ top: -header_full_height, }) } function headerSlideDown() { $('.main_header').animate({ top: 0, }) } /* Header ends !!! */ /* !!! Range relativity begins */ $('input.slider_price').each(function () { setRightRange(this) }) $('input.slider_kcal').each(function () { setRightRange(this) }) function setRightRange(obj) { var value = +$(obj).attr('value'); var active_bar = $(obj).parent().find('.selected-bar'); var min_value = +active_bar.parent().parent().find('.scale span:first-of-type ins').text(); var max_value = +active_bar.parent().parent().find('.scale span:last-of-type ins').text(); var pointer = active_bar.parent().find('.pointer.high'); var length = max_value - min_value; var offset = ((100 * value) / length) + '%'; active_bar.width(offset); pointer.css('left', offset) } /* Range relativity ends !!! */ $('.footer_cart').on('click', function() { if (!header_state) { headerSlideDown(); header_state = true; } })<file_sep>/js/custom_scroll - копия.js function () { if (tab_index = "tab_1") {} else if (tab_index = "tab_2") {} else if (tab_index = "tab_3") {} } function scrollInit(wrapper_sel) { var selector = DefineScroll(wrapper_sel); wrapper_selector = selector; container_selector = selector + ' ' + '.scroll_container'; runner_selector = selector + ' ' + '.scroll_runner'; setRunnerSize(); addScrollListeners(); } var wrapper_selector, container_selector, runner_selector; var DefineScroll = function (wrapper_sel) { if (wrapper_sel === undefined) { return '.scroll_container_wrapper' } else { return wrapper_sel } } var container_step_size=300, runner_step = 0, runner_marker = true, step = 0; function addScrollListeners() { var listeners = ['wheel', 'keydown', 'touchstart', 'touchmove', 'touchend']; for (var i = 0; i < listeners.length; i++) { window.addEventListener(listeners[i], function (e) { pageScroll(e); }) } }; function pageScroll(e) { direction = ScrollDirection.defineScrollDirection(e); containerMove(); runnerMove(); } function container () { return document.querySelector(container_selector) }; function thumb { return container().parentElement.querySelector(runner_selector) }; function wrapper_height (elem) { return elem.parentElement.offsetHeight; }; function container_height (elem) { return elem.offsetHeight; }; function container_step_size () { return (100 * container_step_size / this.container_height(container())) }; function runner_step_size () { return this.container_step_size() }; function setRunnerSize () { container = container(); console.log(this.wrapper_height(container)) thumb().style.height = 100 / this.container_height(container) * this.wrapper_height(container) + "%"; }; var ScrollDirection = { getKeyCode: function (e) { if (e.keyCode == 40) { return 'down' } else if (e.keyCode == 38) { return 'up' } }, getTouchCoord: function (e) { return e.touches[0].clientY }, getSwipeDirection: function (e) { if (e.type == 'touchstart') { this.firstCoord = this.getTouchCoord(e); } else if (e.type == 'touchmove') { this.lastCoord = this.getTouchCoord(e); } else if (e.type == 'touchend') { if (this.lastCoord - this.firstCoord > 10) { return 'up'; } else if (this.lastCoord - this.firstCoord < -10) { return 'down'; } } }, getWheelDirection: function (e) { if (e.deltaY > 0) { return 'down' } else if (e.deltaY < 0) { return 'up' } }, defineScrollDirection: function (e) { if (e.type == "keydown") { return this.getKeyCode(e); } else if (e.type == "touchstart" || e.type == "touchmove" || e.type == "touchend") { return this.getSwipeDirection(e); } else if (e.type == "wheel") { return this.getWheelDirection(e); } }, } /* Elements moving */ function runnerMove () { var direction = direction, step_size = container_step_size(), runner_marker = runner_marker, thumb = thumb(), runner_step_size = runner_step_size(); if (direction == 'down') { //- if (runner_marker) { this.runner_step += runner_step_size; thumb.style.top = this.runner_step + "%"; } else { this.runner_step = (100 - parseFloat(thumb.style.height)); thumb.style.top = this.runner_step + "%"; } } else if (direction == 'up') { //+ if (runner_marker) { this.runner_step -= runner_step_size; thumb.style.top = this.runner_step + "%"; } else { this.runner_step = 0; thumb.style.top = this.runner_step + "%"; } } }; function containerMove () { var direction = this.direction, step_size = this.container_step_size, container = this.container(), wrapper_height = this.wrapper_height(container), container_height = this.container_height(container); if (direction == 'down') { if (container_height - wrapper_height + this.step > step_size) { //- this.runner_marker = true; this.step -= step_size; container.style.transform = "translateY(" + this.step + "px)"; } else { this.runner_marker = false; container.style.transform = "translateY(-" + (container_height - wrapper_height) + "px)"; } } else if (direction == 'up') { if (this.step + step_size < 0) { this.runner_marker = true; this.step += step_size; container.style.transform = "translateY(" + this.step + "px)"; } else { this.runner_marker = false; this.step = 0; container.style.transform = "translateY(" + this.step + "px)"; } } };<file_sep>/js/external_scripts.js /* !!! Settings of external modules begins */ // настройки слайдера $(document).ready(function () { $('.slider').slick({ autoplay: true, dots: true, mobileFirst: true, swipeToSlide: true, }); }); // бегунок в фильтрах $('.slider_price').jRange({ from: 10, to: 100, step: 1, scale: [10, 100], format: '%s', width: "100%", theme: "theme-red", showLabels: false, }); $('.slider_kcal').jRange({ from: 50, to: 2000, step: 50, scale: [50, 2000], format: '%s', width: "100%", theme: "theme-red", showLabels: false, }); /* Settings of external modules ends !!! */<file_sep>/js/_custom_scroll.js ; (function () { var step_size = 300; /* Amount of scrolling pictures */ /* Define scroll container */ var container; function defineScrollContainer(e) { if (document.querySelector('.scroll_container')) { container = e.target; while (!container.classList.contains('scroll_container')) { if (container.tagName == 'BODY') { break } container = container.parentElement; } if (container.tagName == 'BODY') { container = false } } } /* Define container height */ function defineContainerHeight(elem) { return elem.offsetHeight; } /* Define wrapper height */ function defineWrapperHeight(elem) { return elem.parentElement.offsetHeight; } var containers = document.querySelectorAll('.scroll_container'); for (var i = 0; i < containers.length; i++) { // Set size of scroll runner var runner = containers[i].parentElement.querySelector('.scroll_runner'); function setRunnerHeight() { runner.style.height = 100 / defineContainerHeight(containers[i]) * defineWrapperHeight(containers[i]) + "%"; } setRunnerHeight() } /* Set runner sizes on all containers var containers = document.querySelectorAll('.scroll_container'); for (var i = 0; i < containers.length; i++) { // Set size of scroll runner var runner = containers[i].parentElement.querySelector('.scroll_runner'); function setRunnerHeight() { runner.style.height = 100 / defineContainerHeight(containers[i]) * defineWrapperHeight(containers[i]) + "%"; } setRunnerHeight() }*/ /* Manage container */ var step = 0; function containerMove(step_size) { if (direction == 'to_top') { //- if (defineContainerHeight(container) - defineWrapperHeight(container) + step > step_size) { //- runner_marker = true; step -= step_size; container.style.transform = "translateY(" + step + "px)"; } else { runner_marker = false; container.style.transform = "translateY(-" + (defineContainerHeight(container) - defineWrapperHeight(container)) + "px)"; } } else if (direction == 'to_bottom') { //+ if (step + step_size < 0) { runner_marker = true; step += step_size; container.style.transform = "translateY(" + step + "px)"; } else { runner_marker = false; step = 0; container.style.transform = "translateY(" + step + "px)"; } } } /* Manage scroll runner */ var runner_step = 0, runner_marker = true; function runnerMove(step_size) { var runner = container.parentElement.querySelector('.scroll_runner'), runner_step_size = 100 / defineContainerHeight(container) * step_size; if (direction == 'to_top') { //- if (runner_marker) { runner_step += runner_step_size; runner.style.top = runner_step + "%"; } else { runner_step = (100 - parseFloat(runner.style.height)); runner.style.top = runner_step + "%"; } } else if (direction == 'to_bottom') { //+ if (runner_marker) { runner_step -= runner_step_size; runner.style.top = runner_step + "%"; } else { runner_step = 0; runner.style.top = runner_step + "%"; } } } /* Catch touch */ function containerTouch() { document.addEventListener('touchstart', takeCoords); document.addEventListener('touchmove', takeCoords); document.addEventListener('touchend', takeCoords); } var x1, x2; function takeCoords(e) { if ($('.scroll_container').height()) { defineScrollContainer(e); if (container) { if (e.type == "touchstart") { x1 = e.touches[0].clientY; } else if (e.type == "touchmove") { x2 = e.touches[0].clientY; } else if (e.type == "touchend") { calcTouchDifference(e); } } } } var direction; function calcTouchDifference(e) { direction = null; var difference = x1 - x2; if (x1 > x2 && difference > 10 && x2 !== 0) { direction = 'to_top'; x1 = 0; x2 = 0; } else if (x2 > x1 && difference < -10) { direction = 'to_bottom'; x1 = 0; x2 = 0; } if (direction !== null) { containerMove(step_size); runnerMove(step_size); } } containerTouch() })();
bab37a4404d8775504708bbeb6add3273c92be72
[ "JavaScript" ]
6
JavaScript
crevanwoo/enchilada
ba5d4cf218e1d276571fb4108372e7be44c52f9c
9a16d050e850bec1aa67e960046f0e34c01f8e2e
refs/heads/main
<file_sep># homework_sankey ### code 里放了代码, csv 表格文件存了数据 + 代码和csv 要放同一个目录下 + .py可以用python 命令运行 + .ipynb 是jupyter notebook特有文件格式, 可以在notebook 网页上导入 + .html 可以用chrome 直接打开 ### 参考文章 + sankey 图的介绍[绘制桑基图(sankey diagram):快速追踪目标变化的可视工具 | 一起大数据-技术文章心得 (17bigdata.com)](http://www.17bigdata.com/绘制桑基图sankey-diagram:快速追踪目标变化的可视工具/) + 常见的python 可视化库[这5款Python可视化神器,总有一款适合你! - 简书 (jianshu.com)](https://www.jianshu.com/p/1ac6d36459ed) > 1. Matplotlib 最常见,函数图像 > 2. pyecharts 基于百度开源的Echarts开发的Python版可视化工具 web集成支持 > 3. plotly.py更偏重于交互式图形可视化。plotly.py是基于plotly.js进行开发,它继承了plotly.js的诸多优点,例如,可以绘制科学图表、SVG地图、3D图形、财务图表等丰富图形。 + 偏门: Power BI 数据分析软件制图 <file_sep>#!/usr/bin/env python # coding: utf-8 # In[35]: import pandas as pd # import pands to handle csv from pyecharts.charts import Page,Sankey from pyecharts import options as opts import collections # try to use OrderedDict # In[36]: data = pd.read_csv('sankey_exercise1.csv',sep = ';',encoding = 'utf-8',header=None) # data and data stream(hidden stored) are stored in this csv print(data) # In[37]: nodes = [] nodes.append({'name':'A1'}) for i in data[0].unique(): dictnode = {} dictnode = collections.OrderedDict() dictnode['name'] = i nodes.append(dictnode) print(nodes) # In[38]: links = [] for i in data.values: diclink = {} diclink = collections.OrderedDict() diclink['source'] = i[0] diclink['target'] = i[1] diclink['value'] = i[2] links.append(diclink) print(links) # In[39]: c = (Sankey().add("scale/tone",nodes,links,linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source",type_="dotted"),label_opts=opts.LabelOpts(position="right",),).set_global_opts(title_opts=opts.TitleOpts(title="sankey_exercise1"))) c.render('result0430.html')
11224383acbb86b516e4c1b1374fc9998413f217
[ "Markdown", "Python" ]
2
Markdown
FXHuang/homework_sankey
d1c0e356cfb59a2310d6b5fff3f1f65af4d79303
b1beefa16683ea184df7c703adf7f44220cafcb1
refs/heads/master
<repo_name>CSheesley/sweater_weather<file_sep>/app/models/backgrounds.rb class Backgrounds def initialize(search_info) @search_info = search_info end def list data = PhotoService.new(@search_info).api_response data[:results].map do |image| image_hash = {} image.each do |key, value| image_hash[:unsplash_id] = image[:id] image_hash[:description] = image[:description] image_hash[:urls] = image[:urls] end image_hash end end end <file_sep>/app/models/user.rb class User < ApplicationRecord validates_presence_of :email validates_uniqueness_of :email has_many :favorites has_secure_password def generate_api_key self.update_attributes(api_key: SecureRandom.urlsafe_base64) end end <file_sep>/app/controllers/api/v1/forecast_controller.rb class Api::V1::ForecastController < ApplicationController def show weather_data = WeatherData.new(params[:location]) render json: WeatherDataSerializer.new(weather_data).to_hash end end <file_sep>/app/controllers/api/v1/users_controller.rb class Api::V1::UsersController < ActionController::API def create user = User.new(user_params) if user.save user.generate_api_key render status: 201, json: { api_key: user.api_key } else render status: 400, json: { invalid: user.errors.full_messages.join(", ") } end end private def user_params params.permit(:email, :password, :password_confirmation) end end <file_sep>/app/controllers/api/v1/favorites_controller.rb class Api::V1::FavoritesController < ApiController before_action :user def create city = City.find_or_create_city(search_location) Favorite.create(user_id: user.id, city_id: city.id, name: city.name) render status: 201, json: { outcome: "Successfully Added" } end def index render json: FavoritesSerializer.new(user.favorites).to_hash end def destroy to_remove = user.favorites.find_by(city_id: favorite_to_remove.id) to_remove.destroy render json: FavoritesSerializer.new(user.favorites).to_hash end private def search_location search = favorite_params[:location] formatted = search.downcase.delete(" ") end def favorite_params params.permit(:location, :api_key) end def favorite_to_remove split = destroy_params[:location].split(",") city_input = split[0] state_input = split[1].delete(" ") city = City.find_by(name: city_input, state_abrev: state_input) end def destroy_params params.permit(:location, :api_key) end end <file_sep>/spec/services/dark_sky_service_spec.rb require 'rails_helper' describe 'DarkSkyService' do describe 'Instance Methods' do context '#all_info' do it 'returns all weather data' do latitude = 39.7392 longitude = -104.9902 weather_info = DarkSkyService.new(latitude, longitude).full_info expect(weather_info[:currently].present?).to eq(true) expect(weather_info[:hourly][:data].count).to eq(50) expect(weather_info[:daily][:data].count).to eq(8) end end end end <file_sep>/app/services/dark_sky_service.rb class DarkSkyService def initialize(latitude, longitude) @lat = latitude @long = longitude end def full_info get_json end private def get_json response = conn.get JSON.parse(response.body, symbolize_names: true) end def conn Faraday.new("https://api.darksky.net/forecast/#{ENV['DARK_SKY_API_KEY']}/#{@lat},#{@long}") do |f| f.params['exclude']= "minutely,alerts,flags" f.adapter Faraday.default_adapter end end end <file_sep>/spec/models/cities_spec.rb require 'rails_helper' describe City, type: :model do describe 'Validations' do it { should validate_presence_of :search_name } it { should validate_presence_of :latitude } it { should validate_presence_of :longitude } it { should validate_presence_of :name } it { should validate_presence_of :state_abrev } it { should validate_presence_of :country } end describe 'Relationships' do it {should have_many :favorites } end describe 'Class Methods' do context '::find_or_create_city()' do it 'finds or creates a new city based on search input info' do search_name = "denver,co" expect(City.count).to eq(0) City.find_or_create_city(search_name) expect(City.count).to eq(1) expect(City.first.name).to eq("Denver") expect(City.first.state_abrev).to eq("CO") City.find_or_create_city(search_name) #finds existing city - no new city is added to table expect(City.count).to eq(1) end end end describe 'Instance Methods' do context '#find_or_create_background' do it 'finds a background_img for a city if it does not already have one' do denver = City.create( { search_name: "denver,co", latitude: 39.7392, longitude: 104.9902, name:"Denver", state_abrev: "CO", country: "United States", background_img: nil } ) expect(denver.background_img).to eq(nil) new_image = denver.find_or_create_background expect(denver.background_img).to eq(new_image) expect(denver.background_img.class).to eq(String) end it 'does not creates a background_img for a city which already has one' do denver = City.create( { search_name: "denver,co", latitude: 39.7392, longitude: 104.9902, name:"Denver", state_abrev: "CO", country: "United States", background_img: "fake-phot-url" } ) expect(denver.background_img).to eq("fake-phot-url") expect(denver.background_img.present?).to eq(true) denver.find_or_create_background expect(denver.background_img).to eq("fake-phot-url") end end end end <file_sep>/app/serializers/backgrounds_serializer.rb class BackgroundsSerializer def initialize(background_data) @background_data = background_data end def to_hash { data: @background_data } end end <file_sep>/app/services/location_service.rb class LocationService def initialize(location) @location = location end def lat lat_long[:lat].truncate(4) end def long lat_long[:lng].truncate(4) end def lat_long results = get_json[:results][0] results[:geometry][:location] end def details info = get_json[:results][0] info[:address_components] end private def get_json response = conn.get JSON.parse(response.body, symbolize_names: true) end def conn Faraday.new('https://maps.googleapis.com/maps/api/geocode/json') do |f| f.params['key']=ENV['GOOGLE_API_KEY'] f.params['address']=@location f.adapter Faraday.default_adapter end end end <file_sep>/spec/requests/api/v1/favorites/remove_favorite_spec.rb require 'rails_helper' describe 'DELETE /api/v1/favorites' do context 'with a valid api key' do it 'removes a city from the list of favorites' do user = create(:user, api_key: "abc123") denver = City.find_or_create_city("denver,co") golden = City.find_or_create_city("golden,co") user.favorites.create(city_id: denver.id) user.favorites.create(city_id: golden.id) expect(user.favorites.count).to eq(2) delete_body = { "location": "Denver, CO", # If you decide to store cities in your database you can send an id if you prefer "api_key": "abc123" } delete '/api/v1/favorites', params: delete_body delete_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(200) expect(delete_response.count).to eq(1) expect(delete_response[0][:location]).to eq("Golden, CO") expect(user.favorites.count).to eq(1) end end context 'with an invalid api key' do it 'does not remove a city from the favorites, and a 401 code is returned' do user = create(:user, api_key: "abc123") denver = City.find_or_create_city("denver,co") golden = City.find_or_create_city("golden,co") user.favorites.create(city_id: denver.id) user.favorites.create(city_id: golden.id) expect(user.favorites.count).to eq(2) delete_body = { "location": "Denver, CO", # If you decide to store cities in your database you can send an id if you prefer "api_key": "xyz123" } delete '/api/v1/favorites', params: delete_body delete_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(401) expect(delete_response[:invalid]).to eq("Unauthorized") expect(user.favorites.count).to eq(2) end end end <file_sep>/spec/services/location_service_spec.rb require 'rails_helper' describe 'LocationService', type: :service do describe 'Instance Methods' do context '#lat_long' do it 'returns original API data in the form of a hash' do location = "denver,co" lat_long = LocationService.new(location).lat_long expect(lat_long.class).to eq(Hash) expect(lat_long[:lat]).to eq(39.7392358) expect(lat_long[:lng]).to eq(-104.990251) end end context '#lat' do it 'returns a latitude measurement formatted to four decimals' do location = "denver,co" latitude = LocationService.new(location).lat expect(latitude).to eq(39.7392) end end context '#long' do it 'returns a longitude measurement formatted to four decimals' do location = "denver,co" longitude = LocationService.new(location).long expect(longitude).to eq(-104.9902) end end end end <file_sep>/app/controllers/api/v1/backgrounds_controller.rb class Api::V1::BackgroundsController < ApplicationController def show background_data = Backgrounds.new(params[:location]).list render json: BackgroundsSerializer.new(background_data).to_hash end end <file_sep>/app/models/weather_data.rb class WeatherData def initialize(search_info) @search_info = search_info end def location @_city ||= City.find_or_create_city(@search_info) @_city.find_or_create_background return @_city end def api_weather_data @_data ||= DarkSkyService.new(location.latitude, location.longitude).full_info end def currently api_weather_data[:currently] end def today api_weather_data[:daily][:data][0] end def hourly api_weather_data[:hourly][:data][1..8] end def daily api_weather_data[:daily][:data][1..5] end def hourly_formatted hourly.map do |hour| hour_hash = {} hour.each do |key, value| hour_hash[:time] = hour[:time] hour_hash[:hour] = Time.at(hour[:time]).strftime("%l%p") hour_hash[:temp] = hour[:temperature].round end hour_hash end end def rest_of_week_formatted daily.map do |day| daily_hash = {} day.each do |key, value| daily_hash[:date] = day[:time] daily_hash[:day] = Time.at(day[:time]).strftime("%A") daily_hash[:icon] = day[:icon] daily_hash[:chance_precip] = "#{(day[:precipProbability] * 100).round}%" daily_hash[:precip_type] = day[:precipType] daily_hash[:high] = day[:temperatureHigh].round daily_hash[:low] = day[:temperatureLow].round end daily_hash end end end <file_sep>/app/models/city.rb class City < ApplicationRecord validates_presence_of :search_name, :latitude, :longitude, :name, :state_abrev, :country has_many :favorites def self.find_or_create_city(location) if City.find_by(search_name: location) return City.find_by(search_name: location) else city_info = LocationService.new(location) City.create(search_name: location, latitude: city_info.lat, longitude: city_info.long, name: city_info.details[0][:short_name], state_abrev: city_info.details[2][:short_name], country: city_info.details[3][:long_name]) end end def find_or_create_background unless self.background_img.present? background = PhotoService.new(self.search_name) self.background_img = background.city_image end end def location "#{name}, #{state_abrev}" end def weather_data WeatherData.new(search_name) end end <file_sep>/spec/requests/api/v1/favorites/list_favorites_spec.rb require 'rails_helper' describe 'GET /api/v1/favorites' do context 'with a valid api key' do it 'returns a list of favorite locations and current weather info' do user = create(:user, api_key: "abc123") denver = City.find_or_create_city("denver,co") golden = City.find_or_create_city("golden,co") user.favorites.create(city_id: denver.id) user.favorites.create(city_id: golden.id) get_body = { "api_key": "abc123" } get '/api/v1/favorites', params: get_body favorites_response = JSON.parse(response.body, symbolize_names: true) first_fav = favorites_response.first expect(response.status).to eq(200) expect(favorites_response.count).to eq(2) expect(first_fav[:location]).to eq("Denver, CO") expect(first_fav[:current_weather].present?).to eq(true) end end context 'with an invalid api key' do it 'no favorites are shown, and a 401 status code is returned' do user = create(:user, api_key: "abc123") denver = City.find_or_create_city("denver,co") golden = City.find_or_create_city("golden,co") user.favorites.create(city_id: denver.id) user.favorites.create(city_id: golden.id) get_body = { "api_key": "xyz123" } get '/api/v1/favorites', params: get_body error_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(401) expect(error_response[:invalid]).to eq("Unauthorized") end end end <file_sep>/spec/requests/api/v1/backgrounds/image_spec.rb require 'rails_helper' describe 'GET /api/v1/backgrounds' do it 'returns a background image for a location' do get '/api/v1/backgrounds?location=denver,co' backgrounds = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(200) expect(backgrounds.class).to eq(Hash) expect(backgrounds[:data].class).to eq(Array) expect(backgrounds[:data].count <= 10).to eq(true) expected_keys = :unsplash_id, :description, :urls expect(backgrounds[:data].first.keys).to eq(expected_keys) end end <file_sep>/spec/services/photo_service_spec.rb require 'rails_helper' describe 'PhotoService', type: :service do describe 'Instance Methods' do context 'city_img' do it 'returns a URL for a background image based on search location' do denver = City.create( { search_name: "denver,co", latitude: 39.7392, longitude: 104.9902, name:"Denver", state_abrev: "CO", country: "United States", background_img: nil } ) city_name = denver.name image = PhotoService.new(city_name).city_image expect(image.class).to eq(String) expect(image).to include("https://images.unsplash.com/photo") end end end end <file_sep>/app/services/photo_service.rb class PhotoService def initialize(search_info) @city_name = search_info.split(",")[0] end def api_response get_json(@city_name) end def city_image image_data = get_json(@city_name) image_data[:results][0][:urls][:regular] end private def get_json(search_info) response = conn.get("?query=#{search_info}") output = JSON.parse(response.body, symbolize_names: true) end def conn Faraday.new("https://api.unsplash.com/search/photos") do |f| f.params['client_id']=ENV['UNSPLASH_API_KEY'] f.params['orientation']='portrait' f.params['page']=1 f.adapter Faraday.default_adapter end end end <file_sep>/app/controllers/api_controller.rb class ApiController < ActionController::API def user user = User.find_by(api_key: favorite_params[:api_key]) unless user render status: 401, json: { invalid: "Unauthorized" } else user end end end <file_sep>/db/migrate/20190621212928_change_cities_id_name.rb class ChangeCitiesIdName < ActiveRecord::Migration[5.2] def change rename_column :favorites, :cities_id, :city_id end end <file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Favorite.destroy_all City.destroy_all User.destroy_all user = User.create(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', api_key: 'abc123') cities = City.create( { search_name: "denver,co", latitude: 39.7392, longitude: -104.9902, name:"Denver", state_abrev: "CO", country: "United States" } ) <file_sep>/spec/requests/api/v1/favorites/add_favorite_spec.rb require 'rails_helper' describe 'POST /api/v1/favorites' do context 'with a valid api_key' do it 'adds a favorite for the user, and returns a 201 status code' do user = create(:user, api_key: "abc123") expect(user.favorites.count).to eq(0) post_body = { "location": "Denver, CO", "api_key": "abc123" } post '/api/v1/favorites', params: post_body favorite_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(201) expect(favorite_response[:outcome]).to eq("Successfully Added") expect(user.favorites.count).to eq(1) end end context 'with an invalid api_key' do it 'no favorites are added, and a 401 status code is returned' do user = create(:user, api_key: "abc123") expect(user.favorites.count).to eq(0) post_body = { "location": "Denver, CO", "api_key": "xyz123" } post '/api/v1/favorites', params: post_body favorite_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(401) expect(favorite_response[:invalid]).to eq("Unauthorized") expect(user.favorites.count).to eq(0) end end end <file_sep>/spec/requests/api/v1/users/account_creation_spec.rb require 'rails_helper' describe 'POST /api/v1/users' do context 'with valid information' do it 'creates an account for a user, and provides an api_key in the response' do post_body = { "email": "<EMAIL>", "password": "<PASSWORD>", "password_confirmation": "<PASSWORD>" } post '/api/v1/users', params: post_body creation_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(201) expect(creation_response[:api_key].present?).to eq(true) end end context 'with invalid information' do it 'returns an error message and a 400 code' do user = create(:user, email: "<EMAIL>") post_body = { "email": "<EMAIL>", "password": "<PASSWORD>", "password_confirmation": "<PASSWORD>" } post '/api/v1/users', params: post_body error_response = JSON.parse(response.body, symbolize_names: true) error_message = "Email has already been taken, Password confirmation doesn't match Password" expect(response.status).to eq(400) expect(error_response[:invalid]).to eq(error_message) end end end <file_sep>/spec/models/user_spec.rb require 'rails_helper' describe User, type: :model do describe 'Validations' do it { should validate_presence_of :email } it { should validate_uniqueness_of :email } end describe 'Relationships' do it { should have_many :favorites } end describe 'Instance Methods' do context '#generate_api_key' do it 'generates an api_key for a user' do user = User.create(email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>" ) expect(user.api_key.present?).to eq(false) user.generate_api_key expect(user.api_key.present?).to eq(true) expect(user.api_key.class).to eq(String) end end end end <file_sep>/README.md # Sweater Weather This is a solo project completed at the Turing School of Software & Design - as the last project of Module 3 (Professional Rails Applications). The goal of this project was to build out a number of API endpoints which would provide the necessary information for creating a mock web page (below). In order to do achieve this, multiple external API's were called, Models and PORO's were created, and custom Serializers were used. ![mock](mock_webpage.png) The original project link can be found here: https://backend.turing.io/module3/projects/sweater_weather ## Endpoints *An api key is created and given when a user creates an account. That key is only needed for account specific requests* Weather for a city: **GET** `https://sweater-weather-3400.herokuapp.com/api/v1/forecast?location=denver,co` Background images for a city: **GET** `https://sweater-weather-3400.herokuapp.com/api/v1/backgrounds?location=denver,co` Creating an account: **POST** `https://sweater-weather-3400.herokuapp.com/api/v1/users` ``` Example body: { "email": "<EMAIL>", "password": "<PASSWORD>", "password_confirmation": "<PASSWORD>" } ``` Logging in: **POST** `https://sweater-weather-3400.herokuapp.com/api/v1/sessions` ``` Example body: { "email": "<EMAIL>", "password": "<PASSWORD>" } ``` Adding Favorite Locations: **POST** `https://sweater-weather-3400.herokuapp.com/api/v1/favorites` ``` Example body: { "location": "Denver, CO", "api_key": "jgn983hy48thw9begh98h4539h4" } ``` Listing Favorite Locations: **GET** `https://sweater-weather-3400.herokuapp.com/api/v1/favorites` ``` Example body: { "api_key": "jgn983hy48thw9begh98h4539h4" } ``` Removing Favorite Locations: **DELETE** `https://sweater-weather-3400.herokuapp.com/api/v1/favorites` ``` Example body: { "location": "Denver, CO", "api_key": "jgn983hy48thw9begh98h4539h4" } ``` ## Local Setup Obtain and define the following API keys in a `config/application.yml` file: ``` Google Geocoding - ENV['GOOGLE_API_KEY'] Darksky Weather Data - ENV['DARK_SKY_API_KEY'] Unsplash Photos - ENV['UNSPLASH_API_KEY'] ``` Clone down the repo ``` $ git clone https://github.com/CSheesley/sweater_weather ``` Install the gem packages ``` $ bundle install ``` Set up the database ``` $ rake db:{create,migrate,seed} ``` Run the test suite: ``` $ bundle exec rspec ``` ## Versions Ruby 2.4.1 Rails 5.2.3 ## Future Iterations - Build out an accompanying front end application in JavaScript. - Using JavaScript for certain time related keys to use client's time zone. - Implement low-level caching strategies. <file_sep>/app/serializers/weather_data_serializer.rb class WeatherDataSerializer def initialize(weather_data) @location = weather_data.location @currently = weather_data.currently @today = weather_data.today @hourly = weather_data.hourly_formatted @rest_of_week = weather_data.rest_of_week_formatted end def to_hash { data: { current: { icon: @currently[:icon], conditions: @currently[:summary], temp: @currently[:temperature].round, high: @today[:temperatureHigh].round, low: @today[:temperatureLow].round, city_state: "#{@location.name}, #{@location.state_abrev}", country: @location.country, search_time: Time.at(@currently[:time]).strftime("%l:%M %p"), date: Time.at(@currently[:time]).strftime("%m/%d"), latitude: @location.latitude, longitude: @location.longitude }, details: { icon: @currently[:icon], conditions: @currently[:summary], feels_like: @currently[:apparentTemperature].round, humidity: "#{(@currently[:humidity] * 100).round}%", visibility: "#{'%.2f' % (@currently[:visibility])} miles", uv_index: @currently[:uvIndex], summary: @today[:summary], }, forecast: { hourly: @hourly, extended: @rest_of_week } } } end end <file_sep>/spec/requests/api/v1/forecast/weather_info_spec.rb require 'rails_helper' describe 'GET /api/v1/forecast' do it 'returns current and future weather information' do get '/api/v1/forecast?location=denver,co' weather_info = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(200) expect(weather_info.class).to eq(Hash) expect(weather_info[:data][:current][:city_state]).to eq("Denver, CO") expect(weather_info[:data][:details].present?).to eq(true) expect(weather_info[:data][:forecast][:hourly].count).to eq(8) expect(weather_info[:data][:forecast][:extended].count).to eq(5) end end <file_sep>/app/serializers/favorites_serializer.rb class FavoritesSerializer def initialize(favorites) @favorites = favorites end def to_hash @favorites.map do |favorite| { location: favorite.city.location, current_weather: current_weather(favorite.city) } end end def current_weather(city) weather_data = city.weather_data { icon: weather_data.currently[:icon], conditions: weather_data.currently[:summary], temp: weather_data.currently[:temperature].round, high: weather_data.today[:temperatureHigh].round, low: weather_data.today[:temperatureLow].round, city_state: city.location, country: city.country, search_time: Time.at(weather_data.currently[:time]).strftime("%l:%M %p"), date: Time.at(weather_data.currently[:time]).strftime("%m/%d"), latitude: city.latitude, longitude: city.longitude } end end <file_sep>/spec/requests/api/v1/sessions/log_in_spec.rb require 'rails_helper' describe 'POST /api/v1/sessions' do context 'with valid information' do it 'logs a user in if they have an account' do user = create(:user, email: "<EMAIL>", password: "<PASSWORD>", api_key: "abc123" ) post_body = { "email": "<EMAIL>", "password": "<PASSWORD>" } post '/api/v1/sessions', params: post_body session_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(200) expect(session_response[:api_key]).to eq("abc123") end end context 'with invalid credentials' do it 'returns an invalid credentials message with a 400 status code' do user = create(:user, email: "<EMAIL>", password: "<PASSWORD>", api_key: "abc123" ) post_body = { "email": "<EMAIL>", "password": "<PASSWORD>" } post '/api/v1/sessions', params: post_body session_response = JSON.parse(response.body, symbolize_names: true) expect(response.status).to eq(400) expect(session_response[:invalid]).to eq("Invalid Credentials") end end end <file_sep>/app/controllers/api/v1/sessions_controller.rb class Api::V1::SessionsController < ActionController::API def create user = User.find_by(email: user_params[:email]) if user && user.authenticate(user_params[:password]) session[:user_id] = user.id render json: { api_key: user.api_key} else render status: 400, json: { invalid: 'Invalid Credentials' } end end private def user_params params.permit(:email, :password) end end
19604731030e4fc4b116aa1467c93e434f382947
[ "Markdown", "Ruby" ]
31
Ruby
CSheesley/sweater_weather
c3865e82b632fd5c5e9ea1561d9b2333b395877f
bb90b6d79b63fa072f416b3d7bb9f5e7671e45c5
refs/heads/master
<file_sep>/** * Created by zhangsihao on 17-4-18. */ const BunyanEggLogger = require('../'); const EggConsoleLogger = require('egg-logger').EggConsoleLogger; describe('Test logger adapter', function () { let eggLogger = new EggConsoleLogger({ level: 'debug' }); let logger = BunyanEggLogger.createLogger(eggLogger, { name: 'bunyan' }); it('Test log', function () { logger.trace('hahaha'); logger.info('haha %d', 1); logger.info({ foo: 'bar' }); logger.error(new Error('some err')); logger.error(new Error('another err'), { foo: 'bar' }) }) }); <file_sep># bunyan-egg-logger egg-logger adapter for bunyan
c08ae2b6cc59466d601b7da327aae60451712f3c
[ "JavaScript", "Markdown" ]
2
JavaScript
jasonz93/bunyan-egg-logger
01f4fd4fd86b4b3a43e0a21309924028f5f87500
36af8799c2a08d70be53435ff6b8d3e45759c3ae
refs/heads/main
<repo_name>AtanasiyMarina/Adaptive_layout<file_sep>/scripts.js 'use strict' let colorsArr = document.querySelectorAll('.color-parameters__frame'); colorsArr.forEach(item =>{ item.addEventListener('click',event =>{ event.preventDefault(); colorsArr.forEach(item =>{ item.classList.remove('color-parameters__frame_black_frame'); }) item.classList.add('color-parameters__frame_black_frame'); }) }) let lang = document.querySelector('.home__lang'); let svg = document.querySelector('.home__svg'); lang.addEventListener('click',event =>{ event.preventDefault(); svg.classList.toggle('home__svg_active'); }) let productName = document.querySelectorAll('.product-name'); productName.forEach(item =>{ item.addEventListener('click',event => { event.preventDefault(); }) }) let menu = document.querySelector('.home__menu'); console.log(menu) menu.addEventListener('click', event =>{ event.preventDefault(); menu.classList.toggle('active'); })
fcee5eae344e03bb3d9c2521f97370ba4fc4c4ae
[ "JavaScript" ]
1
JavaScript
AtanasiyMarina/Adaptive_layout
c29cabc6f2e27de72d45407a1a0b57e85e8a3f3c
5356b36ee512dc8914113eadb7358e7fcdc1cca9
refs/heads/master
<file_sep>import {combineReducers} from 'redux'; import tasksReducer from './tasksReducer.js' import usersReducer from './usersReducer.js' import loadingReducer from './loadingReducer.js' const reducers = combineReducers({ tasks: tasksReducer, users: usersReducer, loader : loadingReducer }); export default reducers;<file_sep>import React from "react"; import { connect } from "react-redux"; import { bindActionCreators } from "redux"; import { deleteUser, updateUser } from "../actions/action.js"; import UserModalWindow from "./common/UsersModalWindow.js"; class UsersList extends React.Component { constructor(props) { super(props); this.state = { showModalForEdit: false }; this.ModalClose = this.ModalClose.bind(this); } ModalClose() { this.setState({ showModalForEdit: false }); } render(){ return( <div> </div> ) } } function mapStateToProps(state){ return { users : state.users.users } } function mapDispatchToProps(dispatch){ return bindActionCreators({deleteUser,updateUser} , dispatch) } export default connect(mapStateToProps,mapDispatchToProps)(UsersList)<file_sep>const tasksReducer = (state=[] , action) =>{ switch(action.type){ case 'ADD_TASK': state = state.concat(action.payload); break; case 'DELETE_TASK': console.log('INSIDE DELETE'); state = state.slice(); state.splice(action.payload,1); break; case 'UPDATE_TASK': console.log('Update task received in reducer'); const i = action.payload.index ; console.log(i); console.log(state[i]) state=state.slice(); state[i].field1 = action.payload.field1 ; state[i].field2 = action.payload.field2 ; break; } return state; } export default tasksReducer;<file_sep>export const addTask = task => ({ type: 'ADD_TASK', payload: task }) export const deleteTask = taskId => ({ type: 'DELETE_TASK', payload: taskId }) export const updateTask = task => ({ type:'UPDATE_TASK', payload:task }) export const addUser = task => ({ type: 'ADD_USER', payload: task }) export const deleteUser = userId => ( { type: 'DELETE_USER', payload: userId } ) export const updateUser = task => ({ type:'UPDATE_USER', payload:task }) export const loadoff = ()=>( { type : 'LOAD_OFF', payload : null } ) export const loadon = ()=>( { type : 'LOAD_ON', payload : null } )<file_sep>import React from 'react'; import logo from './logo.svg'; import UsersTab from './components/UsersTab.js' ; import TodosTab from './components/TodosTab.js' ; import './App.css'; function App() { return ( <div className="App"> <UsersTab/> </div> ); } export default App; <file_sep>import React from "react"; import { connect } from "react-redux"; import { bindActionCreators } from "redux"; import {addUser} from "../actions/action.js"; import {Button} from "antd"; import UsersList from "./UsersList.js"; import UserModalWindow from "./common/UsersModalWindow.js"; class UsersTab extends React.Component { constructor(props) { super(props); this.state = { showModal: false }; } render(){ let ModalClose = () => this.setState({ showModal: false }); return( <div> <Button variant="primary" onClick={() => { this.setState({ showModal: true }); }} > Create a User </Button> <UserModalWindow show={this.state.showModal} onHide = {ModalClose} user="true" update="false" /> <UsersList /> </div> ) } } function mapDispatchToProps(dispatch){ return bindActionCreators({addUser} , dispatch); } export default connect(()=>{},mapDispatchToProps)(UsersTab) ;
dd34592f4e44fc3d3564744a71cf97b4a6874b9c
[ "JavaScript" ]
6
JavaScript
fahhome/asz
91fb5c53c5a6844cab39946d5cf127e3c8e4387b
0f1ba5226eaae337b61bf1c7ff54e82ada588b39
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AmoScript : MonoBehaviour { public GunScript gunScript;//PistolについてるGunscriptを参照 public AudioClip supplement;//弾薬を補充した時に流れる音 //AudioSource audioSource; void OnTriggerEnter(Collider col) { // もしPlayerにさわったら if (col.gameObject.tag == "Player") { //Gunscriptのramaining(残弾数)を10増やす gunScript.remaining += 10; //オーディオを違う位置から流す(AudioSource不要) AudioSource.PlayClipAtPoint(supplement, this.transform.position,10.0f); // 自分は消える Destroy(this.gameObject); } } /* void OnCollisionEnter(Collision collision) { // もしPlayerにさわったら if (collision.gameObject.tag == "Player") { gunScript.remaining += 10; } // 自分は消える Destroy(this.gameObject); } */ } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayerScript: MonoBehaviour { public int playerHP = 100; Slider HPSlider;//HPバーを定義 AudioSource audioSource;//音を流す場所を宣言 public AudioClip damage;//ダメージを喰らった時に流れる音 //public Text HPLabel; private void Start() { //HPSliderという名前のオブジェクトを探してくる HPSlider = GameObject.Find("HPSlider").GetComponent<Slider>(); //音を流す場所をこのオブジェクトのAudioSourceに定義 audioSource = gameObject.GetComponent<AudioSource>(); } // ゲームの1フレームごとに呼ばれるメソッド void Update() { //HPバーの値をplayerHPと同期 HPSlider.value = playerHP; } //HPLabel.text = "PlayerHP:" + playerHP.ToString(); //Debug.Log(playerHP); // ダメージを与えられた時に行いたい命令を書く void Damage(){ playerHP = playerHP -30; //ダメージ音を再生 audioSource.PlayOneShot(damage); if (playerHP<=0) { SceneManager.LoadScene("GameOver"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { private float h; private float v; private float speed; private float jumpspeed = 10f; private CharacterController cc; private Vector3 dir; //以下Raycast関連変数 int layerMask; bool isSliding; RaycastHit slideHit;//当たったオブジェクトの情報を格納 float maxDistsnce = 100; float slideSpeed = 0.5f;//滑り落ちるスピード 1だと早い private Rigidbody rb; Vector3 slideVector; // UnityStandardAssets.Characters.FirstPerson.FirstPersonController FirstPersonController;//こうやったら呼び出せる? float timeRunning = 0.0f; private AudioSource audioSource; private Vector3 position; private Vector3 velocity; // Use this for initialization void Start() { h = 0; v = 0; speed = 20; dir = Vector3.zero; cc = gameObject.GetComponent<CharacterController>(); //Physics.gravity = new Vector3(0, 20.81f, 0); layerMask = 1 << LayerMask.NameToLayer("Ground"); rb = GetComponent<Rigidbody>(); slideVector = new Vector3(0, slideSpeed, 0); audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { h = Input.GetAxis("Horizontal");//水平方向の速度を取得 v = Input.GetAxis("Vertical"); //Debug.Log(h); if (Physics.Raycast(transform.position, Vector3.down, out slideHit,maxDistsnce,layerMask)) { //Debug.Log("Ray出てます!!!"); //衝突した際の面の角度とが滑らせたい角度以上かどうかを調べます。 if (Vector3.Angle(slideHit.normal, Vector3.up) > cc.slopeLimit) { //Debug.Log("slopeLimitを超えました" + cc.slopeLimit); isSliding = true; } else { //Debug.Log("slopeLimit以下になりました" + cc.slopeLimit); isSliding = false; } } //dir = transform.TransformDirection(dir); //ジャンプ軌道 //dir *= speed; //if (Input.GetKeyDown(KeyCode.Space)) //{ // if (cc.isGrounded) // { // dir.y = jumpspeed; // audioSource.PlayOneShot(jumpSound); // cc.Move(dir * Time.deltaTime); // } // else // { // audioSource.PlayOneShot(cannotJump); // } //} if (isSliding) {//滑るフラグが立ってたら //timeRunning += Time.deltaTime; //Debug.Log("滑る処理です"); //FirstPersonController.m_CharacterController.isGrounded = false; Vector3 hitNormal = slideHit.normal; dir.x += hitNormal.x *slideSpeed; dir.y -= hitNormal.y *slideSpeed;//y軸だけ引くことで滑り落ちるらしい https://gomafrontier.com/unity/2990 dir.z += hitNormal.z * slideSpeed; //velocity = new Vector3(hitNormal.x, -1*(Quaternion.FromToRotation(Vector3.up, slideHit.normal) * transform.forward * slideSpeed).y, hitNormal.z); //position = transform.position - velocity * Time.deltaTime; //transform.position = position; //Debug.Log("速度は"+dir); cc.Move(dir *Time.deltaTime);//character controller で滑り落とす //slideVector = new Vector3(0, (Quaternion.FromToRotation(Vector3.down, slideHit.normal) * transform.forward * slideSpeed).y, 0); //rb.AddForce(slideVector); } else { dir = new Vector3(0, 0, 0);//resetする } //Debug.Log("角度は" + dir); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingEnemyScript2 : MonoBehaviour { UnityEngine.AI.NavMeshAgent agent; //NavMeshのエージェント GameObject player; //プレイヤー float distance; float maxDistance = 5; // Use this for initialization void Start() { agent = GetComponent<UnityEngine.AI.NavMeshAgent>(); player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update() { distance = Mathf.Sqrt(Mathf.Pow((player.transform.position.x - this.transform.position.x), 2) + Mathf.Pow((player.transform.position.y - this.transform.position.y), 2)); //Debug.Log(distance); if (distance < maxDistance) { // 目的地をプレイヤーに設定する。 agent.SetDestination(player.transform.position); } } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityStandardAssets.Characters.FirstPerson;//これをやると見つけてくれる public class ScoreManager : MonoBehaviour { public static ScoreManager instance; public int enemyCount = 0; //敵を倒した数 public Text scoreLabel; //UIテキスト public GameObject clearPanel;//クリアした時に出るパネル public GameObject Player;//playerにfpsControllerがついている public GameObject Pistol;// AudioSource audioSource; public AudioClip clearSound; bool isCalledOnce = false; void Awake(){ if (instance == null) { instance = this; //DontDestroyOnLoad (this.gameObject); } else { Destroy (this.gameObject); } } void Start() { clearPanel.SetActive(false);//最初非表示 audioSource = GetComponent<AudioSource>(); if (scoreLabel == null) { if (GameObject.Find("EnemyCount")) { // EnemyCountという名前のオブジェクトを探し変数に入れる scoreLabel = GameObject.Find("EnemyCount").GetComponent<Text>(); } } } void Update() { if (scoreLabel) { // 倒した数をTextに表示する。 scoreLabel.text = "倒した数:" + enemyCount.ToString(); } else { if (GameObject.Find("EnemyCount")) { scoreLabel = GameObject.Find("EnemyCount").GetComponent<Text>(); } } if(enemyCount >= 5) { if (!isCalledOnce) { isCalledOnce = true; Clear(); } else { if ((Input.GetKeyDown(KeyCode.Space))) { Player.GetComponent<FirstPersonController>().enabled = true; Pistol.GetComponent<GunScript>().enabled = true; clearPanel.SetActive(false);//クリア画面表示 SceneManager.LoadScene("APEX"); enemyCount = 0; } } } } void Clear() { clearPanel.SetActive(true);//クリア画面表示 Player.GetComponent<FirstPersonController>().enabled = false; Pistol.GetComponent<GunScript>().enabled = false; audioSource.PlayOneShot(clearSound); } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.AI; using System.Collections.Generic; public class GunScript : MonoBehaviour { //public AudioClip gunSound; public GameObject explosion; public GameObject sparks; AudioSource audioSource; RaycastHit hit; const int magazineSize = 10;//銃に最大何発入るか public int remaining = 20;//予備弾薬 int currentMagazine = magazineSize;//最初は満タンに入れてます //テキスト関連 public Text bulletText;//現弾薬数(銃に入ってる弾薬数) public Text remainingText;//予備弾薬数(所持してる弾薬数) public AudioClip gun; public AudioClip reload; public AudioClip cannotReload; // ゲームが始まった時に1回呼ばれるメソッド void Start () { bulletText.text = "現弾薬数:" + currentMagazine.ToString(); remainingText.text = "予備弾薬数:" + remaining.ToString(); audioSource = gameObject.AddComponent<AudioSource>(); } // ゲームの1フレームごとに呼ばれるメソッド void Update () { if (Input.GetMouseButtonDown(0)) { if (currentMagazine > 0)//弾薬が銃に入っていたら { audioSource.PlayOneShot(gun); //gunを鳴らす Shot(); Instantiate(explosion, transform.position, Quaternion.identity); } else { Reload(); } } if (Input.GetKeyDown(KeyCode.R))//Rキーが押されたらリロード { Reload(); /* if(currentMagazine + remaining <= 0) { RemaingText.text = "弾切れです"; } */ } bulletText.text = currentMagazine.ToString(); remainingText.text = remaining.ToString(); } // 銃をうつ時に行いたいことをこの中に書く void Shot(){ currentMagazine--; Vector3 center = new Vector3(Screen.width / 2, Screen.height / 2, 0); Ray ray = Camera.main.ScreenPointToRay(center);//画面の真ん中にRayを飛ばす float distance = 100; if (Physics.Raycast(ray,out hit,distance)) { Instantiate(sparks, hit.point, Quaternion.identity); if (hit.collider.tag=="Enemy") { hit.collider.SendMessage("Damage"); }  } } // 銃をうつ時に行いたいことをこの中に書く void Reload() { if(currentMagazine == magazineSize) { audioSource.PlayOneShot(cannotReload); return; } if (remaining >= magazineSize)//フルでリロードできる時 { remaining = currentMagazine + remaining - magazineSize;//残り弾薬数 currentMagazine = magazineSize;//リロード完了 } else if (remaining > 0 && remaining < magazineSize)//フルではできない時 { if (currentMagazine + remaining >= 10) { remaining = currentMagazine + remaining - magazineSize;//残り弾薬数 currentMagazine = magazineSize;//リロード完了 } else { currentMagazine = currentMagazine + remaining; remaining = 0; } } else { audioSource.PlayOneShot(cannotReload); return; } audioSource.PlayOneShot(reload); //reloadを鳴らす } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BatteryScript : MonoBehaviour { public PlayerScript playerScript; public AudioClip healSound; void OnTriggerEnter(Collider col) { // もしPlayerにさわったら if (col.gameObject.tag == "Player") { if(playerScript.playerHP <= 90) { playerScript.playerHP += 10; } else if(playerScript.playerHP >90 && playerScript.playerHP < 100) { playerScript.playerHP = 100; } else { return; } AudioSource.PlayClipAtPoint(healSound, col.transform.position,10f);//オーディオを違う位置から流す方法 Destroy(this.gameObject);//消える前に音を流さないと(コルーチンもありかも) } } //audioSource.PlayOneShot(healSound);を使う場合はaudiosourceの定義とコンポーネント追加がいる //AudioSource audioSource; //void Start() //{ // audioSource = gameObject.AddComponent<AudioSource>(); //} //private IEnumerator DelayMethod() //{ // yield return new WaitForSeconds(1.0f); // Destroy(this.gameObject); //} }
c5734bfe2320a12807c6e79b106019eabad9282a
[ "C#" ]
7
C#
ryuryudragno/FPSGame
45926803cb881dfee7c70f46b7a66359e712d063
b11737905eb45917d8a8eda64b22fbea313fc2f5
refs/heads/master
<file_sep>import React, { Component } from 'react' export default class DevOps extends Component { render() { return ( <div> <section> <div className="site-section bg-light" id="devops-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '40px'}}>DevOps</h2> </div> </div> <div className="container"> <div className="row-mb"> </div> <div className="row site-section " id="devops-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>How Kubernetes operators can rescue DevSecOps</h2> <h2 className="section-title" style={{fontSize: '28px'}}> in the midst of a pandemic</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}>Presented by <NAME>, Distinguished Engineer, Master Inventor</p> <p style={{fontSize: '13px', fontStyle: 'italic'}}>&amp; Swati Nair, Developer (IBM)</p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/kubernetes_133.png" alt="Image" className="img-fluid" /> </div> <div className="col-lg-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>DevSecOps challenges</h3> <p>Shikha and Swati shared that as application development expands within the cloud, the responsibilities of DevSecOps teams also increases. The use of microservices overlaps with operations such as upgrades and downgrades, which is also overlapped by security measures to ensure that applications and data are not at risk. </p> <p style={{color: 'rgb(88, 44, 131)'}}>WT Note: While the presenter mentions Kubernetes and Docker, which are open source container systems and services, the concepts presented apply to other containerized app platforms as well, such as Azure App Service.</p> <p>Imposed upon this is the challenge of getting applications to market quickly, as well as ensuring performance. </p> <p>The solution proposed is to break legacy code into containers. Maintain the code with services to automate processes.</p> <h3>Breaking monoliths into containers</h3> <p>When translating a legacy application into a cloud application, the first steps are easy. Review the code to find logical break points for containerization. Containers can run in any compute environment and are isolated, which improves security.</p> <p>The challenge occurs once the application is containerized and requires ongoing upgrade, downgrade, or service maintenance.</p> <h3>Using Kubernetes to automate maintenance tasks </h3> <p>Kubernetes is an open-source container and service manager application. With Kubernetes, you can easily scale, implement services, and upgrade or download with simple commands. These tasks are more easily maintained by grouping nodes into master nodes.</p> <h3>Nodes and master nodes</h3> <p>Once nodes are grouped into master nodes, you can monitor and control changes more easily across an application. You can also use operators, custom Kubernetes controllers, that manage applications and their components.</p> <h3>Defining operators</h3> <p>Operators help DevOpsSec teams to create a design pattern of controllers that maintain nodes and master nodes. Operators take knowledge of an application’s lifecycle to automate checks that were previously completed as manual processes by DevOpsSec teams. </p> <p>Access features to build or customize operators for horizonal or vertical scaling of your application or to provide updates that were previously applied manually.</p> <p>Prerequisites to building an operator:</p> <ul> <li>Have a basic knowledge of Golang and Kubernetes</li> <li>Know your application well</li> <li>Have Kubernetes and the Operator-SDK installed</li> </ul> <h3>Building operators</h3> <ul> <li>Create a new project</li> <li>Add the Memcached API</li> <li>Define the configurable types in _types.go that you need the operator to control</li> </ul> </div> </div> <div className="site-section bg-light" id="devops-section"> <div className="container"> <div className="row mb-5"> </div> <div className="row site-section" id="devops-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>Infrastructure as code: Equip yourself </h2> <h2 className="section-title" style={{fontSize: '28px'}}>for the changing world</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}>Presented by <NAME>, Senior Product Development Manager, Intuit</p> <p style={{fontSize: '13px', fontStyle: 'italic'}}>&amp; Swati Nair, Developer (IBM)</p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/infrastructure_as_code33.png" alt="Image" className="img-fluid" /> </div> <div className="col-sm-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>Optimizing infrastructure</h3> <p>Sonali expressed that as engineers, we work hard to get quality, stable solutions to customers in a timely manner. An optimized infrastructure can get quality software to market faster with limited human error.</p> <h3>Scrapping manual processes</h3> <p>With CI/CD, key IT infrastructure tasks from 'racking and stacking' to deployment can be automated. The more automation there is, the less chance there is of human error and the faster an organization can deploy.</p> <p>Cloud development lends itself to this automation.</p> <h3>Challenges in cloud computing </h3> <p>In the cloud, we can easily scale for our application needs. But the cloud can’t currently help with configuration inconsistencies. Even if your systems are in the cloud, they can still be configured inconsistently.</p> <p>Here are the challenges Sonali identified:</p> <ul> <li><b style={{color: 'rgb(88, 44, 131)'}}>Server sprawl:</b> Now that we can easily spawn servers with the click of a button, we can over-generate servers. This can create inconsistencies between servers.</li> <li><b style={{color: 'rgb(88, 44, 131)'}}>Snowflake servers:</b> This model lends to ‘snowflake servers’ – fragile servers that no one is supposed to touch. Over time, this can result in a pool of ‘snowflakes.'</li> <li><b style={{color: 'rgb(88, 44, 131)'}}>Automation fear</b></li> <li><b style={{color: 'rgb(88, 44, 131)'}}>Mismatched configuration across servers</b></li> </ul> <h3>Best practices</h3> <ul> <li>Version control your infrastructure-as-code files</li> <li>Continually test systems and processes</li> <li>Rely upon CI/CD</li> <li>Use self-documenting systems and implement code reviews</li> <li>Monitor continuously</li> <li>Collaborate continuously</li> <li>Apply incremental changes</li> <li>Be agile and strict</li> </ul> </div> </div> <div className="site-section" id="devops-section"> <div className="container"> <div className="row mb-5"> </div> <div className="row site-section" id="devops-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>DevOps + data science: Reduce time to </h2> <h2 className="section-title" style={{fontSize: '28px'}}>data driven decisions</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}><NAME>, Data Scientist &amp;</p> <p style={{fontSize: '13px', fontStyle: 'italic'}}><NAME>, Software Engineering Coach, Target</p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/reduce_time_data_decisions33.png" alt="Image" className="img-fluid" /> </div> <div className="col-sm-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>Sharing data with stakeholders in real time</h3> <p>Real time feedback is more important than ever for smooth operations and deployment in our current climate. Koel and Jacob used opensource technology and data science to enhance the DevOps dashboard and share data with stakeholders in real time.</p> <h3>Data Science for DevOps and roadblocks</h3> <p>For DevOps, the data science used must translate to the DevOps dashboard.</p> <ul> <li>Sharing the dashboard with a business partner can be challenging. Any changes to the dashboard have to be sent again.</li> <li>For the experience to be interactive, data must be fully accessible and live from the user’s end; nor should there be a software download requirement. Data should be accessed from a link that the user bookmarks.</li> </ul> <p>Challenges to using commercial dashboard services:</p> <ul> <li>There can be limitations within commercial dashboard use. They tend to be inflexible.</li> <li>Changes to the dashboard may not properly update for business partners</li> <li>There can be scalability and rendering issues as the data store increases</li> </ul> <p>To overcome this, the dashboard must be connected to the actual application and its data stores.</p> <h3>Consequences </h3> <p>Outdated information results and business partners not getting the updates they need or in wasted development time used to refresh the content.</p> <h3>Solution objectives</h3> <ul> <li>Instead of using a commercial dashboard, begin by using lightweight, scalable microservices that react in real time to changes in data.</li> <li>Find out exactly what your end-user audience needs to remain informed and accessible. Build a small app based on that. It doesn’t have to be beautiful or elaborate to start. Start small and build from there to develop a useful dashboard for visualization.</li> <li>Use the coding languages your organization employs for data science as a platform.</li> </ul> <h3>Solution</h3> <ul> <li>Use Docker to containerize the application dashboard. It’s lightweight and always runs consistently. This creates a space of control for endless customization within the dashboard.</li> <li>Add data pipelines to the dashboard application with auto refresh.</li> <li>Trigger an automated build for CI/CD to always publish the latest.</li> <li>Use GitHub to trigger iterative builds.</li> <li>Use Drone as a continuous integration delivery service. Each time a change is detected, Drone updates the docker image in a new container, automatically removes the old container, and deploys.</li> <li>Use Kubernetes Autoscale as demand increases or decreases.</li> </ul> <h3>Summary</h3> <p>This solution creates an automated dashboard that is agile, scalable, and reflects data in real-time. It also leaves room for customization and design.</p> </div> </div> </div></div></div></div></div></section> <section> <div className="row site-section" id="devops-section"> </div> </section> </div> ); } };<file_sep>import React, { Component } from 'react' export default class Culture extends Component { render() { return ( <div> <section> <div className="row site-section" id="culture-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '40px'}}>Culture</h2> </div> </div> <div className="container"> <div className="row-mb"> </div> <div className="row site-section " id="culture-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>Abie Award Series: Why we need to make </h2> <h2 className="section-title" style={{fontSize: '28px'}}>the internet less racist and sexist</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}>Presented by Dr <NAME>, Imperial College, London</p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/culture133.png" alt="Image" className="img-fluid" /> </div> <div className="col-lg-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>Underrepresentation in STEM workplaces</h3> <p>As a woman working in computer science with a physics background, Dr. Wade was inspired to ask the question. “Why am I the only woman in this computer science and lab setting? Why am I the only person of color here?” </p> <h3>Underrepresentation in education</h3> <p>What we know is that access to computer science education, only 10% of AP students are represented in physics, engineering, and computer science disciplines.</p> <p>High Schools have a hard time recruiting teachers. Girls are more likely to study physics if they go to an all-girls school. This introduces a class bias as well as a gender bias.</p> <p>In the UK, only 35 professors of computer science are black women.</p> <h3>What can we do differently?</h3> <p>Dr. Wade acknowledged that we’ve started STEM programs to reach out to young women to connect with new audiences. But audiences have so many distractions, will they remember these efforts in the long term?</p> <p>What parents, teachers, and girls consume online has the longest lasting impact. Less than one in five main characters are girls and only one in ten are of color. Text books from black women are never represented. </p> <h3>Introducing diverse role models in Wikipedia biography pages</h3> <p>The fifth most frequently visited website in the world is Wikipedia. During the pandemic, it’s an incredible source for non-partisan information. However, the majority of Wikipedia authors are white, male, and living in North America, which is reflected in the content provided.</p> <p>Less than 5% of biographical articles are about women or women of color. Dr. Wade has been supplementing with biographies about women and people of color with over 1,800 pages submitted. </p> <p>An example is the article added about Gladys West, a mathematician featured in the film ‘Hidden Figures,’ who was both a woman and a person of color. Once added, the US government and 200 other authors and editors joined Dr. Wade to add inspiring content with diversity represented.</p> <p>Five million people have since accessed these pages.</p> <h3>Amplifying underrepresented groups</h3> <p>Dr. Wade encourages us to listen and learn about these individuals to push them forward –either as a woman, a person of color, or an ally. We can all affect change for the next generation and lift others as we climb. </p> <p>Dr. Wade also issued a warning and encouragement. As an advocate or ally, we’ll likely receive pushback. She reminds us “Don’t read the comments. Keep going.”</p> </div> </div> <div className="site-section bg-light" id="culture-section"> <div className="container"> <div className="row mb-5"> </div> <div className="row site-section" id="culture-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>Becoming visible: Increasing engagement &amp;</h2> <h2 className="section-title" style={{fontSize: '28px'}}>talent pipelines for women of color in tech</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}>Presented by <NAME>, Senior Learning Solutions, Medidata Solutions </p> <p style={{fontSize: '13px', fontStyle: 'italic'}}>&amp; <NAME>, Diversity &amp; Inclusion Lead, Medidata Solutions </p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/talent_pipelines33.png" alt="Image" className="img-fluid" /> </div> <div className="col-sm-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>Safeguarding our diversity</h3> <p>The presenters shared that although it’s been proven that diversified cultures outperform, women of color are three times more likely to be regarded as someone of a lower employment level, are two times more likely to have others take credit for their work, and are 1.5 times more likely to leave an organization in response to microaggressions. </p> <h3>Employment resource groups offer a solution</h3> <p>Developing employment resource groups provide a way address these issues.</p> <p>Four keys to ERG development:</p> <ul> <li>Top-down organizational support</li> <li>ERG foundation building</li> <li>Leveraging leaders and influencers</li> <li>Deploying talent ambassadors</li> </ul> <p>The panel reminded attendees that it is “a marathon” to set up this structure for both grassroots and top-down leadership development. Be patient as you grow in these areas.</p> <h3>Top-down organizational support</h3> <p>Leveraging organizational support begins with organization-wide awareness from the top. The responsibility isn’t only on the employees. This can be in the form of policies and research groups sponsored by executive leadership. </p> <p>The most effective practice is to integrate the business goals with employee resource goals. This ensures overall company awareness, as it’s a part of the operating rhythm. </p> <h3>ERG foundation building</h3> <p>The presenters expressed that program development is like building a house. You can’t build a house without building a solid foundation. Develop a roadmap for building an inclusive culture. This should also include a method for showing improvement and the benefits of implementation.</p> <h3>Leveraging leaders and influencers</h3> <p>Identify the leaders and influencers in your culture and pull them into the effort. Determine a method to sustain this model of engagement to avoid burnout. These efforts are completed outside of work responsibilities, so leaders and influencers can burn out depending on the professional challenges they face. At Medidata, they found the greatest success by being inclusive and keeping meetings fun and casual with the understanding that people may not always be able to volunteer their time. </p> <p>A committee structure helps with this, which allows membership to fluctuate. It’s great if the committee has a budget and periodic events to recruit additional leaders, influencers and ambassadors.</p> <h3>Deploying talent ambassadors</h3> <p>Talent ambassadors can be leaders, influencers, mentors, or anyone on staff that can assist employees in career growth. This can range from informal sessions where talent ambassadors actively grow the careers of the community in a particular area or as a part of a more formal career growth process. This helps all employees to grow their skills and provides women of color with opportunities to grow.</p> </div> </div> </div></div></div></section> <div className="row site-section" id="culture-section"> </div> </div> ); } };<file_sep>#Welcome to the GHC in Under 5 site! This site is a collection of women in technology themed articles from sessions I attended during the Grace Hopper Celebration, 2020. The content is intended for anyone interested in burgeoning technoloies and in advocating for the advancement of women in STEM fields. ##About this site In keeping with the women in technology theme, I decided to use newly learned React development techniques to build the site. ##Contact me For inquiries, drop me a line at <EMAIL>. <file_sep>import React, { Component } from 'react' export default class IoT extends Component { render() { return ( <section> <div className="site-section bg-light" id="iot-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '40px'}}>Internet of Things</h2> </div> </div> <div className="container"> <div className="row-mb"> </div> <div className="row site-section " id="iot-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>IoT + blockchain: Why it matters to you</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}>Presented by <NAME>, Senior Technical Staff Member, IBM &amp; </p> <p style={{fontSize: '13px', fontStyle: 'italic'}}><NAME>, Senior Technical Staff Member, IBM</p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/blockchain33.png" alt="Image" className="img-fluid" /> </div> <div className="col-lg-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>Blockchain basics</h3> <p>A blockchain is a distributed ledger of all transactions and the state the items tracked within that ledger. Blockchains contain smart contracts with the business logic for processing transactions. Blockchains are: </p> <ul> <li><b style={{color: 'rgb(88, 44, 131)'}}>Immutable:</b> The record of all transactions can’t be changed and are easily audited. </li> <li><b style={{color: 'rgb(88, 44, 131)'}}>Secure:</b> Transactions are secure, authenticated, and verifiable.</li> <li><b style={{color: 'rgb(88, 44, 131)'}}>Distributed:</b> The transaction ledger and node reside on each chain in the blockchain network, which circumvents performance and user issues associated with a centralized data store.</li> <li><b style={{color: 'rgb(88, 44, 131)'}}>Transparent:</b> Each member of the blockchain can view all transactions, engendering trust in the network.</li> </ul> <h3>About the internet of things (IoT)</h3> <p>IoTs are physical objects embedded with software, electronics, sensors, and network connectivity, which enables them to collect and exchange data. Smart watches, cars, buildings, and manufacturing machinery can all be considered as IoTs. </p> <p>Depending on the object, IoTs can collect data such as physical locations, temperature, acceleration, light sensitivity, security, performance, and user interactions. This includes the ability to track objects through a distribution chain.</p> <h3>How these work together</h3> <p>IoT blockchains can work together to monitor the movement and security of exchanged goods. Great parings are using IoT blockchain to track goods in a food supply chain, detect and prevent counterfeit operations, or validate the identity and qualifications of a supplier.</p> <h3>IoT blockchain example 1: Tracking and tracing in food chains </h3> <p>With IoT blockchain, there is transparency in all aspects of food production and its transfer. This transparency extends from the food’s origin to the consumer. With RFID tags, sensors, and cameras in each stop in the chain, vendors and consumers alike can trust that the food is fresh, uncontaminated, and safe to eat. This exponentially reduces food waste.</p> <h3>IoT blockchain example 2: Ensuring pharmaceutical compliance</h3> <p>Drugs and vaccines produced can also be tagged and tracked at every point in their production and distribution. The transparency in pharma distribution prevents unauthorized distribution or counterfeiting. All aspects of the drug manufacture are visible to all in the chain. This can save billions of dollars that can be reinvested in healthcare.</p> <h3>Blockchain networks transform supplier management</h3> <ul> <li>Blockchain verifies the identity of the supplier; others in the chain can see this certification.</li> <li>Product information is gathered during production to ensure quality.</li> <li>Products are tagged or coded for tracking.</li> <li>Vendors and consumers can trust the quality of the products, resulting in compliance and less waste.</li> </ul> <h3>Summary</h3> <p>IoT blockchain combinations have far-reaching impacts on how goods are produced, distributed, and consumed, saving businesses and consumers money by ensuring quality and compliance while eradicating waste. This powerful combination is one method for building a better, safer world, both economically and ecologically.</p> </div> </div> <div className="site-section bg-light" id="iot-section"> <div className="container"> <div className="row mb-5"> </div> <div className="row site-section" id="iot-section"> <div className="col-12 text-center" data-aos="fade"> <h2 className="section-title" style={{fontSize: '28px'}}>Living in the material world: Reconciling humans and</h2> <h2 className="section-title" style={{fontSize: '28px'}}>technology through smart materials</h2> <p style={{fontSize: '13px', fontStyle: 'italic'}}>Presented by <NAME>, Technology R&amp;D Specialist, Accenture Labs </p> </div> <div className="col-12 text-center" data-aos="fade-up" data-aos-delay> <img src="images/IOT33.png" alt="Image" className="img-fluid" /> </div> <div className="col-sm-2 text-left" data-aos="fade"> </div> <div className="col-sm-8 text-left" data-aos="fade"> <h3>About smart materials</h3> <p>Smart materials are objects that can store and transmit data. Your car and cell phone are good examples of existing smart materials. As the internet of things grows, smart materials will become more sophisticated and will expand to include everyday textiles and building materials.</p> <p>Example: Smart floors that can detect when an elderly resident has fallen and can communicate with other devices to obtain help.</p> <p>Infrastructures of smart objects that communicate with one another constitute the foundation of a smart city.</p> <h3>Challenges of smart cities</h3> <ul> <li>Privacy and anonymity. </li> <li>The need for human-centric technology.</li> <li>Digital overstimulation.</li> <li>Upkeep of an urban infrastructure.</li> </ul> <h3>How physical materials help</h3> <ul> <li>They can introduce less invasive methods of capturing data to preserve user privacy. </li> <li>They enable personalization in products and services for a more inclusive, human-centric experience.</li> <li>They communicate in more natural and seamless ways to tackle digital overstimulation.</li> <li>They add autonomy to physical objects that lends itself to infrastructure upkeep and sustainability. </li> </ul> <h3>Examples of human-centered smart materials</h3> <ul> <li>Intelligent walls and floors that can tell if someone has fallen and alert others to help. </li> <li>Remote health wearables that can detect symptoms early on.</li> <li>HTI researchers and designers creating building materials that look like wooden panels but that contain the sensors of a smart home.</li> <li>Nanoseptic touchpoints that automatically clean and disinfect surfaces. </li> </ul> <h3>What makes a material smart?</h3> <p>A smart material is any material that can react to external stimuli in a visible or tangible way. They can also be a collection of materials and electronics used to create a responsive system. </p> <p>Additional examples of smart materials and material systems:</p> <ul> <li>The Jackard jacket has embedded sensors that can operate your smart phone. Tap or brush a sleeve to turn your phone on or play music while biking. </li> <li>A collection of products, such as smart watches and smart running shoes, that exchange data to track progress and ensure that an exercise session is healthful and not harmful.</li> </ul> <h3>Wait…this gets crazy… (crazy awesome)!</h3> <ul> <li>Nutritionally-balanced meals that have biodegradable packaging and contain sensors that ensure that the food is safe. </li> <li>Cars with self-healing coats that can repair their own scratches and never need to be washed. These also have self-cleaning textiles. The dash has no distracting buttons; the user touches the dash to control the AC and other controls.</li> <li>Streets have sensors imbedded to detect traffic volumes which users can view from their smart cars.</li> <li>Office buildings are 3D printed with no waste materials. Energy is pulled from coated windows that use solar to power the building.</li> <li>Homes with self-cleaning surfaces had me at ‘hello.’ :-)</li> </ul> </div> </div> </div></div></div></section> ); } };<file_sep>import React, { Component } from 'react' export default class Carousel extends Component { render() { return ( <section className="site-section"> <div className="container"> <div className="row mb-5 justify-content-center"> <div className="col-md-7 text-center"> <h2 className="section-title mb-3" data-aos="fade-up" data-aos-delay style={{fontSize: '40px'}}>Let's dive in!</h2> <p className="lead" data-aos="fade-up" data-aos-delay={100}>Browse a collection of the innovations presented by women in technology at this year's GHC conference.</p> </div> </div> <div className="row"> <div className="col-lg-6 mb-5" data-aos="fade-up" data-aos-delay> <div className="owl-carousel slide-one-item-alt"> <img src="images/featured.jpg" alt="Image" className="img-fluid" /> <img src="images/human_centered_ai.png" alt="Image" className="img-fluid" /> <img src="images/leveraging_data_cscience.jpg" alt="Image" className="img-fluid" /> <img src="images/talent_pipelines.jpg" alt="Image" className="img-fluid" /> <img src="images/cyber_security.jpg" alt="Image" className="img-fluid" /> <img src="images/infrastructure_as_code.jpg" alt="Image" className="img-fluid" /> <img src="images/IOT.jpg" alt="Image" className="img-fluid" /> <img src="images/reactjs55.png" alt="Image" className="img-fluid" /> </div> <div className="custom-direction"> <a href="#" className="custom-prev"><span><span className="icon-keyboard_backspace" /></span></a><a href="#" className="custom-next"><span><span className="icon-keyboard_backspace" /></span></a> </div> </div> <div className="col-lg-5 ml-auto" data-aos="fade-up" data-aos-delay={100}> <div className="owl-carousel slide-one-item-alt-text"> <div> <h2 className="section-title mb-3">Featured: Machine learning solutions in healthcare </h2> <p className="lead">Tap into machine learning automation to reduce healthcare costs and improve patient outcomes.</p> <p><a href="#feature-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">Artificial intelligence</h2> <p className="lead">Learn how women in engineering are designing next-gen super computers. Explore ethics in AI.</p> <p><a href="#ai-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">Big data</h2> <p className="lead">Leverage data science in the fight against COVID-19. Discover quantum's role in next-gen data processing.</p> <p><a href="#bigdata-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">Culture</h2> <p className="lead">Exradicate racism and sexism in the workplace and in cyberspace.</p> <p><a href="#culture-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">Cyber security</h2> <p className="lead">Protect yourself from cyber security attacks in changing times.</p> <p><a href="#cybersecurity-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">DevOps</h2> <p className="lead">Accelerate decision processes in deployment to assist during a pandemic. </p> <p><a href="#devops-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">Internet of things</h2> <p className="lead">Explore the social and ecological benefits of blockchain. Glimpse cities of the future as envisioned by women in tech. </p> <p><a href="#iot-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> <div> <h2 className="section-title mb-3">ReactJS Development</h2> <p className="lead">Transform a legacy HTML site into a ReactJS app.</p> <p><a href="#reactjs-section" className="btn btn-primary mr-2 mb-2">Learn More</a></p> </div> </div> </div> </div> </div> </section> ); } };<file_sep>import React, { Component } from 'react' export default class Footer extends Component { render() { return ( <footer className="site-footer"> <div className="container"> <div className="row"> <div className="col-md-9"> <div className="row"> <div className="col-md-5"> <h2 className="footer-heading mb-4">About Me</h2> <p>I'm a technical writer at athenahealth who is exploring technologies to optimize product communications.</p> <p>I built this site to share my findings from GHC 2020 and also to practice developing within a React framework.</p> <p>React uses JS6, which is translated into JS5 for browsers. I need a lot of practice. :-)</p> <p>It was my pleasure to develop the site and an honor to attend GHC!</p> </div> <div className="col-md-3 ml-auto"> <h2 className="footer-heading mb-4">Quick Links</h2> <ul className="list-unstyled"> <li><a href="#feature-section" className="smoothscroll">Featured</a></li> <li><a href="#ai-section" className="smoothscroll">AI</a></li> <li><a href="#bigdata-section" className="smoothscroll">Big Data</a></li> <li><a href="#culture-section" className="smoothscroll">Culture</a></li> <li><a href="#cybersecurity-section" className="smoothscroll">Cyber Security</a></li> <li><a href="#devops-section" className="smoothscroll">DevOps</a></li> <li><a href="#iot-section" className="smoothscroll">IoT</a></li> <li><a href="#reactjs-section" className="smoothscroll">ReactJS</a></li> </ul> </div> </div> </div> <div className="row pt-5 mt-5 text-center"> <div className="col-md-12"> <div className="border-top pt-5"> </div> </div> </div> </div> </div></footer> ); } };
9d075e4faf0382eb1c2bd0c5b0b25c208d654aac
[ "JavaScript", "Text" ]
6
JavaScript
whittark/ghc
676d4372681f7e37d18fc3f3f87336ae8ca80dca
bc01494a0ab60b5a982309d3a15ba1e004d6c985
refs/heads/master
<file_sep>import Ember from 'ember'; import config from '../config/environment'; export function moreThanOnePage(params) { let totalStreams = params[0]; let totalPages = Math.ceil(totalStreams/config.APP.STREAMS_PER_PAGE); return (totalPages > 1) } export default Ember.Helper.helper(moreThanOnePage); <file_sep>import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'form', submit: function(e) { e.preventDefault(); if (this.searchTerms != "") { this.get('onSubmit')(this.searchTerms); } } }); <file_sep>import Ember from 'ember'; import config from '../config/environment'; export function calculateTotalPages(params) { let totalStreams = params[0]; let totalPages = Math.ceil(totalStreams/config.APP.STREAMS_PER_PAGE); totalPages = totalPages < 1 ? 1 : totalPages; // For UI purposes, don't allow 0 total pages return totalPages; } export default Ember.Helper.helper(calculateTotalPages); <file_sep>import { paginatorButtonDisableCheck } from '../../../helpers/paginator-button-disable-check'; import { module, test } from 'qunit'; module('Unit | Helper | paginator button disable check'); // Replace this with your real tests. test('it works', function(assert) { let result = paginatorButtonDisableCheck([42]); assert.ok(result); }); <file_sep>import Ember from 'ember'; export default Ember.Component.extend({ actions: { /** * Can use the same code for +1 and -1 */ sendChangePageAction(numPages) { this.sendAction('changePage', numPages); } } }); <file_sep>import Ember from 'ember'; export default Ember.Component.extend({ actions: { sendSearchAction(searchTerms) { this.sendAction('search', searchTerms); } } }); <file_sep>import Ember from 'ember'; export function paginatorButtonDisableCheck(params) { let curPage = params[0], numPages = params[1], direction = params[2] // The direction that the button is incrementing if (curPage <= 1 && direction < 0) { return true; } if (curPage >= numPages && direction > 0) { return true; } return false; } export default Ember.Helper.helper(paginatorButtonDisableCheck); <file_sep>import Ember from 'ember'; export default Ember.Controller.extend({ // Specify query parameters queryParams: ['q', 'page'], /** * Query parameters are automatically bound to these properties * Defaults values are set */ q: null, page: 1, actions: { changePage(numPages) { this.transitionToRoute("search.results", { queryParams: { page: this.get('page') + numPages, q: this.get('q') }}); } } }); <file_sep>import Ember from 'ember'; export default Ember.Controller.extend({ actions: { searchStreams(searchTerms) { this.transitionToRoute("search.results", { queryParams: { page: 1, q: searchTerms }}); } } });
b7e22fd88012453f6b2d664ad7b106aeecc61e28
[ "JavaScript" ]
9
JavaScript
jkeat/search-twitch
fed073affb6ed57e759eadb92570626d5d1414b6
5a98c9c9d34f9840cc3159e81cddb238c9ad6850
refs/heads/master
<repo_name>AWSKRUG1TEAM/APP<file_sep>/app/common/constant/defaultValue.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import { Dimensions, Platform, StatusBar } from 'react-native' /** Internal Dependency **/ export const StatusBarHeight = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight;<file_sep>/app/component/camera/camera.component.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import React, { Component } from 'react'; import { AppRegistry, Dimensions, StyleSheet, Text, TouchableHighlight, View, } from 'react-native'; import NativeCamera from 'react-native-camera'; import Header from './../../common/ui/header/header' import {NavigationActions} from 'react-navigation' import Icon from 'react-native-vector-icons/EvilIcons'; /** Internal Dependency **/ import styles from './camera.style' export default class Camera extends Component { constructor(props) { super(props) this.state = { handleFocusChanged: () => {} } } _onPressLeftBtn = () => { const backAction = NavigationActions.back(); this.props.navigation.dispatch(backAction) } render() { return ( <View style={styles.container}> <Header title={'Camera'} back={true} onPressLeftBtn={this._onPressLeftBtn}/> <View style={styles.cameraContainer}> <NativeCamera ref={(cam) => { this.camera = cam; }} style={styles.preview} aspect={NativeCamera.constants.Aspect.fill} defaultOnFocusComponent={true} onFocusChanged={ this.state.handleFocusChanged } > </NativeCamera> <TouchableHighlight onPress={() => {this.takePicture()}}> <View style={styles.outCircle}> <View style={styles.circle}> </View> </View> </TouchableHighlight> </View> </View> ); } takePicture() { const options = {}; //options.location = ... this.camera.capture({metadata: options}).then((data) => { console.log(data); this._onPressLeftBtn(); }).catch(err => { console.error(err) }); } }<file_sep>/app/component/camera/camera.style.js /** * Copyright (c) 2017 Team Mondrian. All Rights Reserved. * @flow * @author yuhogyun */ /** External dependencies **/ import React, {StyleSheet, Dimensions, PixelRatio, Platform} from 'react-native'; /** Internal Dependency **/ const {width, height, scale} = Dimensions.get('window') export default styles = StyleSheet.create({ container: { flex: 1, }, cameraContainer: { flex: 1 }, preview: { flex: 1, backgroundColor: 'pink' }, capture: { position: 'absolute', // backgroundColor: 'rgba(100,0,0,1)', // borderRadius: 1 }, outCircle: { position: 'absolute', bottom: 0, alignSelf: 'center', justifyContent: 'center', width: 100, height: 100, borderRadius: 500, backgroundColor: 'rgba(80,80,80,0.5)', marginBottom: 50, }, circle: { flex: 0.5, width: 50, borderRadius: 500, backgroundColor: 'white', alignSelf: 'center', } }); <file_sep>/app/component/main/main.component.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import React, {Component, PropTypes} from 'react' import { Text, View, ScrollView, TouchableOpacity } from 'react-native' import Camera from 'react-native-camera'; // import moment from 'moment' /** Internal dependencies **/ import styles, {width} from './main.style' import Header from './../../common/ui/header/header' class Main extends Component { constructor(props) { super(props); this.navigate = this.props.navigation.navigate; this.state = { scrollViewOpacity: 0 } } componentDidMount() { setTimeout(() => { this._scrollView.scrollTo({x: width, animated: false}); }, 0); // trick: } _onPressLeftBtn = () => { // Todo: Drawer // this.navigate.navigation('Dr', {name: 'fromMain'}); } _onPressRightBtn = () => { const { navigate } = this.props.navigation; // Todo: react props문법, ref: https://facebook.github.io/react-native/docs/props.html navigate('Camera', {name: 'fromMain'}); // Todo: ref: https://facebook.github.io/react-native/docs/navigation.html } render() { return ( <View style={{flex: 1}}> <Header title={'Date here'} onPressLeftBtn={this._onPressLeftBtn} onPressRightBtn={this._onPressRightBtn}/> <ScrollView showsHorizontalScrollIndicator={false} horizontal={true} pagingEnabled={true} style={{flex: 1}} ref={ref => this._scrollView = ref}> <View style={styles.innerContainer}> <Text>Page 1</Text> </View> <View style={styles.innerContainer}> <Text>Page 2</Text> </View> <View style={styles.innerContainer}> <Text>Page 3</Text> </View> </ScrollView> </View> ); } } export default Main; <file_sep>/app/component/login/login.style.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import { StyleSheet, Platform } from 'react-native' /** Internal dependencies **/ export default StyleSheet.create({ container: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'black' }, halfContainer: { flex: 0.6, marginLeft: 20, marginRight: 20 }, mainTitle: { marginTop: 20, marginLeft: 20, fontSize: 30, color: 'white' }, forms: { marginTop: 20 }, firstSubTitle: { color: 'white', textAlign: 'right', marginRight: 20, marginTop: 10 }, secondSubTitle: { marginLeft: 20, marginTop: 10, color: 'white', }, background: { flex: 0.4, width: null, height: null, resizeMode: 'cover' } });<file_sep>/index.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; /** Internal dependencies **/ import AppNavigator from './app/AppNavigator' export default class AwesomeProject extends Component { render() { return ( <AppNavigator/> ); } } AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);<file_sep>/app/component/login/login.component.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import React, {Component, PropTypes} from 'react' import { Text, View, TouchableOpacity, Image } from 'react-native' // Todo: ref: https://react-native-training.github.io/react-native-elements/API/HTML_style_headings/ import { Button, FormLabel, FormInput, FormValidationMessage } from 'react-native-elements'; /** Internal dependencies **/ import styles from './login.style' class Login extends Component { constructor(props) { super(props); } render() { return ( <View style={styles.container}> <Image source={require('./../../assets/image/blurImage.png')} style={styles.background}> </Image> <View style={styles.halfContainer}> <View> <Text style={styles.mainTitle}> 1 Day 4 Cuts </Text> </View> <View style={styles.forms}> <FormLabel>Email</FormLabel> <FormInput onChangeText={() => {}}/> <FormLabel>Password</FormLabel> <FormInput onChangeText={() => {}}/> </View> <TouchableOpacity> <Text style={styles.firstSubTitle}> Forgot your password? </Text> </TouchableOpacity> <Button raised icon={{name: 'done', size: 32}} buttonStyle={{backgroundColor: 'red', borderRadius: 10}} textStyle={{textAlign: 'center'}} title={`Login`} onPress={() => { this.navigateToMain()} } style={{marginTop: 20}} /> <TouchableOpacity> <Text style={styles.secondSubTitle}> Don't have an account? </Text> </TouchableOpacity> </View> </View> ); } navigateToMain() { const { navigate } = this.props.navigation; // Todo: react props문법, ref: https://facebook.github.io/react-native/docs/props.html navigate('Main', {name: 'fromLogin'}); // Todo: ref: https://facebook.github.io/react-native/docs/navigation.html } } export default Login; <file_sep>/app/common/ui/header/header.style.js /** * Created by yuhogyun on 2017. 10. 6. */ /** External dependencies **/ import React, {StyleSheet, Dimensions, PixelRatio} from 'react-native'; /** Internal dependencies **/ import {StatusBarHeight} from './../../constant/defaultValue' import Colors from './../../constant/colors' import FontWeights from '../../constant/fontWeights' /** Constant **/ const {width, height, scale} = Dimensions.get('window'), vw = width / 100, vh = height / 100, vmin = Math.min(vw, vh), vmax = Math.max(vw, vh); /** StyleSheet **/ export default StyleSheet.create({ header: { height: 52, width: width, marginTop: StatusBarHeight, justifyContent: 'center', alignItems: 'center', // position: 'absolute', }, mainTitle: { fontSize: 17, color: Colors.gray, letterSpacing: -0.1, fontWeight: FontWeights.medium }, leftBtn: { position: 'absolute', left: 13 }, rightBtn: { position: 'absolute', right: 13 }, imgContainer: { width: 34, height: 34, justifyContent: 'center', alignItems: 'center' }, img: { width: 24, height: 24, opacity: 0.7 } }); <file_sep>/app/component/main/main.style.js /** * Created by yuhogyun on 2017. 9. 6.. */ /** External dependencies **/ import { StyleSheet, Platform, Dimensions } from 'react-native' export const {width, height, scale} = Dimensions.get("window"), vw = width / 100, vh = height / 100, vmin = Math.min(vw, vh), vmax = Math.max(vw, vh); /** Internal dependencies **/ export default StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, innerContainer: { width: width, height: height, justifyContent: 'center', alignItems: 'center' }, content: { fontSize: 20, textAlign: 'center', margin: 10, }, });<file_sep>/readme.md # AwesomeProject ## How To Build on your phone. ```bash $ git clone https://github.com/AWSKRUG1TEAM/APP $ cd APP $ npm install $ react-native link $ npm start ``` ## Android ```bash open AwesomeProject/android/ with Android Studio touch run button ``` ## IOS ```bash open AwesomeProject/ios/AwesomeProject.xcodeproj product/scheme/edit scheme, in build configuration set to 'release' project/AwesomeProject, use 'Release' for command-line builds touch run button ``` ## Android Reverse Proxy ```sh $ adb reverse tcp:8081 tcp:8081 ```
c9f58958e3ff926d5f415b0aa9d263a8f5dced9a
[ "JavaScript", "Markdown" ]
10
JavaScript
AWSKRUG1TEAM/APP
30df059cf7389aab74ff91b8b197c151f6022b18
13d9132d26dad8f126d0ea516333c4a62e4cb1c2
refs/heads/master
<repo_name>thatbettina/goals-dashboard<file_sep>/goals.html <!DOCTYPE HTML> <!--[if IEMobile 7 ]><html class="no-js iem7" manifest="default.appcache?v=1"><![endif]--> <!--[if lt IE 7 ]><html class="no-js ie6" lang="en"><![endif]--> <!--[if IE 7 ]><html class="no-js ie7" lang="en"><![endif]--> <!--[if IE 8 ]><html class="no-js ie8" lang="en"><![endif]--> <!--[if (gte IE 9)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]--> <head> <title> My Goals Dashboard</title> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, width=device-width"> <meta name="format-detection" content="telephone=no"> <meta name="author" content="<NAME>" /> <link rel='stylesheet' id='screen-css' href='style.css' type='text/css' media='screen' /> <script type="text/javascript"> window.onload = function() { init() }; var options = { tooltips: { fontSize: '75%' } }; window.onload = function() { init() }; var public_spreadsheet_url = 'https://docs.google.com/spreadsheet/pub?key=<KEY>&output=html'; function init() { Tabletop.init( { key: public_spreadsheet_url, callback: showInfo, simpleSheet: true } ) } // define colors for the pie chart var colors = new Array("#2ecc71", "#e74c3c", "#e67e22", "#16a085"); // array for the entries of the pie data var pieData = []; function showInfo(data, tabletop) { // for each table row, create a value for the pie chart var ind; for (ind = 0; ind < data.length; ind++) { var entry = { // name of income for the label label: data[ind].name, // value of income, cast from string to integer value: +data[ind].incomefor2013, // color from hardcoded colors array color: colors[ind], labelColor: '#FFFFFF', labelFontSize: '12', labelAlign: 'center' } // add entry to pie data pieData.push(entry); } //console.log(pieData); // create pie chart with pie data var mChart = new Chart(document.getElementById("moneyChart").getContext("2d"), options); var myPie = mChart.Pie(pieData, { animation: true, animationSteps: 100, animationEasing: 'easeOutBounce' }); } </script> </head> <body> <div id="nav" class="wrapper bgkPink"> <div class="central" style="padding-left: 12px"> <div class="col1"> <div class="contBlock"> &nbsp; </div> </div> <div class="col6"> <div id="title"> <h2>My Goals Dashboard</h2> <h3> Publicly sharing my goals keeps me honest.</h3> </div> </div> <div class="col1"> <div class="contBlock"> &nbsp; </div> </div> </div> </div> <!-- Module Grid --> <div id="theGrid" class="wrapper bgk endingModuleGutter"> <div class="central leftSpacer"> <div class="centralCol colTopSpaceer"> <div class="contBlock centerAlign"> </div> </div> </div> <!-- Loop the works --> <div class="central leftSpacer"> <div class="centralCol"> <div class="contBlock"> <h1 style="text-align: center; padding-bottom: 6px;">Where does my money come from?</h1> <div class="date" style="text-align: center; padding-bottom: 24px;">Tracking income makes me appreciate money more.</div> <canvas id="moneyChart" width="400" height="400"></canvas> <h2> <p>I have a few side projects, and I wanted to see how much money they were bringing in compared to each other. <p> Because I'm not ready to share the exact numbers of my income, a pie chart allows me to compare them as percentages of my total income rather than using the exact dollar amounts.</p><br><br></h2> <br style='clear: both;' /> </div> </div> </div> <div class="central leftSpacer"> <div class="centralCol"> <div class="contBlock"> <h1 style="text-align: center; padding-bottom: 6px;">How much do I code?</h1> <div class="date" style="text-align: center; padding-bottom: 24px;">...starting only in April...</div> <canvas id="codeChart" height="400" width="400"></canvas> <h2> <p>I first learned how to code in Ruby on Rails last year, and now I've started learning Javascript for charts.js as well as node.js. The more I code, the more I learn. I pulled the number of contributions I've made this year so far from GitHub.<br><br></p></h2> <br style='clear: both;' /> </div> </div> </div> <div class="central leftSpacer"> <div class="centralCol"> <div class="contBlock"> <h1 style="text-align: center; padding-bottom: 6px;">How often do I practice my healthy habits?</h1> <div class="date" style="text-align: center; padding-bottom: 24px;">Health is the foundation for everything else I do.</div> <canvas id="healthChart" width="400" height="400"></canvas> <h2> <p>Every day I try to fit in yoga, meditation, journaling, and 20 wimpy wall pushups. Each blot on the radar is for one week, so each bar represents one day.<br> If I practice all healthy habits every day for one week, the blot should cover the entire radar. <br><br></p></h2> <br style='clear: both;' /> </div> </div> </div> </div> <div class="central leftSpacer"> <div class="centralCol"> <div class="contBlock"> <h1 style="text-align: center; padding-bottom: 6px;">How many pushups can I do at a time?</h1> <div class="date" style="text-align: center; padding-bottom: 24px;">What can I say? I need arm muscles.</div> <h1><center><p>3</center><br><br></p></h1> <br style='clear: both;' /> </div> </div> </div> </div> <script src="Tabletop.js"></script> <script src="Chart.js"></script> <script src="Doughnut.js"></script> <div id="footer" class="wrapper bgkBlue endingModuleGutter"> <div class="central leftSpacer"> <div class="col8 colTopSpaceer"> <div class="contBlock centerAlign"> <h3 class="labelMargins">Made possible by</h3> <p style="padding-bottom: 3px;"> my husband, <br> my coach <a href="https://github.com/autarc">Stefan</a>,<br> <a href="http://www.chartjs.org">Chart.js</a>, &amp; <a href="https://github.com/jsoma/tabletop">Tabletop.js</a> </p> <br> <br> <br> July 2013, Berlin </div> </div> </div> </div> </body> </html><file_sep>/Doughnut.js //Get the context of the canvas element we want to select // var pieData = [ // { // value: 410, // color: "#2ecc71", // label: 'IQS', // labelColor: 'white', // labelFontSize: '12', // labelAlign: 'center' // }, // { // value: 200, // color: "#e74c3c", // label: 'App', // labelColor: '#FFFFFF', // labelFontSize: '12', // labelAlign: 'center' // }, // { // value: 2000, // color: "#e67e22", // label: 'ALG', // labelColor: '#FFFFFF', // labelFontSize: '12', // labelAlign: 'center' // }, // { // value: 1500, // color: "#16a085", // label: 'ROI', // labelColor: '#000000', // labelFontSize: '4', // labelAlign: 'center' // } // ]; // var options = { // tooltips: { // fontSize: '75%' // } // }; // var myChart = new Chart(document.getElementById("moneyChart").getContext("2d"), options); // var myPie = myChart.Pie(pieData, { // animationSteps: 100, // animationEasing: 'easeOutBounce' // }); var lineData = { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], datasets: [ { label:"Lines Coded", fillColor: "#9b59b6", strokeColor: "#bdc3c7", pointColor: "#34495e", pointStrokeColor: "#fff", data: [0, 0, 0, 0, 17, 22, 8] } ] } myChart = new Chart(document.getElementById("codeChart").getContext("2d"), options); var myLine = myChart.Line(lineData, { animation: true, animationSteps: 100, animationEasing: 'easeOutQuart' }); var radarData = { labels : ["Yoga","Meditation","Eating Vegan","Sleeping 8 hours","Journaling", "Push-Ups"], datasets : [ { fillColor : "#95a5a6", strokeColor : "#bdc3c7", pointColor : "#34495e", pointStrokeColor : "#000000", data : [3, 5, 4, 1, 6, 5] }, { fillColor : "#e74c3c", strokeColor : "#bdc3c7", pointColor : "#34495e", pointStrokeColor : "#000000", data : [0, 2, 4, 2, 7, 6] } ] } myChart = new Chart(document.getElementById("healthChart").getContext("2d"), options); var myRadar = myChart.Radar(radarData, { animation: true, animationSteps: 100, animationEasing: 'easeOutQuart' });<file_sep>/README.md goals-dashboard =============== Charting personal goals with charts.js and tabletop.js and Google Spreadsheets at http://bettinashzu.com/JavaScript/goals.html
bfc9a40a0313bf2bac42b3ef3fcedab658d8ca07
[ "JavaScript", "HTML", "Markdown" ]
3
HTML
thatbettina/goals-dashboard
e3afe8fab4f86179c51497fda04be863753ef50c
4281d268462b9fce875d4884941bf79ef91fca95
refs/heads/master
<repo_name>jshep96/Database-coursework<file_sep>/TABLE QUERYS/Guest.sql CREATE TABLE Guest ( GuestID INT PRIMARY KEY IDENTITY (1,1), Title VARCHAR(4) NOT NULL CONSTRAINT chkTitle CHECK (Title IN ('Mr', 'Mrs', 'Miss', 'Ms', 'Dr')), FirstName VARCHAR(20) NOT NULL, LastName VARCHAR(20) NOT NULL, DOB DATE NOT NULL CONSTRAINT chkBrithDate CHECK (DOB >= '1916-01-01'), StreetAddress VARCHAR(100) NOT NULL, PostCode VARCHAR(10) NOT NULL, City VARCHAR(20) NOT NULL, Country VARCHAR(15) NOT NULL, PhoneNo VARCHAR(20) NOT NULL, Email VARCHAR(80) NOT NULL UNIQUE CONSTRAINT chkEmail CHECK (Email LIKE '%_@__%.__%'), LeadGuest VARCHAR(3) NOT NULL CONSTRAINT leadGuest CHECK (LeadGuest IN('YES','NO')) ); <file_sep>/TABLE QUERYS/bannedguest.sql CREATE TABLE BannedGuest ( GuestID INT NOT NULL REFERENCES Guest(GuestID), DateBanned DATETIME NOT NULL, Reasons VARCHAR(100) NOT NULL, CONSTRAINT chkDateBanned CHECK (DateBanned !> GETDATE()), CONSTRAINT PK_Bannedguest PRIMARY KEY (GuestID, DateBanned) );<file_sep>/Scenarios/invoice total paid.sql select TotalPrice, TotalPaid From Invoice inner join booking on Booking.BookingID = Invoice.BookingID where (Booking.CheckIn BETWEEN '20170401' and '20170430') OR (Booking.CheckOut BETWEEN '20170401' and '20170430')<file_sep>/Scenarios/income from activities.sql SELECT SUM(RobinsonShare) AS TotalActivityIncome FROM ActivityInvoice INNER JOIN ActivityBooking ON ActivityInvoice.ActivityID = ActivityBooking.ActivityID INNER JOIN Activity ON Activity.ActivityID = ActivityBooking.ActivityID WHERE Activity.Date BETWEEN '20170401' AND '20170430'; SELECT Activity.ActivityID,ActivityInvoice.TotalCost, ActivityInvoice.RobinsonShare, Activity.Date FROM ActivityInvoice INNER JOIN ActivityBooking ON ActivityInvoice.ActivityID = ActivityBooking.ActivityID INNER JOIN Activity ON Activity.ActivityID = ActivityBooking.ActivityID WHERE Activity.Date BETWEEN '20170401' AND '20170430'; <file_sep>/INSERT QUERYS/BOOKINGSTATUS.sql INSERT INTO BookingStatus VALUES (1, 'Paid in full'), (2, 'Current Guests'), (3, 'Reserved'), (4, 'Reserved'), (5, 'Deposit Due'), (6, 'Deposit Paid'), (7, 'Payment Due'), (8, 'Paid in Full'), (9, 'Current Guests'), (25, 'Reserverd'); SELECT * FROM BookingStatus <file_sep>/TABLE QUERYS/accommodation.sql CREATE TABLE Accomodation ( AccomodationID INT PRIMARY KEY IDENTITY (1,1), AccType VARCHAR(30) NOT NULL, CONSTRAINT chkType CHECK (AccType IN ('Tent', 'Motorhome','Caravan','Glamping yurt')), Capacity TINYINT NOT NULL, PricePerNight SMALLMONEY NOT NULL, ); <file_sep>/Scenarios/5.sql select Guest.GuestID, Guest.FirstName, Guest.LastName, Booking.CheckIn,Booking.CheckOut, Accomodation.AccType FROM Guest INNER JOIN PartyMembers ON PartyMembers.GuestID = Guest.GuestID INNER JOIN Booking ON PartyMembers.PartyID = Booking.PartyID INNER JOIN Accomodation ON Booking.AccommodationID = Accomodation.AccomodationID WHERE GETDATE() BETWEEN Booking.CheckIn AND Booking.CheckOut ORDER BY AccType; <file_sep>/INSERT QUERYS/ativityBooking.sql SELECT Booking.PartyID, CheckIn, CheckOut, ActivityID, DateAndTime , PartySize, TotalPeople FROM Booking CROSS JOIN Activity INNER JOIN Party ON Party.PartyID = Booking.PartyID WHERE Activity.DateAndTime Between Booking.CheckIn AND Booking.CheckOut; INSERT INTO ActivityBooking (PartyID, ActivityID, NumOfPeople) VALUES (1, 4, (SELECT PartySize FROM Party WHERE PartyID = 1)), (2, 4, (SELECT PartySize FROM Party WHERE PartyID = 2)); SELECT * FROM ActivityBooking;<file_sep>/Scenarios/9.sql SELECT Guest.FirstName + ' ' + Guest.LastName AS Name, Booking.NumOfNights , Party.PartySize - 1 AS AdditonalGuests FROM Booking INNER JOIN Party ON Party.PartyID = Booking.PartyID INNER JOIN Guest ON Guest.GuestID = Party.LeadGuestID WHERE Guest.FirstName = 'Quemby' AND Guest.LastName='Fitzpatrick' ; <file_sep>/Scenarios/6.sql INSERT INTO Activity VALUES ('Horse Riding', 8, 16, '18 <NAME>', '20170423', '14:00:00', '16:00:00', 10, 20.00, 1); SELECT *, (SELECT DATENAME(dw ,Date) ) AS DAY FROM Activity WHERE Description ='Horse Riding'; <file_sep>/TABLE QUERYS/activity.sql CREATE TABLE Activity ( ActivityID INT PRIMARY KEY IDENTITY(1,1), Description VARCHAR(50), SuitableAgeMin INT CONSTRAINT chkMin CHECK (SuitableAgeMin !< 0), SuitableAgeMax INT , LocationOfActivity VARCHAR(50) NOT NULL, Date DATE NOT NULL, CONSTRAINT chkActivityDate CHECK (Date !< GETDATE()), StartTime TIME NOT NULL, EndTime TIME NOT NULL, CONSTRAINT chkTime CHECK (EndTime > StartTime), TotalPeople SMALLINT NOT NULL, PricePerPerson SMALLMONEY NOT NULL, OrganiserID INT NOT NULL REFERENCES ActivityOrganiser(OrganiserID) ); <file_sep>/TABLE QUERYS/Party.sql CREATE TABLE Party ( PartyID INT PRIMARY KEY IDENTITY (1,1), PartySize TINYINT NOT NULL, Adults TINYINT NOT NULL, Children TINYINT NOT NULL, Pets TINYINT NOT NULL, GuestID INT REFERENCES LeadGuest(GuestID) ON DELETE NO ACTION ); <file_sep>/INSERT QUERYS/activityinice.sql INSERT INTO ActivityInvoice (PartyID,ActivityID,OrganiserID,TotalCost,RobinsonShare,OrgainserShare) SELECT PartyID , ActivityBooking.ActivityID, Activity.OrganiserID , 0, 0, 0 FROM ActivityBooking, Activity, ActivityOrganiser WHERE Activity.ActivityID = ActivityBooking.ActivityID AND Activity.OrganiserID = ActivityOrganiser.OrganiserID; UPDATE ActivityInvoice SET TotalCost = PricePerPerson * NumOfPeople FROM Activity, ActivityBooking WHERE ActivityInvoice.ActivityID = Activity.ActivityID And Activity.ActivityID = ActivityBooking.ActivityID; UPDATE ActivityInvoice SET RobinsonShare = TotalCost*0.1; UPDATE ActivityInvoice SET OrgainserShare = TotalCost*0.9;<file_sep>/Scenarios/BANNED GUEST TRIGER.sql CREATE TRIGGER Banned ON dbo.Booking after INSERT, UPDATE AS IF EXISTS ( SELECT 1 FROM inserted as x INNER JOIN PartyMembers ON x.PartyID = PartyMembers.PartyID INNER JOIN BannedGuest ON PartyMembers.GuestID = BannedGuest.GuestID ) BEGIN RAISERROR('Banned Guest is trying to make a booking', 16, 1) ROLLBACK TRANSACTION; RETURN END <file_sep>/TABLE QUERYS/Vehicle.sql CREATE TABLE Vehicle ( NumberPlate VARCHAR(20) PRIMARY KEY, VehicleType VARCHAR(20) NOT NULL, Colour VARCHAR(20) NOT NULL, PartyID INT REFERENCES Party(PartyID) ); <file_sep>/TABLE QUERYS/ativity organiser.sql CREATE TABLE ActivityOrganiser ( OrganiserID INT PRIMARY KEY IDENTITY(1,1), CompanyName VARCHAR(100) NOT NULL, CompanyAddress VARCHAR(100) NOT NULL, Website VARCHAR(150) NOT NULL, Email VARCHAR(80) NOT NULL, CONSTRAINT checkEmail CHECK (Email LIKE '%_@__%.__%'), Phone VARCHAR(20) NOT NULL ); <file_sep>/INSERT QUERYS/ACTIVITY.sql INSERT INTO ActivityBooking (PartyID, ActivityID, NumOfPeople) VALUES (1, 4, (SELECT PartySize FROM Party WHERE PartyID = 1)), (2, 5, (SELECT PartySize FROM Party WHERE PartyID = 2)), (3, 9, (SELECT PartySize FROM Party WHERE PartyID = 3)), (3, 6, (SELECT PartySize FROM Party WHERE PartyID = 4)), (7, 7, (SELECT PartySize FROM Party WHERE PartyID = 5)), (6, 8, (SELECT PartySize FROM Party WHERE PartyID = 6)), (3, 1, (SELECT PartySize FROM Party WHERE PartyID = 7)), (8, 10, (SELECT PartySize FROM Party WHERE PartyID = 8)), (9, 3, (SELECT PartySize FROM Party WHERE PartyID = 9)), (1, 2, (SELECT PartySize FROM Party WHERE PartyID = 1)); SELECT * FROM ActivityBooking;<file_sep>/TABLE QUERYS/ACTIVITYBOOKING.sql CREATE TABLE ActivityBooking ( PartyID INT NOT NULL REFERENCES Party(PartyID), ActivityID INT NOT NULL UNIQUE REFERENCES Activity(ActivityID), NumOfPeople SMALLINT NOT NULL CONSTRAINT PK_ActivityBooking PRIMARY KEY (PartyID, ActivityID) ); <file_sep>/TABLE QUERYS/activityInvoic.sql CREATE TABLE ActivityInvoice ( PartyID INT NOT NULL, ActivityID INT NOT NULL, OrganiserID INT NOT NULL, TotalCost SMALLMONEY NOT NULL, RobinsonShare SMALLMONEY NOT NULL, OrgainserShare SMALLMONEY NOT NULL CONSTRAINT FK_ActivityOrganiser FOREIGN KEY (OrganiserID) REFERENCES ActivityOrganiser(OrganiserID), CONSTRAINT FK_ActivityBook FOREIGN KEY (PartyID, ActivityID) REFERENCES ActivityBooking(PartyID,ActivityID), CONSTRAINT PK_ActivityInvoice PRIMARY KEY (OrganiserID, PartyID, ActivityID), CONSTRAINT checkNegative CHECK (TotalCost !< 0 AND RobinsonShare !<0 AND OrgainserShare !<0) );<file_sep>/TABLE QUERYS/Invoice.sql CREATE TABLE Invoice ( AccInvoiceID INT PRIMARY KEY IDENTITY(1,1), BookingID INT REFERENCES Booking(BookingID), TotalPrice MONEY NOT NULL, Deposit MONEY NOT NULL, TotalPaid MONEY, DatePaid DATETIME );<file_sep>/INSERT QUERYS/activityorganiser.sql SELECT * FROM ActivityOrganiser; INSERT INTO ActivityOrganiser VALUES ('Lacys HorseRiding School' , '401 Aliquam Road','LacyHorses.com','<EMAIL>','401 Aliquam Road'), ('JetKarts', '89 Lorem Street', 'JetKarts.co.uk', '<EMAIL>', '06305 288443'), ('Arts & Crafts', '484 Neque St', 'Crafting.com', '<EMAIL>', '01273 056787'), ('BrocksClimbing', '89 Shepherds Close', 'BrocksClimbing.co.uk','<EMAIL>', '05067 002321'), ('Warrens Lesuire Centre', '99 Dictum Street','Warrenslesuire.com','<EMAIL>','02094 747844'), ('Get Waved', '34 Enim Road','Getwaved.co.uk','<EMAIL>','07162 944585'), ('Minisrty Assualt', '53 Massa. Rd. ', 'MinsitryAssualt.co.uk', '<EMAIL>', '01273 456788') ('MarinaSports', '101 Marina Drive','MarinaSpots.com','<EMAIL>','02094 777 866'), ('J&G Stables', '55 Park Lane','jmstables.co.uk','<EMAIL>','07152 777585'), ('Adventurists', '78 Stablefield Road ', 'Adventuristsuk.co.uk', '<EMAIL>', '01273 456788');<file_sep>/TABLE QUERYS/PartyDetails.sql CREATE TABLE PartyMembers ( GuestID INT NOT NULL, PartyID INT NOT NULL CONSTRAINT PK_PartyMem PRIMARY KEY (GuestID, PartyID), CONSTRAINT FK_PartyMemGuest FOREIGN KEY (GuestID) REFERENCES Guest(GuestID), CONSTRAINT FK_PartyMemParty FOREIGN KEY (PartyID) REFERENCES Party(PartyID) ); <file_sep>/INSERT QUERYS/BANNED GUEST.sql SELECT Guest.GuestID, PartyMembers.PartyID, FirstName,LastName, CheckIn, CheckOut FROM Guest INNER JOIN PartyMembers ON Guest.GuestID = PartyMembers.GuestID INNER JOIN Booking ON Booking.PartyID = PartyMembers.PartyID SELECT * FROM BannedGuest; DROP TABLE BannedGuest; INSERT INTO BannedGuest VALUES ((SELECT GuestID FROM Guest WHERE FirstName = 'Dahlia' AND LastName = 'Oliver'), '20170511', 'Fighting with other guests'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Cynthia' AND LastName = 'Dillon'), '20170511', 'Vandalsim'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Quemby' AND LastName = 'Fitzpatrick'), '20170505', 'Unpaid fee'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Gail' AND LastName='Henson'), '20170511', 'Littering'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Jesse'AND LastName='Weaver'), '20170511', 'Abuse towards staff'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Joelle'AND LastName='Barron'), '20170520', 'Vandalism'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Octavia'AND LastName='Navarro'), '20170515', 'Unpaid fee'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Willa'AND LastName='Walker'), '20170428', 'Littering'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Hyatt'AND LastName='Gray'), '20170415', 'Fighting with other guests'), ((SELECT GuestID FROM Guest WHERE FirstName = 'Imani' AND LastName= 'Martin'), '20170415', 'Abuse towards staff'); SELECT * FROM BannedGuest; <file_sep>/INSERT QUERYS/activitytest.sql INSERT INTO Activity VALUES ('Horse Riding', 8, 16, '18 <NAME>', '20170419', '10:30:00', '14:00:00', 5, 20.00, 1), ('Horse Riding', 17, NULL, '18 <NAME>', '20170419', '10:30:00', '14:00:00', 5, 25.00, 9), ('Arts and Crafts', 2, 8 , '21 Broadway Road', '20170423', '12:00:00', '13:30:00', 10, 10.00, 3), ('Go-Karting', 4, 15, '67 Manor House', '20170429','13:00:00', '15:00:00', 15, 20.00, 2), ('Rock Climbing', 10, NULL, 'On Site', '20170502','12:30:00', '13:30:00', 10, 15.00, 4), ('Go-Karting', 16, NULL, '71 Ramsgate Rd', '20170503', '11:00:00', '13:00:00', 10, 30.00, 2), ('Arts and Crafts', 2, 8, '21 BroadWay Road', '20170507', '14:00:00', '15:00:00', 10, 10.00, 3), ('Swimming', 1, NULL, '52 Park Place', '20170507', '12:00:00', '15:00:00', 20, 05.00, 6), ('WaterSkiing', 16, NULL, '39 Scarcroft Road', '20170512', '12:00:00', '13:30:00', 6, 40.00, 8), ('Assualt Course', 12, NULL, '43 West Lane', '20170515', '12:00:00', '14:00:00', 15, 20.00, 10); SELECT * FROM Activity; <file_sep>/INSERT QUERYS/Guest.sql INSERT INTO Guest (Title,FirstName,LastName,DOB,StreetAddress,PostCode,City,PhoneNo,Email) VALUES ('Mr','David','Marshall','19960102','Freshwater Lane', 'RS6 7GH', 'London', '07447455436', '<EMAIL>'); INSERT INTO Guest (Title,FirstName,LastName,DOB,StreetAddress,PostCode,City,PhoneNo,Email) VALUES ('Mrs','Gaby','Walliston','19651018','Bevendean Cresent', 'BN5 HHJ', 'Brighton', '07687743678', '<EMAIL>'); INSERT INTO Guest (Title,FirstName,LastName,DOB,StreetAddress,PostCode,City,PhoneNo,Email) VALUES ('Mr','Frank','Lang','19500824','Gouster Road', 'HJ9 7HJ', 'London', '07663455388', '<EMAIL>'); <file_sep>/README.md # Database-coursework created a database using Microsoft SQL Server and SQL. Includes stored procedures, triggers and transactions.
bae7c5860ebfa2c60876f7d6a3fdfffc7a52801b
[ "Markdown", "SQL" ]
26
SQL
jshep96/Database-coursework
7960f5c3844a57a8a1c34047f9043040b5a17424
7234cd4ecda52d26bf206b566a5c128a1c2a6225
refs/heads/main
<repo_name>noman-ismail/todo-list<file_sep>/database/todo-list.sql -- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 1172.16.58.3 -- Generation Time: Jun 19, 2021 at 03:41 PM -- Server version: 10.4.19-MariaDB -- PHP Version: 8.0.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `todo-list` -- -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1), (4, '2021_06_17_143303_create_todos_table', 1); -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `todos` -- CREATE TABLE `todos` ( `id` bigint(20) UNSIGNED NOT NULL, `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` mediumtext COLLATE utf8mb4_unicode_ci DEFAULT NULL, `completed` tinyint(1) NOT NULL DEFAULT 0, `user_id` bigint(20) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `todos` -- INSERT INTO `todos` (`id`, `title`, `description`, `completed`, `user_id`, `created_at`, `updated_at`, `deleted_at`) VALUES (1, 'Assignment 1', 'This is Assignment #1', 0, 1, '2021-06-19 06:41:42', '2021-06-19 06:41:42', NULL), (2, 'Assignment 2', 'This is Assignment 2', 0, 1, '2021-06-19 06:42:09', '2021-06-19 06:42:09', NULL), (3, 'Assignment 3', 'This is Assignment 3', 0, 1, '2021-06-19 06:42:28', '2021-06-19 06:42:28', NULL), (4, 'Assignment 4', 'This is Assignment 4', 0, 1, '2021-06-19 06:45:38', '2021-06-19 08:40:41', NULL); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'Noman', '<EMAIL>', NULL, '$2y$10$.qc7Vrw9yMtj0axshyuaKONiaBPdNB6sv01FlOZtBQHFb1G1zZMFa', NULL, '2021-06-19 06:41:08', '2021-06-19 06:41:08'); -- -- Indexes for dumped tables -- -- -- Indexes for table `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indexes for table `todos` -- ALTER TABLE `todos` ADD PRIMARY KEY (`id`), ADD KEY `todos_user_id_index` (`user_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `todos` -- ALTER TABLE `todos` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
a1c2b08fc7ea7f9969a7a8bf91d4b605ec3503ae
[ "SQL" ]
1
SQL
noman-ismail/todo-list
a61f8e99ca4378af461408035545d733a4e6e4c1
db6624f887a95270b917100c2a0f3d2c953324c1
refs/heads/master
<file_sep><?php class Alias extends Eloquent { protected $connection ='mail'; protected $table='alias'; public $timestamps = false; } ?> <file_sep><?php class masterController extends BaseController { public function index() { } public function show($id) { } //creo nueva zona master public function create() { $master = new Domain(); return View::make('add_master.save')->with('master', $master); } //guardo en db public function store() { $name = Input::get('name',null); if ($name != null) { $dominio = Domain::where('name', '=', $name)->first(); if ($dominio != null) { return Redirect::to('add_master/create')->with('notice', 'La zona ya existe'); } $master = new Domain(); $master->name = Input::get('name'); $master->type = Input::get('type'); $master->save(); $id = $master->id; //obtengo id del ultimo registro que inserto // tabla records $records= new Record(); $records->domain_id = $id; $records->name = Input::get('name'); $records->type = 'SOA'; $records->content ='ns1.'.Input::get('name') .' hostmasters.'.Input::get('name').' ' .date("Ymd") ."00 28800 7200 604800 86400"; $records->ttl = '86400'; $records->prio = '0'; $records->change_date = time(); $records->auth = '1'; $records->save(); // tabla zones $zones = new Zone(); $zones->domain_id = $id; $zones->owner = '1'; $zones->comment = ''; $zones->zone_templ_id= '0'; $zones->save(); return Redirect::to('/')->with('notice', 'La zona ha sido creada correctamente.'); } else { return Redirect::to('add_master/create')->with('notice', 'oops!'); } } public function edit($id) { } public function update($id) { } public function destroy($id) { } } ?> <file_sep># Panel de adminsitracion de servicios web Mini panel de adminsitracion para gestionar servicios web, dns y mail ## Instrucciones 1. Instalar postfix y powerdns 2. Loguearse las siguientes credenciales: `Usuario: admin, Password: <PASSWORD>` 3. Una vez ingresado el usuario podra crear, modificar, listar, borrar tanto dominios como cuentas de correo. <file_sep><?php class mailboxController extends BaseController { // realizo consulta a tabla domains (with -> domains es el nombre de la variable, y el $domains el contenido de la varaiable) public function index() { $mailbox = Mailbox::all(); return View::make('list_mailbox.index')->with('mailbox', $mailbox); } public function show($id) { } public function create() { $mailbox = new Mailbox (); return View::make('list_mailbox.create')->with('mailbox', $mailbox); } public function store() { $length = strlen(Input::get('password')); $name = Input::get('username',null); if ($length < 6) { return Redirect::to('list_mailbox/create')->with('notice', 'oops!'); } if ($name != null) { $address = $name.'@'.Input::get('domain'); //usuario@dominio $usuario = Mailbox::where('username', '=', $address)->first(); if ($usuario != null){ return Redirect::to('list_mailbox/create')->with('notice', 'La direccion solicitada esta en uso'); } $current_timestamp = date("Y-m-d H:i:s"); $mailbox = new Mailbox(); $mailbox->username = Input::get('username').'@'.Input::get('domain'); $pass = Input::get('password'); // $hash = Crypt::encrypt($pass); $hash = crypt($pass); $mailbox->password = $hash; $mailbox->name = Input::get('name'); $mailbox->maildir = Input::get('username').'@'.Input::get('domain').'/'; $mailbox->quota = '0'; $mailbox->local_part = Input::get('username'); $mailbox->domain = Input::get('domain'); $mailbox->created = $current_timestamp; $mailbox->modified = $current_timestamp; if(Input::get('active') == ''){ $mailbox->active = '0'; } else { $mailbox->active ='1'; } $mailbox->save(); $alias = new Alias(); $alias->address = $mailbox->username; $alias->goto = $mailbox->username; $alias->domain = $mailbox->domain; $alias->created = $mailbox->created; $alias->modified = $mailbox->modified; $alias->active = $mailbox->active; $alias->save(); $address = new Address(); $address->id = $mailbox->username; $address->address = $mailbox->username; $address->crypt = $hash; $address->clear = ''; $address->name = $mailbox->name; $address->uid = '5000'; $address->gid = '5000'; $address->home = '/home/vmail/'; $address->domain = $mailbox->domain; $address->maildir = $mailbox->domain.'/'.'test/Maildir/'; $address->imapok = '1'; $address->bool1 = '1'; $address->bool2 = '1'; $address->save(); return Redirect::to('/')->with('notice', 'El mailbox ha sido creado correctamente.'); } else { return Redirect::to('list_mailbox/create')->with('notice', 'oops!'); } } // para poder editar un solo dominio public function edit($id) { $register = Mailbox::where('username', '=', $id)->first(); return View::make('list_mailbox.edit')->with('register', $register); } // actualizo db public function update($id) { $length = strlen(Input::get('password')); if($length >= 6) { $current_timestamp = date("Y-m-d H:i:s"); $mailbox = new Mailbox(); $mailbox->password = <PASSWORD>(Input::get('password')); $mailbox->name = Input::get('name'); $mailbox->modified = $current_timestamp; $mailbox->active = Input::get('active'); $address = new Address(); $address->crypt = $mailbox->password; $address->name = $mailbox->name; //super query Mailbox::where('username', '=', $id)->update(array('password' => $<PASSWORD>, 'name' => $mailbox->name, 'modified' => $mailbox->modified, 'active' => $mailbox->active)); Address::where('id', '=', $id)->update(array('crypt' => $address->crypt, 'name' => $address->name)); return Redirect::to('list_mailbox')->with('notice', 'El mailbox ha sido editado correctamente'); } else { return Redirect::to('list_mailbox/'.$id.'/edit')->with('notice', 'oops!'); } } public function destroy($id) { $mailbox = Mailbox::where('username', '=', $id)-> delete(); $alias = Alias::where('address', '=', $id)-> delete(); $address = Address::where('id', '=', $id)->delete(); return Redirect::to('list_mailbox')->with('notice', 'El mailbox ha sido eliminado correctamente.'); } } ?> <file_sep><?php class Mailbox extends Eloquent { protected $connection ='mail'; protected $table = 'mailbox'; public $timestamps = false; } ?> <file_sep><?php class Zone extends Eloquent { protected $connection ='dns'; public $timestamps = false; } ?> <file_sep><?php class Maildomain extends Eloquent { protected $connection ='mail'; protected $table = 'domain'; public $timestamps = false; public function mailboxs () { return $this->hasMany('Mailbox','domain','domain'); } } ?> <file_sep><?php class Record extends Eloquent { protected $connection ='dns'; public $timestamps = false; } ?> <file_sep><?php class slaveController extends BaseController { //creo nueva zona master public function create() { $slave = new Domain(); return View::make('add_slave.save')->with('slave', $slave); } //guardo en db public function store() { $name = Input::get('name',null); if ($name != null) { $dominio = Domain::where('name', '=', $name)->first(); if ($dominio != null) { return Redirect::to('add_slave/create')->with('notice', 'La zona ya existe'); } $slave = new Domain(); $slave->name = Input::get('name'); $slave->master = Input::get('nameserver'); $slave->type = 'SLAVE'; $slave->save(); $id = $slave->id; //obtengo id del ultimo registro que inserto // tabla records -- comentar esto $records= new Record(); $records->domain_id = $id; $records->name = Input::get('name'); $records->type = 'SOA'; $records->content ='ns1.'.Input::get('name') .' hostmasters.'.Input::get('name').' ' .date("Ymd") ."00 28800 7200 604800 86400"; $records->ttl = '86400'; $records->prio = '0'; $records->change_date = time(); $records->auth = '1'; $records->save(); // tabla zones $zones = new Zone(); $zones->domain_id = $id; $zones->owner = '1'; $zones->comment = ''; $zones->zone_templ_id= '0'; $zones->save(); return Redirect::to('/')->with('notice', 'La zona ha sido creada correctamente.'); } else { return Redirect::to('add_slave/create')->with('notice', 'oops!'); } } public function edit($id) { } public function update($id) { } public function destroy($id) { } } ?> <file_sep><?php class dnsController extends BaseController { // realizo consulta a tabla domains (with -> domains es el nombre de la variable, y el $domains el contenido de la varaiable) public function index() { $domains = Domain::all(); return View::make('list_zones.index')->with('domains', $domains); } public function show($id) { $domain_id = $id; $records = Record::where('domain_id', '=', $domain_id)->get(); return View::make('list_zones.show')->with('records', $records); } public function createRecord($id) { $query = Domain::where('id', '=', $id)->first(); return View::make('list_zones.create', array('query' => $query)); } public function store() { $dominio = '.'.Input::get('dominio'); $name = Input::get('name',null); if ($name != null) { $record = Record::where('name', '=', $name)->first(); if ($record != null) { return Redirect::to('list_zones')->with('notice', 'El registro ya existe'); } $name = Input::get('name',null).$dominio; // tabla records $records= new Record(); $records->domain_id = Input::get('id'); $records->name = Input::get('name').$dominio; $records->type = Input::get('type'); if (Input::get('content') == '') { $records->content ='ns1.'.Input::get('dominio') .' hostmasters.'.Input::get('dominio').' ' .date("Ymd") ."00 28800 7200 604800 86400"; } else { $records->content = Input::get('content'); } $records->ttl = Input::get('ttl'); $records->prio = Input::get('priority'); $records->change_date = time(); $records->auth = '1'; $records->save(); return Redirect::to('list_zones')->with('notice', 'El registro ha sido creada correctamente.'); } else { return Redirect::to('list_zones')->with('notice', 'El nombre de registro ya existe'); } } // para poder editar un solo dominio public function edit($id) { $register = Record::find($id); return View::make('list_zones.edit')->with('register', $register); } // actualizo de registros public function update($id) { $domains = Record::find($id); $domains->name = Input::get('name'); $domains->type = Input::get('type'); $domains->content = Input::get('content'); $domains->prio = Input::get('priority'); $domains->ttl = Input::get('ttl'); $domains->auth = "1"; $domains->save(); $domain_id= $domains->domain_id; $type = $domains->type; if($type == 'SOA') { $zone = Domain::find($domain_id); $zone->name = Input::get('name'); $zone->save(); return Redirect::to('list_zones')->with('notice', 'El registro ha sido modificado correctamente.'); } else { return Redirect::to('list_zones')->with('notice', 'oops!'); } } //elimino las zonas, registro hidden envio informacion para eliminar un registro o una zona completa public function destroy($id) { $aux = Input::get('hidden'); if ($aux == 'record' ) { $records = Record::where('id', '=', $id)-> delete(); return Redirect::to('list_zones')->with('notice', 'El registro ha sido eliminado correctamente.'); } else { // es una zona, borro tooodo $domain = Domain::find($id); $domain_id = $id; $zones = Zone::where('domain_id', '=', $domain_id)-> delete(); $records = Record::where('domain_id', '=', $domain_id)-> delete(); $domain->delete(); return Redirect::to('list_zones')->with('notice', 'El registro ha sido eliminado correctamente.'); } } } ?> <file_sep><?php class Address extends Eloquent { protected $table ='users'; protected $connection ='mail'; public $timestamps = false; } ?> <file_sep><?php class Domain extends Eloquent { protected $connection ='dns'; public $timestamps = false; public function records(){ return $this->hasMany('Record'); } } ?> <file_sep><?php class mailController extends BaseController { public function index() { $domains = Mailist::all(); return View::make('list_domains.index')->with('domains', $domains); } public function create() { $domain = new Maildomain(); return View::make('list_domains.create')->with('domain', $domain); } public function store() { $name = Input::get('name',null); if($name != null) { $domain = Maildomain::where('domain', '=', $name)->first(); if($domain != null) { return Redirect::to('list_domains/create')->with('notice', 'El nombre de dominio ya esta en uso'); } $current_timestamp = date("Y-m-d H:i:s"); $dominio = new Maildomain(); $dominio->domain = Input::get('name'); $dominio->description = Input::get('description'); $dominio->aliases = Input::get('aliases'); $dominio->mailboxes = Input::get('mailboxes'); $dominio->maxquota = Input::get('mailboxes'); $dominio->quota = '0'; $dominio->transport = 'virtual'; if (Input::get('mailserver') == '') { $dominio->backupmx = '0'; }else { $dominio->backupmx = '1'; } $dominio->created = $current_timestamp; $dominio->modified =$current_timestamp; $dominio->active = '1'; $dominio->save(); return Redirect::to('/')->with('notice', 'El dominio se ha sido creado correctamente.'); } else { return Redirect::to('list_domains/create')->with('notice', 'oops!'); } } // para poder editar un solo dominio public function edit($id) { $item = Maildomain::where('domain', '=', $id)->first(); return View::make('list_domains.edit')->with('item', $item); } // actualizo db public function update($id) { $current_timestamp = date("Y-m-d H:i:s"); $dominio = new Maildomain(); $dominio->domain = $id; $dominio->description = Input::get('description'); $dominio->aliases = Input::get('aliases'); $dominio->mailboxes = Input::get('mailboxes'); $dominio->maxquota = Input::get('mailboxes'); $dominio->quota = '0'; $dominio->transport = 'virtual'; if (Input::get('mailserver') == '') { $dominio->backupmx = '0'; }else { $dominio->backupmx = '1'; } $dominio->created = $current_timestamp; $dominio->modified =$current_timestamp; $dominio->active = '1'; //super query Maildomain::where('domain', '=', $id)->update(array('domain' => $id, 'description' => $dominio->description, 'aliases' => $dominio->aliases, 'mailboxes' => $dominio->mailboxes, 'maxquota' => $dominio->maxquota, 'quota' => $dominio->quota, 'transport' => 'virtual', 'backupmx' => $dominio->backupmx, 'modified' => $dominio->modified, 'active' => '1')); return Redirect::to('list_domains')->with('notice', 'El dominio ha sido modificado correctamente.'); } public function destroy($id) { $dominio = Maildomain::where('domain', '=', $id)-> delete(); return Redirect::to('list_domains')->with('notice', 'El dominio ha sido eliminado correctamente.'); } } ?> <file_sep><?php class Mailist extends Eloquent { protected $connection ='mail'; protected $table = 'domain'; public $timestamps = false; } ?>
3e339ce7d20f00d50f0fdd01384b2033ed2f02db
[ "Markdown", "PHP" ]
14
PHP
mauhftw/web-services
ffd7d000fdd9d326177cf33a889dec0de4aecaa0
e307d4efb6bd78cf1d4966f09858014909fc58c6
refs/heads/master
<file_sep>version: "3.4" services: homebridge: image: gtfunes/homebridge:latest restart: always network_mode: host volumes: - ./volumes/homebridge:/homebridge environment: - TZ=${TZ} - PGID=${PGID} - PUID=${PUID} - HOMEBRIDGE_CONFIG_UI=1 - HOMEBRIDGE_CONFIG_UI_PORT=80 <file_sep># Your timezone, https://en.wikipedia.org/wiki/List_of_tz_database_time_zones TZ=America/Argentina/Buenos_Aires # UNIX PUID and PGID, find with: id $USER PUID=1000 PGID=1000 <file_sep>#!/bin/bash apt-get update apt-get install git docker docker-compose -y systemctl enable docker && systemctl start docker git clone https://github.com/gtfunes/vagrant-homebridge.git chown -R vagrant:vagrant vagrant-homebridge cd vagrant-homebridge cp .env.example .env usermod -aG docker $(whoami) docker-compose up -d
53c743aabf0f2f325c442e93e4df8cbca2fc5e07
[ "YAML", "Shell" ]
3
YAML
gtfunes/vagrant-homebridge
d9760cf657d8ff21d260934d0cd711361c31d253
4d783b21ea13bb76d96dd74b8d68b98cc913f372
refs/heads/main
<file_sep>'use strict' function getSquare(num1, num2) { let sum = (num1 * num1) + (num2 * num2) return sum * sum } let getSquareOptie2 = function (number1, number2) { let result = (number1 * number1) + (number2 * number2) return result * result } let getSquareViaArrow = (nummer1, nummer2) => { let result = (nummer1 * nummer1) + (nummer2 * nummer2) return result * result } console.log(getSquare(4, 5)); console.log(getSquareOptie2(4, 5)); console.log(getSquareViaArrow(4, 5));
24625f933f7d46e5016959ba4809574f89dd7507
[ "JavaScript" ]
1
JavaScript
DashaDafusun/Opdracht_19_functions
5b3625701dea93a844f278a7d6cd94d9c6a70e3f
593ab16106e7fb2f9b55a6ab84bea94209e5fc88
refs/heads/master
<file_sep>#!/bin/bash function hex_to_readable () { if [ -f clears.txt ]; then echo -e '\e[31mBE AWARE -\e[0m you already have a file called clears.txt, this will be altered.' fi read -e -p "Enter input list: " HEXLIST if [ -f "$HEXLIST" ]; then while IFS= read -r LINE; do grep -m1 '$HEX' <<< "$LINE" | awk -F: '{print $NF}' | sed 's/$HEX//' | cut -d '[' -f2 | cut -d ']' -f1 >> tmp_extract done < $HEXLIST else echo -e "\e[31mFile does not exist, try again\e[0m"; hex_to_readable fi for LINE in $(cat tmp_extract); do CONV=$(echo HEX: $LINE; echo ' | Plain: '; echo $LINE | xxd -ps -r | iconv -f cp1252 -t utf8; echo -e '\n') echo $CONV >> clears.txt done echo -e "\nResults can be found in \e[32mclears.txt\e[0m\n" rm tmp_extract } main () { hex_to_readable } main<file_sep># HEX to (human) readable Little script to parse your Hashcat cracked ***$HEX[1234567890]*** to (human) readable format. ## Input Create a file that contains at least the ***$HEX[1234567890]*** or the *--show* output from Hashcat as shown below. ```plain $HEX[31303838333a4d6172796c616e64] $HEX[3435343533356c3a66647266] ``` ```plain b9ee56f2d714f1ccd9798df5fc3a1277:$HEX[31303838333a4d6172796c616e64] bb4339131ed529effe0adbb7d558b9ea:$HEX[3435343533356c3a66647266] ``` ## Output Script will create *clears.txt* file which contains the original HEX value and the plaintext variant. Some example output: ```plain HEX: 56696c6c616c6f626f7335353a | Plain: Villalobos55: HEX: 4bfc6e646967756e673139 | Plain: Kündigung19 HEX: 466f72e761666532 | Plain: Forçafe2 HEX: 536368e464656c323321 | Plain: Schädel23! HEX: 4672fc686c696e673230313821 | Plain: Frühling2018! HEX: 5073616c6d37333a3236 | Plain: Psalm73:26 HEX: 44fc7373656c646f72662e3139 | Plain: Düsseldorf.19 ```
91deb7280ce8a8caa918ceffe35f58ab8633beb9
[ "Markdown", "Shell" ]
2
Shell
crypt0rr/hex-to-readable
b4e733fc208086d1652158cce3d2716bc0cb13ac
b5b57e50590fa9f0a30851cc3f632ab4060a4160
refs/heads/master
<file_sep># Web Server Backend and Frontend with html on NodeJS with MySQL <file_sep>var http = require('http'); var express = require('express'); var bodyParser = require('body-parser'); var path = require('path'); var port = process.env.PORT || 8080; var app = express(); app.use(bodyParser.urlencoded({ extended: false })) app.use(bodyParser.json()); var mysql = require('mysql'); var con = mysql.createConnection({ host: "192.168.56.3", user: "root", password: "<PASSWORD>", database: "mydb" }); con.connect(function (err) { if (err) throw err; console.log("Connected!"); var sql = "DROP TABLE customers"; con.query(sql, function (err, result) { if (err) throw err; console.log("Table deleted"); }); var sql = "CREATE TABLE customers (name VARCHAR(255), id VARCHAR(255))"; con.query(sql, function (err, result) { if (err) throw err; console.log("Table created"); }); }); app.get('/', function (req, res) { console.log('GET="/"'); res.sendFile(path.join(__dirname + '/principal.html')); }); app.post('/add', function (req, res) { console.log('POST="/add"'); console.log(req.body) var sql = "INSERT INTO customers (name, id) VALUES ('" + req.body.name + "', '" + req.body.id + "')"; con.query(sql, function (err, result) { if (err) throw err; console.log("1 record inserted"); }); res.sendFile(path.join(__dirname + '/principal.html')); }); app.get('/list', function (req, res) { console.log('GET="/list"'); con.query("SELECT * FROM customers", function (err, result, fields) { if (err) throw err; res.status(200).send(result) }); }); http.createServer(app).listen(port);
b07e15cb52ea5fe1c0022867a752d3a8235ba062
[ "Markdown", "JavaScript" ]
2
Markdown
Jorge-Andres-Moreno/backend-Node.JS-MongoDB
a89e67f988d35e9d1d3d361c3b81211f156cf56e
e0e6c65b5ca0baf86c5c93944892a99d9aa32bcf
refs/heads/master
<file_sep>collection = [1,2,3,4] def my_each(collection) while i <= collection[3] do |i| yield puts "There it is" end
f00157ba12bee819fe22b2075eeb43bf3df4ead6
[ "Ruby" ]
1
Ruby
ShayMotion/my-each-online-web-sp-000
239affed54818faa46ee8b1e740f8350e89b3513
f0b0c8ced66af2f969e8cad0c9d7503e8b4f2789