text
stringlengths
184
4.48M
'use strict'; // selecting Elements const player0El = document.querySelector('.player--0'); const player1El = document.querySelector('.player--1'); const score0El = document.querySelector('#score--0'); const score1El = document.getElementById('score--1'); const current0El =document.getElementById('current--0'); const current1El =document.getElementById('current--1'); const diceEl =document.querySelector('.dice'); const btnNew = document.querySelector('.btn--new'); const btnRoll = document.querySelector('.btn--roll'); const btnHold = document.querySelector('.btn--hold'); let score,currentScore,activePlayer,playing; // starting condtion const init = function(){ score = [0,0]; currentScore=0; activePlayer = 0; playing = true; score0El.textContent=0; score1El.textContent=0; current0El.textContent=0; current1El.textContent=0; diceEl.classList.add('hidden'); player0El.classList.remove('player--winner'); player1El.classList.remove('player--winner'); player0El.classList.add('player--active'); player1El.classList.remove('player--active'); }; init(); const switchPlayer = function(){ document.getElementById(`current--${activePlayer}`).textContent=0; currentScore=0; activePlayer = activePlayer=== 0 ? 1:0; player0El.classList.toggle('player--active'); player1El.classList.toggle('player--active'); } // rolling dice functionality btnRoll.addEventListener('click',function(){ if(playing){ // 1. Generating a dandom dice btnRoll const dice =Math.trunc(Math.random()*6)+1; // 2. diplay dice diceEl.classList.remove('hidden'); diceEl.src = `dice-${dice}.png`; // 3. checjfor rolled 1: if true,switch to next player if(dice !==1){ // Add dice to current score currentScore=currentScore+dice; document.getElementById(`current--${activePlayer}`).textContent=currentScore; } else{ // switch to next player switchPlayer(); } } }); btnHold.addEventListener('click',function(){ if(playing){ // 1. Add current score to active player's score score[activePlayer] += currentScore; console.log(score[activePlayer]); document.getElementById(`score--${activePlayer}`).textContent=score[activePlayer]; // 2.check if player's score is>=100 if(score[activePlayer]>=100){ // finish the game playing=false; diceEl.classList.add('hidden'); document.querySelector(`.player--${activePlayer}`).classList.add('player--winner'); document.querySelector(`.player--${activePlayer}`).classList.remove('player--active'); }else{ // switch to the next player switchPlayer(); } } }); btnNew.addEventListener('click',init);
--- title: "\"2024 Approved Avatar Architecture Your Uncomplicated Guide to Virtual Existence\"" date: 2024-06-19T23:49:56.366Z updated: 2024-06-20T23:49:56.366Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "\"This Article Describes 2024 Approved: Avatar Architecture: Your Uncomplicated Guide to Virtual Existence\"" excerpt: "\"This Article Describes 2024 Approved: Avatar Architecture: Your Uncomplicated Guide to Virtual Existence\"" keywords: "\"Avatar Build Tips,Virtual Life Basics,Simplified Avatar Design,Building In-Game Characters,Easy Avatar Creation Guide,Fundamentals of Virtual Existence,Simplicity in Virtual Identity Formation\"" thumbnail: https://thmb.techidaily.com/31e82f83edcdc65ad4f95de4a88750a749956ca58ec25424a7976e33fcb26a46.jpg --- ## Avatar Architecture: Your Uncomplicated Guide to Virtual Existence ##### Versatile Video Editor - Wondershare Filmora An easy yet powerful editor Numerous effects to choose from Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Metaverse is currently similar to the phrase Internet in the early 1970s. Back in the days defining the internet was practically impossible, but people had an idea of what it would bring. However, Metaverse goes hand in hand with the avatar Metaverse. As the name Meta suggests, Metaverse refers to a digital reality whose main objective is to blend in virtual reality, augmented reality, social media platforms, cryptocurrencies, and online gaming. Of course, we currently have platforms that feature avatars and virtual identities, but they include one flaw: all these features work on the same platform. This individuality syndrome is what Metaverse wishes to solve. In our case, we are discussing the **Metaverse Avatar** and the most straightforward way to create one. Join us as we walk on the journey to creating a Metaverse avatar in the simplest way possible. Read on! #### In this article 01 [What is an Avatar?](#part1) 02 [What does Avatar Mean to Metaverse?](#part2) 03 [How to Create Metaverse Avatar with Ease?](#part3) 04 [Don't Forget to Bring Your NFT Avatar Makers to Metaverse](#part4) ## Part 1: What is an Avatar? Generally, an avatar refers to an icon or figure representing a person in a video game, social media platform, etc. In other words, a representation of you on the internet. When Metaverse Avatar comes about, think of an icon representing you in the VR (Virtual Reality). Therefore, as technical experts talk of Metaverse, an avatar is equally essential. Why? Because it is what you use to identify yourself in the digital world. Think of it in the sense of how you go about opening a social media account. Typically, you will upload your photo as a visual representation of yourself on the platform. The same case happens when dealing with Metaverse; you need an avatar. However, in this case, you don't need your real photo since you settle for a figure where you dress it and design it as per your taste and preference. ![what is an avatar](https://images.wondershare.com/filmora/article-images/2021/what-is-an-avatar.jpg) ## Part 2: What does Avatar Mean to Metaverse? As mentioned above, Metaverse is a technological evolution aiming to blend various platforms such as video games and social media and allow people to interact with each other efficiently. Reports show that experts often mention Metaverse and avatars hand in hand. In other words, they feature a dependent relationship. You probably don't understand why avatars are crucial in Metaverse when you think of the two. And this is the area that this section wishes to address. What is the importance of Avatars for the Metaverse community? Avatars refer to various individuals' representations when dealing with the digital world. In simple terms, you use an avatar in place of you in the virtual world. Avatar Metaverse gives the users a sense of identity while navigating through the internet. With the help of an avatar, you express your identity to the online community. However, note that the critical feature in Avatars that makes it extremely important in Metaverse is interoperability is the ability for the avatars to communicate between various platforms easily. For example, when you buy things for your Avatar, this feature allows you to move around multiple online platforms with these changes. Avatars in Metaverse give a sense of togetherness in the virtual world. ![how avatar](https://images.wondershare.com/filmora/article-images/2021/how-avatar-look-like.jpg) ## Part 3: How to Create Metaverse Avatar with Ease? If you have heard about Metaverse avatars, you probably have ideas of what you figure you want the virtual world to use when recognizing you. However, the technology is a bit new, and very few people know what to do. Fortunately, this article is here to give you all the correct answers. We highlight the top Avatar creating hack that will make your **Avatar Metaverse** creating experience bigger and better. Check it out! Currently, there are several Metaverse avatar creators you will come across, including the ready player me Avatar. This option is quite popular since it resembles you and you can edit as per your taste. However, there are basic rules one needs to follow, and that is what this section will focus on regarding avatar creation. ### Find a high-quality Avatar-making application There are multiple apps you will come across that allows you to make an avatar. Settle for the right tool depending on the ecosystem you are using; for example, android and iOS users can settle for the Zmoji software. ### Launch the application and kick off the Avatar creating process Most of the software you meet will inquire about your gender to know the right style for you. You can choose to upload a photo so that the avatar maker can generate a figure that has closely related features to you. Besides, you can choose to settle for ready player me avatars available. ### Customize the figure Under this step, you will have various facial features such as nose size, lips shape, eye size, hair size, color options, etc. Change your Avatar to look like your heart's desires. ### Save all the necessary changes After settling for the best option, save your Avatar, and you can share or use them in various digital environments. The steps above define one of the simplest ways to create an Avatar Metaverse ready for use after the development phase. ## Part 4: Don't Forget to Bring Your NFT Avatar Makers to Metaverse From Metaverse's definition, you probably understand that technology experts are trying to create a solid online community where people can comfortably interact with each other. Also, every person uses a specific avatar on all these digital platforms. Therefore all the applications, including the metaverse avatar NFT makers, are welcome to join the community. ![Filmora AR Sticker](https://images.wondershare.com/filmora/guide/filmora-ar-sticker-directory.jpg) #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects![Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora box](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) Today, most people settle for the metaverse avatar NFT that developers generate by creating unique algorithms. Over the years, their popularity keeps rising thanks to the fantastic features, and the companies behind these metaverse avatars NFT have sold out millions. If you are pretty keen on video editing, you have probably heard of the Filmora software. It is a popular application among videographers for video editing purposes. However, after the introduction of metaverse Avatars, the software now holds the power of creating the ready player for me avatars. After all, the software features AR, Augmented Reality stickers. Note that the AR stickers often come in handy when Avatar makers wish to create metaverse avatars NFT. If you want to create your NFT avatar, then Wondershare Filmora will be the right solution. So, move ahead in your journey of metaverse avatar making with Wondershare Filmora. ### Conclusion After this technological evolution took the internet on a storm, we often hear the Metaverse world from technical experts. Also, it would be a lie to conclude that we know a lot about this growing community. After all, it represents the future of the internet, and not much is apparent in the area. However, we are confident that Metaverse Avatars are a must-have for its success. With that in mind, this article focuses on explaining facts about avatars and the simplest way of making one. Check out the points above to get an insight into Avatars in Metaverse. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Metaverse is currently similar to the phrase Internet in the early 1970s. Back in the days defining the internet was practically impossible, but people had an idea of what it would bring. However, Metaverse goes hand in hand with the avatar Metaverse. As the name Meta suggests, Metaverse refers to a digital reality whose main objective is to blend in virtual reality, augmented reality, social media platforms, cryptocurrencies, and online gaming. Of course, we currently have platforms that feature avatars and virtual identities, but they include one flaw: all these features work on the same platform. This individuality syndrome is what Metaverse wishes to solve. In our case, we are discussing the **Metaverse Avatar** and the most straightforward way to create one. Join us as we walk on the journey to creating a Metaverse avatar in the simplest way possible. Read on! #### In this article 01 [What is an Avatar?](#part1) 02 [What does Avatar Mean to Metaverse?](#part2) 03 [How to Create Metaverse Avatar with Ease?](#part3) 04 [Don't Forget to Bring Your NFT Avatar Makers to Metaverse](#part4) ## Part 1: What is an Avatar? Generally, an avatar refers to an icon or figure representing a person in a video game, social media platform, etc. In other words, a representation of you on the internet. When Metaverse Avatar comes about, think of an icon representing you in the VR (Virtual Reality). Therefore, as technical experts talk of Metaverse, an avatar is equally essential. Why? Because it is what you use to identify yourself in the digital world. Think of it in the sense of how you go about opening a social media account. Typically, you will upload your photo as a visual representation of yourself on the platform. The same case happens when dealing with Metaverse; you need an avatar. However, in this case, you don't need your real photo since you settle for a figure where you dress it and design it as per your taste and preference. ![what is an avatar](https://images.wondershare.com/filmora/article-images/2021/what-is-an-avatar.jpg) ## Part 2: What does Avatar Mean to Metaverse? As mentioned above, Metaverse is a technological evolution aiming to blend various platforms such as video games and social media and allow people to interact with each other efficiently. Reports show that experts often mention Metaverse and avatars hand in hand. In other words, they feature a dependent relationship. You probably don't understand why avatars are crucial in Metaverse when you think of the two. And this is the area that this section wishes to address. What is the importance of Avatars for the Metaverse community? Avatars refer to various individuals' representations when dealing with the digital world. In simple terms, you use an avatar in place of you in the virtual world. Avatar Metaverse gives the users a sense of identity while navigating through the internet. With the help of an avatar, you express your identity to the online community. However, note that the critical feature in Avatars that makes it extremely important in Metaverse is interoperability is the ability for the avatars to communicate between various platforms easily. For example, when you buy things for your Avatar, this feature allows you to move around multiple online platforms with these changes. Avatars in Metaverse give a sense of togetherness in the virtual world. ![how avatar](https://images.wondershare.com/filmora/article-images/2021/how-avatar-look-like.jpg) ## Part 3: How to Create Metaverse Avatar with Ease? If you have heard about Metaverse avatars, you probably have ideas of what you figure you want the virtual world to use when recognizing you. However, the technology is a bit new, and very few people know what to do. Fortunately, this article is here to give you all the correct answers. We highlight the top Avatar creating hack that will make your **Avatar Metaverse** creating experience bigger and better. Check it out! Currently, there are several Metaverse avatar creators you will come across, including the ready player me Avatar. This option is quite popular since it resembles you and you can edit as per your taste. However, there are basic rules one needs to follow, and that is what this section will focus on regarding avatar creation. ### Find a high-quality Avatar-making application There are multiple apps you will come across that allows you to make an avatar. Settle for the right tool depending on the ecosystem you are using; for example, android and iOS users can settle for the Zmoji software. ### Launch the application and kick off the Avatar creating process Most of the software you meet will inquire about your gender to know the right style for you. You can choose to upload a photo so that the avatar maker can generate a figure that has closely related features to you. Besides, you can choose to settle for ready player me avatars available. ### Customize the figure Under this step, you will have various facial features such as nose size, lips shape, eye size, hair size, color options, etc. Change your Avatar to look like your heart's desires. ### Save all the necessary changes After settling for the best option, save your Avatar, and you can share or use them in various digital environments. The steps above define one of the simplest ways to create an Avatar Metaverse ready for use after the development phase. ## Part 4: Don't Forget to Bring Your NFT Avatar Makers to Metaverse From Metaverse's definition, you probably understand that technology experts are trying to create a solid online community where people can comfortably interact with each other. Also, every person uses a specific avatar on all these digital platforms. Therefore all the applications, including the metaverse avatar NFT makers, are welcome to join the community. ![Filmora AR Sticker](https://images.wondershare.com/filmora/guide/filmora-ar-sticker-directory.jpg) #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects![Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora box](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) Today, most people settle for the metaverse avatar NFT that developers generate by creating unique algorithms. Over the years, their popularity keeps rising thanks to the fantastic features, and the companies behind these metaverse avatars NFT have sold out millions. If you are pretty keen on video editing, you have probably heard of the Filmora software. It is a popular application among videographers for video editing purposes. However, after the introduction of metaverse Avatars, the software now holds the power of creating the ready player for me avatars. After all, the software features AR, Augmented Reality stickers. Note that the AR stickers often come in handy when Avatar makers wish to create metaverse avatars NFT. If you want to create your NFT avatar, then Wondershare Filmora will be the right solution. So, move ahead in your journey of metaverse avatar making with Wondershare Filmora. ### Conclusion After this technological evolution took the internet on a storm, we often hear the Metaverse world from technical experts. Also, it would be a lie to conclude that we know a lot about this growing community. After all, it represents the future of the internet, and not much is apparent in the area. However, we are confident that Metaverse Avatars are a must-have for its success. With that in mind, this article focuses on explaining facts about avatars and the simplest way of making one. Check out the points above to get an insight into Avatars in Metaverse. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Metaverse is currently similar to the phrase Internet in the early 1970s. Back in the days defining the internet was practically impossible, but people had an idea of what it would bring. However, Metaverse goes hand in hand with the avatar Metaverse. As the name Meta suggests, Metaverse refers to a digital reality whose main objective is to blend in virtual reality, augmented reality, social media platforms, cryptocurrencies, and online gaming. Of course, we currently have platforms that feature avatars and virtual identities, but they include one flaw: all these features work on the same platform. This individuality syndrome is what Metaverse wishes to solve. In our case, we are discussing the **Metaverse Avatar** and the most straightforward way to create one. Join us as we walk on the journey to creating a Metaverse avatar in the simplest way possible. Read on! #### In this article 01 [What is an Avatar?](#part1) 02 [What does Avatar Mean to Metaverse?](#part2) 03 [How to Create Metaverse Avatar with Ease?](#part3) 04 [Don't Forget to Bring Your NFT Avatar Makers to Metaverse](#part4) ## Part 1: What is an Avatar? Generally, an avatar refers to an icon or figure representing a person in a video game, social media platform, etc. In other words, a representation of you on the internet. When Metaverse Avatar comes about, think of an icon representing you in the VR (Virtual Reality). Therefore, as technical experts talk of Metaverse, an avatar is equally essential. Why? Because it is what you use to identify yourself in the digital world. Think of it in the sense of how you go about opening a social media account. Typically, you will upload your photo as a visual representation of yourself on the platform. The same case happens when dealing with Metaverse; you need an avatar. However, in this case, you don't need your real photo since you settle for a figure where you dress it and design it as per your taste and preference. ![what is an avatar](https://images.wondershare.com/filmora/article-images/2021/what-is-an-avatar.jpg) ## Part 2: What does Avatar Mean to Metaverse? As mentioned above, Metaverse is a technological evolution aiming to blend various platforms such as video games and social media and allow people to interact with each other efficiently. Reports show that experts often mention Metaverse and avatars hand in hand. In other words, they feature a dependent relationship. You probably don't understand why avatars are crucial in Metaverse when you think of the two. And this is the area that this section wishes to address. What is the importance of Avatars for the Metaverse community? Avatars refer to various individuals' representations when dealing with the digital world. In simple terms, you use an avatar in place of you in the virtual world. Avatar Metaverse gives the users a sense of identity while navigating through the internet. With the help of an avatar, you express your identity to the online community. However, note that the critical feature in Avatars that makes it extremely important in Metaverse is interoperability is the ability for the avatars to communicate between various platforms easily. For example, when you buy things for your Avatar, this feature allows you to move around multiple online platforms with these changes. Avatars in Metaverse give a sense of togetherness in the virtual world. ![how avatar](https://images.wondershare.com/filmora/article-images/2021/how-avatar-look-like.jpg) ## Part 3: How to Create Metaverse Avatar with Ease? If you have heard about Metaverse avatars, you probably have ideas of what you figure you want the virtual world to use when recognizing you. However, the technology is a bit new, and very few people know what to do. Fortunately, this article is here to give you all the correct answers. We highlight the top Avatar creating hack that will make your **Avatar Metaverse** creating experience bigger and better. Check it out! Currently, there are several Metaverse avatar creators you will come across, including the ready player me Avatar. This option is quite popular since it resembles you and you can edit as per your taste. However, there are basic rules one needs to follow, and that is what this section will focus on regarding avatar creation. ### Find a high-quality Avatar-making application There are multiple apps you will come across that allows you to make an avatar. Settle for the right tool depending on the ecosystem you are using; for example, android and iOS users can settle for the Zmoji software. ### Launch the application and kick off the Avatar creating process Most of the software you meet will inquire about your gender to know the right style for you. You can choose to upload a photo so that the avatar maker can generate a figure that has closely related features to you. Besides, you can choose to settle for ready player me avatars available. ### Customize the figure Under this step, you will have various facial features such as nose size, lips shape, eye size, hair size, color options, etc. Change your Avatar to look like your heart's desires. ### Save all the necessary changes After settling for the best option, save your Avatar, and you can share or use them in various digital environments. The steps above define one of the simplest ways to create an Avatar Metaverse ready for use after the development phase. ## Part 4: Don't Forget to Bring Your NFT Avatar Makers to Metaverse From Metaverse's definition, you probably understand that technology experts are trying to create a solid online community where people can comfortably interact with each other. Also, every person uses a specific avatar on all these digital platforms. Therefore all the applications, including the metaverse avatar NFT makers, are welcome to join the community. ![Filmora AR Sticker](https://images.wondershare.com/filmora/guide/filmora-ar-sticker-directory.jpg) #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects![Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora box](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) Today, most people settle for the metaverse avatar NFT that developers generate by creating unique algorithms. Over the years, their popularity keeps rising thanks to the fantastic features, and the companies behind these metaverse avatars NFT have sold out millions. If you are pretty keen on video editing, you have probably heard of the Filmora software. It is a popular application among videographers for video editing purposes. However, after the introduction of metaverse Avatars, the software now holds the power of creating the ready player for me avatars. After all, the software features AR, Augmented Reality stickers. Note that the AR stickers often come in handy when Avatar makers wish to create metaverse avatars NFT. If you want to create your NFT avatar, then Wondershare Filmora will be the right solution. So, move ahead in your journey of metaverse avatar making with Wondershare Filmora. ### Conclusion After this technological evolution took the internet on a storm, we often hear the Metaverse world from technical experts. Also, it would be a lie to conclude that we know a lot about this growing community. After all, it represents the future of the internet, and not much is apparent in the area. However, we are confident that Metaverse Avatars are a must-have for its success. With that in mind, this article focuses on explaining facts about avatars and the simplest way of making one. Check out the points above to get an insight into Avatars in Metaverse. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Metaverse is currently similar to the phrase Internet in the early 1970s. Back in the days defining the internet was practically impossible, but people had an idea of what it would bring. However, Metaverse goes hand in hand with the avatar Metaverse. As the name Meta suggests, Metaverse refers to a digital reality whose main objective is to blend in virtual reality, augmented reality, social media platforms, cryptocurrencies, and online gaming. Of course, we currently have platforms that feature avatars and virtual identities, but they include one flaw: all these features work on the same platform. This individuality syndrome is what Metaverse wishes to solve. In our case, we are discussing the **Metaverse Avatar** and the most straightforward way to create one. Join us as we walk on the journey to creating a Metaverse avatar in the simplest way possible. Read on! #### In this article 01 [What is an Avatar?](#part1) 02 [What does Avatar Mean to Metaverse?](#part2) 03 [How to Create Metaverse Avatar with Ease?](#part3) 04 [Don't Forget to Bring Your NFT Avatar Makers to Metaverse](#part4) ## Part 1: What is an Avatar? Generally, an avatar refers to an icon or figure representing a person in a video game, social media platform, etc. In other words, a representation of you on the internet. When Metaverse Avatar comes about, think of an icon representing you in the VR (Virtual Reality). Therefore, as technical experts talk of Metaverse, an avatar is equally essential. Why? Because it is what you use to identify yourself in the digital world. Think of it in the sense of how you go about opening a social media account. Typically, you will upload your photo as a visual representation of yourself on the platform. The same case happens when dealing with Metaverse; you need an avatar. However, in this case, you don't need your real photo since you settle for a figure where you dress it and design it as per your taste and preference. ![what is an avatar](https://images.wondershare.com/filmora/article-images/2021/what-is-an-avatar.jpg) ## Part 2: What does Avatar Mean to Metaverse? As mentioned above, Metaverse is a technological evolution aiming to blend various platforms such as video games and social media and allow people to interact with each other efficiently. Reports show that experts often mention Metaverse and avatars hand in hand. In other words, they feature a dependent relationship. You probably don't understand why avatars are crucial in Metaverse when you think of the two. And this is the area that this section wishes to address. What is the importance of Avatars for the Metaverse community? Avatars refer to various individuals' representations when dealing with the digital world. In simple terms, you use an avatar in place of you in the virtual world. Avatar Metaverse gives the users a sense of identity while navigating through the internet. With the help of an avatar, you express your identity to the online community. However, note that the critical feature in Avatars that makes it extremely important in Metaverse is interoperability is the ability for the avatars to communicate between various platforms easily. For example, when you buy things for your Avatar, this feature allows you to move around multiple online platforms with these changes. Avatars in Metaverse give a sense of togetherness in the virtual world. ![how avatar](https://images.wondershare.com/filmora/article-images/2021/how-avatar-look-like.jpg) ## Part 3: How to Create Metaverse Avatar with Ease? If you have heard about Metaverse avatars, you probably have ideas of what you figure you want the virtual world to use when recognizing you. However, the technology is a bit new, and very few people know what to do. Fortunately, this article is here to give you all the correct answers. We highlight the top Avatar creating hack that will make your **Avatar Metaverse** creating experience bigger and better. Check it out! Currently, there are several Metaverse avatar creators you will come across, including the ready player me Avatar. This option is quite popular since it resembles you and you can edit as per your taste. However, there are basic rules one needs to follow, and that is what this section will focus on regarding avatar creation. ### Find a high-quality Avatar-making application There are multiple apps you will come across that allows you to make an avatar. Settle for the right tool depending on the ecosystem you are using; for example, android and iOS users can settle for the Zmoji software. ### Launch the application and kick off the Avatar creating process Most of the software you meet will inquire about your gender to know the right style for you. You can choose to upload a photo so that the avatar maker can generate a figure that has closely related features to you. Besides, you can choose to settle for ready player me avatars available. ### Customize the figure Under this step, you will have various facial features such as nose size, lips shape, eye size, hair size, color options, etc. Change your Avatar to look like your heart's desires. ### Save all the necessary changes After settling for the best option, save your Avatar, and you can share or use them in various digital environments. The steps above define one of the simplest ways to create an Avatar Metaverse ready for use after the development phase. ## Part 4: Don't Forget to Bring Your NFT Avatar Makers to Metaverse From Metaverse's definition, you probably understand that technology experts are trying to create a solid online community where people can comfortably interact with each other. Also, every person uses a specific avatar on all these digital platforms. Therefore all the applications, including the metaverse avatar NFT makers, are welcome to join the community. ![Filmora AR Sticker](https://images.wondershare.com/filmora/guide/filmora-ar-sticker-directory.jpg) #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects![Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmora box](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) Today, most people settle for the metaverse avatar NFT that developers generate by creating unique algorithms. Over the years, their popularity keeps rising thanks to the fantastic features, and the companies behind these metaverse avatars NFT have sold out millions. If you are pretty keen on video editing, you have probably heard of the Filmora software. It is a popular application among videographers for video editing purposes. However, after the introduction of metaverse Avatars, the software now holds the power of creating the ready player for me avatars. After all, the software features AR, Augmented Reality stickers. Note that the AR stickers often come in handy when Avatar makers wish to create metaverse avatars NFT. If you want to create your NFT avatar, then Wondershare Filmora will be the right solution. So, move ahead in your journey of metaverse avatar making with Wondershare Filmora. ### Conclusion After this technological evolution took the internet on a storm, we often hear the Metaverse world from technical experts. Also, it would be a lie to conclude that we know a lot about this growing community. After all, it represents the future of the internet, and not much is apparent in the area. However, we are confident that Metaverse Avatars are a must-have for its success. With that in mind, this article focuses on explaining facts about avatars and the simplest way of making one. Check out the points above to get an insight into Avatars in Metaverse. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://article-knowledge.techidaily.com/2024-approved-mastering-quantum-hdr-principles/"><u>2024 Approved Mastering Quantum HDR Principles</u></a></li> <li><a href="https://article-knowledge.techidaily.com/updated-2024-approved-reactivate-windows-photo-viewer-with-ease-win-11/"><u>[Updated] 2024 Approved Reactivate Windows Photo Viewer with Ease (Win 11)</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-heartfelt-cheers-access-to-free-and-paid-otu-ideas/"><u>[New] Heartfelt Cheers Access to Free & Paid OTU Ideas</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-in-2024-guide-to-mastering-windows-movie-maker-in-w11-for-beginners/"><u>[New] In 2024, Guide to Mastering Windows Movie Maker in W11 for Beginners</u></a></li> <li><a href="https://article-knowledge.techidaily.com/11-must-know-hues-for-professional-grading/"><u>11 Must-Know Hues for Professional Grading</u></a></li> <li><a href="https://article-knowledge.techidaily.com/updated-mastering-pc-hd-video-viewing-and-editing-with-windows-hdr-support/"><u>[Updated] Mastering PC HD Video Viewing & Editing with Windows HDR Support</u></a></li> <li><a href="https://article-knowledge.techidaily.com/updated-in-2024-discover-the-full-screen-fusion-potential-with-sierras-multimedia-capabilities/"><u>[Updated] In 2024, Discover the Full-Screen Fusion Potential with Sierra's Multimedia Capabilities</u></a></li> <li><a href="https://article-knowledge.techidaily.com/new-dial-in-focus-background-out-of-the-way-for-2024/"><u>[New] Dial In Focus Background Out Of The Way for 2024</u></a></li> <li><a href="https://article-knowledge.techidaily.com/updated-2024-approved-the-best-cheap-action-cameras-to-purchase-for-under-100/"><u>[Updated] 2024 Approved The Best Cheap Action Cameras to Purchase for Under $100</u></a></li> <li><a href="https://extra-resources.techidaily.com/elevating-your-gopro-footage-through-color-grading/"><u>Elevating Your GoPro Footage Through Color Grading</u></a></li> <li><a href="https://android-location-track.techidaily.com/3-ways-to-track-vivo-v30-lite-5g-without-them-knowing-drfone-by-drfone-virtual-android/"><u>3 Ways to Track Vivo V30 Lite 5G without Them Knowing | Dr.fone</u></a></li> <li><a href="https://some-tips.techidaily.com/new-mobile-friendly-youtubing-with-no-high-subscriber-count/"><u>[New] Mobile-Friendly YouTubing with No High Subscriber Count</u></a></li> <li><a href="https://facebook-video-share.techidaily.com/new-youtubes-beauty-titans-whos-leading/"><u>[New] YouTube's Beauty Titans Who's Leading ?</u></a></li> <li><a href="https://instagram-clips.techidaily.com/in-2024-elevate-your-account-25-top-instagram-tags-for-maximum-engagement/"><u>In 2024, Elevate Your Account 25 Top Instagram Tags for Maximum Engagement</u></a></li> <li><a href="https://blog-min.techidaily.com/how-to-downgrade-iphone-se-without-losing-anything-drfone-by-drfone-ios-system-repair-ios-system-repair/"><u>How to Downgrade iPhone SE without Losing Anything? | Dr.fone</u></a></li> <li><a href="https://vp-tips.techidaily.com/best-practices-in-apple-podcast-file-formatting/"><u>Best Practices in Apple Podcast File Formatting</u></a></li> <li><a href="https://eaxpv-info.techidaily.com/updated-in-2024-how-to-craft-standout-names-for-your-youtube-channel/"><u>[Updated] In 2024, How to Craft Standout Names for Your YouTube Channel</u></a></li> <li><a href="https://vp-tips.techidaily.com/updated-2024-approved-a-comprehensive-guide-accumulating-massive-amounts-of-tiktok-videos/"><u>[Updated] 2024 Approved A Comprehensive Guide Accumulating Massive Amounts of TikTok Videos</u></a></li> <li><a href="https://some-skills.techidaily.com/the-future-of-interaction-with-microsofts-hololens-review-for-2024/"><u>The Future of Interaction with Microsoft's HoloLens Review for 2024</u></a></li> </ul></div>
// // BoxTextFieldView.swift // HotmartCosmos // // Created by Douglas Seabra Pedrosa on 10/12/21. // import Foundation import UIKit final class BoxTextFieldView: ThemedCodedView, Bindable { // MARK: - View Metrics private enum Constants { static let textFiedlBorderWidth: CGFloat = 1.0 static let textFielHeight: CGFloat = 48.0 static let textFieldWidth: CGFloat = 48.0 static let minBoxItems: Int = 1 static let maxBoxItems: Int = 6 static let dashPattern: [NSNumber] = [10, 4] } // MARK: - View Elements private lazy var textFieldStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .equalCentering stackView.alignment = .center stackView.spacing = Spacing().spacing2.value return stackView }() private let descriptionStackView: UIStackView = { let stackView = StackViewBuilder { $0.axis = .horizontal $0.spacing = Spacing().spacing2.value $0.distribution = .fill }.build() stackView.setContentHuggingPriority(.required, for: .vertical) return stackView }() private let descriptionLabel: UILabel = { let view = UILabel() view.isHidden = true view.numberOfLines = .zero view.textAlignment = .center view.setContentCompressionResistancePriority(.required, for: .horizontal) view.setContentHuggingPriority(.required, for: .vertical) return view }() // MARK: - Private Properties private var viewModel: BoxTextFieldModel? private var action: ((BoxTextFieldAction) -> Void)? private var textFields: [UITextField] { textFieldStackView.subviews.compactMap({ $0 as? UITextField }) } private var value: String { textFields .compactMap(\.text) .reduce("", { $0 + $1 }) } private var numberOfItems: Int = .zero // MARK: - ThemedCodedView override func configurateColors() { guard let system = viewModel?.getSystem() else { return } descriptionLabel.font = system.descriptionTypography.font configureTextForSystem(system) } // MARK: - CodedView override func addSubviews() { addSubview(textFieldStackView) addSubview(descriptionStackView) descriptionStackView.addArrangedSubview(descriptionLabel) } override func constrainSubviews() { constrainTextFieldStackView() constrainDescriptionStackView() } private func constrainTextFieldStackView() { textFieldStackView.anchor( top: topAnchor, leading: leadingAnchor, trailing: trailingAnchor ) } private func constrainDescriptionStackView() { descriptionStackView.anchor( top: textFieldStackView.bottomAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor, topConstant: Spacing().spacing1.value ) } private func constrainTextFields() { textFields.forEach { $0.widthAnchor.constraint(equalToConstant: Constants.textFieldWidth).isActive = true $0.heightAnchor.constraint(equalToConstant: Constants.textFielHeight).isActive = true } } @discardableResult override func becomeFirstResponder() -> Bool { textFields.first?.becomeFirstResponder() ?? false } // MARK: - Private Methods private func configureForState() { guard let state = viewModel?.state else { return } let styleColor = state.getBorderColor() let styleBackgroundColor = state.getBackgroundColor() descriptionLabel.textColor = styleColor textFields.forEach { $0.textColor = state.getTextColor() if case .disabled = state { $0.isEnabled = false $0.isUserInteractionEnabled = false $0.layer.borderColor = UIColor.clear.cgColor configureDashBorder(textField: $0, strokeColor: styleColor, fillColor: styleBackgroundColor) } else { clearDashBorder(textField: $0) $0.isEnabled = true $0.isUserInteractionEnabled = true $0.layer.borderColor = styleColor.cgColor } } } private func configureTextForSystem(_ system: SystemBoxTextField) { textFields.forEach { $0.font = system.textTypography.font } } private func makeTextField(_ index: Int) -> CustomDeleteActionTextField { let textField = CustomDeleteActionTextField() textField.font = Cosmos.typography.bodyStrong.text2Strong.font textField.textColor = Cosmos.colors.productColors.neutralProductColor.neutral900.color textField.contentMode = .center textField.textAlignment = .center textField.layer.borderWidth = Constants.textFiedlBorderWidth textField.layer.cornerRadius = BorderRadiusGroup().small.value textField.delegate = self textField.deleteDelegate = self textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged) return textField } @objc func textFieldDidChange(textField: UITextField) { guard let text = textField.text else { return } action?(.textDidChange(value)) if text.count > .one { textField.text = "\(text[text.index(before: text.endIndex)])" } guard let textCount = textField.text?.utf16.count, textCount >= .one else { return } guard let indexOfTextField = textFields.firstIndex(of: textField), textFields.indices.contains(indexOfTextField + .one) else { endEditing(true) action?(.textFinishEdit(value)) return } let nextTextField = textFields[indexOfTextField + .one] nextTextField.becomeFirstResponder() } private func selectTextField(_ textField: UITextField, isSelected: Bool) { guard let system = viewModel?.getSystem() else { return } if isSelected { textField.backgroundColor = system.activeBackgroundColor.color textField.layer.borderColor = system.activeColor.color.cgColor } else { textField.backgroundColor = textField.text?.isEmpty == false ? system.activeBackgroundColor.color : system.defaultBackgroundColor.color textField.layer.borderColor = system.defaultColor.color.cgColor } } private func setupBeginEditing() { guard let system = viewModel?.getSystem() else { return } textFields.forEach { $0.layer.borderColor = system.defaultColor.color.cgColor $0.backgroundColor = $0.text?.isEmpty == false ? system.activeBackgroundColor.color : system.defaultBackgroundColor.color $0.textColor = system.textColor.color } descriptionLabel.isHidden = true } private func removeAllTextFields() { textFieldStackView.removeSubviews() } private func clearDashBorder(textField: UITextField) { guard let border = textField.layer.sublayers?.first(where: { $0 is CAShapeLayer }), let dashBorder = border as? CAShapeLayer else { return } dashBorder.fillColor = UIColor.clear.cgColor dashBorder.strokeColor = UIColor.clear.cgColor } private func configureDashBorder(textField: UITextField, strokeColor: UIColor, fillColor: UIColor) { guard let border = textField.layer.sublayers?.first(where: { $0 is CAShapeLayer }), let dashBorder = border as? CAShapeLayer else { textField.addDashedBorder( strokeColor: strokeColor, fillColor: fillColor, cornerRadius: BorderRadiusGroup().small.value, customWidth: Constants.textFieldWidth, customHeight: Constants.textFielHeight ) return } dashBorder.fillColor = fillColor.cgColor dashBorder.strokeColor = strokeColor.cgColor } private func createTextFields() { guard textFieldStackView.subviews.count != numberOfItems else { return } removeAllTextFields() for tag in Constants.minBoxItems ... numberOfItems { let textField = makeTextField(tag) textField.tag = tag textFieldStackView.addArrangedSubview(textField) } constrainTextFields() } public func setValue(_ value: String) { if value.isEmpty { textFields.forEach { textField in textField.text = .empty } } value.enumerated().forEach { item in let index = item.offset guard textFields.indices.contains(index) else { return } textFields[index].text = String(item.element) } if value.count == numberOfItems { action?(.textFinishEdit(value)) } } // MARK: - Bind Model func bindViewModel(_ viewModel: CosmosModel) { guard let model = viewModel as? BoxTextFieldModel else { return } self.viewModel = model numberOfItems = model.numberOfItems > Constants.maxBoxItems ? Constants.maxBoxItems : model.numberOfItems createTextFields() configureForState() if let description = model.description { descriptionLabel.isHidden = false descriptionLabel.text = description } else { descriptionLabel.isHidden = true } if let value = model.value { setValue(value) } textFields.forEach { $0.isSecureTextEntry = model.isSecureTextEntry $0.keyboardType = model.keyboardType } } func bindAction(_ externalAction: ((BoxTextFieldAction) -> Void)?) { action = { textFieldAction in externalAction?(textFieldAction) } } } extension BoxTextFieldView: UITextFieldDelegate, CustomDeleteActionTextFieldDelegate { public func textFieldDidBeginEditing(_ textField: UITextField) { setupBeginEditing() selectTextField(textField, isSelected: true) action?(.textFieldDidBeginEditing) } public func textFieldDidEndEditing(_ textField: UITextField) { selectTextField(textField, isSelected: false) } public func textFieldDidSelectDeleteButton(_ textField: UITextField) { guard let index = textFields.firstIndex(of: textField) else { return } if index - .one >= .zero { textField.text = .empty textFields[index - .one].becomeFirstResponder() textFields[index - .one].text = .empty } else { textField.resignFirstResponder() } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() action?(.textFieldReturnPressed(textField)) return true } } public protocol CustomDeleteActionTextFieldDelegate: AnyObject { func textFieldDidSelectDeleteButton(_ textField: UITextField) } final class CustomDeleteActionTextField: UITextField { public weak var deleteDelegate: CustomDeleteActionTextFieldDelegate? override public func deleteBackward() { deleteDelegate?.textFieldDidSelectDeleteButton(self) super.deleteBackward() } override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(UIResponderStandardEditActions.paste(_:)) { return false } return super.canPerformAction(action, withSender: sender) } }
library(igraph) library(reshape2) library(ggplot2) # Function to compute modules and their sizes compute_modules <- function(cor_matrix) { # Coherent Modules: Keep only positive correlations, set negative to NA coherent_matrix <- cor_matrix coherent_matrix[coherent_matrix < 0] <- NA # Incoherent Modules: Keep only negative correlations, set positive to NA and take abs incoherent_matrix <- cor_matrix incoherent_matrix[incoherent_matrix > 0] <- NA incoherent_matrix <- abs(incoherent_matrix) results <- list( coherent_modules = NA, coherent_sizes = NA, incoherent_modules = NA, incoherent_sizes = NA ) # Coherent modules computation if (sum(!is.na(coherent_matrix)) > 0) { edge_list_coherent <- melt(coherent_matrix, na.rm = TRUE) colnames(edge_list_coherent) <- c("from", "to", "weight") graph_coherent <- graph_from_data_frame(edge_list_coherent, directed = FALSE) if (vcount(graph_coherent) > 1) { community_coherent <- cluster_louvain(graph_coherent, weights = E(graph_coherent)$weight) results$coherent_modules <- length(community_coherent) results$coherent_sizes <- mean(sizes(community_coherent)) } } # Incoherent modules computation if (sum(!is.na(incoherent_matrix)) > 0) { edge_list_incoherent <- melt(incoherent_matrix, na.rm = TRUE) colnames(edge_list_incoherent) <- c("from", "to", "weight") graph_incoherent <- graph_from_data_frame(edge_list_incoherent, directed = FALSE) if (vcount(graph_incoherent) > 1) { community_incoherent <- cluster_louvain(graph_incoherent, weights = E(graph_incoherent)$weight) results$incoherent_modules <- length(community_incoherent) results$incoherent_sizes <- mean(sizes(community_incoherent)) } } return(results) } #################################################### FILTER DATA # Create unique study ID column if not already present moddat$study_id <- sub("~.*", "", moddat$STUDY_PLOT) # Get a list of unique study IDs study_ids <- unique(moddat$study_id) # Group by STUDY_ID and count the number of unique species (from Gn1 and Gn2) species_counts <- moddat %>% group_by(study_id) %>% summarise( species_count = length(unique(c(Gn1, Gn2))) # Ensure we are counting unique species from both columns ) # Filter out studies with fewer than 15 species filtered_studies <- species_counts %>% filter(species_count >= 10) %>% pull(study_id) # Filter the main dataset to include only the studies with at least 15 species filtered_data <- moddat %>% filter(study_id %in% filtered_studies & !is.na(cor)) ################################################### compute modules # Assuming filtered_data contains your study data and correlation matrices # Assuming filtered_data contains your study data and correlation matrices study_ids <- unique(filtered_data$STUDY_ID) # Initialize a list to store results per study module_results <- list() # Loop through each study for (study_id in study_ids) { # Subset the data for the current study subset_data <- filtered_data[filtered_data$STUDY_ID == study_id, ] # Get the list of unique genus (Gn1 + Gn2) unique_genus <- unique(c(subset_data$Gn1, subset_data$Gn2)) # Compute the community size as the number of unique genus community_size <- length(unique_genus) # Initialize an empty correlation matrix cor_matrix <- matrix(NA, nrow = length(unique_genus), ncol = length(unique_genus)) rownames(cor_matrix) <- unique_genus colnames(cor_matrix) <- unique_genus # Fill the correlation matrix for (i in 1:nrow(subset_data)) { g1 <- subset_data$Gn1[i] g2 <- subset_data$Gn2[i] cor_value <- subset_data$cor[i] cor_matrix[g1, g2] <- cor_value cor_matrix[g2, g1] <- cor_value } # Replace the diagonal with NA to exclude self-correlations diag(cor_matrix) <- 1 # Compute modules for coherent and incoherent cases study_result <- compute_modules(cor_matrix) # Add the study ID and community size to the results study_result$study_id <- study_id study_result$community_size <- community_size # Append to the list of results module_results[[study_id]] <- study_result } # Combine all results into a data frame for easier plotting module_results_df <- do.call(rbind, lapply(module_results, as.data.frame)) ################################################## PLOT BY STUDY ID # Plot the number of coherent and incoherent modules across studies plot_modules <- ggplot(module_results_df, aes(x = reorder(study_id, -community_size))) + geom_point(aes(y = coherent_modules, color = "Coherent Modules"), size = 3) + geom_point(aes(y = incoherent_modules, color = "Incoherent Modules"), size = 3) + labs(x = "Study ID (Ordered by Community Size)", y = "Number of Modules") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + scale_color_manual( values = c("Coherent Modules" = "#B2182B", # Strong Red (RdBu palette) "Incoherent Modules" = "#2166AC") # Strong Blue (RdBu palette) ) # Display the plot for the number of modules print(plot_modules) # Plot the average module size for coherent and incoherent modules plot_sizes <- ggplot(module_results_df, aes(x = reorder(study_id, -community_size))) + geom_point(aes(y = coherent_sizes, color = "Coherent Module Size"), size = 3) + geom_point(aes(y = incoherent_sizes, color = "Incoherent Module Size"), size = 3) + labs(x = "Study ID (Ordered by Community Size)", y = "Average Module Size") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + scale_color_manual( values = c("Coherent Module Size" = "#B2182B", # Strong Red (RdBu palette) "Incoherent Module Size" = "#2166AC") # Strong Blue (RdBu palette) ) # Display the plot for module sizes print(plot_sizes) ggarrange(plot_modules, plot_sizes, common.legend = TRUE, ncol = 2, nrow = 1) ggsave(here::here("AF_pilot/output/modules.png"), height = 6, width = 9) ################################################## PLOT BY COMMUNITY SIZE # Plot the number of coherent and incoherent modules across studies, with community size on the x-axis plot_modules <- ggplot(module_results_df, aes(x = community_size)) + geom_point(aes(y = coherent_modules, color = "Coherent Modules"), size = 3) + geom_point(aes(y = incoherent_modules, color = "Incoherent Modules"), size = 3) + labs(x = "Community Size", y = "Number of Modules", title = "Number of Coherent and Incoherent Modules by Community Size") + theme_minimal() + scale_color_manual( values = c("Coherent Modules" = "#B2182B", # Strong Red (RdBu palette) "Incoherent Modules" = "#2166AC") # Strong Blue (RdBu palette) ) # Display the plot for the number of modules print(plot_modules) # Plot the average module size for coherent and incoherent modules, with community size on the x-axis plot_sizes <- ggplot(module_results_df, aes(x = community_size)) + geom_point(aes(y = coherent_sizes, color = "Coherent Module Size"), size = 3) + geom_point(aes(y = incoherent_sizes, color = "Incoherent Module Size"), size = 3) + labs(x = "Community Size", y = "Average Module Size", title = "Average Module Size by Community Size") + theme_minimal() + scale_color_manual( values = c("Coherent Module Size" = "#B2182B", # Strong Red (RdBu palette) "Incoherent Module Size" = "#2166AC") # Strong Blue (RdBu palette) ) # Display the plot for module sizes print(plot_sizes) ############################################## #Heterogeneity in modules' coherence ############################################# # Assuming you have the function to compute coherent and incoherent modules from previous steps # Initialize a list to store results per study module_diff_results <- list() # Loop through each study for (study_id in study_ids) { # Subset the data for the current study subset_data <- filtered_data[filtered_data$STUDY_ID == study_id, ] # Get the list of unique genus (Gn1 + Gn2) unique_genus <- unique(c(subset_data$Gn1, subset_data$Gn2)) # Initialize an empty correlation matrix cor_matrix <- matrix(NA, nrow = length(unique_genus), ncol = length(unique_genus)) rownames(cor_matrix) <- unique_genus colnames(cor_matrix) <- unique_genus # Fill the correlation matrix for (i in 1:nrow(subset_data)) { g1 <- subset_data$Gn1[i] g2 <- subset_data$Gn2[i] cor_value <- subset_data$cor[i] cor_matrix[g1, g2] <- cor_value cor_matrix[g2, g1] <- cor_value } # Replace the diagonal with NA to exclude self-correlations diag(cor_matrix) <- NA # Print the correlation matrix for the first study for debugging if (study_id == study_ids[1]) { print(paste("Correlation matrix for study:", study_id)) print(cor_matrix) } # Compute modules for the current study study_result <- compute_modules(cor_matrix) # Print module detection result for debugging print(paste("Study ID:", study_id, "Num Modules:", length(study_result$modules))) # Check if any modules were detected if (length(study_result$modules) == 0) { next # Skip to the next study if no modules were detected } # Initialize a list to store the means of correlations within each module module_means <- c() # Loop through each module and compute the mean correlation within the module for (module in study_result$modules) { # Extract the indices corresponding to the module module_indices <- match(module, rownames(cor_matrix)) if (length(module_indices) > 1) { # Ensure module has more than 1 genus sub_matrix <- cor_matrix[module_indices, module_indices] # Compute the mean correlation within the module (excluding NAs) module_mean <- mean(sub_matrix, na.rm = TRUE) # Append the module mean to the list if it's valid if (!is.na(module_mean)) { module_means <- c(module_means, module_mean) } } } # Check if we have valid module means before calculating variance if (length(module_means) > 1) { # Calculate variance of module means to quantify the difference module_variance <- var(module_means, na.rm = TRUE) } else { module_variance <- NA # Not enough modules to compute variance } # Print intermediate results for debugging print(paste("Study ID:", study_id, "Module Means:", paste(module_means, collapse = ","), "Variance:", module_variance)) # Add the results to the list module_diff_results[[study_id]] <- data.frame( study_id = study_id, module_variance = module_variance, num_modules = length(study_result$modules) ) } # Combine all results into a data frame for easier plotting module_diff_df <- do.call(rbind, module_diff_results) # Plot the module variance across studies module_diff_plot <- ggplot(module_diff_df, aes(x = study_id, y = module_variance)) + geom_point(size = 3, color = "blue") + labs(x = "Study ID", y = "Variance of Module Means", title = "Variance of Mean Correlations Across Modules per Study") + theme_classic() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # Display the plot print(module_diff_plot)
using AgendaApp.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AgendaApp.Data.Mappings { /// <summary> /// Classe de mapeamento para a entidade 'Tarefa' /// </summary> public class TarefaMap : IEntityTypeConfiguration<Tarefa> { public void Configure(EntityTypeBuilder<Tarefa> builder) { //nome da tabela builder.ToTable("TAREFA"); //chave primária builder.HasKey(t => t.Id); //campo 'id' builder.Property(t => t.Id) .HasColumnName("ID"); //nome do campo //campo 'nome' builder.Property(t => t.Nome) .HasColumnName("NOME") //nome do campo .HasMaxLength(150) //max de caracteres .IsRequired(); //not null (obrigatório) //campo 'data' builder.Property(t => t.Data) .HasColumnName("DATA") //nome do campo .HasColumnType("date") //tipo do campo .IsRequired(); //not null (obrigatório) //campo 'hora' builder.Property(t => t.Hora) .HasColumnName("HORA") //nome do campo .HasColumnType("time") //tipo do campo .IsRequired(); //not null (obrigatório) //campo 'prioridade' builder.Property(t => t.Prioridade) .HasColumnName("PRIORIDADE") //nome do campo .IsRequired(); //not null (obrigatório) //campo 'categoriaid' builder.Property(t => t.CategoriaId) .HasColumnName("CATEGORIAID") //nome do campo .IsRequired(); //not null (obrigatório) //mapeamento do relacionamento (1pN) builder.HasOne(t => t.Categoria) //tarefa TEM 1 Categoria .WithMany(c => c.Tarefas) //categoria TEM MUITAS Tarefas .HasForeignKey(t => t.CategoriaId); //Chave estrangeira } } }
import { Request, Response } from 'express'; import { allUsersService, changePasswordService, createNewUserService, deleteAccountService, getUserDataService, loginService } from '../services'; import * as types from '../utils/types/index'; import httpStatus from 'http-status'; export async function singUp(req: Request, res: Response) { try { const body: types.SignUpBody = req.body; await createNewUserService(body); res.status(201).send({ message: 'User created successfully!' }); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { return res.status(error.status || httpStatus.INTERNAL_SERVER_ERROR).send({ message: error.message }); } } export async function singIn(req: Request, res: Response) { try { const body: types.SignInBody = req.body; const response = await loginService(body); res.status(200).send(response); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { return res.status(error.status || httpStatus.INTERNAL_SERVER_ERROR).send({ message: error.message }); } } export async function userData(_req: Request, res: Response) { try { const userId: number = res.locals.user.id; const response = await getUserDataService(userId); res.status(200).send(response); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { return res.status(error.status || httpStatus.INTERNAL_SERVER_ERROR).send({ message: error.message }); } } export async function changePassword(req: Request, res: Response) { try { const userId: number = res.locals.user.id; const newPassword: string = req.body.password; await changePasswordService({ userId, newPassword }); res.status(200).send({ message: 'Password Changed Successfully' }); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { return res.status(error.status || httpStatus.INTERNAL_SERVER_ERROR).send({ message: error.message }); } } export async function deleteAccount(_req: Request, res: Response) { try { const userId: number = res.locals.user.user_id; await deleteAccountService(userId); res.status(200).send({ message: 'User Deleted Successfully' }); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { return res.status(error.status || httpStatus.INTERNAL_SERVER_ERROR).send({ message: error.message }); } } export async function allUsers(_req: Request, res: Response) { try { const response = await allUsersService(); res.status(200).send(response); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { return res.status(error.status || httpStatus.INTERNAL_SERVER_ERROR).send({ message: error.message }); } }
package MyPackage; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Disabled; import org.mockito.MockedStatic; import static org.mockito.ArgumentMatchers.*; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import static org.mockito.Mockito.*; import java.lang.reflect.Field; public class HalsteadDifficultyCheckTest { @Test public void getTokensTest() { HalsteadDifficultyCheck check = new HalsteadDifficultyCheck(); // expected tokens int[] expectedTokens = Globals.OPERANDS_OPERATORS; assertArrayEquals(expectedTokens, check.getDefaultTokens()); assertArrayEquals(new int[0], check.getRequiredTokens()); assertArrayEquals(expectedTokens, check.getAcceptableTokens()); } @Test public void beginTreeTest() { HalsteadDifficultyCheck check = new HalsteadDifficultyCheck(); DetailAST ast = mock(DetailAST.class); // operator count starts at 0 when no tokens are visited check.beginTree(ast); assertEquals(0, check.getUniqueOperands()); assertEquals(0, check.getUniqueOperators()); assertEquals(0, check.getOperands()); } @Test public void finishTreeTest() { HalsteadDifficultyCheck check = spy(new HalsteadDifficultyCheck()); DetailAST ast = mock(DetailAST.class); double difficulty = 0; // expected message String msg = "Halstead Difficulty:" + difficulty; // stub log method doNothing().when(check).log(anyInt(), anyString()); doReturn(0).when(ast).getLineNo(); check.finishTree(ast); // make sure the correct check result was logged verify(check).log(0, msg); // set operators to go down other branch check.setOperandsOne(); doReturn(1).when(ast).getLineNo(); difficulty = check.getUniqueOperators()/2.0 * check.getOperands()/check.getUniqueOperands(); msg = "Halstead Difficulty:" + difficulty; check.finishTree(ast); verify(check).log(1, msg); } @Test public void visitTokenTest() { HalsteadDifficultyCheck check = new HalsteadDifficultyCheck(); DetailAST ast = mock(DetailAST.class); // test operator branch doReturn(Globals.OPERATORS[0]).when(ast).getType(); doReturn("operator").when(ast).getText(); int initialUniqueOperators = check.getUniqueOperators(); int initialUniqueOperands = check.getUniqueOperands(); int initialOperands = check.getOperands(); // make sure unique operator count is incremented once on same operator and other counts remain the same check.visitToken(ast); check.visitToken(ast); assertEquals(initialUniqueOperators+1, check.getUniqueOperators()); assertEquals(initialUniqueOperands, check.getUniqueOperands()); assertEquals(initialOperands, check.getOperands()); // test operand branch doReturn(Globals.OPERANDS[0]).when(ast).getType(); doReturn("operand").when(ast).getText(); // check if repeated operands only increments total operands twice and unique operands once check.visitToken(ast); check.visitToken(ast); assertEquals(initialUniqueOperators+1, check.getUniqueOperators()); assertEquals(initialUniqueOperands+1, check.getUniqueOperands()); assertEquals(initialOperands+2, check.getOperands()); } }
/* * File: aVector.h * Author: Haolan Ye (Benjamin) * Created on June 5, 2015, 11:59 AM * Purpose: template class */ #ifndef AVECTOR_H #define AVECTOR_H #include <iostream> #include <new> // Needed for bad_alloc exception #include <cstdlib> // Needed for the exit function using namespace std; template <class T> class aVector { private: T *aptr; // To point to the allocated array int actSize; // Actual Size of the array int usdSize; // Number of elements in the array void memError(); // Handles memory allocation errors void subError(); // Handles subscripts out of range public: // Default constructor aVector() { actSize = 1; usdSize = 0; aptr=new T[actSize]; } T *getPtr() const {return aptr;} // Constructor declaration aVector(int); // Copy constructor declaration aVector(const aVector &); // Destructor declaration ~aVector(); // Accessor to return the array size int size() const { return usdSize; } // Accessor to return a specific element T getElementAt(int position); // Overloaded [] operator declaration T &operator[](const int &); void push(T); void pop_back(); //aVector<T>& operator =(aVector<T>&); }; // Constructor with size argument template <class T> aVector<T>::aVector(int s) { usdSize = s; actSize = 2*s; // Allocate memory for the array. try { aptr = new T[actSize]; } catch (bad_alloc) { memError(); } // Initialize the array. for (int count=0;count<actSize;count++) *(aptr + count) = 0; } // Copy Constructor for aVector class. template <class T> aVector<T>::aVector(const aVector &obj) { // Copy the array size. actSize=obj.actSize; // Allocate memory for the array. aptr = new T[actSize]; if (aptr == 0) memError(); // Copy the elements of object's array. for(int count = 0; count < usdSize; count++) *(aptr + count) = *(obj.aptr + count); for(int i=usdSize;i<actSize;i++) *(aptr+i)=0; } // Destructor template <class T> aVector<T>::~aVector() { } //push function template <class T> void aVector<T>::push(T o) { if(usdSize>=actSize) { actSize*=2; T *arr=new T[actSize]; if(arr==0) memError(); for(int i=0;i<usdSize;i++) { arr[i]=aptr[i]; } for(int i=usdSize;i<actSize;i++) { arr[i]=0; } arr[usdSize]=o; usdSize++; delete []aptr; aptr=arr; } else { aptr[usdSize]=o; usdSize++; } } template <class T> void aVector<T>::pop_back() { if(usdSize==0) { subError(); } else { T* arr=new T[actSize]; if(arr==0) memError(); for(int i=0;i<usdSize-1;i++) { arr[i]=aptr[i]; } for(int i=usdSize-1;i<actSize;i++) { arr[i]=0; } usdSize--; delete []aptr; aptr=arr; } } // memError function. Displays an error message and // terminates the program when memory allocation fails. template <class T> void aVector<T>::memError() { cout << "ERROR:Cannot allocate memory.\n"; exit(EXIT_FAILURE); } // subError function. Displays an error message and // terminates the program when a subscript is out of range. template <class T> void aVector<T>::subError() { cout << "ERROR: Subscript out of range.\n"; exit(EXIT_FAILURE); } // getElementAt function. The argument is a subscript. // This function returns the value stored at the subscript // in the array. template <class T> T aVector<T>::getElementAt(int sub) { if (sub < 0 || sub >= usdSize) subError(); return aptr[sub]; } // Overloaded [] operator. The argument is an integer // This function returns a reference to the element // in the array indexed by the integer. template <class T> T &aVector<T>::operator[](const int &sub) { if (sub < 0 || sub >= usdSize) subError(); return aptr[sub]; } /* template <class T> aVector<T>& aVector<T>::operator =(aVector<T>& right) { delete []aptr; aptr=new T[right.size()]; for(int i=0;i<right.size();i++) { aptr[i]=right.getElementAt(i); } cout<<"aaaa"<<endl; delete []aptr; usdSize=right.size(); aptr=new T[usdSize]; for(int i=0;i<right.size();i++) { this->aptr[i]=right.getElementAt(i); } return *this; } */ #endif
<template> <!-- 景点详情 --> <div class="page-sight-detail"> <!-- 页面头部 --> <van-nav-bar left-text="返回" left-arrow fixed @click-left="goBack" /> <!-- //页面头部 --> <!-- 大图 --> <div class="sight-banner"> <van-image width="100%" height="100%" :src="sightDetail.img" /> <div class="tip"> <router-link class="pic-sts" :to="{ name: 'sightimage', params: { id } }" > <van-icon name="video-o" /> <span>{{ sightDetail.img_count }} 图片</span> </router-link> <div class="title">{{ sightDetail.name }}</div> </div> </div> <!-- //大图 --> <!-- 评分景点介绍 --> <div class="sight-info"> <div class="left" @click="goPage()"> <div class="info-title"> <strong>{{ sightDetail.score }}分</strong> <small>很棒</small> </div> <div class="info-tips">{{ sightDetail.comment_count }}评论</div> <van-icon name="arrow" /> </div> <div class="right"> <div class="info-title"> <span>景点介绍</span> </div> <div class="info-tips">开放时间、贴士</div> <van-icon name="arrow" /> </div> </div> <!-- //评分景点介绍 --> <!-- 地址信息 --> <van-cell :title="fullArea" icon="location-o" is-link :title-style="{ 'text-align': 'left' }" > <!-- 使用 right-icon 插槽来自定义右侧图标 --> <template #right-icon> <van-icon name="arrow" /> </template> </van-cell> <!-- //地址信息 --> <!-- 门票列表 --> <div class="sight-ticket"> <van-cell title="门票" icon="bookmark-o" :title-style="{ 'text-align': 'left' }" /> <div class="ticket-item" v-for="item in ticketList" :key="item.pk"> <div class="left"> <div class="title">{{item.name}}</div> <div class="tips"> <van-icon name="clock-o" /> <span>{{ item.desc }}</span> </div> <div class="tags"> <van-tag mark type="primary">标签</van-tag> </div> </div> <div class="right"> <div class="price"> <span>¥</span> <strong>{{ item.sell_price }}</strong> </div> <router-link :to="{name: 'ordersubmit', params: {id: item.pk}}"> <van-button type="warning" size="small">预定</van-button> </router-link> </div> </div> </div> <!-- //门票列表 --> <!-- 用户评价 --> <div class="sight-comment"> <van-cell title="热门评论" icon="comment-o" :title-style="{ 'text-align': 'left' }"/> <comment-item v-for="item in commentList" :key="item.id" :itemp="item"/> <router-link class="link-more" :to="{ name: 'sightcomment', params: { id } }" >查看更多</router-link> </div> <!-- //用户评价 --> </div> </template> <script> // 评论相的组件 import CommentItem from '@/components/sight/CommentItem.vue' import { ajax } from '@/utils/ajax' import { SightApi } from '@/utils/apis' export default { components:{ CommentItem }, data() { return { id: '', // 景点详细信息 sightDetail:{}, // 门票列表 ticketList: [], // 评论列表 commentList: [] } }, computed: { // 地址的全部信息 fullArea () { let area=this.sightDetail.province+this.sightDetail.city if (this.sightDetail.area) { area=area+this.sightDetail.area } if (this.sightDetail.town) { area=area+this.sightDetail.town } return area } }, watch: { $route () { this.loadData() } }, methods: { /** * 跳转到景点的评论列表 */ goPage () { this.$router.push({name:'sightcomment', params: {id: this.id}}) }, loadData () { this.id = this.$route.params.id // 获取景点信息 this.getSightDetail() // 获取门票列表 this.getTicketList() // 获取评论列表 this.getCommentList() }, goBack() { this.$router.go(-1) }, // 获取景点详细信息接口 getSightDetail () { const url =SightApi.sightDetailUrl.replace('#{id}', this.id) ajax.get(url).then(({data}) => { this.sightDetail=data }) }, // 门票列表接口 getTicketList () { const url =SightApi.sightTicketlUrl.replace('#{id}', this.id) ajax.get(url).then(({data: {objects}}) => { this.ticketList=objects }) }, // 评论列表接口 getCommentList () { const url =SightApi.sightCommentlUrl.replace('#{id}', this.id) ajax.get(url).then(({data: {objects}}) => { this.commentList.push(objects.shift()) }) } }, created() { this.loadData() } } </script> <style lang="less"> .page-sight-detail { .van-nav-bar { background-color: transparent; } //景点大图 .sight-banner { position: relative; .tip { position: absolute; left: 10px; bottom: 10px; font-size: 16px; color: #fff; .pic-sts { color: #fff; border-radius: 30px; font-size: 14px; background-color: rgba(0, 0, 0, 0.4); } } } // 评分、景点介绍 .sight-info { display: flex; background-color: #fff; border-bottom: 1px solid #f6f6f6; & > div { flex: 1; position: relative; } .right { border-left: 1px solid #f6f6f6; } .info-title { text-align: left; padding: 5px 10px; strong { color: #ff8300; } } .info-tips { color: #999; font-size: 12px; text-align: left; padding: 5px 10px; } .van-icon { position: absolute; right: 5px; top: 5px; } } // 门票列表 .sight-ticket { margin-top: 10px; background-color: #fff; .ticket-item { display: flex; border-bottom: 1px solid #f6f6f6; padding-bottom: 10px; .left { flex: 1; text-align: left; padding: 5px 10px; .title { padding: 5px 0; } .tips { font-size: 12px; } } .right { width: 100px; .price { color: #ff9800; strong { font-size: 20px; } } .van-button { width: 60px; } } } } .sight-comment{ margin-top: 10px; background-color: #fff; .link-more{ display: block; color: #666; padding: 10px; } } } </style>
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ExamplesComponent } from './examples.component'; const routes: Routes = [ { path: '', component: ExamplesComponent, children: [ { path: 'product-list', loadChildren: () => import('./lazy-loaded/product-list/product-list.module').then(m => m.ProductListModule) }, { path: 'product-list-categories', loadChildren: () => import('./lazy-loaded/product-list-categories/product-list-categories.module').then(m => m.ProductListCategoriesModule) }, { path: 'user-search', loadChildren: () => import('./lazy-loaded/user-search/user-search.module').then(m => m.UserSearchModule) }, ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ExamplesRoutingModule { }
import { useState, useEffect } from 'react'; import RNOrientation, { orientation as RNOrientationType } from 'react-native-orientation'; export enum Orientation { horizontal, vertical, } const mapOrientation = (rnOrientation: RNOrientationType): Orientation => ( rnOrientation === 'PORTRAIT' ? Orientation.vertical : Orientation.horizontal ); export const useOrientation = (): Orientation => { const [orientation, setOrientation] = useState<Orientation>( () => mapOrientation(RNOrientation.getInitialOrientation()), ); useEffect(() => { const handleOrientationChange = (rnOrientation: RNOrientationType) => setOrientation(mapOrientation(rnOrientation)); RNOrientation.addOrientationListener(handleOrientationChange); return () => { RNOrientation.removeOrientationListener(handleOrientationChange); }; }); return orientation; };
@component('shop::emails.layout') <div style="margin-bottom: 34px;"> <span style="font-size: 22px;font-weight: 600;color: #121A26"> @lang('shop::app.emails.orders.refunded.title') </span> <br> <p style="font-size: 16px;color: #5E5E5E;line-height: 24px;"> @lang('shop::app.emails.dear', ['customer_name' => $refund->order->customer_full_name]),👋 </p> <p style="font-size: 16px;color: #5E5E5E;line-height: 24px;"> @lang('shop::app.emails.orders.refunded.greeting', [ 'invoice_id' => $refund->increment_id, 'order_id' => '<a href="' . route('shop.customers.account.orders.view', $refund->order_id) . '" style="color: #2969FF;">#' . $refund->order->increment_id . '</a>', 'created_at' => core()->formatDate($refund->order->created_at, 'Y-m-d H:i:s') ]) </p> </div> <div style="font-size: 20px;font-weight: 600;color: #121A26"> @lang('shop::app.emails.orders.refunded.summary') </div> <div style="display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between;margin-bottom: 40px;"> @if ($refund->order->shipping_address) <div style="line-height: 25px;"> <div style="font-size: 16px;font-weight: 600;color: #121A26;"> @lang('shop::app.emails.orders.shipping-address') </div> <div style="font-size: 16px;font-weight: 400;color: #384860;margin-bottom: 40px;"> {{ $refund->order->shipping_address->company_name ?? '' }}<br/> {{ $refund->order->shipping_address->name }}<br/> {{ $refund->order->shipping_address->address1 }}<br/> {{ $refund->order->shipping_address->postcode . " " . $refund->order->shipping_address->city }}<br/> {{ $refund->order->shipping_address->state }}<br/> ---<br/> @lang('shop::app.emails.orders.contact') : {{ $refund->order->billing_address->phone }} </div> <div style="font-size: 16px;font-weight: 600;color: #121A26;"> @lang('shop::app.emails.orders.shipping') </div> <div style="font-size: 16px;font-weight: 400;color: #384860;"> {{ $refund->order->shipping_title }} </div> </div> @endif @if ($refund->order->billing_address) <div style="line-height: 25px;"> <div style="font-size: 16px;font-weight: 600;color: #121A26;"> @lang('shop::app.emails.orders.billing-address') </div> <div style="font-size: 16px;font-weight: 400;color: #384860;margin-bottom: 40px;"> {{ $refund->order->billing_address->company_name ?? '' }}<br/> {{ $refund->order->billing_address->name }}<br/> {{ $refund->order->billing_address->address1 }}<br/> {{ $refund->order->billing_address->postcode . " " . $refund->order->billing_address->city }}<br/> {{ $refund->order->billing_address->state }}<br/> ---<br/> @lang('shop::app.emails.orders.contact') : {{ $refund->order->billing_address->phone }} </div> <div style="font-size: 16px;font-weight: 600;color: #121A26;"> @lang('shop::app.emails.orders.payment') </div> <div style="font-size: 16px;font-weight: 400;color: #384860;"> {{ core()->getConfigData('sales.payment_methods.' . $refund->order->payment->method . '.title') }} </div> @php $additionalDetails = \Webkul\Payment\Payment::getAdditionalDetails($refund->order->payment->method); @endphp @if (! empty($additionalDetails)) <div style="font-size: 16px; color: #384860;"> <div>{{ $additionalDetails['title'] }}</div> <div>{{ $additionalDetails['value'] }}</div> </div> @endif </div> @endif </div> <div style="padding-bottom: 40px;border-bottom: 1px solid #CBD5E1;"> <table style="overflow-x: auto; border-collapse: collapse; border-spacing: 0;width: 100%"> <thead> <tr style="color: #121A26;border-top: 1px solid #CBD5E1;border-bottom: 1px solid #CBD5E1;"> @foreach (['name', 'price', 'qty'] as $item) <th style="text-align: left;padding: 15px"> @lang('shop::app.emails.orders.' . $item) </th> @endforeach </tr> </thead> <tbody style="font-size: 16px;font-weight: 400;color: #384860;"> @foreach ($refund->items as $item) <tr> <td style="text-align: left;padding: 15px"> {{ $item->name }} @if (isset($item->additional['attributes'])) <div> @foreach ($item->additional['attributes'] as $attribute) <b>{{ $attribute['attribute_name'] }} : </b>{{ $attribute['option_label'] }}</br> @endforeach </div> @endif </td> <td style="text-align: left;padding: 15px">{{ core()->formatPrice($item->price, $refund->order_currency_code) }} </td> <td style="text-align: left;padding: 15px">{{ $item->qty }}</td> </tr> @endforeach </tbody> </table> </div> <div style="display: grid;justify-content: end;font-size: 16px;color: #384860;line-height: 30px;padding-top: 20px;padding-bottom: 20px;"> <div style="display: grid;gap: 100px;grid-template-columns: repeat(2, minmax(0, 1fr));"> <span> @lang('shop::app.emails.orders.subtotal') </span> <span style="text-align: right;"> {{ core()->formatPrice($refund->sub_total, $refund->order_currency_code) }} </span> </div> @if ($refund->order->shipping_address) <div style="display: grid;gap: 100px;grid-template-columns: repeat(2, minmax(0, 1fr));"> <span> @lang('shop::app.emails.orders.shipping-handling') </span> <span style="text-align: right;"> {{ core()->formatPrice($refund->shipping_amount, $refund->order_currency_code) }} </span> </div> @endif @foreach (Webkul\Tax\Helpers\Tax::getTaxRatesWithAmount($refund->order, false) as $taxRate => $taxAmount ) <div style="display: grid;gap: 100px;grid-template-columns: repeat(2, minmax(0, 1fr));"> <span> @lang('shop::app.emails.orders.tax') {{ $taxRate }} % </span> <span style="text-align: right;"> {{ core()->formatPrice($refund->tax_amount, $refund->order_currency_code) }} </span> </div> @endforeach @if ($refund->discount_amount > 0) <div style="display: grid;gap: 100px;grid-template-columns: repeat(2, minmax(0, 1fr));"> <span> @lang('shop::app.emails.orders.discount') </span> <span style="text-align: right;"> {{ core()->formatPrice($refund->discount_amount, $refund->order_currency_code) }} </span> </div> @endif <div style="display: grid;gap: 100px;grid-template-columns: repeat(2, minmax(0, 1fr));font-weight: bold"> <span> @lang('shop::app.emails.orders.grand-total') </span> <span style="text-align: right;"> {{ core()->formatPrice($refund->grand_total, $refund->order_currency_code) }} </span> </div> </div> @endcomponent
import {FC, useEffect, useState} from "react"; import {TaskType} from "@typescript/interfaces"; import TaskRow from "../TasksTable/TaskRow"; import TasksTable from "@ui/Tasks/TasksTable"; import TaskInteractionDialog from "@components/Tasks/TaskInteractionDialog"; import {FormikValues} from "formik"; import {requestsService} from "@services/requestsService"; import {FilesService} from "@services/filesService"; import {useMainSelector} from "@store/selectors"; interface TasksList { array: TaskType[], control: boolean } export const TasksList: FC<TasksList> = ( { array, control } ) => { let state = useMainSelector(); let localApartmentId = state.user?.apartment_user.apartment.id; let userId = state.user?.user_id; let [open, setOpen] = useState<boolean>(false); let [values, setValues] = useState<FormikValues>(); let [initialValues, setInitialValues] = useState<TaskType>({} as TaskType); const handleEdit = (files: string[]) => { let {id} = initialValues; let { description, theme, urgently } = values as TaskType; requestsService.taskUpdate( description as string, theme, urgently, id, values?.type_key, files, setOpen ); } useEffect(() => { if (values) { let {owner_images} = values; let currentFiles: string[] = []; let uploads: File[] = []; FilesService.filterFiles(owner_images, uploads, currentFiles); if (uploads.length) { FilesService.filesUploadRequest(uploads) .then(response => { let data = FilesService.imagesArrayCreator(response); let files = data.concat(currentFiles); handleEdit(files); }) .catch(err => console.log(err)) } else { handleEdit(currentFiles); } } }, [values]); return ( <> <TaskInteractionDialog submitAction={"Редактировать задачу"} open={open} initialValues={initialValues} setOpen={setOpen} title={"Редактировать задачу"} setValues={setValues} /> <TasksTable control={control}> { array.length ? array.map((task: TaskType) => { let { apartment_id, owner_id, urgently, apartment_house, theme, id, task_status, created_at, tags } = task; const handleEdit = () => { setOpen(true); setInitialValues(task); } let isAvailableForView = userId == owner_id || localApartmentId == apartment_id; return ( <TaskRow isAvailableForView={isAvailableForView} apartment_id={apartment_id} owner_id={task.owner_id} handleEdit={handleEdit} urgently={urgently} control={control} apartment_house={control ? apartment_house : null} theme={theme} id={id} task_status={task_status} created_at={created_at} tags={tags} key={id} /> ) }) : null } </TasksTable> </> ) }
import { createContext, useContext, useEffect, useMemo, useState } from "react"; import { Theme, ThemeManager } from "@/app/services/themeManager"; type ThemeContextProps = { theme: Theme; setTheme: (theme: Theme) => void; isRestored: boolean; }; const ThemeContext = createContext<ThemeContextProps | null>(null); type Props = { children: React.ReactNode; }; export const ThemeProvider = ({ children }: Props) => { const themeManager = useMemo(() => { return new ThemeManager( typeof document === "undefined" ? null : document.documentElement, "theme", Theme.Preferred ); }, []); const [isRestored, setIsRestored] = useState<boolean>(false); const [theme, setTheme] = useState<Theme>(themeManager.defaultTheme!); const handleThemeChange = (newTheme: Theme) => { if (newTheme === undefined) return; setTheme(newTheme); }; useEffect(() => { themeManager.restore(); setTheme(themeManager.get()); setIsRestored(true); themeManager.on("change", handleThemeChange); return () => themeManager.removeListener("change", handleThemeChange); }, [themeManager]); useEffect(() => { if (!isRestored) return; themeManager.set(theme); }, [theme, isRestored, themeManager]); const value = { theme, setTheme, isRestored, }; return ( <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider> ); }; export const useThemeContext = (): ThemeContextProps => { const context = useContext(ThemeContext); if (!context) { throw new Error( "useThemeContext must be used inside the ThemeProvider" ); } return context; };
import asyncHandler from "express-async-handler"; import generateToken from "../utilis/generateToken.js"; import User from "../models/userModel.js"; import nodemailer from "nodemailer"; import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; // @desc Auth user & get token // @routes POST /api/users/login // @access Public const authUser = asyncHandler(async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }); if (user && (await user.matchPassword(password))) { res.json({ _id: user._id, name: user.name, email: user.email, isAdmin: user.isAdmin, token: generateToken(user._id), hasError: false, }); } else { res.json({ hasError: true, message: "Authentication failed", }); } }); // @desc Register a new user // @routes POST /api/users // @access Public const registerUser = asyncHandler(async (req, res) => { const { name, email, password } = req.body; const userExists = await User.findOne({ email }); if (userExists) { res.json({ hasError: true, message: "User already exist", }); } const user = await User.create({ name, email, password, }); if (user) { var transporter = nodemailer.createTransport({ host: "mail.midraconsulting.com", port: 8889, secure: false, // upgrade later with STARTTLS auth: { user: "bobby@midraconsulting.com", pass: "1nt3n@t10n@l", }, }); let content = `<td style="padding:0 35px;"> <h1 style="color:#1e1e2d; font-weight:500; margin:0;font-size:32px;font-family:'Rubik',sans-serif;"> Welcome ${name}</h1> <span style="display:inline-block; vertical-align:middle; margin:29px 0 26px; border-bottom:1px solid #cecece; width:100px;"></span> <p style="color:#455056; font-size:15px;line-height:24px; margin:0;"> Thanks for registering with us, we hope you find what you need. we offer smooth and seamless purchase, you are always welcome to spend all your money, </p> <a href="https://mcbee.herokuapp.com/" style="background:#3a8bcd;text-decoration:none !important; font-weight:500; margin-top:35px; color:#fff;text-transform:uppercase; font-size:14px;padding:10px 24px;display:inline-block;border-radius:50px;">Visit Site</a> </td>`; let data = forgotPasswordTemplate(content); const mailOptions = { from: "bobby@midraconsulting.com", // sender address to: email, // list of receivers subject: "Welcome", // Subject line html: data, // plain text body }; transporter.sendMail(mailOptions, function (err, info) { if (err) console.log(""); else res.json({ _id: user._id, name: user.name, email: user.email, isAdmin: user.isAdmin, token: generateToken(user._id), message: "User created successfully", hasError: false, }); }); res.json({ _id: user._id, name: user.name, email: user.email, isAdmin: user.isAdmin, token: generateToken(user._id), message: "User created successfully", hasError: false, }); } else { res.json({ hasError: true, message: "Invalid User Data", }); } }); // @desc Get user profile // @routes Get /api/users/profile // @access Private const getUserProfile = asyncHandler(async (req, res) => { const user = await User.findById(req.user._id); if (user) { res.json({ _id: user._id, name: user.name, email: user.email, isAdmin: user.isAdmin, }); } else { res.status(404); throw new Error("User not found"); } }); // @desc Update user profile // @routes PUT /api/users/profile // @access Private const updateUserProfile = asyncHandler(async (req, res) => { const user = await User.findById(req.user._id); if (user) { user.name = req.body.name || user.name; user.email = req.body.email || user.email; if (req.body.password) { user.password = req.body.password; } const updatedUser = await user.save(); res.json({ _id: updatedUser._id, name: updatedUser.name, email: updatedUser.email, isAdmin: updatedUser.isAdmin, token: generateToken(updatedUser._id), }); } else { res.status(404); throw new Error("User not found"); } }); // @desc Get all users // @routes Get /api/users // @access Private/Admin const getUsers = asyncHandler(async (req, res) => { const users = await User.find({}); res.json(users); }); // @desc Delete user // @routes DELETE /api/users/:id // @access Private/Admin const deleteUsers = asyncHandler(async (req, res) => { const user = await User.findById(req.params.id); if (user) { await user.remove(); res.json({ message: "User removed" }); } else { res.status(404); throw new Error("User not found"); } }); // @desc Get user by ID // @routes Get /api/users/:id // @access Private/Admin const getUserById = asyncHandler(async (req, res) => { const user = await User.findById(req.params.id).select("-password"); if (user) { res.json(user); } else { res.status(404); throw new Error("User not found"); } }); // @desc Update user // @routes PUT /api/users/:id // @access Private/Admin const updateUser = asyncHandler(async (req, res) => { const user = await User.findById(req.params.id); if (user) { user.name = req.body.name || user.name; user.email = req.body.email || user.email; user.isAdmin = req.body.isAdmin; const updatedUser = await user.save(); res.json({ _id: updatedUser._id, name: updatedUser.name, email: updatedUser.email, isAdmin: updatedUser.isAdmin, }); } else { res.status(404); throw new Error("User not found"); } }); // desc forgot password // roue POST /api/users/forgot const forgotPassword = asyncHandler(async (req, res) => { const { email } = req.body; const existingEmail = await User.findOne({ email }); if (existingEmail) { var transporter = nodemailer.createTransport({ host: "mail.midraconsulting.com", port: 8889, secure: false, // upgrade later with STARTTLS auth: { user: "bobby@midraconsulting.com", pass: "1nt3n@t10n@l", }, }); const token = generateToken(existingEmail._id); let content = `<td style="padding:0 35px;"> <h1 style="color:#1e1e2d; font-weight:500; margin:0;font-size:32px;font-family:'Rubik',sans-serif;">Password Reset</h1> <span style="display:inline-block; vertical-align:middle; margin:29px 0 26px; border-bottom:1px solid #cecece; width:100px;"></span> <p style="color:#455056; font-size:15px;line-height:24px; margin:0;"> We cannot simply send you your old password. A unique link to reset your password has been generated for you. To reset your password, click the following link and follow the instructions. </p> <a href="https://mcbee.herokuapp.com/auth/reset-password/${token}" style="background:#3a8bcd;text-decoration:none !important; font-weight:500; margin-top:35px; color:#fff;text-transform:uppercase; font-size:14px;padding:10px 24px;display:inline-block;border-radius:50px;">Reset Password</a> </td>`; let data = forgotPasswordTemplate(content); const mailOptions = { from: "bobby@midraconsulting.com", // sender address to: email, // list of receivers subject: "RESET PASSWORD", // Subject line html: data, // plain text body }; transporter.sendMail(mailOptions, function (err, info) { if (err) res.json({ message: "Error sending mail, try again", hasError: true, }); else res.json({ hasError: false, message: "please check your email for reset link", }); }); } else { res.json({ message: "User does not exist", hasError: true, }); } }); // Desc Reset Password // Route POST api/users/reset const resetPassword = asyncHandler(async (req, res) => { const { token, password, resetPassword } = req.body; const salt = await bcrypt.genSalt(10); const passwordHash = await bcrypt.hash(password, salt); if (token) { const decoded = jwt.verify(token, process.env.JWT_SECRET); if (!decoded.id) { res.json({ hasError: true, message: "Error: email not verified", }); } const user = await User.findByIdAndUpdate(decoded.id, { password: passwordHash, }); if (user) { res.json({ hasError: false, user: user, }); } else { res.json({ hasError: true, message: "Error: email not verified", }); } } else { res.json({ hasError: true, message: "Error: please try again", }); } }); // Desc Change Password // Route POST api/users/change const changePassword = asyncHandler(async (req, res) => { const { password, newPassword } = req.body; const user = await User.findById(req.user._id); let match = await user.matchPassword(password); if (match) { const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(newPassword, salt); const updatedPassword = await User.findByIdAndUpdate(user._id, { password: hashedPassword, }); const changedPassword = await updatedPassword.save(); res.json({ changedPassword, message: "password changed successfully", hasError: false, }); } else { res.json({ hasError: true, message: "incorrect password", }); } }); const forgotPasswordTemplate = (content) => { return ` <html lang="en-US"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Reset Password Email Template</title> <meta name="description" content="Reset Password Email Template."> <style type="text/css"> a:hover {text-decoration: underline !important;} </style> </head> <body marginheight="0" topmargin="0" marginwidth="0" style="margin: 0px; background-color: #f2f3f8;" leftmargin="0"> <!--100% body table--> <table cellspacing="0" border="0" cellpadding="0" width="100%" bgcolor="#f2f3f8" style="@import url(https://fonts.googleapis.com/css?family=Rubik:300,400,500,700|Open+Sans:300,400,600,700); font-family: 'Open Sans', sans-serif;"> <tr> <td> <table style="background-color: #f2f3f8; max-width:670px; margin:0 auto;" width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td style="height:80px;">&nbsp;</td> </tr> <tr> <td style="text-align:center;"> <a style="text-decoration: none" href="http://mcbee.herokuapp.com" title="logo" target="_blank"> <img src="http://mcbee.herokuapp.com/uploads/logoBlue.png" style="width: 150px" alt="" /> </a> </td> </tr> <tr> <td style="height:20px;">&nbsp;</td> </tr> <tr> <td> <table width="95%" border="0" align="center" cellpadding="0" cellspacing="0" style="max-width:670px;background:#fff; border-radius:3px; text-align:center;-webkit-box-shadow:0 6px 18px 0 rgba(0,0,0,.06);-moz-box-shadow:0 6px 18px 0 rgba(0,0,0,.06);box-shadow:0 6px 18px 0 rgba(0,0,0,.06);"> <tr> <td style="height:40px;">&nbsp;</td> </tr> <tr> ${content} </tr> <tr> <td style="height:40px;">&nbsp;</td> </tr> </table> </td> <tr> <td style="height:20px;">&nbsp;</td> </tr> <tr> <td style="text-align:center;"> <p style="font-size:14px; color:rgba(69, 80, 86, 0.7411764705882353); line-height:18px; margin:0 0 0;">&copy; <strong>mcbee Inc.</strong></p> </td> </tr> <tr> <td style="height:80px;">&nbsp;</td> </tr> </table> </td> </tr> </table> <!--/100% body table--> </body> </html> `; }; export { authUser, registerUser, getUserProfile, updateUserProfile, getUsers, deleteUsers, getUserById, updateUser, forgotPassword, resetPassword, changePassword, };
<?php namespace App\Controller\admin; use App\Entity\Category; use App\Form\CategoryType; use App\Repository\CategoryRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; #[Route('/admin/category')] class CategoryController extends AbstractController { public function __construct( private CategoryRepository $categoryRepository, private EntityManagerInterface $entityManager ) { } #[Route('/', name: 'app_category')] public function index(): Response { $categoryEntities = $this->categoryRepository->findAll(); return $this->render('category/index.html.twig', [ 'categories' => $categoryEntities ]); } #[Route('/show/{id}', name: 'app_category_show')] public function detail($id): Response { $categoryEntitie = $this->categoryRepository->find($id); if ($categoryEntitie === null) { return $this->redirectToRoute('app_home'); } return $this->render('category/show.html.twig', [ 'category' => $categoryEntitie ]); } #[Route('/add', name: 'app_category_add')] public function add(Request $request): Response { $category = new Category(); $form = $this->createForm(CategoryType::class, $category); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->entityManager->persist($category); $this->entityManager->flush(); return $this->redirectToRoute('app_category'); } return $this->render('category/add.html.twig', [ 'form' => $form->createView() ]); } #[Route('/delete/{id}', name: 'app_category_delete')] public function delete($id): Response { $category = $this->categoryRepository->find($id); if($category !== null) { $this->entityManager->remove($category); $this->entityManager->flush(); } return $this->redirectToRoute('app_category'); } #[Route('/edit/{id}', name: 'app_category_edit')] public function edit($id, Request $request): Response { $category = $this->categoryRepository->find($id); // if ($category === null) { // return $this->redirectToRoute('app_category'); // } $form = $this->createForm(CategoryType::class, $category); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->entityManager->persist($category); $this->entityManager->flush(); return $this->redirectToRoute('app_category'); } return $this->render('category/edit.html.twig', [ 'form' => $form->createView() ]); } }
<!DOCTYPE html> <meta charset="utf-8" /> <!-- Load d3.js --> <script src="https://d3js.org/d3.v6.js"></script> <!-- Load plotly.js into the DOM --> <script src="https://cdn.plot.ly/plotly-2.16.1.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script> <body> <label>Election Type:</label> <select id="electionType"> <option value="president">總統</option> <option value="legislator-at-large">不分區立委</option> <option value="legislator">區域立委</option> </select> <label>Year:</label> <select id="year"> <option value="2016">2016</option> <option value="2020">2020</option> </select> <!-- Create a div where the graph will take place --> <div id="map" class="graph"></div> <div id="edu1" class="graph"></div> <div id="pie1" class="graph"></div> <div id="edu2" class="graph"></div> <div id="pie2" class="graph"></div> <div id="presidentBarChart" class="graph"></div> <div id="legislatoratlargeBarChart" class="graph"></div> <div id="partyRatioBarChart" class="graph"></div> </body> <script> //file list const files = { president: { 2016: { by_city: "/dataset/voteData/cleaned/president/2016/by_city.csv", by_nation: "/dataset/voteData/cleaned/president/2016/by_nation.csv", candidate: "/dataset/voteData/cleaned/president/2016/candidate.csv", }, 2020: { by_city: "/dataset/voteData/cleaned/president/2020/by_city.csv", by_nation: "/dataset/voteData/cleaned/president/2020/by_nation.csv", candidate: "/dataset/voteData/cleaned/president/2020/candidate.csv", }, }, "legislator-at-large": { 2016: { by_city: "/dataset/voteData/cleaned/legislator-at-large/2016/by_city.csv", by_nation: "/dataset/voteData/cleaned/legislator-at-large/2016/by_nation.csv", candidate: "/dataset/voteData/cleaned/legislator-at-large/2016/candidate.csv", }, 2020: { by_city: "/dataset/voteData/cleaned/legislator-at-large/2020/by_city.csv", by_nation: "/dataset/voteData/cleaned/legislator-at-large/2020/by_nation.csv", candidate: "/dataset/voteData/cleaned/legislator-at-large/2020/candidate.csv", }, }, legislator: { 2016: { by_district: "/dataset/voteData/cleaned/legislator/2016/by_district.csv", candidate: "/dataset/voteData/cleaned/legislator/2016/candidate.csv", }, 2020: { by_district: "/dataset/voteData/cleaned/legislator/2020/by_district.csv", candidate: "/dataset/voteData/cleaned/legislator/2020/candidate.csv", }, }, }; const years = ["2016", "2020"]; </script> <!-- Choropleth Map --> <script> function getGeometry(json, cityName) { //rtype: polygon of zone for (var i = 0; i < json["features"].length; i++) { if (json["features"][i]["id"] == cityName) { return json["features"][i]; } } } function findWinner(cityData) { //rtype: winner party name var items = cityData.map(function (i) { //map to ["親民黨", "4.34"] return [i["candidate_party"], i["ticket_percentage"]]; }); items.sort(function (a, b) { return +b[1] - +a[1]; }); return items[0][0]; } function partyColor(party) { switch (party) { case "親民黨": return "rgba(227, 104, 47, 0.8)"; case "中國國民黨": return "rgba(9, 0, 136, 0.8)"; case "民主進步黨": return "rgba(64,145,39, 0.8)"; case "樹黨": return "rgba(177,199,62, 0.8)"; case "中華統一促進黨": return "rgba(41, 53, 127, 0.8)"; case "軍公教聯盟黨": return "rgba(200, 42, 37, 0.8)"; case "台灣工黨": return "rgba(243, 244, 81, 0.8)"; case "新黨": return "rgba(238, 209, 70, 0.8)"; case "泛盟黨": return "rgba(164, 206, 232, 0.8)"; case "大愛憲改聯盟": return "rgba(163, 36, 28, 0.8)"; case "時代力量": return "rgba(230, 184, 62, 0.8)"; default: return intToRGB(hashCode(party)); } } function hashCode(str) { // java String#hashCode var hash = 0; for (var i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); } return hash; } function intToRGB(i) { var c = (i & 0x00FFFFFF) .toString(16) .toUpperCase(); return "#" + ("00000".substring(0, 6 - c.length) + c); } async function plotWinnerMap(title, dataByCity, candidateData) { let geoJson = await d3.json("Taiwan_geo.json"); let cities = Array.from(new Set(d3.map(dataByCity, (d) => d.city))); let candidateInfo = {}; //compatible with president and legialator-at-large let candidates = !candidateData.columns.includes("candidate") ? Array.from( new Set( candidateData.map((d) => [ d["candidate_party"], d["candidate_party"], ]) ) ) : Array.from( new Set( candidateData.map((d) => [d["candidate"], d["candidate_party"]]) ) ); for (let c of candidates) { candidateInfo[c[0]] = { party: c[1], color: partyColor(c[1]), winZone: { type: "FeatureCollection", features: [] }, }; } console.log(dataByCity) for (let i = 0; i < dataByCity.length; i += candidates.length) { var cityData = dataByCity.slice(i, i + candidates.length); var cityName = cityData[0].city; var winnerParty = findWinner(cityData); var winner = Object.keys(candidateInfo).find( (key) => candidateInfo[key]["party"] == winnerParty ); var cityGeometry = getGeometry(geoJson, cityName); console.log(cityName, cityGeometry) candidateInfo[winner]["winZone"]["features"].push(cityGeometry); } var layers = []; for (let candidate in candidateInfo) { var layer = { sourcetype: "geojson", source: candidateInfo[candidate]["winZone"], type: "fill", color: candidateInfo[candidate]["color"], }; layers.push(layer); } var layout = { mapbox: { center: { lon: 121, lat: 23.5 }, zoom: 6.5, style: "light", layers: layers, }, width: 1200, height: 800, title: title, }; var config = { mapboxAccessToken: "pk.eyJ1IjoiYTA1MTI4IiwiYSI6ImNsY2JybmJyYTIyZzEzb2w3dGl3cXpkdXYifQ.aIV8apormocbhm8GpqbySg", }; //legends by adding dummy traces let data = candidates.map((c) => { return { type: "scattermapbox", lat: [46], lon: [-74], z: [0], name: c[0] == c[1] ? c[0] : c[0] + " (" + c[1] + ")", showlegend: true, line: { color: partyColor(c[1]) }, }; }); Plotly.newPlot("map", data, layout, config); } </script> <!-- party ratio bar chart --> <script> async function partyRatioBarChart(title, dataByDistrict) { var partyInfo = {}; dataByDistrict.forEach(function (row) {//count elected party if (row["elected"] == "True") { let party = row["candidate_party"] if (!(party in partyInfo)) {//this party first elected partyInfo[party] = 1 } else { partyInfo[party] += 1 } } }); var partyColors = []; for (let i in partyInfo) {//get party colors partyColors.push(partyColor(i)) } var trace1 = { x: Object.keys(partyInfo), y: Object.values(partyInfo), marker: { color: partyColors, }, type: "bar", text: Object.values(partyInfo).map(String), }; var data = [trace1]; var layout = { title: title, }; Plotly.newPlot("partyRatioBarChart", data, layout); } </script> <!-- edu level --> <script> function legislatorEduPlot(id, title, candidateData, filterElected = false) { let candidates = {}; let eduLevels = [...new Set(candidateData.map(d => d["education_level"]))]; for (let row of candidateData) { if (!Object.keys(candidates).includes(row["candidate_party"])) { candidates[row["candidate_party"]] = {}; for (let e of eduLevels) { candidates[row["candidate_party"]][e] = 0; } } if (filterElected) { if (row["elected"] == "True") candidates[row["candidate_party"]][row["education_level"]]++; } else { candidates[row["candidate_party"]][row["education_level"]]++; } } let parties = Object.keys(candidates); let data = []; for (let e of eduLevels) { data.push({ name: e, type: 'bar', x: parties, y: parties.map(p => candidates[p][e]), }); } let layout = { title: title, barmode: 'stack', }; Plotly.newPlot(id, data, layout); } function legislatorPieChart(id, title, candidateData, filterElected = false) { let candidatesByEdu = {}; let candidatesByGender = {}; let eduLevels = [...new Set(candidateData.map(d => d["education_level"]))]; let genders = [...new Set(candidateData.map(d => d["gender"]))]; for (let e of eduLevels) candidatesByEdu[e] = 0; for (let g of genders) candidatesByGender[g] = 0; let total = 0; for (let row of candidateData) { if (filterElected) { if (row["elected"] == "True") { candidatesByEdu[row["education_level"]]++; candidatesByGender[row["gender"]]++; total++; } } else { candidatesByEdu[row["education_level"]]++; candidatesByGender[row["gender"]]++; total++; } } let data = [{ values: eduLevels.map((e) => candidatesByEdu[e]), labels: eduLevels, domain: { column: 0 }, name: 'education level', hoverinfo: 'label+percent+name', hole: .4, type: 'pie' }, { values: genders.map((g) => candidatesByGender[g]), labels: genders, domain: { column: 1 }, name: 'gender', hoverinfo: 'label+percent+name', hole: .4, type: 'pie' }]; let layout = { title: title, annotations: [ { font: { size: 15 }, showarrow: false, text: 'education<br>level', x: 0.15, y: 0.5 }, { font: { size: 15 }, showarrow: false, text: 'gender', x: 0.82, y: 0.5 } ], height: 400, width: 600, showlegend: true, grid: { rows: 1, columns: 2 } }; Plotly.newPlot(id, data, layout); } </script> <script> function presidentBarChart(dataByCity, title, divID) { let x = [...new Set(d3.map(dataByCity, d => d.candidate))]; let y = {}; let cities = [...new Set(d3.map(dataByCity, d => d.city))]; for (let c of cities) { y[c] = new Array(x.length); } for (let row of dataByCity) { y[row.city][x.indexOf(row.candidate)] = row.ticket; } let data = []; for (let c of cities) { data.push({ x: x, y: y[c], type: 'bar', name: c, text: new Array(x.length).fill(c), textposition: 'auto', marker: { color: intToRGB(hashCode(c)), }, }); } var layout = { title: title, barmode: 'stack', height: 800 }; Plotly.newPlot(divID, data, layout); } function legislatoratlargeBarChart(dataByCity, title, divID) { let x = [...new Set(d3.map(dataByCity, d => d.candidate_party))]; let y = {}; let cities = [...new Set(d3.map(dataByCity, d => d.city))]; for (let c of cities) { y[c] = new Array(x.length); } for (let row of dataByCity) { y[row.city][x.indexOf(row.candidate_party)] = row.ticket; } let data = []; for (let c of cities) { data.push({ x: x, y: y[c], type: 'bar', name: c, text: new Array(x.length).fill(c), textposition: 'auto', marker: { color: intToRGB(hashCode(c)), }, }); } var layout = { title: title, barmode: 'stack', height: 800 }; Plotly.newPlot(divID, data, layout); } </script> <!-- helper function --> <script> function district2City(districtData){ let electedCandidate = districtData.filter(row => row.elected == "True")//get all elected candidate let cityData = electedCandidate.reduce((group, row1) =>{//group by city let city = row1.city group[city] = group[city] ?? [] group[city].push(row1) return group }, {}) let topParty = [] for(let i in cityData){//for each city find major party let partyCounter = cityData[i].reduce((party, row) => { party[row.candidate_party] = party[row.candidate_party] ? ++party[row.candidate_party] : 1 return party },{}) if(partyCounter.length > 1){ partyCounter = partyCounter.sort(function (a, b) { return +b[1] - +a[1]; }); } topParty[i] = partyCounter[0] topParty.push({ "city":i, "candidate_party":Object.keys(partyCounter)[0], "elected":"True" }) topParty.push({//unless "city":i, "candidate_party":Object.keys(partyCounter)[0], "elected":"False" }) } console.log(topParty) return topParty } </script> <script> $("#electionType").on("change", function (e) { let electionType = document.getElementById("electionType").value; let selectedFiles = files[electionType]; let year = +document.getElementById("year").value; for (let e of document.getElementsByClassName("graph")) { Plotly.purge(e.id); } //redraw here ... if (electionType == "president") presidentPlot(selectedFiles, year); if (electionType == "legislator-at-large") legislatoratlargePlot(selectedFiles, year); if (electionType == "legislator") legislatorPlot(selectedFiles, year); // other election type ... }); $("#year").on("change", function (e) { let electionType = document.getElementById("electionType").value; let selectedFiles = files[electionType]; let year = +document.getElementById("year").value; for (let e of document.getElementsByClassName("graph")) { Plotly.purge(e.id); } //redraw here ... if (electionType == "president") presidentPlot(selectedFiles, year); if (electionType == "legislator-at-large") legislatoratlargePlot(selectedFiles, year); if (electionType == "legislator") legislatorPlot(selectedFiles, year); // other election type ... }); async function presidentPlot(files, year) { let dataByNation = await d3.csv(files[year].by_nation); let dataByCity = await d3.csv(files[year].by_city); let candidateData = await d3.csv(files[year].candidate); //draw winner map let title = year + "總統選舉地圖"; plotWinnerMap(title, dataByCity, candidateData); presidentBarChart(dataByCity, year + "總統選票分佈", "presidentBarChart"); } async function legislatoratlargePlot(files, year) { let dataByNation = await d3.csv(files[year].by_nation); let dataByCity = await d3.csv(files[year].by_city); let candidateData = await d3.csv(files[year].candidate); //draw winner map let title = year + "不分區選舉地圖"; plotWinnerMap(title, dataByCity, candidateData); legislatoratlargeBarChart(dataByCity, year + "不分區立委選票分佈", "legislatoratlargeBarChart"); } async function legislatorPlot(files, year) { let dataByDistrict = await d3.csv(files[year].by_district); var candidateData = await d3.csv(files[year].candidate); let title = year + "區域立委"; //draw education levels legislatorEduPlot("edu1", '各政黨候選人教育程度', candidateData); legislatorPieChart("pie1", "各政黨候選人教育程度比例", candidateData); legislatorEduPlot("edu2", '各政黨得選人教育程度', candidateData, true); legislatorPieChart("pie2", "各政黨得選人教育程度比例", candidateData, true); //todo: draw winner map (not compatible with plotWinnerMap !) let dataByCity = district2City(dataByDistrict) candidateData = [ { "candidate":"中國國民黨", "candidate_party":"中國國民黨" }, { "candidate":"民主進步黨", "candidate_party":"民主進步黨" }, ] candidateData["columns"] = ["candidate", "candidate_party"] plotWinnerMap(title, dataByCity, candidateData); //draw party ratio partyRatioBarChart(title, dataByDistrict, candidateData); } function mainPlot() { presidentPlot(files["president"], 2016); } mainPlot(); </script>
--UC1 Create AddressBook Database create database AddressBook_serviceDB; use AddressBook_serviceDB; --UC2 Add AddressBook Table create table AddressBook( FirstName varchar(100), LastName varchar(100), Address varchar(100), City varchar(100), State varchar (100), Zip bigint, PhoneNumber bigint, Email varchar(100) ); select * from AddressBook; --UC3 Insert Contact Details in Table insert into AddressBook(FirstName,LastName,Address,City,State,Zip,PhoneNumber,Email) values('Yuvaj','Rai','DGG','DGG','CG',201013,2548796124,'uv@gmail.com'), ('Amit','Kumar','Delhi','Delhi','DL',254685,9644556677,'amit@gmail.com'), ('Vikas','Kumar','Kanpur','Kanpur','UP',322001,9644556677,'vikas@gmail.com'), ('Nilesh','Singh','Lucknow','Lucknow','UP',250020,9656556677,'nilesh@gmail.com'); select * from AddressBook; --UC4 Edit Contact by Person's Name update AddressBook set PhoneNumber=8218501014 where FirstName= 'Yuvaj'; select * from AddressBook; --UC5 Delete Existing Contact Using Name delete AddressBook where FirstName='Vikas'; select * from AddressBook; --UC6 Retrive Person belongings to City or State select * from AddressBook where City='Lucknow' or State='UP'; --UC7 Size of AddressBook select COUNT(*) as StateCount, State from AddressBook group by State; select COUNT(*) as StateCount, City from AddressBook group by City; --UC8 Sort Entries By Alphabatically select * from AddressBook order by FirstName; --UC9 Identify Each AddressBook with Name and Type alter table AddressBook add ContactType varchar(100) not null default 'Friend'; update AddressBook set ContactType='Family' where FirstName='Amit'; select * from AddressBook; --UC10 Get Count by Count type select COUNT(*) as Type, ContactType from AddressBook group by ContactType; --UC11 Add Person to both Family and Friend insert into AddressBook(FirstName,LastName,Address,City,State,Zip,PhoneNumber,Email,ContactType) values('Krisha','murthy','DGG','DGG','CG',491445,9644556677,'krish07@gmail.com','Friend'), ('Krisha','murthy','DGG','DGG','CG',491445,9644556677,'krish07@gmail.com','Family'); select * from AddressBook; --UC12 Creating Table Using Normalization and ER Diagram Create table Address_Book1( AddressBookId Int Identity(1,1) Primary Key, AddressBookName varchar(100));
//function overloading(Multiplication) using System; public class Program { int a=2,b=4; public void Mul() { Console.WriteLine("Multiplication is: " +(a*b)); } public void Mul(int a,int b) { Console.WriteLine("Multiplication is: " +(a*b)); } public int Mul(int a,int b,int c) { return (a*b); } public void Mul(string a,string b) { Console.WriteLine("Multiplication is: " +(Convert.ToInt32(a)+Convert.ToInt32(b))); } public static void Main() { Program p=new Program(); p.Mul(); p.Mul(1,2); Console.WriteLine(p.Mul(1,2,3)); p.Mul("5","4"); } } Output: Multiplication is: 8 Multiplication is: 2 2 Multiplication is: 9 ------------------------------------------------------------------------------------------------------------------- //Operator Overloading(Multiplication) using System; public class Mul { public int n1,n2; public Mul(int n1,int n2) { this.n1=n1; this.n2=n2; } public static Mul operator * (Mul M1,Mul M2) { Mul M3=new Mul(0,0); M3.n1=M1.n1 * M2.n1; M3.n2=M1.n2 * M2.n2; return M3; } } public class Class1 { public static void Main() { Mul M1=new Mul(6,5); Mul M2=new Mul(2,2); Mul M3=new Mul(0,0); Console.WriteLine("Values before sum Number 1: " + M3.n1 + " Number 2: " + M3.n2); M3=M1*M2; Console.WriteLine("Values after sum Number 1: " + M3.n1 + " Number 2: " + M3.n2); Console.ReadLine(); } } Output: Values before sum Number 1: 0 Number 2: 0 Values after sum Number 1: 12 Number 2: 10 ------------------------------------------------------------------------------------------------------------------- //virtual and override class public class BaseClass{ public virtual void Print(){ Console.WriteLine("Base Class"); } } public class DerivedClass:BaseClass { public override void Print() { Console.WriteLine("Derived Class"); } } public class Class1 { public static void Main() { BaseClass baseclass=new BaseClass(); baseclass.Print(); baseclass=new DerivedClass(); Console.ReadLine(); } } -------------------------------------------------------------------------------------------------------------------- //Base derived class using System; public class ClassA { int n1, n2; public ClassA() { Console.WriteLine("I am Base class Constructor"); } public ClassA(int i, int j) { n1 = i; n2 = j; Console.WriteLine("Parameterized Constructor Invoked"); Console.WriteLine("Values are" + n1 + " and " + n2); } public virtual void Swap() { Console.WriteLine("Hi I am swap Function "); } } public class DerivedClass : ClassA { public DerivedClass() : base() { } public DerivedClass(int i,int j) : base(i, j) { base.Swap(); } } public class Class3 { public static void Main() { DerivedClass d = new DerivedClass(); DerivedClass d2 = new DerivedClass(10, 20); Console.ReadLine(); } } Output: I am Base class Constructor Parameterized Constructor Invoked Values are10 and 20 Hi I am swap Function ------------------------------------------------------------------------------------------------------------------- Create a C# program that prompts the user for three names of people and stores them in an array of Person-type objects. There will be two people of the Student type and one person of the Teacher type. To do this, create a Person class that has a Name property of type string, a constructor that receives the name as a parameter and overrides the ToString () method. Then create two more classes that inherit from the Person class, they will be called Student and Teacher. The Student class has a Study method that writes by console that the student is studying. The Teacher class will have an Explain method that writes to the console that the teacher is explaining. Remember to also create two constructors on the child classes that call the parent constructor of the Person class. End the program by reading the people (the teacher and the students) and execute the Explain and Study methods. using System; public class InheritanceObjects { public static void Main(string[] args) { int total = 3; Person[] persons = new Person[total]; for (int i = 0; i < total; i++) { if (i == 0) { persons[i] = new Teacher(Console.ReadLine()); } else { persons[i] = new Student(Console.ReadLine()); } } for (int i = 0; i < total; i++) { if (i == 0) { ((Teacher)persons[i]).Explain(); } else { ((Student)persons[i]).Study(); } } } public class Person { protected string Name { get; set; } public Person(string name) { Name = name; } public override string ToString() { return "Hello! My name is " + Name; } ~Person() { Name = string.Empty; } } public class Teacher : Person { public Teacher(string name) : base(name) { Name = name; } public void Explain() { Console.WriteLine("Explain"); } } public class Student : Person { public Student(string name) : base(name) { Name = name; } public void Study() { Console.WriteLine("Study"); } } } Input: Juan Sara Carlos Output: Explain Study Study ---------------------------------------------------------------------------------------------------------- using Systems; class Shape { public double Area() { return 0; } public double Perimeter() { return 0; } } class Rectangle:Shape { double side1,side2; public Rectangle(double side1,double side2) { this.side1=side1; this.side2=side2; } public double Area() { return side1*side2; } public double perimeter() { return(2*(side1+side2)); } } class Circle:Shape { double radius; public Circle(double radius) { this.radius=radius; } public double Area() { return((22/7)*(radius*radius)); } public double Perimeter() { return(2*(22/7)*radius); } class Class11 { public static void Main() { Rectangle r=new Rectangle(3.5,2.5); Console.WriteLine("Area of rectangle:" + r.Area()); Console.WriteLine("Perimeter of rectangle:" + r.Perimeter()); console.WriteLine(); Circle c=new Circle(2.5); Console.WriteLine("Area of circle:" + c.Area()); Console.WriteLine("Perimeter of circle:" + c.Perimeter()); console.ReadLine(); } } ------------------------------------------------------------------------------------------------------------------- Create a C# program that prompts the user for three names of people and stores them in an array of Person-type objects. There will be two people of the Student type and one person of the Teacher type. To do this, create a Person class that has a Name property of type string, a constructor that receives the name as a parameter and overrides the ToString () method. Then create two more classes that inherit from the Person class, they will be called Student and Teacher. The Student class has a Study method that writes by console that the student is studying. The Teacher class will have an Explain method that writes to the console that the teacher is explaining. Remember to also create two constructors on the child classes that call the parent constructor of the Person class. End the program by reading the people (the teacher and the students) and execute the Explain and Study methods. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Day_4 { public class Person { public string Name { get; set; } public Person(string Name) { this.Name = Name; } public override string ToString() { return "Hello! My name is "+Name; } ~Person() { Name = string.Empty; } } public class Teacher:Person { public Teacher(string name):base(name) { Name = name; } public void Explain() { Console.WriteLine("Explain"); } } public class Student:Person { public Student(string name) : base(name) { Name = name; } public void Study() { Console.WriteLine("Study"); } } class Class4 { public static void Main() { int Total = 3; Person[] people = new Person[Total]; int[] a = new int[2]; for (int i = 0; i < Total; i++) { if(i==0) { people[i] = new Teacher(Console.ReadLine()); } else { people[i] = new Student(Console.ReadLine()); } } for (int i = 0; i < Total; i++) { if(i==0) { ((Teacher)people[i]).Explain(); float p=(float)a[0]; } else { ((Student)people[i]).Study(); } } Console.ReadLine(); } } }
const express = require("express"); const cors = require("cors"); const { uuid, isUuid } = require("uuidv4"); const app = express(); app.use(express.json()); app.use(cors()); const repositories = []; function validateRepositoriesIds(request, response, next) { const { id } = request.params; if (!isUuid(id)) { return response.status(400).json({ error: "Invalid repository ID." }); } return next(); } app.use("/repositories/:id", validateRepositoriesIds); app.get("/repositories", (request, response) => { response.json(repositories); }); app.post("/repositories", (request, response) => { const { title, url, techs } = request.body; repository = { title, url, techs, id: uuid(), likes: 0 }; repositories.push(repository); return response.json(repository); }); app.put("/repositories/:id", (request, response) => { const { title, url, techs } = request.body; const { id } = request.params; const repositoryIndex = repositories.findIndex( (repository) => repository.id === id ); if (repositoryIndex < 0) { return response.status(400).json({ error: "Repository not found." }); } repositories[repositoryIndex] = { ...repositories[repositoryIndex], title, url, techs, }; return response.json(repositories[repositoryIndex]); }); app.delete("/repositories/:id", (request, response) => { const { id } = request.params; const repositoryIndex = repositories.findIndex( (repository) => repository.id === id ); if (repositoryIndex < 0) { return response.status(400).json({ error: "Repository not found." }); } repositories.splice(repositoryIndex, 1); return response.status(204).send(); }); app.post("/repositories/:id/like", (request, response) => { const { id } = request.params; const repositoryIndex = repositories.findIndex( (repository) => repository.id === id ); if (repositoryIndex < 0) { return response.status(400).json({ error: "Repository not found." }); } repositories[repositoryIndex].likes++; return response.json(repositories[repositoryIndex]); }); module.exports = app;
from socket import * import threading HOST = "127.0.0.1" PORT = 3000 def log(prefix: str, message: str): print(f"[{prefix}]\t\t{message}") def run_client(client_id : int, message:str): clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((HOST, PORT)) log("INFO", f"Client {client_id} connected to server") log("INFO", f"Sending message {message}") clientSocket.sendall(message.encode()) data:bytes = clientSocket.recv(1024) log("INFO", f"Message Received from server: {data.decode()}") clientSocket.close() def main(): messages = ["Hello from client 1", "Hello from client 2", "Hello from client 3", "Hello from client 4", "Hello from client 5"] for i in range(0, len(messages)): message = messages[i] client_thread = threading.Thread(target=run_client, args=(i+1, message)) client_thread.start() if __name__ == '__main__': main()
;;; Copyright 2021-2023 Google LLC ;;; ;;; This file is part of cl-avro. ;;; ;;; cl-avro is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; cl-avro is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with cl-avro. If not, see <http://www.gnu.org/licenses/>. (in-package #:cl-user) (defpackage #:cl-avro.internal.ipc.error (:use #:cl) (:local-nicknames (#:api #:cl-avro) (#:internal #:cl-avro.internal) (#:record #:cl-avro.internal.record) (#:intern #:cl-avro.internal.intern)) (:import-from #:cl-avro.internal.recursive-descent.pattern #:define-pattern-method) (:import-from #:cl-avro.internal.record #:fields #:objects #:booleans)) (in-package #:cl-avro.internal.ipc.error) (define-condition api:rpc-error (error) ((metadata :initarg :metadata :type api:map<bytes> :reader api:metadata :documentation "Metadata from server")) (:default-initargs :metadata (make-instance 'api:map<bytes> :size 0)) (:documentation "Base condition for rpc errors.")) (define-condition api:undeclared-rpc-error (api:rpc-error) ((message :initarg :message :type api:string :reader api:message :documentation "Error message from server.")) (:report (lambda (condition stream) (format stream (api:message condition)))) (:default-initargs :message (error "Must supply MESSAGE")) (:documentation "Undeclared error from server.")) (define-condition api:declared-rpc-error (api:rpc-error) ((schema :type api:record :reader internal:schema :allocation :class)) (:documentation "Declared error from server.")) (declaim (ftype (function (symbol fields objects list booleans) (values api:declared-rpc-error &optional)) %make-error)) (defun %make-error (type fields values initargs initargp-vector) (loop with error = (apply #'make-condition type initargs) for field across fields for value across values for initargp across initargp-vector for writers = (internal:writers field) when initargp do (let ((writer (fdefinition (first writers)))) (funcall writer value error)) finally (return error))) (declaim (ftype (function (symbol fields objects api:map<bytes>) (values api:declared-rpc-error &optional)) make-error)) (defun make-error (type fields values metadata) (loop with initargs of-type list = (list :metadata metadata) and initargp-vector = (make-array (length fields) :element-type 'boolean :initial-element nil) for index below (length fields) for field = (elt fields index) for value = (elt values index) for initarg = (first (closer-mop:slot-definition-initargs field)) if initarg do (push value initargs) (push initarg initargs) else do (setf (elt initargp-vector index) t) finally (return (%make-error type fields values initargs initargp-vector)))) (declaim (ftype (function (symbol api:record-object &optional api:map<bytes>) (values api:declared-rpc-error &optional)) internal:make-declared-rpc-error)) (defun internal:make-declared-rpc-error (type error &optional (metadata (make-instance 'api:map<bytes> :size 0))) (loop with fields of-type fields = (api:fields (class-of error)) with values = (make-array (length fields) :element-type 'api:object) for index below (length fields) for field = (elt fields index) for name of-type symbol = (nth-value 1 (api:name field)) for value of-type api:object = (slot-value error name) do (setf (elt values index) value) finally (return (make-error type fields values metadata)))) (declaim (ftype (function (api:declared-rpc-error) (values api:record-object &optional)) internal:to-record)) (defun internal:to-record (error) (loop with schema of-type api:record = (internal:schema error) with fields of-type fields = (api:fields schema) with values = (make-array (length fields) :element-type 'api:object) for index below (length fields) for field = (elt fields index) for reader = (fdefinition (first (internal:readers field))) for value = (funcall reader error) do (setf (elt values index) value) finally (return (record:make-object schema fields values)))) (declaim (ftype (function (api:field) (values cons &optional)) %%add-accessors-and-initargs)) (defun %%add-accessors-and-initargs (field) (let ((initargs (list :name (nth-value 1 (api:name field)) :type (api:type field) :allocation (closer-mop:slot-definition-allocation field) :initargs (closer-mop:slot-definition-initargs field) :documentation (documentation field t)))) (let ((initfunction (closer-mop:slot-definition-initfunction field))) (when initfunction (push initfunction initargs) (push :initfunction initargs) (push (closer-mop:slot-definition-initform field) initargs) (push :initform initargs))) (multiple-value-bind (default defaultp) (api:default field) (when defaultp (push default initargs) (push :default initargs))) (multiple-value-bind (order orderp) (api:order field) (when orderp (push order initargs) (push :order initargs))) (let ((aliases (api:aliases field))) (when aliases (push aliases initargs) (push :aliases initargs))) (let ((readers (internal:readers field)) (writers (internal:writers field)) (symbol (gensym))) (unless readers (push symbol readers)) (unless (or writers (closer-mop:slot-definition-initargs field)) (push `(setf ,symbol) writers)) (push readers initargs) (push :readers initargs) (push writers initargs) (push :writers initargs)) initargs)) (declaim (ftype (function (fields) (values list &optional)) %add-accessors-and-initargs)) (defun %add-accessors-and-initargs (fields) (map 'list #'%%add-accessors-and-initargs fields)) (declaim (ftype (function (api:record) (values api:record &optional)) add-accessors-and-initargs)) (defun add-accessors-and-initargs (record) (let ((initargs (list :direct-default-initargs (closer-mop:class-direct-default-initargs record) :documentation (documentation record t) :direct-superclasses (closer-mop:class-direct-superclasses record)))) (multiple-value-bind (deduced-namespace provided-namespace namespace-provided-p) (api:namespace record) (when namespace-provided-p (push provided-namespace initargs) (push :namespace initargs)) (when (and deduced-namespace (or (null provided-namespace) (string/= deduced-namespace provided-namespace))) (push deduced-namespace initargs) (push :enclosing-namespace initargs))) (let ((aliases (api:aliases record))) (when aliases (push aliases initargs) (push :aliases initargs))) (push (%add-accessors-and-initargs (api:fields record)) initargs) (push :direct-slots initargs) (apply #'reinitialize-instance record initargs))) (declaim (ftype (function (api:field) (values cons &optional)) make-condition-slot)) (defun make-condition-slot (field) (let ((name (nth-value 1 (api:name field))) (type (api:type field)) (documentation (documentation field t)) (initargs (closer-mop:slot-definition-initargs field)) (readers (internal:readers field)) (writers (internal:writers field))) `(,name :type ,type ,@(when documentation `(:documentation ,documentation)) ,@(mapcan (lambda (initarg) `(:initarg ,initarg)) initargs) ,@(mapcan (lambda (reader) `(:reader ,reader)) readers) ,@(mapcan (lambda (writer) `(:writer ,writer)) writers)))) (declaim (ftype (function (api:record) (values list &optional)) make-condition-slots)) (defun make-condition-slots (record) (map 'list #'make-condition-slot (api:fields record))) (declaim (ftype (function (symbol list list api:record) (values cons &optional)) expand-define-condition)) (defun expand-define-condition (name slots options record) `(progn (define-condition ,name (api:declared-rpc-error) ((schema :allocation :class :initform ,record) ,@slots) ,@options) (find-class ',name))) (declaim (ftype (function (api:record &optional symbol) (values class &optional)) to-error)) (defun to-error (record &optional (name (make-symbol (api:name record)))) (let* ((record (add-accessors-and-initargs record)) (condition-slots (make-condition-slots record)) (condition-options (when (documentation record t) `((:documentation ,(documentation record t)))))) (eval (expand-define-condition name condition-slots condition-options record)))) (defmethod internal:write-jso ((error class) seen canonical-form-p) (assert (subtypep error 'api:declared-rpc-error) ()) (closer-mop:ensure-finalized error) (let* ((record (internal:schema (closer-mop:class-prototype error))) (jso (internal:write-jso record seen canonical-form-p))) (when (typep jso 'st-json:jso) (setf (st-json:getjso "type" jso) "error")) jso)) (define-pattern-method 'internal:read-jso '(lambda ((jso ("type" "error")) fullname->schema enclosing-namespace) (setf (st-json:getjso "type" jso) "record") (let* ((record (internal:read-jso jso fullname->schema enclosing-namespace)) (condition (to-error record))) (setf (gethash (api:fullname record) fullname->schema) condition) condition))) (eval-when (:compile-toplevel :load-toplevel :execute) (declaim (ftype (function (list) (values &optional)) assert-valid-options)) (defun assert-valid-options (options) (loop ;; TODO should I add :name that overrides like named-schemas? with expected-keys = '(:namespace :enclosing-namespace :aliases :default-initargs :documentation :report) initially (assert (every #'consp options) (options) "Expected a list of cons cells: ~S" options) for (key &rest) in options unless (member key expected-keys) do (error "Unknown key ~S, expected one of ~S" key expected-keys) collect key into keys finally (loop for expected-key in expected-keys do (setf keys (delete expected-key keys :count 1)) finally (when keys (error "Duplicate keys: ~S" keys)))) (values)) (declaim (ftype (function (list) (values list &optional)) options->record-initargs)) (defun options->record-initargs (options) (loop with keys = '(:namespace :enclosing-namespace :aliases :documentation) for key in keys for assoc = (assoc key options) when assoc nconc (list key (cdr assoc)))) (declaim (ftype (function (list) (values list &optional)) options->condition-options)) (defun options->condition-options (options) (loop with keys = '(:default-initargs :documentation :report) for key in keys when (assoc key options) collect it)) (declaim (ftype (function (list symbol symbol (function (t) (values t &optional))) (values list &optional)) %gather-into)) (defun %gather-into (field from to transform) (loop while (member from field) collect (funcall transform (getf field from)) into gathered do (remf field from) finally (when gathered (setf (getf field to) gathered)) (return field))) (declaim (ftype (function (list symbol symbol &optional (function (t) (values t &optional))) (values list &optional)) gather-into)) (defun gather-into (fields from to &optional (transform #'identity)) (flet ((%gather-into (field) (%gather-into field from to transform))) (mapcar #'%gather-into fields))) (declaim (ftype (function (list) (values list &optional)) to-direct-slots)) (defun to-direct-slots (fields) (flet ((add-name (field) (push :name field)) (expand-accessors (field) (loop while (member :accessor field) do (push (getf field :accessor) field) (push :reader field) (push (getf field :accessor) field) (push :writer field) (remf field :accessor) finally (return field))) (writer-transform (writer) (declare ((or cons symbol) writer)) (if (consp writer) writer `(setf ,writer)))) (setf fields (mapcar #'add-name fields) fields (mapcar #'expand-accessors fields) fields (gather-into fields :reader :readers) fields (gather-into fields :writer :writers #'writer-transform) fields (gather-into fields :initarg :initargs))))) (defmacro api:define-error (name (&rest fields) &body options) (declare (symbol name)) (assert-valid-options options) (let ((record-initargs (list* ;; if this is the same symbol as name, then ;; I can't use the ctor twice :name (make-symbol (string name)) :direct-slots (to-direct-slots fields) (options->record-initargs options))) (condition-options (options->condition-options options)) (record (gensym)) (condition-slots (gensym))) `(eval-when (:compile-toplevel :load-toplevel :execute) (let* ((,record (add-accessors-and-initargs (let ((class (find-class ',name nil))) (if class (let ((record (internal:schema (closer-mop:class-prototype class)))) (apply #'reinitialize-instance record ',record-initargs)) (apply #'make-instance 'api:record ',record-initargs))))) (,condition-slots (make-condition-slots ,record))) (eval (expand-define-condition ',name ,condition-slots ',condition-options ,record)))))) ;;; intern (defmethod api:intern ((instance class) &key (null-namespace api:*null-namespace*)) (assert (subtypep instance 'api:declared-rpc-error) (instance) "Not an error class") (let* ((schema (internal:schema (closer-mop:class-prototype instance))) (class-name (api:intern schema :null-namespace null-namespace))) (assert (eq instance (to-error schema (class-name instance)))) ;; Muffle bogus warning about changing meta class (handler-bind ((warning #'muffle-warning)) (setf (find-class class-name) instance)) class-name))
import {isFunction, MODIFIER} from './globals'; export class KeyboardHandler { /** @type {VimController} */ #controller; /** * Current key code * Used to implement the "fluent DSL", which is currently consumed by * vim_keymap.js * * @type {number|string} */ #fluentKeyCode = undefined; /** * The complete keymap used by this editor * @remarks * A keymap is a collection of _keymappings_ (key-codes) and their * associated behaviour * @todo DSL can be implemented in a more sound manner: * Instead of accessing the keymap directly, the fluent DSL * should return a "context object" after each call, * that can be used to further modify the keymap * in a way that is not dependent of KeyboardHandler internal state * (i.e. #fluentKeyCode could be removed). * * @private * @type {Object<number|string, Keymapping>} */ #keymap = {}; /** @type {Logger} */ #logger; /** * Retrieve the current, complete keymap * @todo We should have a method that returns a single keymapping, instead * of exposing the whole keymap * * @return {Object<number|string, Keymapping>} */ get keymap() { return this.#keymap; } /** * * @param {Logger} logger * @param {VimController} controller */ constructor(logger, controller) { this.#logger = logger; this.#controller = controller; } /** * * @param {Function<VimController,number>} action * @param {number} modifier */ action(action, modifier = MODIFIER.NONE) { if (!this.#fluentKeyCode) { return undefined; } this.#keymap[this.#fluentKeyCode].actions[modifier] = action; return this; } /** * @param {number} prefix * @param {number|string} code * @param {number} modifier * @param {function} record * @param {function} before * @param {function} after * @return void */ executeMapping(prefix, code, modifier, record = undefined, before = undefined, after = undefined) { if (isFunction(before)) { before(); } const keymapping = this.#keymap[code]; if (!keymapping) { this.#logger.log(this.executeMapping, `No keymapping found for code ${code}.`); return; } const action = keymapping.actions[modifier]; if (!action) { this.#logger.log(this.executeMapping, `No action found for code ${code} and modifier ${modifier}.`); return; } if (!isFunction(action)) { this.#logger.log(this.executeMapping, `INVALID action found for code ${code} and modifier ${modifier}!`); return; } if (isFunction(record)) { record(); } action.call(this.#controller, prefix); if (isFunction(after)) { after(); } } /** * @param {number|string} code * @param {string} name * @return {KeyboardHandler} The instance of the class for chaining method calls. * @todo Currently, `code` can be either a string or a number. * A string is used for a "chord" of keys (e.g. 'gg'), and that's * implemented in a weird manner. * The most direct fix would be changing this argument to a `Array<number>` * instead, but I'm not sure about the impact yet. */ map(code, name) { if (!this.#keymap[code]) { this.#keymap[code] = new Keymapping(); } const keymapping = this.#keymap[code]; keymapping.name = name; keymapping.mode = undefined; keymapping.record = false; this.#fluentKeyCode = code; return this; } /** * Sets the mode for the current code in the internal key storage. * If no current code is present, the method will exit without modifications. * * @param {number} mode - The mode to be set for the current code. * @return {KeyboardHandler|undefined} The instance of the class for chaining method calls. */ mode(mode) { if (!this.#fluentKeyCode) { return undefined; } this.#keymap[this.#fluentKeyCode].mode = mode; return this; } /** * Updates the record status for the current code in the internal keys object. * @todo 'record' is a misnomer; this actually identifies a _destructive_ * action - one that can modify the current state of the editor, and * therefore generates undo history * * @param {boolean} value If this mapping should be recorded into the undo history * @return {KeyboardHandler|undefined} The instance of the class for chaining method calls. */ record(value) { if (!this.#fluentKeyCode) { return undefined; } this.#keymap[this.#fluentKeyCode].record = value; return this; } } class Keymapping { /** @type {Object<number, Function<VimController,number>>} */ #actions = {}; /** @type number */ #mode = 0; /** @type string */ #name; /** @type boolean */ #record = false; get actions() { return this.#actions; } get mode() { return this.#mode; } set mode(value) { this.#mode = value; } get name() { return this.#name; } set name(value) { this.#name = value; } get record() { return this.#record; } set record(value) { this.#record = value; } }
function [ x, y, z, ts ] = particle_track_ode_grid_sigmaVar(X, Y, ZZ, U, V, W, tt, ... tspan, cc, options, odesolver) % PARTICLE_TRACK_ODE_GRID Generates particle tracks from a set of currents % defined on a rectangular grid using PDE solver % % Usage: [x,y,ts] = particle_track_ode_andreas(X,Y,U,V,tt,tspan,cc,options,odesolver ) % % This function is largely inspired by Bruce Lipphardt's trajectories code. % The principal difference is the method of interpolating from the grid to % an arbitrary space time point is different (he uses interpn, I use % interp2 plus linear interpolation by hand between previous and next % time of current time). Also, this assumes that % % Inputs % ------ % X = x-coordinate of rectangular grid % Y = Y-coordinate of rectangular grid % % U,V = currents at locations in X,Y. The third dimension should % be time. Units should be consistent with those in X and tt. % % tt = times at which the currents are defined. Must have length equal % to the third dimension of U. % % tspan = time period over which to generate tracks. See ode45 for more % details on possible tspan formats (some of which might not work with % this function). % % cc = a two column matrix of initial positions for the particles. % % options = options for the ODE solver. See odeset, ode45 and the other % solvers for details on format and creating. Defaults to no special options. % % odesolver = ode solver function to use. Defaults to ode45. % % OUTPUTS: % % x,y = coordinates of particles. Each column is a different starting % position (row of cc) and each row is a time in ts. % % ts = times of positions in x and y. A column vector. % % NOTE: This function appears to be hopelessly slow in matlab R13 (6.5) % unless you play with the default tolerances of ode45. See ODESET % function and, in particular, the absolute and relative tolerances for % more information. You might also want to play with MaxStep, the % maximum time step to take. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % $Id: particle_track_ode_grid.m 001 2018-02-12 10:55:10Z ef $ % modified by Isabel Jalon-Rojas for 3D version % % Copyright (C) 2014-2018 Erick Fredj % Licence: GPL (Gnu Public License) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist( 'odesolver', 'var' ) odesolver = 'ode45'; end if ~exist( 'options', 'var' ) options = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Do tracking. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ntraj = size(cc,1); y0 = [ cc(:,1); cc(:,2); cc(:,3) ]; [ts,A] = feval( odesolver, @ptrack_ode_worker_func, tspan, y0, options, ... X, Y, ZZ, U, V, W, tt); [x,y,z] = deal( A(:,1:ntraj), A(:,ntraj+1:2*ntraj), A(:,2*ntraj+1:end)); %%%%%%----------------------Subfunctions--------------------%%%%%%% % % 2020-09-01 | V. Marieu | Routine slightly modified for optimization %--------------------------------------------------------------------- function f = ptrack_ode_worker_func( T, y, X, Y, ZZ, ux, uy, uz, tt) % This function will be used to actually do tracking. ntraj = length(y)/3; % Particle initial position [xx,yy,zz] = deal( y(1:ntraj), y(ntraj+1:2*ntraj), y(2*ntraj+1:end) ); % Find timesteps corresponding to T in (day) d = tt - T; % If outside time range, return NaNs if all(d<0) || all(d>0) return end % Linear interpolation of the velocity field in the time domain. dlt = max( d( d<0 ) ); dgt = min( d( d>=0 ) ); if dgt == 0 %[ux,uy,uz,e] = deal( ux( :, :, :, d == 0 ), uy( :, :, :, d == 0 ), uz( :, :, :, d == 0 ), E(:, :, d == 0) ); [ux,uy,uz,ZZ] = deal( ux( :, :, :, d == 0 ), uy( :, :, :, d == 0 ), uz( :, :, :, d == 0 ), ZZ( :, :, :, d == 0 )); else ilt = d == dlt; igt = d == dgt; dd = dgt - dlt; clt = dgt / dd; cgt = -dlt / dd; ux = clt * ux( :, :, :, ilt ) + cgt * ux( :, :, :, igt ); uy = clt * uy( :, :, :, ilt ) + cgt * uy( :, :, :, igt ); uz = clt * uz( :, :, :, ilt ) + cgt * uz( :, :, :, igt ); ZZ = clt * ZZ( :, :, :, ilt ) + cgt * ZZ( :, :, :, igt ); % e = clt * E( :, :, ilt ) + cgt * E(:, :, igt ); end % Then fit to specific points of interest (xx,yy,zz). % nn = ~isnan(xx) & ~isnan(yy) & ~isnan(zz); [UX,UY,UZ] = deal( NaN( size(xx) ) ); % find the index of specific points p=find(nn); np = sum(nn); % fit the pom velocity field len_Z=size(ZZ,3); uxi=zeros(len_Z,np); uyi=zeros(len_Z,np); uzi=zeros(len_Z,np); hi=zeros(len_Z,np); % Interpolate the velocity field at (xx,yy) position for every ZZ for i=1:len_Z %IJR 21/06/2019 uxi(i,1:np) = interp2( X, Y, ux(:,:,i), xx(nn), yy(nn), 'linear' ); uyi(i,1:np) = interp2( X, Y, uy(:,:,i), xx(nn), yy(nn), 'linear' ); uzi(i,1:np) = interp2( X, Y, uz(:,:,i), xx(nn), yy(nn), 'linear' ); hi(i,1:np) = interp2( X, Y, ZZ(:,:,i), xx(nn), yy(nn), 'linear' ); end uxi(isnan(uxi))=0; uyi(isnan(uyi))=0; uzi(isnan(uzi))=0; % Interpolate the velocity field at zz vertical position for itraj = 1:np if isnan(sum(hi(:,itraj))) | hi(len_Z,itraj)>zz(nn(itraj)) | zz(nn(itraj))>0 %out of domain or sinking or beaching UX(p(itraj))=0; UY(p(itraj))=0; UZ(p(itraj))=0; else UX(p(itraj))=interp1(hi(:,itraj),uxi(:,itraj),zz(nn(itraj))); UY(p(itraj))=interp1(hi(:,itraj),uyi(:,itraj),zz(nn(itraj))); UZ(p(itraj))=interp1(hi(:,itraj),uzi(:,itraj),zz(nn(itraj))); end end f = [ UX(:); UY(:); UZ(:) ];
package com.shop.common.enums; import lombok.Getter; /** * @author : Ran * Project: shop * Package: com.yingran.shop.enums * @date : 2019/10/25 0:44 */ @Getter public enum ResultEnum { SUCCESS(0, "成功"), PARAM_ERROR(1, "参数不正确"), PRODUCT_NOT_EXIST(10, "商品不存在"), PRODUCT_STOCK_ERROR(11, "商品库存不正确"), ORDER_NOT_EXIST(12, "订单不存在"), ORDERDETAIL_NOT_EXIST(13, "订单详情不存在"), ORDER_STATUS_ERROR(14, "订单状态不正确"), ORDER_UPDATE_FAIL(15, "订单更新失败"), ORDER_DETAIL_EMPTY(16, "订单详情为空"), ORDER_PAY_STATUS_ERROR(17, "订单支付状态不正确"), CART_EMPTY(18, "购物车为空"), ORDER_OWNER_ERROR(19, "该订单不属于当前用户"), WECHAT_MP_ERROR(20, "微信公众账号方面错误"), WXPAY_NOTIFY_MONEY_VERIFY_ERROR(21, "微信支付异步通知金额校验不通过"), ORDER_CANCEL_SUCCESS(22, "订单取消成功"), ORDER_FINISH_SUCCESS(23, "订单完结成功"), PRODUCT_STATUS_ERROR(24, "商品状态不正确"), LOGIN_FAIL(25, "登录失败, 登录信息不正确"), LOGOUT_SUCCESS(26, "登出成功"), BINDDEVICE_ERROR(27, "设备不合法,请联系客服"), BINDDEVICEREPEAT_ERROR(28, "重复绑定"), DEVICE_NO(29, "没有可用的设备"), TOKEN_EMPTY(50008, "token缺失,请重新登录"), AUTH_NOT_ENOUGH(31, "对不起,你没有访问权限!"), TOKEN_EXPIRE(50014, "token过期,请重新登录"), ; private Integer code; private String message; ResultEnum(Integer code, String message) { this.code = code; this.message = message; } }
## `storage() -> Dict[int, CodeSnippet]` #### Description: This method returns the storage of code snippets. It belongs to the class SnippetStorage. #### Parameters: This method does not take any parameters. #### Returns: - `Dict[int, CodeSnippet]`: A dictionary where the keys are integers representing the snippet IDs and the values are instances of the CodeSnippet class. #### Exceptions: This method does not throw any exceptions. #### Usage Cases: ```python # Retrieve the storage of code snippets snippet_storage = SnippetStorage() storage = snippet_storage.storage() print(storage) ``` #### How it Works: This method simply returns the `_storage` attribute of the SnippetStorage class, which is a dictionary containing code snippets. #### Dependencies: - `CodeSnippet`: Represents a code snippet object. - `Dict[int, CodeSnippet]`: A dictionary data structure where the keys are integers and the values are instances of the CodeSnippet class. - This method does not have any additional dependencies.
<?php /** * テーブルのスキーマを同期する関数。 * 指定されたカラムがテーブルに存在しなければ追加し、不要なカラムは削除する。 * * @param PDOObject $pdoObject データベース接続オブジェクト * @param string $tableName テーブル名 * @param array $requiredColumns 必要なカラムの配列 * @return void */ function syncTableSchema(PDOObject $pdoObject, string $tableName, array $requiredColumns): void { // テーブル名のサニタイズ $safeTableName = preg_replace('/[^a-zA-Z0-9_]/', '', $tableName); // テーブルが存在するかを確認 if (!$pdoObject->tableExists($safeTableName)) { // テーブルが存在しない場合、新規作成 $columnsSql = implode(", ", array_map(function ($col) { $safeColumnName = preg_replace('/[^a-zA-Z0-9_]/', '', $col['name']); return "`$safeColumnName` {$col['type']}" . (isset($col['options']) ? " {$col['options']}" : ""); }, $requiredColumns)); $sql = "CREATE TABLE `$safeTableName` ($columnsSql) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; try { $pdoObject->get()->exec($sql); } catch (PDOException $e) { throw new RuntimeException('テーブル作成エラー: ' . $e->getMessage()); } return; } // 現在のカラムを取得 $existingColumns = $pdoObject->getTableColumns($tableName); // 必要なカラムの名前を取得 $requiredColumnNames = array_column($requiredColumns, 'name'); // 追加する必要があるカラムを見つける $columnsToAdd = array_filter($requiredColumns, function($col) use ($existingColumns) { return !in_array($col['name'], $existingColumns); }); // 削除する必要があるカラムを見つける $columnsToDelete = array_diff($existingColumns, $requiredColumnNames); // カラムを追加 foreach ($columnsToAdd as $col) { $safeColumnName = preg_replace('/[^a-zA-Z0-9_]/', '', $col['name']); $sql = "ALTER TABLE `$safeTableName` ADD COLUMN `$safeColumnName` {$col['type']}" . (isset($col['options']) ? " {$col['options']}" : ""); try { $pdoObject->get()->exec($sql); } catch (PDOException $e) { throw new RuntimeException('カラム追加エラー: ' . $e->getMessage()); } } // カラムを削除 foreach ($columnsToDelete as $col) { $safeColumnName = preg_replace('/[^a-zA-Z0-9_]/', '', $col); $sql = "ALTER TABLE `$safeTableName` DROP COLUMN `$safeColumnName`"; try { $pdoObject->get()->exec($sql); } catch (PDOException $e) { throw new RuntimeException('カラム削除エラー: ' . $e->getMessage()); } } }
package main import ( "database/sql" "fmt" "log" "os" "strings" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" "github.com/joho/godotenv" "github.com/marinazv/FinalGo/cmd/server/routes" _ "github.com/marinazv/FinalGo/docs" "github.com/marinazv/FinalGo/pkg/middleware" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" ) // @title Examen Final Backend III // @version 1.0 // @description Desafío Final: Sistema de reserva de turnos // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email support@swagger.io // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host localhost:9090 // @BasePath /api/v1 // @securityDefinitions.basic BasicAuth // @externalDocs.description OpenAPI // @externalDocs.url https://swagger.io/resources/open-api/ func main() { // Recover from panic. defer func() { if err := recover(); err != nil { log.Fatal(err) os.Exit(1) } }() // Load the environment variables. err := godotenv.Load() if err != nil { log.Fatal(err) } // Connect to the database. db := connectDB() // Create a new Gin engine. engine := gin.New() engine.Use(gin.Recovery()) // Add the logger middleware. engine.Use(middleware.Logger()) // Add the swagger handler. engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // Run the application. runApp(db, engine) // Close the connection. defer db.Close() } func runApp(db *sql.DB, engine *gin.Engine) { // Run the application. router := routes.NewRouter(engine, db) // Map all routes. router.MapRoutes() if err := engine.Run(os.Getenv("LOCAL_PORT")); err != nil { panic(err) } } // connectDB connects to the database. func connectDB() *sql.DB { var dbUsername, dbPassword, dbHost, dbPort, dbName string dbUsername = os.Getenv("DB_USERNAME") dbPassword = os.Getenv("DB_PASSWORD") dbHost = os.Getenv("DB_HOST") dbPort = os.Getenv("DB_PORT") dbName = os.Getenv("DB_NAME") // Create the data source. dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true", dbUsername, dbPassword, dbHost, dbPort, dbName) fmt.Print(dataSource) // Open the connection. db, err := sql.Open("mysql", dataSource) if err != nil { panic(err) } // Check the connection. err = db.Ping() if err != nil { panic(err) } // Leer el contenido del archivo sqlBytes, err := os.ReadFile("schema.txt") if err != nil { log.Fatal(err) } // Convertir el contenido a una cadena sqlString := string(sqlBytes) // Divide el contenido en sentencias SQL individuales sqlStatements := strings.Split(sqlString, ";") // Ejecutar cada sentencia SQL en la base de datos for _, statement := range sqlStatements { statement = strings.TrimSpace(statement) if statement == "" { continue } if _, err := db.Exec(statement); err != nil { log.Printf("Error al ejecutar sentencia SQL: %v", err) } } return db }
#![cfg_attr(feature = "unstable", feature(test))] use std::collections::HashMap; #[cfg(not(test))] fn main() { let input = include_str!("../../assets/input.txt").trim(); dbg!(part2(input, "rx")); } #[derive(Debug, Clone, Copy, PartialEq)] enum Pulse { High, Low, } #[derive(Debug)] enum Module<'a> { FlipFlop(Pulse), Conjunction(HashMap<&'a str, Pulse>), Broadcast, } fn lcm(first: usize, second: usize) -> usize { first * second / gcd(first, second) } fn gcd(first: usize, second: usize) -> usize { let mut max = first; let mut min = second; if min > max { let val = max; max = min; min = val; } loop { let res = max % min; if res == 0 { return min; } max = min; min = res; } } fn part2(input: &str, output : &str) -> String { let mut to_rx = ""; let mut modules = { let mut mods = input.lines().map(|l| { let mut node_dest = l.split_terminator(" -> "); let node = node_dest.next().unwrap(); let destinations = node_dest.next().unwrap().split_terminator(", ").map(|r| r.trim()).collect::<Vec<_>>(); if destinations.contains(&output) { assert_eq!(l.chars().next().unwrap(), '&'); to_rx = &node[1..]; } if let Some(node_name) = node.strip_prefix('%') { //FlipFlop (node_name, (Module::FlipFlop(Pulse::Low), destinations)) } else if let Some(node_name) = node.strip_prefix('&') { // Conjunction (node_name, (Module::Conjunction(HashMap::new()), destinations)) } else { (node, (Module::Broadcast, destinations)) } }).collect::<HashMap<&str, (Module, Vec<_>)>>(); let mut conj_module_initializer : HashMap<&str, Vec<&str>> = HashMap::new(); for (input, (_t, destinations)) in &mods { for dest in destinations { if let Some((Module::Conjunction(_), _)) = mods.get(dest) { if conj_module_initializer.contains_key(dest) { conj_module_initializer.get_mut(dest).unwrap().push(input); } else { conj_module_initializer.insert(dest, vec![input]); } } } } for (name, inputs) in conj_module_initializer { mods.get_mut(name).unwrap().0 = Module::Conjunction( inputs.iter().map(|i| (*i, Pulse::Low)).collect::<HashMap<_, _>>() ); } mods }; //println!("{modules:?} {to_rx}"); // our check { let mut cycle_starts = HashMap::new(); let mut cycles = HashMap::new(); let mut i : u64 = 0; let num_kc = { if let Module::Conjunction(v) = &modules.get(to_rx).unwrap().0 { v.len() } else { 0 } }; while cycles.len() != num_kc { let mut queue_signals = vec![("button", "broadcaster", Pulse::Low)]; let mut index = 0; while index != queue_signals.len() { let (from, to, signal) = queue_signals[index]; // found an output with low before finding cycles: if to == output && signal == Pulse::Low { return i.to_string(); } if let Some(entry) = modules.get_mut(&to) { if to == to_rx && signal == Pulse::High { if let Some(v) = cycle_starts.insert(from, i + 1) { cycles.insert(from, (i+1) - v); } } match &mut entry.0 { Module::Broadcast => { for d in &entry.1 { queue_signals.push((to, d, signal)); } } Module::FlipFlop(v) => { if let Pulse::Low = signal { // flip the flipflop and send the update let out_signal = if let Pulse::Low = v { Pulse::High } else { Pulse::Low }; for d in &entry.1 { queue_signals.push((to, d, out_signal)); } *v = out_signal; } }, Module::Conjunction(ref mut m) => { m.insert(from, signal); let out_signal = if m.iter().all(|(_k, v)| *v == Pulse::High) { Pulse::Low } else { Pulse::High }; for d in &entry.1 { queue_signals.push((to, d, out_signal)); } } } } index += 1; } i += 1; } //println!("{cycles:?}"); cycles.values().fold(1, |acc, v| lcm(acc, *v as usize)).to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input() { let input = include_str!("../../assets/test2.txt").trim(); assert_eq!(part2(input, "output"), "0"); } } #[cfg(all(feature = "unstable", test))] mod bench { use super::*; extern crate test; use self::test::Bencher; #[bench] fn bench_part2(b: &mut Bencher) { let input = test::black_box(include_str!("../../assets/input.txt").trim()); b.iter(move || { //std::thread::sleep(std::time::Duration::from_nanos(1000)); let _ = part2(input, "rx"); }); } }
import { NextFunction, Request, Response } from "express"; import jwt from "jsonwebtoken"; import { SECRET_KEY } from "../../secrets"; import { UnAuthorize } from "../errorHandling/unauthorize"; import { ErrorCode } from "../errorHandling/root"; const JWT_SECRET = SECRET_KEY; // interface CustomRequest extends Request{ // user?: any // } export const authenticatedUser = ( req: Request, res: Response, next: NextFunction ) => { try { const token = req.cookies.authToken; if (!token) { return next( new UnAuthorize("Unauthorized - Invalid token", ErrorCode.UNAUTHORIZED) ); } const decoded = jwt.verify(token, JWT_SECRET); // Attach user information to the request object // Why Not Attach to res? // You might wonder why we attach it to req and not res (the response object). Here's why: // req: Represents the incoming request. It's part of the middleware chain, so any modifications (like adding req.user) are accessible to subsequent middlewares and handlers. // res: Represents the outgoing response. Attaching data to res does not propagate it forward through the request lifecycle. req.user = decoded; console.log(req.user,"in mid") next(); } catch (err) { next( new UnAuthorize("Unauthorized - Invalid token", ErrorCode.UNAUTHORIZED) ); } };
// // CategoryControllerViewController.swift // TaskListReload // // Created by Владимир Юшков on 06.10.2021. // import UIKit class CategoryController: UIViewController { let categoryView = CategoryView() var tasks: [Task] var category: String init(category: String, task: [Task]) { self.tasks = task self.category = category super.init(nibName: nil, bundle: nil) categoryView.tableView.delegate = self categoryView.tableView.dataSource = self modalPresentationStyle = .fullScreen categoryView.categoryTitle.text = category addTargets() } func addTargets() { categoryView.backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside) } @objc func backButtonTapped() { dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() view = categoryView } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CategoryController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 64 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tasks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TaskCell.reuseId, for: indexPath) as! TaskCell cell.titleLabel.text = tasks[indexPath.row].title switch tasks[indexPath.row].category { case Category.importantUrgent.rawValue: cell.categoryImageView.image = UIImage(systemName: SystemImages.importantUrgent.rawValue) case Category.importantNotUrgent.rawValue: cell.categoryImageView.image = UIImage(systemName: SystemImages.importantNotUrgent.rawValue) case Category.minorUrgent.rawValue: cell.categoryImageView.image = UIImage(systemName: SystemImages.minorUrgent.rawValue) case Category.minorNotUrgent.rawValue: cell.categoryImageView.image = UIImage(systemName: SystemImages.minorNotUrgent.rawValue) default: cell.categoryImageView.image = UIImage(systemName: SystemImages.minorNotUrgent.rawValue) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedRow = tasks[indexPath.row] let vc = TaskController(task: selectedRow) present(vc, animated: true, completion: nil) } }
import React from "react"; import styles from "./notificationbar.module.css"; import { styled } from "@mui/material/styles"; import FormControlLabel from "@mui/material/FormControlLabel"; import Switch from "@mui/material/Switch"; import { BiLinkExternal } from "react-icons/bi"; const NotificationBar = () => { const IOSSwitch = styled((props) => ( <Switch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} /> ))(({ theme }) => ({ width: 42, height: 26, padding: 0, "& .MuiSwitch-switchBase": { padding: 0, margin: 2, transitionDuration: "300ms", "&.Mui-checked": { transform: "translateX(16px)", color: "#fff", "& + .MuiSwitch-track": { backgroundColor: theme.palette.mode === "dark" ? "#2ECA45" : "rgb(0, 116, 228)", opacity: 1, border: 0, }, "&.Mui-disabled + .MuiSwitch-track": { opacity: 0.5, }, }, "&.Mui-focusVisible .MuiSwitch-thumb": { color: "#33cf4d", border: "6px solid #fff", }, "&.Mui-disabled .MuiSwitch-thumb": { color: theme.palette.mode === "light" ? theme.palette.grey[100] : theme.palette.grey[600], }, "&.Mui-disabled + .MuiSwitch-track": { opacity: theme.palette.mode === "light" ? 0.7 : 0.3, }, }, "& .MuiSwitch-thumb": { boxSizing: "border-box", width: 22, height: 22, }, "& .MuiSwitch-track": { borderRadius: 26 / 2, backgroundColor: theme.palette.mode === "light" ? "#E9E9EA" : "#39393D", opacity: 1, transition: theme.transitions.create(["background-color"], { duration: 500, }), }, })); return ( <div className={styles.container}> <div> <FormControlLabel control={<IOSSwitch sx={{ m: 1 }} />} label="Receive email notifications about my wishlist." /> </div> <div className={styles.externalLink}> <p className={styles.heading}> Manage all your communication preferences </p> <BiLinkExternal className={styles.icon} /> </div> </div> ); }; export default NotificationBar;
################### Required packages ################## #install.packages("caret", dependencies=c("Depends", "Suggests")) #install.packages('Boruta') #install.packages('RANN') require("caret") require("Boruta") require("RANN") library(tidyverse) library(caret) library(Boruta) library(tidyr) library(RANN) ################### Assembly of training set ################## metrics=read.table("/Users/zeidh//Desktop/THESIS/Metrics/qualitiyMetricsAllLibraries_pe_se.txt",header = T) metrics$quality_manual <- droplevels(as.factor(metrics$quality_manual)) metrics %>% group_by(quality_manual)%>% summarize((n())) #metrics$quality_manual = gsub(x = metrics$quality_manual,pattern = "E",replacement = "P") metrics=select(metrics,-c(file,gene,end)) ################## Data partitioning ################## # create a list of 80% of the rows in the original dataset we can use for training validation_index <- createDataPartition(metrics$quality_manual, p=0.80, list=FALSE) testData <- metrics[-validation_index,] # select 20% of the data for validation trainData <- metrics[validation_index,] # use the remaining 80% of data to training and testing the models #dataset=na.exclude(dataset) ################## Pre processing ################### #Note imputation made performance on validation set worse even though there are no NAs #Meaning norrmalizatiton was having a negative effect #preProcess_missingdata_model <- preProcess(trainData, method='knnImpute') #trainData <- predict(preProcess_missingdata_model, newdata = trainData) # !anyNA(trainData) #preProcess_missingdata_model <- preProcess(testData, method='knnImpute') #testData <- predict(preProcess_missingdata_model, newdata = testData) #Note if we had any categorical variables we would need to one hot encode them #But in this case we don't so our dataset is complete ################### Preliminary plotting ################## #just to see if any variables are obviously important #x <- trainData[,c("Reads","complexity","Background","spikiness","entropy","coverage")] #metrics #y <- trainData[,5] #classification #scales <- list(x=list(relation="free"), y=list(relation="free")) #featurePlot(x=x, y=y, plot="box",scales =scales) #featurePlot(x=x, y=y, plot="density",scales =scales,strip=strip.custom(par.strip.text=list(cex=.7))) #featurePlot(x = metrics[, c("Background","Reads","complexity","spikiness","entropy")],y = metrics$quality_manual,plot = "pairs",auto.key = list()) #pairs(metrics[, c("complexity","spikiness","entropy","Background","Reads")],col=metrics$quality_manual) ################## Training models ################## control <- trainControl(method="cv", number=10,classProbs = T) metric <- "Accuracy" library(DMwR) set.seed(9560) smote_train <- SMOTE(quality_manual ~ ., data = trainData) smote_outside <- train(quality_manual ~ ., data = smote_train, method = "treebag", nbagg = 50, metric = "ROC", trControl = control) library(ROSE) set.seed(9560) rose_train <- ROSE::ROSE(quality_manual ~ ., data = trainData)$data set.seed(5627) rose_outside <- train(quality_manual ~ ., data = rose_train, method = "treebag", nbagg = 50, metric = "ROC", trControl = control) outside_models <- list(SMOTE = smote_outside,ROSE=rose_outside) outside_resampling <- resamples(outside_models) test_roc <- function(model, data) { library(pROC) roc_obj <- roc(data$quality_manual, predict(model, data, type = "prob")[, "good"], levels = c("good", "poor")) ci(roc_obj) } outside_test <- lapply(outside_models, test_roc, data = trainData) outside_test <- lapply(outside_test, as.vector) outside_test <- do.call("rbind", outside_test) colnames(outside_test) <- c("lower", "ROC", "upper") outside_test <- as.data.frame(outside_test) summary(outside_resampling) #Linear (lda), non-linear(CART,kNN), advanced models=c("lda","rpart","knn","svmRadial","rf","gbm") #model=models[1] for (model in models){ set.seed(7) fit <- train(quality_manual~., data=trainData, method=model, metric=metric, trControl=control) assign(paste0("fit.",model),fit) #results=resamples(list(get(paste0("fit.",model)))) } #trainData=select(trainData,-c( Reads_per_Mb, Mode_GC, Mode_insert_size ,Sequencing_for_0.05x_cov)) #testData=select(testData,-c( Reads_per_Mb, Mode_GC, Mode_insert_size ,Sequencing_for_0.05x_cov)) #set.seed(7) fit.gbm = train(quality_manual~., data=trainData, method="gbm", metric=metric, trControl=control) fit.rf <- train(quality_manual~., data=trainData, method=, metric=metric, trControl=control) results <- resamples(list(lda=fit.lda,rpart=fit.rpart,knn=fit.knn,svmRadial=fit.svmRadial,rf=fit.rf,gbm=fit.gbm)) summary(results) dotplot(results) #default_knn_mod = train(quality_manual ~ .,data = trainData,method = "knn",trControl = trainControl(method = "cv", number = 5),preProcess = c("center", "scale"),tuneGrid = expand.grid(k = seq(1, 101, by = 2))) #fit.gbm.imp <- varImp(fit.gbm) #plot(fit.rf.imp, main="Variable Importance with Random Forest") plot(fit.gbm, main="Model Accuracies with Random Forest") plot(fit.rf, main="Model Accuracies with Random Forest") #Running best model on testData/test set predictions <- predict(fit.rf, na.omit(testData)) confusionMatrix(predictions, testData$quality_manual) predictions <- predict(rose_outside, na.omit(testData)) confusionMatrix(predictions, testData$quality_manual)
import Divisao from "./Divisao"; import Paragrafo from "./Paragrafo"; import Titulo from "./Titulo"; import Map from "./Map"; import CardOds from "./CardOds"; function Container() { return ( <div className="h-full p-8 flex flex-col gap-y-6 bg-no-repeat bg-cover bg-fixed" style={{ backgroundImage: "url(https://i.imgur.com/wXsxreG.png)" }} > <main className="flex flex-col gap-y-6"> <Titulo titulo="Objetivos de Desenvolvimento Sustentável" /> <Paragrafo msg="Os Objetivos de Desenvolvimento Sustentável são um apelo global à ação para acabar com a pobreza, proteger o meio ambiente e o clima e garantir que as pessoas, em todos os lugares, possam desfrutar de paz e de prosperidade. Estes são os objetivos para os quais as Nações Unidas estão contribuindo a fim de que possamos atingir a Agenda 2030 no Brasil." /> </main> <Divisao /> <Titulo titulo="Onde Estamos?" /> <div className="w-full h-[400px]"> <Map /> </div> <Titulo titulo="Objetivos Envolvidos no Ai Lixo:" /> <CardOds background="bg-[#E5243B]" numero="1" titulo="Erradicação da pobreza" urlImg="https://i.imgur.com/6ErjJKo.png" alt="Erradicação" msg="O projeto de reciclagem de resíduos eletrônicos pode contribuir para a erradicação da pobreza, proporcionando oportunidades de emprego em diferentes etapas do processo de reciclagem. Além disso, a revenda de peças e componentes eletrônicos recuperados pode gerar renda para pessoas que vivem em condições de pobreza." /> <CardOds flexDirection="flex-row-reverse" background="bg-[#C5192D]" numero="4" titulo="Educação de Qualidade" urlImg="https://i.imgur.com/uRpUhIC.png" alt="Educação" msg="O projeto pode desempenhar um papel fundamental na educação da população sobre a importância da reciclagem de resíduos eletrônicos. Por meio do site e de programas de conscientização, as pessoas podem aprender sobre o que é o e-lixo, como reciclá-lo de maneira adequada e quais são os benefícios ambientais e sociais associados a essa prática. Isso promove a educação de qualidade e a conscientização ambiental." /> <CardOds background="bg-[#A21942]" numero="8" titulo="Trabalho decente e crescimente econômico" urlImg="https://i.imgur.com/HiUdx0d.png" alt="Trabalho" msg="Ao criar empregos na coleta, desmontagem, reciclagem e recondicionamento de resíduos eletrônicos, o projeto contribui para a promoção de trabalho decente e o crescimento econômico. Além disso, ao recuperar materiais valiosos dos resíduos eletrônicos, o projeto pode gerar receita, impulsionando a economia local." /> <CardOds flexDirection="flex-row-reverse" background="bg-[#FD6925]" numero="9" titulo="Indústria, inovação e infraestrutura" urlImg="https://i.imgur.com/N7fLdBG.png" alt="Educação" msg="O projeto promove a inovação na gestão de resíduos eletrônicos, incentivando a criação de soluções tecnológicas para o tratamento e a reciclagem desses materiais. Também estimula a infraestrutura necessária para a coleta, o processamento e o recondicionamento dos resíduos eletrônicos." /> <CardOds background="bg-[#FD9D24]" numero="11" titulo="Cidades e comunidades sustentáveis" urlImg="https://i.imgur.com/PP2gIyi.png" alt="Cidades" msg="A reciclagem de resíduos eletrônicos contribui para a criação de cidades e comunidades sustentáveis, reduzindo a quantidade de resíduos eletrônicos descartados em aterros sanitários. Isso diminui os impactos ambientais e melhora a qualidade de vida nas comunidades locais, reduzindo a exposição a substâncias tóxicas presentes em eletrônicos obsoletos." /> <CardOds flexDirection="flex-row-reverse" background="bg-[#BF8B2E]" numero="12" titulo="Consumo e produção responsáveis" urlImg="https://i.imgur.com/CBrOkCg.png" alt="Consumo" msg="Promover a reciclagem de resíduos eletrônicos incentiva o consumo e a produção responsáveis. As pessoas são incentivadas a prolongar a vida útil de seus dispositivos eletrônicos, reutilizando e reciclando-os, em vez de descartá-los prematuramente. Isso reduz a demanda por novos produtos eletrônicos e minimiza o desperdício." /> <CardOds background="bg-[#19486A]" numero="17" titulo="Parcerias e meios de implementação" urlImg="https://i.imgur.com/yujWc5c.png" alt="Parcerias" msg="O projeto de reciclagem de resíduos eletrônicos pode estabelecer parcerias com organizações governamentais, empresas privadas, organizações não governamentais e comunidades locais. Essas parcerias podem viabilizar a implementação bem-sucedida do projeto, reunindo recursos, conhecimento e esforços para alcançar os objetivos dos ODS relacionados." /> </div> ); } export default Container;
from datetime import datetime from typing import Any, Literal, TypedDict from traderpilot.constants import PairWithTimeframe from traderpilot.enums import RPCMessageType ProfitLossStr = Literal["profit", "loss"] class RPCSendMsgBase(TypedDict): pass # ty1pe: Literal[RPCMessageType] class RPCStatusMsg(RPCSendMsgBase): """Used for Status, Startup and Warning messages""" type: Literal[RPCMessageType.STATUS, RPCMessageType.STARTUP, RPCMessageType.WARNING] status: str class RPCStrategyMsg(RPCSendMsgBase): """Used for Status, Startup and Warning messages""" type: Literal[RPCMessageType.STRATEGY_MSG] msg: str class RPCProtectionMsg(RPCSendMsgBase): type: Literal[RPCMessageType.PROTECTION_TRIGGER, RPCMessageType.PROTECTION_TRIGGER_GLOBAL] id: int pair: str base_currency: str | None lock_time: str lock_timestamp: int lock_end_time: str lock_end_timestamp: int reason: str side: str active: bool class RPCWhitelistMsg(RPCSendMsgBase): type: Literal[RPCMessageType.WHITELIST] data: list[str] class __RPCEntryExitMsgBase(RPCSendMsgBase): trade_id: int buy_tag: str | None enter_tag: str | None exchange: str pair: str base_currency: str quote_currency: str leverage: float | None direction: str limit: float open_rate: float order_type: str stake_amount: float stake_currency: str fiat_currency: str | None amount: float open_date: datetime current_rate: float | None sub_trade: bool class RPCEntryMsg(__RPCEntryExitMsgBase): type: Literal[RPCMessageType.ENTRY, RPCMessageType.ENTRY_FILL] class RPCCancelMsg(__RPCEntryExitMsgBase): type: Literal[RPCMessageType.ENTRY_CANCEL] reason: str class RPCExitMsg(__RPCEntryExitMsgBase): type: Literal[RPCMessageType.EXIT, RPCMessageType.EXIT_FILL] cumulative_profit: float gain: ProfitLossStr close_rate: float profit_amount: float profit_ratio: float exit_reason: str | None close_date: datetime # current_rate: float | None order_rate: float | None final_profit_ratio: float | None is_final_exit: bool class RPCExitCancelMsg(__RPCEntryExitMsgBase): type: Literal[RPCMessageType.EXIT_CANCEL] reason: str gain: ProfitLossStr profit_amount: float profit_ratio: float exit_reason: str | None close_date: datetime class _AnalyzedDFData(TypedDict): key: PairWithTimeframe df: Any la: datetime class RPCAnalyzedDFMsg(RPCSendMsgBase): """New Analyzed dataframe message""" type: Literal[RPCMessageType.ANALYZED_DF] data: _AnalyzedDFData class RPCNewCandleMsg(RPCSendMsgBase): """New candle ping message, issued once per new candle/pair""" type: Literal[RPCMessageType.NEW_CANDLE] data: PairWithTimeframe RPCOrderMsg = RPCEntryMsg | RPCExitMsg | RPCExitCancelMsg | RPCCancelMsg RPCSendMsg = ( RPCStatusMsg | RPCStrategyMsg | RPCProtectionMsg | RPCWhitelistMsg | RPCEntryMsg | RPCCancelMsg | RPCExitMsg | RPCExitCancelMsg | RPCAnalyzedDFMsg | RPCNewCandleMsg )
#ifndef REQUEST_H #define REQUEST_H #include "../../Config/config.h" #include <cstdlib> namespace Routes { /** * @brief Data Transfer Object for creating a new mayor. */ struct CreateMayorDTO { // Name of the mayor char name[MAX_MAYOR_NAME]; // Address of the mayor char address[MAX_MAYOR_ADDRESS]; }; /** * @brief Data Transfer Object for creating a new city. */ struct CreateCityDTO { // Name of the city char name[MAX_CITY_NAME]; // Brief history of the city char history[MAX_CITY_HISTORY]; // Population of the city size_t population; // Year of establishment unsigned int year; // Geographical coordinates [latitude, longitude] double coordinates[2]; // Mayor information for the city CreateMayorDTO mayor; }; /** * @brief Represents a pair of city IDs. */ struct CityPair { // ID of the first city size_t city1; // ID of the second city size_t city2; }; /** * @brief Data Transfer Object for updating mayor information. */ struct UpdateMayorDTO { // Updated name of the mayor char name[MAX_MAYOR_NAME]; // Updated address of the mayor char address[MAX_MAYOR_ADDRESS]; }; /** * @brief Data Transfer Object for updating city information. */ struct UpdateCityDTO { // ID of the city to update size_t cityId; // Updated history of the city char history[MAX_CITY_HISTORY]; // Updated population of the city size_t population; // Updated year of establishment unsigned int year; // Updated geographical coordinates double coordinates[2]; // Updated mayor information UpdateMayorDTO mayor; }; /** * @brief Options for requesting city information. */ struct RequestCityOptions { // Name of the city to request char cityName[MAX_CITY_NAME]; }; /** * @brief Enumerates the types of requests that can be made. */ enum RequestType { CREATE_CITY, UPDATE_CITY, DELETE_CITY, GET_CITIES, GET_ALL_CITIES, DISTANCE_BETWEEN_CITIES, DISPLAY_MAYOR, }; /** * @brief Represents a request to the router. * * This struct is designed to be a POD (Plain Old Data) type to allow * easy serialization for logging purposes. */ struct Request { // Type of the request RequestType type; // Data associated with the request union request { CreateCityDTO createCity; UpdateCityDTO updateCity; RequestCityOptions requestCityOptions; CityPair cityPair; size_t cityId; } data; }; } #endif // REQUEST_H
package com.nisovin.magicspells.spells.buff; import java.util.Map; import java.util.UUID; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventPriority; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.event.player.PlayerToggleSprintEvent; import com.nisovin.magicspells.MagicSpells; import com.nisovin.magicspells.util.SpellData; import com.nisovin.magicspells.spells.BuffSpell; import com.nisovin.magicspells.util.MagicConfig; import com.nisovin.magicspells.util.config.ConfigData; import com.nisovin.magicspells.spelleffects.EffectPosition; public class HasteSpell extends BuffSpell { private final Map<UUID, HasteData> players; private final ConfigData<Integer> strength; private final ConfigData<Integer> boostDuration; private final ConfigData<Integer> accelerationDelay; private final ConfigData<Integer> accelerationAmount; private final ConfigData<Integer> accelerationIncrease; private final ConfigData<Integer> accelerationInterval; private final ConfigData<Boolean> icon; private final ConfigData<Boolean> hidden; private final ConfigData<Boolean> ambient; private final ConfigData<Boolean> powerAffectsStrength; public HasteSpell(MagicConfig config, String spellName) { super(config, spellName); strength = getConfigDataInt("effect-strength", 3); boostDuration = getConfigDataInt("boost-duration", 300); accelerationDelay = getConfigDataInt("acceleration-delay", 0); accelerationAmount = getConfigDataInt("acceleration-amount", 0); accelerationIncrease = getConfigDataInt("acceleration-increase", 0); accelerationInterval = getConfigDataInt("acceleration-interval", 0); icon = getConfigDataBoolean("icon", true); hidden = getConfigDataBoolean("hidden", false); ambient = getConfigDataBoolean("ambient", false); powerAffectsStrength = getConfigDataBoolean("power-affects-strength", true); players = new HashMap<>(); } @Override public boolean castBuff(SpellData data) { if (!(data.target() instanceof Player target)) return false; players.put(target.getUniqueId(), new HasteData(data)); return true; } @Override public boolean recastBuff(SpellData data) { stopEffects(data.target()); turnOffBuff(data.target()); return castBuff(data); } @Override public boolean isActive(LivingEntity entity) { return players.containsKey(entity.getUniqueId()); } @Override public void turnOffBuff(LivingEntity entity) { HasteData data = players.remove(entity.getUniqueId()); if (data == null) return; MagicSpells.cancelTask(data.task); entity.removePotionEffect(PotionEffectType.SPEED); } @Override protected void turnOff() { for (UUID id : players.keySet()) { Player player = Bukkit.getPlayer(id); if (player == null) continue; player.removePotionEffect(PotionEffectType.SPEED); HasteData data = players.get(id); if (data != null) MagicSpells.cancelTask(data.task); } players.clear(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerToggleSprint(PlayerToggleSprintEvent event) { Player player = event.getPlayer(); if (!isActive(player)) return; if (isExpired(player)) { turnOff(player); return; } HasteData data = players.get(player.getUniqueId()); if (event.isSprinting()) { event.setCancelled(true); addUseAndChargeCost(player); playSpellEffects(EffectPosition.CASTER, player, data.data); player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, data.boostDuration, data.strength, data.ambient, !data.hidden, data.icon)); if (data.acceleration) { data.task = MagicSpells.scheduleRepeatingTask(() -> { if (data.count >= data.accelerationAmount) { MagicSpells.cancelTask(data.task); return; } data.count++; player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, data.boostDuration, data.strength + (data.count * data.accelerationIncrease), data.ambient, !data.hidden, data.icon)); }, data.accelerationDelay, data.accelerationInterval); } } else { player.removePotionEffect(PotionEffectType.SPEED); playSpellEffects(EffectPosition.DISABLED, player, data.data); MagicSpells.cancelTask(data.task); data.count = 0; } } @EventHandler public void onPlayerToggleSneak(PlayerToggleSneakEvent event) { Player player = event.getPlayer(); if (!isActive(player)) return; player.removePotionEffect(PotionEffectType.SPEED); HasteData data = players.get(player.getUniqueId()); if (data == null) return; MagicSpells.cancelTask(data.task); } public Map<UUID, HasteData> getPlayers() { return players; } private class HasteData { private final int accelerationIncrease; private final int accelerationInterval; private final int accelerationAmount; private final int accelerationDelay; private final int boostDuration; private final int strength; private final boolean acceleration; private final boolean ambient; private final boolean hidden; private final boolean icon; private final SpellData data; private int count; private int task; private HasteData(SpellData data) { this.data = data; int strength = HasteSpell.this.strength.get(data); if (powerAffectsStrength.get(data)) strength = Math.round(strength * data.power()); this.strength = strength; accelerationIncrease = HasteSpell.this.accelerationIncrease.get(data); accelerationInterval = HasteSpell.this.accelerationInterval.get(data); accelerationAmount = HasteSpell.this.accelerationAmount.get(data); accelerationDelay = HasteSpell.this.accelerationDelay.get(data); boostDuration = HasteSpell.this.boostDuration.get(data); ambient = HasteSpell.this.ambient.get(data); hidden = HasteSpell.this.hidden.get(data); icon = HasteSpell.this.icon.get(data); acceleration = accelerationDelay >= 0 && accelerationAmount > 0 && accelerationIncrease > 0 && accelerationInterval > 0; } } }
package br.com.emendes.timemanagerapi.unit.mapper; import br.com.emendes.timemanagerapi.dto.request.ActivityRequest; import br.com.emendes.timemanagerapi.dto.response.ActivityResponse; import br.com.emendes.timemanagerapi.mapper.impl.ActivityMapperImpl; import br.com.emendes.timemanagerapi.model.Status; import br.com.emendes.timemanagerapi.model.entity.Activity; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import static br.com.emendes.timemanagerapi.util.creator.IntervalCreator.intervals; import static br.com.emendes.timemanagerapi.util.creator.UserCreator.withAllParameters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @DisplayName("Unit tests for ActivityMapperImpl") class ActivityMapperImplTest { private ActivityMapperImpl activityMapper; @BeforeEach void setUp() { activityMapper = new ActivityMapperImpl(); } @Test @DisplayName("toActivity must return Activity when map successfully") void toActivity_MustReturnActivity_WhenMapSuccessfully() { ActivityRequest activityRequest = ActivityRequest.builder() .name("Activity xpto") .description("Description xpto") .build(); Activity actualActivity = activityMapper.toActivity(activityRequest); assertThat(actualActivity).isNotNull(); assertThat(actualActivity.getName()).isNotNull().isEqualTo("Activity xpto"); assertThat(actualActivity.getDescription()).isNotNull().isEqualTo("Description xpto"); assertThat(actualActivity.getId()).isNull(); assertThat(actualActivity.getCreatedAt()).isNull(); assertThat(actualActivity.getStatus()).isNull(); } @Test @DisplayName("toActivity must thrown IllegalArgumentException when activityRequest is null") void toActivity_MustThrownIllegalArgumentException_WhenActivityRequestIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> activityMapper.toActivity(null)) .withMessage("activityRequest must not be null"); } @Test @DisplayName("toActivityResponse must return ActivityResponse when map successfully") void toActivityResponse_MustReturnActivityResponse_WhenMapSuccessfully() { Activity activity = Activity.builder() .id(100_000L) .name("Activity xpto") .description("Description xpto") .status(Status.ACTIVE) .createdAt(LocalDateTime.parse("2023-10-06T13:40:00")) .intervals(intervals()) .user(withAllParameters()) .build(); ActivityResponse actualActivityResponse = activityMapper.toActivityResponse(activity); assertThat(actualActivityResponse).isNotNull(); assertThat(actualActivityResponse.getId()).isEqualTo(100_000L); assertThat(actualActivityResponse.getName()).isNotNull().isEqualTo("Activity xpto"); assertThat(actualActivityResponse.getDescription()).isNotNull().isEqualTo("Description xpto"); assertThat(actualActivityResponse.getCreatedAt()).isNotNull().isEqualTo("2023-10-06T13:40:00"); assertThat(actualActivityResponse.getStatus()).isNotNull().isEqualTo(Status.ACTIVE); } @Test @DisplayName("toActivityResponse must thrown IllegalArgumentException when activity is null") void toActivityResponse_MustThrownIllegalArgumentException_WhenActivityIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> activityMapper.toActivityResponse(null)) .withMessage("activity must not be null"); } @Test @DisplayName("merge must modify Activity name and description when merge successfully") void merge_MustModifyActivityNameAndDescription_WhenMergeSuccessfully() { ActivityRequest activityRequest = ActivityRequest.builder() .name("Activity xpto updated") .description("Description xpto updated") .build(); Activity activity = Activity.builder() .id(100_000L) .name("Activity xpto") .description("Description xpto") .status(Status.ACTIVE) .createdAt(LocalDateTime.parse("2023-10-06T13:40:00")) .intervals(intervals()) .user(withAllParameters()) .build(); activityMapper.merge(activityRequest, activity); assertThat(activity).isNotNull(); assertThat(activity.getName()).isNotNull().isEqualTo("Activity xpto updated"); assertThat(activity.getDescription()).isNotNull().isEqualTo("Description xpto updated"); } @Test @DisplayName("merge must thrown IllegalArgumentException when activity is null") void merge_MustThrownIllegalArgumentException_WhenActivityIsNull() { ActivityRequest activityRequest = ActivityRequest.builder() .name("Activity xpto updated") .description("Description xpto updated") .build(); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> activityMapper.merge(activityRequest, null)) .withMessage("activity must not be null"); } @Test @DisplayName("merge must thrown IllegalArgumentException when activityRequest is null") void merge_MustThrownIllegalArgumentException_WhenActivityRequestIsNull() { Activity activity = Activity.builder() .id(100_000L) .name("Activity xpto") .description("Description xpto") .status(Status.ACTIVE) .createdAt(LocalDateTime.parse("2023-10-06T13:40:00")) .intervals(intervals()) .user(withAllParameters()) .build(); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> activityMapper.merge(null, activity)) .withMessage("activityRequest must not be null"); } }
package med.voll.api.infra.springdoc; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Contact; import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.security.SecurityScheme; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SpringDocConfiguration { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .components(new Components() .addSecuritySchemes("bearer-key", new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT"))) .info(new Info() .title("Voll.med API") .description("API Rest de la aplicación Voll.med, que contiene las funcionalidades CRUD de médicos y de pacientes, además de reserva y cancelamiento de consultas") .contact(new Contact() .name("Equipo Backend") .email("backend@voll.med")) .license(new License() .name("Apache 2.0") .url("http://voll.med/api/licencia"))); } }
import 'package:equatable/equatable.dart'; import 'package:game_repository/game_repository.dart'; import 'package:lobby_repository/lobby_repository.dart'; /// Keys const _kId = 'id'; const _kPlayers = 'players'; const _kCustomParams = 'customParams'; const _kHostId = 'hostId'; const _kDeck = 'deck'; const _kDiscardPile = 'discardPile'; /// Gettet keys const _kPlayerCount = 'playerCount'; /// {@template game} /// A Game. /// {@endtemplate} class Game extends Equatable { /// {@macro game} Game({ required this.id, required this.players, required this.hostId, required this.deck, required this.discardPile, this.customParams = const {}, this.defaultCardVisibility = DefaultCardVisibility.owner, }); /// Creates a [Game] from a json object. Game.fromJson(Map<String, dynamic> json) : this( id: json[_kId] as String, players: (json[_kPlayers] as List<Map<String, dynamic>>? ?? []) .map(Player.fromJson) .toList(), customParams: json.containsKey(_kCustomParams) ? json[_kCustomParams] as Map<String, dynamic> : {}, hostId: json[_kHostId] as String, deck: (json[_kDeck] as List<String>? ?? []) .map(Card.fromString) .toList(), discardPile: (json[_kDiscardPile] as List<String>? ?? []) .map(Card.fromString) .toList(), ); /// Creates a [Game] from a [Lobby]. Game.fromLobby(Lobby lobby) : this( id: lobby.id, players: lobby.players.map(Player.fromLobbyPlayer).toList(), hostId: lobby.hostId, deck: [], discardPile: [], ); /// The id of the game. final String id; /// The list of players in the game. final List<Player> players; /// The id of the host of the game. final String hostId; /// The custom parameters of the game. final Map<String, dynamic> customParams; /// The deck of the game. List<Card> deck; /// The discard pile of the game. List<Card> discardPile; /// The default visibility of cards in the game. final DefaultCardVisibility defaultCardVisibility; /// Returns a json representation of the game. Map<String, Object> toJson() { return { _kId: id, _kPlayers: players.map((player) => player.toJson()).toList(), _kCustomParams: customParams, _kHostId: hostId, _kDeck: deck.map((card) => card.toString()).toList(), _kDiscardPile: discardPile.map((card) => card.toString()).toList(), }; } /// Returns the value of the given key. If the key is not found, returns null. dynamic getProperty(String key) { switch (key) { case _kId: return id; case _kPlayers: return players; case _kHostId: return hostId; case _kDeck: return deck; case _kDiscardPile: return discardPile; case _kPlayerCount: return playerCount; default: return customParams[key]; } } /// Returns the number of players in the game. int get playerCount => players.length; @override List<Object?> get props => [ id, players, hostId, customParams, deck, discardPile, defaultCardVisibility, ]; }
import matplotlib.pyplot as plt import numpy as np def plot_loss_curves( train_losses, test_losses, title="Training and Test Loss (Log Scale)", save_path=None, show_plot=True ): """ Plot training and test loss curves. Parameters: - train_losses (list of float): Training losses for each epoch. - test_losses (list of float): Test losses for each epoch. - save_path (str): Path to save the plot image (optional). - show_plot (bool): Whether to display the plot on the screen (default: True). """ epochs = range(1, len(train_losses) + 1) log_train_losses = np.log(train_losses) log_test_losses = np.log(test_losses) plt.figure() plt.plot(epochs, log_train_losses, "bo-", label="Training loss (log scale)") plt.plot(epochs, log_test_losses, "ro-", label="Test loss (log scale)") plt.title(title) plt.xlabel("Epochs") plt.ylabel("Log Loss") plt.legend() if save_path: plt.savefig(save_path) if show_plot: plt.show() else: plt.close() def plot_activation_distribution(activation_values, title="Activation Distribution", save_path=None, show_plot=True): """ Plot the distribution of activation values. Parameters: - activation_values (list of float): Activation values to plot. - title (str): Title of the plot. - save_path (str): Path to save the plot image (optional). - show_plot (bool): Whether to display the plot on the screen (default: True). """ plt.figure() plt.hist(activation_values, bins=50, alpha=0.75) plt.title(title) plt.xlabel("Activation Value") plt.ylabel("Frequency") if save_path: plt.savefig(save_path) if show_plot: plt.show() else: plt.close() if __name__ == "__main__": # Example usage train_losses = [0.5, 0.4, 0.3, 0.2, 0.1] test_losses = [0.6, 0.5, 0.4, 0.35, 0.3] plot_loss_curves(train_losses, test_losses, show_plot=True) activation_values = [0.1, 0.2, 0.3, 0.4, 0.5] * 100 plot_activation_distribution(activation_values, show_plot=True)
/** * @file gpiodev.h * @author Sunip K. Mukherjee (sunipkmukherjee@gmail.com) * @brief Header file containing function prototypes and properties of * the GPIO sysfs access module. * @version 1.0 * @date 2020-08-30 * * @copyright Copyright (c) 2020 * * @license GPL v3 */ #ifndef _GPIODEV_H #define _GPIODEV_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <pthread.h> #ifndef DOXYGEN #define PINOUT_AD9361 0 //!< Activate GPIO LUT for AD9361 (SPACE HAUC) #define PINOUT_AD9364 1 //!< Activate GPIO LUT for AD9364 (Test) #endif #define PINOUT_RPI 2 //!< Activate GPIO LUT for Raspberry Pi (Default) #ifndef GPIODEV_PINOUT /** * @brief GPIODEV_PINOUT parameter defines the pin LUT used. The values can be 0 (PINOUT_AD9361), 1 (PINOUT_AD9364), 2 (PINOUT_RPI) * */ #define GPIODEV_PINOUT PINOUT_RPI #endif #ifndef GPIODEV_SINGLE_INSTANCE /** * @brief GPIODEV_SINGLE_INSTANCE = 0 allows any number of programs using gpiodev library to operate simultaneously. * Set this value > 0 to allow PID locking of the gpiodev interface. * */ #define GPIODEV_SINGLE_INSTANCE 0 #else #undef GPIODEV_SINGLE_INSTANCE #define GPIODEV_SINGLE_INSTANCE 1 #warning "gpiodev: GPIODEV_SINGLE_INSTANCE specified. Only one program will be allowed to call gpioInitialize()" #endif static int gpiodev_pinout __attribute__((used)) = GPIODEV_PINOUT; //!< Runtime variable to determine pin layout program is compiled with #define GPIO_LOW 0 //!< Low voltage on GPIO #define GPIO_HIGH 1 //!< High voltage on GPIO /** * @brief Enumerates the available GPIO Pin modes. * */ enum GPIO_MODE { GPIO_IN, //!< Mode GPIO input GPIO_OUT, //!< Mode GPIO output GPIO_IRQ_FALL, //!< Trigger IRQ on falling edge GPIO_IRQ_RISE, //!< Trigger IRQ on rising edge GPIO_IRQ_BOTH, //!< Trigger IRQ on both rising and falling edge }; /** * @brief Enumerates available GPIO pull up states, only available on Raspberry Pi * */ enum GPIO_PUD { GPIO_PUD_OFF, //!< Disable pull up/down GPIO_PUD_DOWN, //!< Set pin as pull down GPIO_PUD_UP, //!< Set pin as pull up }; #ifndef eprintf /** * @brief Wrapper to print a string to stderr with printf like arg support. Prepends provided string with the function from which it is called * and line number by default, and appends a newline. * */ #define eprintf(str, ...) \ { \ fprintf(stderr, "%s, %d: " str "\n", __func__, __LINE__, ##__VA_ARGS__); \ fflush(stderr); \ } #endif /** * @brief IRQ callback function of form void func(void *ptr). ptr points to the location of any input parameter/struct * */ typedef void (*gpio_irq_callback_t)(void *); #ifdef GPIODEV_INTERNAL /** * @brief GPIO look up table for easy access. Currently mapped to AD9361 CRR * system. The indices map the ps7 GPIO pins to physical pins */ static int gpio_lut_pins[] = #if (GPIODEV_PINOUT == PINOUT_AD9361) { -1, 976, // TR_BF 977, // TX_LD 978, // RX_LD 979, // PWR_TGL 980, // 5V_CTRL 981, // TR_UDC 982, // CS_UDC 983, // TS_CS_1 984, // TS_CS_2 985, // TS_CS_3 986, // TS_CS_4 987, // TS_CS_5 988, // TS_CS_6 989, // TS_CS_7 990, // CAM_RST 991, // PLL_LOCK 960 // FIFO_RST }; #elif (GPIODEV_PINOUT == PINOUT_AD9364) { 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991}; #elif (GPIODEV_PINOUT == PINOUT_RPI) { -1, -1, // Pin 1, 3V3 -1, // Pin 2, 5V -1, // Pin 3, I2C1 SDA -1, // Pin 4, GND -1, // Pin 5, I2C1 SCL -1, // Pin 6, GND 4, // Pin 7, GPCLK0 -1, // Pin 8, UART TX -1, // Pin 9, GND -1, // Pin 10, UART RX 17, // Pin 11 18, // Pin 12, PCM CLK 27, // Pin 13 -1, // Pin 14, GND 22, // Pin 15 23, // Pin 16 -1, // Pin 17, 3V3 Power 24, // Pin 18 -1, // Pin 19, SPI0 MOSI -1, // Pin 20, GND -1, // Pin 21, SPI0 MISO 25, // Pin 22 -1, // Pin 23, SPI0 SCLK -1, // Pin 24, SPI0 CE0 -1, // Pin 25, GND -1, // Pin 26, SPI0 CE1 0, // Pin 27, EEPROM SDA 1, // Pin 28, EEPROM SCL 5, // Pin 29 -1, // Pin 30, GND 6, // Pin 31 12, // Pin 32, PWM0 13, // Pin 33, PWM1 -1, // Pin 34, GND 19, // Pin 35, PCM FS 16, // Pin 36 26, // Pin 37 20, // Pin 38, PCM DIN -1, // Pin 39, GND 21, // Pin 40, PCM DOUT }; #endif /** * @brief Initialize GPIO sysfs subsystem. Should be called before calling gpioSetMode(). Otherwise called by default on the first instance gpioSetMode() is run. */ int gpioInitialize(void); /** * @brief Free allocated memory for GPIO pins etc. Should be called before exiting the program, set to be called automatically. */ void gpioDestroy(void); /** * @brief Number of avaliable GPIO pins in the system. */ const int NUM_GPIO_PINS = sizeof(gpio_lut_pins) / sizeof(int); /** * @brief Structure containing complete definition of the GPIO pin system, used * only by the init and destroy functions. Read and write functions use a subset * for cache purposes. */ typedef struct { int *fd_val; /// File descriptors containing the GPIO inout values uint8_t *mode; /// I/O modes of the GPIO pin, can assume values GPIO_IN, GPIO_OUT and GPIO_INOUT uint8_t *val; /// Last read/set value of the GPIO pin uint8_t *pud; /// Status of pull up of the GPIO pin, by default no pull up int *fd_mode; /// File descriptors to IO modes of the GPIO pins int fd_export; /// File descriptor for GPIO export int fd_unexport; /// File descriptor for GPIO unexport } gpioprops; /** @brief Structure containing information for GPIO pin access. * Small footprint for cache optimizations. The pointers must be * populated at initialization. */ typedef struct { int *fd; /// File descriptions for accessing GPIO inout uint8_t *val; /// Value of last read/set values uint8_t *mode; /// Mode of the GPIO pin } gpiopins; typedef struct { int pin; // pin number gpio_irq_callback_t callback; // callback function void *userdata; // callback user data int tout_ms; // poll timeout } gpio_irq_params; #endif // GPIODEV_INTERNAL /** * @brief Set mode of GPIO Pins. * * @param pin of type int, corresponds to the LUT index * @param mode of type enum GPIO_MODE * * @returns Positive on success, negative on failure */ int gpioSetMode(int pin, enum GPIO_MODE mode); /** * @brief Register GPIO Pin as interrupt * * @param pin of type int, corresponds to the LUT index * @param mode of type enum GPIO_MODE * @param func Pointer to callback function of type void func(unsigned long long ptr) * @param userdata Pointer to userdata to be passed to callback function * @param tout_ms Timeout for poll in ms (-1 for indefinite) * @return int Positive on success, negative on error */ int gpioRegisterIRQ(int pin, enum GPIO_MODE mode, gpio_irq_callback_t func, void *userdata, int tout_ms); /** * @brief Unregister IRQ handler on pin and set mode to standard input * * @param pin Pin number * @return int Positive on success, negative on error, zero on no change */ int gpioUnregisterIRQ(int pin); /** * @brief This function blocks until an interrupt is received on the GPIO pin, * or if the interrupt times out * * @param pin Pin index in LUT * @param mode GPIO_IRQ_* * @param tout_ms IRQ poll timeout * @return int Positive on interrupt (number of interrupts received), 0 on timeout, negative on error */ int gpioWaitIRQ(int pin, enum GPIO_MODE mode, int tout_ms); /** * @brief Write values GPIO_HIGH or GPIO_LOW to the GPIO pin indicated. * gpioRead or gpioWrite WILL NOT WORK if this function is not called * prior to GPIO use. * * @param pin of type int, corresponds to the LUT index * @param val of type int, either GPIO_HIGH or GPIO_LOW * * @returns Positive on success, negative on failure */ int gpioWrite(int pin, int val); /** * @brief Read value of the GPIO pin indicated. * * @param pin of type int, corresponds to the LUT index * * @returns The state of the pin, or error if not GPIO_LOW or GPIO_HIGH */ int gpioRead(int pin); /** * @brief Set pull-up on a pin (available only in Raspberry Pi) * * @param pin Physical pin number * @param pud of type enum GPIO_PUD * @return int returns positive on success, negative on error */ int gpioSetPullUpDown(int pin, enum GPIO_PUD pud); #ifdef __cplusplus } #endif #endif // _GPIODEV_H
/** * Модуль с дополнительными функциями * @member common * @module common */ //модуль для работы с запросами в БД const query = require('./queryDB'); //модуль для работы с ассинхронными функуиями const q = require('q'); //бибдиотека для обработки данных const _ = require('underscore'); //модуль для ассинхронной обработки данных const async = require('async'); /** * Функция проверки устройства для получения выводимого типа изображений * @function getTypeImg * @exports * @member common * @module common */ exports.getTypeImg = data => { let result = 'webp'; if (data.isiPad == 'true' || data.isiPod == 'true' || data.isiPhone == 'true' || data.isMac == 'true') { result = 'jpg'; } return result; }; /** * Функция проверки типа устройства * @function getTypeDevice * @exports * @member common * @module common */ exports.getTypeDevice = data => { let result = 'desktop'; if (data.isMobile == 'true') { result = 'mobile'; } if (data.isTablet == 'true') { result = 'tablet'; } if (data.isDesktop == 'true') { result = 'desktop'; } return result; }; /** * Получение всех активных категорий продуктов * @function getTypeCategory * @exports * @async * @memberof common * @return {Array} список активных категорий продуктов */ exports.getAllProduct = async () => { let defer = q.defer(); let sql = 'SELECT * FROM kreditproducts WHERE STATUS="true"'; await query.select(sql).then(async res => { //массив для хранения результата let arr = []; //группируем данные по ипу продукта let data = await _.groupBy(res.data, 'typeproduct'); //получаем ключи результата(типы продуктов являются ключами) let listKeys = _.keys(data); //обход значений и формирование массива async.eachOfSeries(listKeys, async (row, ind) => { //создаем объект для формирвоания спска let obj = { //тип продукта typeProduct: row, //список продуктов этой категории продуктов list: data[row] }; //добавление объекта в массив arr.push(obj); }); //добавление результата в ожидание defer.resolve(arr); }); //возврат результата return defer.promise; }; /** Полученмие списка навигационного меню сгурппирвоанного по родительскому менюы * @async * @function getNavBar * @memberof common * @exports * @return {Array} список элементов меню навигации */ exports.getNavBar = async () => { //создание ожидания let defer = q.defer(); //текст запроса let sql = 'SELECT * FROM navbar'; let list; //выборка query.select(sql).then(async res => { //массив для хранения результата let arr = []; //группирвоака данных по главным разделам let data = _.groupBy(res.data, 'parent'); //получаем ключи результата(типы продуктов являются ключами) let listKeys = _.keys(data); //перебор всех записей await async.eachOfSeries(listKeys, async (row, ind) => { //групирока данных let group = _.where(res.data, { parent: row }); //со0здание объекта let obj = {}; //проверка длины группы if (group.length == 1) { //присовение объекту значения группы obj = group[0]; //очистка свойства 'list' obj.list = []; } else { //присовение обхекту значения obj = { //зачение родителя parent: row, //устанвока стутуса родителя //список подменю list: group }; } //добавление в массив объекта arr.push(obj); }); defer.resolve(arr); }); return defer.promise; }; /** * Получение 9 случайных кредитных продуктов * @function getRandomProduct * @memberof common * @exports * @return {Array} список кредитныз продуктов */ exports.getRandomProduct = async () => { let defer = q.defer(); let sql = 'SELECT * FROM kreditproducts WHERE status="true" ORDER BY RAND() LIMIT 3'; await query.select(sql).then(res => { defer.resolve(res.data); }); return defer.promise; }; /** * Получение списка регионов * @function getRegions * @memberof common * @exports * @return {Array} список регионов */ exports.getRegions = async () => { let defer = q.defer(); let sql = 'SELECT * FROM geoproduct WHERE status="true" GROUP BY region_name'; let list; await query.select(sql).then(res => { list = res.data; }); await processingGeo(list).then(res => { defer.resolve(res); }); return defer.promise; }; /** * Обрабока полученных регионов * @function processingRegions * @param {Array} list список регионов * @return {Object} объект со списком */ const processingGeo = async list => { let defer = q.defer(); let count = Math.ceil(list.length / 2); let result = { b1: [], b2: [] }; let indexB = 0; let t = 0; await async.eachOfSeries(list, async (row, ind) => { if (indexB == 0) { if (t < count) { await result.b1.push(row); t++; } else { t = 0; indexB++; } } if (indexB == 1) { if (t < count) { await result.b2.push(row); t++; } else { t = 0; indexB++; } } if (ind == list.length - 1) { defer.resolve(result); } }); return defer.promise; }; /** * получение списка городов региона * @function getCity * @return {Array} список городов */ exports.getCity = async arg => { let defer = q.defer(); let sql = `SELECT * FROM geoproduct WHERE rid=${arg.rid} AND city_name != '' AND status='true' GROUP BY city_name`; let list; await query.select(sql).then(res => { list = res.data; }); await processingGeo(list).then(res => { defer.resolve(res); }); return defer.promise; }; /** * пполучение типа устройства * @function getTypeDevice * @exports * @param {Object} arg * @param {Object} arg.ctx Параметры useragent */ exports.getTypeDevice = arg => { let result = ''; if (arg.isDesktop) { result = 'desktop'; } if (arg.isTablet || arg.isMobile) { result = 'mobile'; } if (result == '') { result = 'desktop'; } return result; }; /** * Получение списка всех городов * @function getAllCity * @exports * @async * @return {Array} список всех городов */ exports.getAllCity = async () => { let defer = q.defer(); let sql = `SELECT * FROM geoproduct WHERE STATUS='true' AND city_name!='' GROUP BY city_name`; let list; await query.select(sql).then(res => { list = res.data; }); await procesingAllCity(list).then(res => { defer.resolve(res); }); return defer.promise; }; /** * Формирование списка всех гордов с облостями * @function procesingAllCity * @async * @return {Array} список всех городов и регионов */ const procesingAllCity = async list => { let defer = q.defer(); let result = {}; await async.eachOfSeries(list, async (row, ind) => { result[`${row.city_name}(${row.region_name})`] = null; }); defer.resolve(JSON.stringify(result)); return defer.promise; };
import { Container, Heading, SkeletonText, Table, TableContainer, Tbody, Td, Th, Thead, Tr, } from "@chakra-ui/react" import { useQuery, useQueryClient } from "@tanstack/react-query" import { createFileRoute, useNavigate } from "@tanstack/react-router" import { useEffect } from "react" import { z } from "zod" import { SubscriptionsService } from "../../client/index.ts" import ActionsMenu from "../../components/Common/ActionsMenu.tsx" import Navbar from "../../components/Common/Navbar.tsx" import AddSubscription from "../../components/Subscription/AddSubscription.tsx" import { PaginationFooter } from "../../components/Common/PaginationFooter.tsx" const subscriptionsSearchSchema = z.object({ page: z.number().catch(1), }) export const Route = createFileRoute("/_layout/items")({ component: Subscriptions, validateSearch: (search) => subscriptionsSearchSchema.parse(search), }) const PER_PAGE = 5 function getSubscriptionsQueryOptions({ page }: { page: number }) { return { queryFn: () => SubscriptionsService.readSubscriptions({ skip: (page - 1) * PER_PAGE, limit: PER_PAGE }), queryKey: ["subscriptions", { page }], } } function SubscriptionsTable() { const queryClient = useQueryClient() const { page } = Route.useSearch() const navigate = useNavigate({ from: Route.fullPath }) const setPage = (page: number) => navigate({ search: (prev: {[key: string]: string}) => ({ ...prev, page }) }) const { data: subscriptions, isPending, isPlaceholderData, } = useQuery({ ...getSubscriptionsQueryOptions({ page }), placeholderData: (prevData) => prevData, }) const hasNextPage = !isPlaceholderData && subscriptions?.data.length === PER_PAGE const hasPreviousPage = page > 1 useEffect(() => { if (hasNextPage) { queryClient.prefetchQuery(getSubscriptionsQueryOptions({ page: page + 1 })) } }, [page, queryClient, hasNextPage]) return ( <> <TableContainer> <Table size={{ base: "sm", md: "md" }}> <Thead> <Tr> <Th>ID</Th> <Th>Title</Th> <Th>Description</Th> <Th>Actions</Th> </Tr> </Thead> {isPending ? ( <Tbody> <Tr> {new Array(4).fill(null).map((_, index) => ( <Td key={index}> <SkeletonText noOfLines={1} paddingBlock="16px" /> </Td> ))} </Tr> </Tbody> ) : ( <Tbody> {subscriptions?.data.map((subscription) => ( <Tr key={subscription.id} opacity={isPlaceholderData ? 0.5 : 1}> <Td>{subscription.id}</Td> <Td isTruncated maxWidth="150px"> {subscription.title} </Td> <Td color={!subscription.description ? "ui.dim" : "inherit"} isTruncated maxWidth="150px" > {subscription.description || "N/A"} </Td> <Td> <ActionsMenu type={"Subscription"} value={subscription} /> </Td> </Tr> ))} </Tbody> )} </Table> </TableContainer> <PaginationFooter page={page} onChangePage={setPage} hasNextPage={hasNextPage} hasPreviousPage={hasPreviousPage} /> </> ) } function Subscriptions() { return ( <Container maxW="full"> <Heading size="lg" textAlign={{ base: "center", md: "left" }} pt={12}> Subscriptions Management </Heading> <Navbar type={"Subscription"} addModalAs={AddSubscription} /> <SubscriptionsTable /> </Container> ) }
import { $query, $update, StableBTreeMap, Vec, int8, match, Result, Opt, nat64, ic, int32, Principal } from 'azle'; import { Address, binaryAddressFromAddress, TransferFee, Ledger, Tokens, TransferResult, } from 'azle/canisters/ledger'; import {Token, InitPayload, Proposal, ProposalPayload, JoinPayload, RedeemPayload, TransferPayload, QueryPayload, AddressPayload, DaoData } from '../types'; const proposalStorage = new StableBTreeMap<int32, Proposal>(0, 44, 10000); const sharesStorage = new StableBTreeMap<Principal, nat64>(1, 100, 100); // investor vote mapping ${Principal + proposalId} const votesMapping = new StableBTreeMap<string, boolean>(2, 120, 100); let totalShares: nat64; let availableFunds: nat64; let lockedFunds: nat64; let contributionEnds: nat64; let nextProposalId: int32; let quorum: nat64; let voteTime: nat64; let admin: Principal; let network: int8; let initialized: boolean; let canisterAddress: Address; let icpCanister: Ledger; let tokenCanister: Token; $update export async function init(payload: InitPayload): Promise<Result<string, string>> { // check if canister is already initialized if(initialized){ ic.trap("already initialized") } if(payload.quorum < 0 || payload.quorum > 100){ ic.trap("quorum must be between 0 and 100") } // initialize variables contributionEnds = ic.time() + payload.contributionTime; quorum = payload.quorum; voteTime = payload.voteTime; admin = ic.caller(); nextProposalId = 0; totalShares = BigInt(0); availableFunds = BigInt(0); lockedFunds = BigInt(0); canisterAddress = payload.canisterAddress; icpCanister = new Ledger(Principal.fromText(payload.canisterAddress)); tokenCanister = new Token(Principal.fromText(payload.tokenAddress)); initialized = true; // set up network for testing if (payload.network == 0){ //set up dummyTokens network = 0; await tokenCanister.initializeSupply('ICToken', payload.canisterAddress, 'ICT', 1_000_000_000_000n).call(); }else{ network = 1; } return Result.Ok<string, string>("Initialized"); } // function to return dao configuration data $query export function getDaoData(): Result<DaoData, string> { // check if canister is already initialized if(!initialized){ return Result.Err<DaoData, string>("not yet initialized") } return Result.Ok<DaoData, string>({ totalShares: totalShares.toString(), availableFunds: availableFunds.toString(), lockedFunds: lockedFunds.toString(), contributionEnds: contributionEnds.toString(), nextProposalId: nextProposalId.toString(), quorum: quorum.toString(), voteTime: voteTime.toString(), admin: admin.toString(), network: network.toString(), initialized }) } // function to deposit icp tokens and join the dao $update export async function joinDAO(payload: JoinPayload): Promise<Result<string, string>> { // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let amount = payload.amount; // check if contribution period has ended if(ic.time() > contributionEnds){ return Result.Err<string, string>("cannot contribute after contributionEnds"); } // check if amount is not less than 0 if(amount <= BigInt(0)){ return Result.Err<string, string>("please enter an amount greater than zero"); } let caller = ic.caller() // if network is set to local network use dummy tokens if(network == 0){ let status = (await tokenCanister.transfer(ic.caller().toString(), canisterAddress, amount).call()).Ok; if(!status){ ic.trap("Failed to Donate") } } else { // initiate deposit await deposit(amount); } // update user shares const updatedShares = match(sharesStorage.get(caller), { Some: shares => shares + amount, None: () => BigInt(0) + amount }) // store in storage sharesStorage.insert(caller, updatedShares); // update total shares totalShares = totalShares + amount; // update available shares availableFunds = availableFunds + amount; return Result.Ok<string, string>("DAO joined successfully") } $query export function getShares(payload: AddressPayload): nat64{ // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let address: Principal; if(payload.address == ""){ address = ic.caller(); }else{ address = Principal.fromText(payload.address) } // get user shares return match(sharesStorage.get(address), { Some: shares => shares, None: () => 0n }) } // function to withdraw icp tokens from dao $update export async function redeemShares(payload: RedeemPayload): Promise<Result<string, string>> { // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let caller = ic.caller(); let amount = payload.amount; // check if the available amount is greater than the amount if(availableFunds < amount){ return Result.Err<string, string>("not enough available funds"); } // get the updated shares const updatedShares = match(sharesStorage.get(caller), { Some: shares => { if(shares < amount){ ic.trap("not enough shares") }; return shares - amount; }, None: () => ic.trap("you don't have any shares") }) // if network is set to local network use dummy tokens if(network == 0){ let status = (await tokenCanister.transfer(canisterAddress, ic.caller().toString(), amount).call()).Ok; if(!status){ ic.trap("Failed to Redeem shares") } } else { // transfer funds await transfer(ic.caller().toString(), amount); } // check if user shares become 0 and remove user from dao or update the remaining amount if(updatedShares == BigInt(0)){ sharesStorage.remove(caller); }else{ sharesStorage.insert(caller, updatedShares); } // update the amount in storage totalShares = totalShares - amount; availableFunds = availableFunds - amount; return Result.Ok<string, string>("shares redeemed succesfully") } // function to transfer shares from one user to another $update export function transferShares(payload: TransferPayload): Result<string, string> { // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let caller = ic.caller(); let to = Principal.fromText(payload.to); let amount = payload.amount; // get updated shares for sender const updatedFromShares = match(sharesStorage.get(caller), { Some: shares => { if(shares < amount){ ic.trap("not enough shares") }; return shares - amount; }, None: () => ic.trap("you don't have any shares") }) // get updated shares of recipient const updatedToShares = match(sharesStorage.get(to), { Some: shares => shares + amount, None: () => BigInt(0) + amount }) // check if user shares become 0 and remove user from dao or update the remaining amount if(updatedFromShares == BigInt(0)){ sharesStorage.remove(caller); }else{ sharesStorage.insert(caller, updatedFromShares); } // update the recipients record in the storage sharesStorage.insert(to, updatedToShares); return Result.Ok<string, string>("shares transferred succesfully") } // function to create a new proposal $update export function createProposal(payload: ProposalPayload): Result<string, string>{ // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let caller = ic.caller(); // check if available funds is enough if(availableFunds < payload.amount){ return Result.Err<string, string>("not enough available funds"); } // check if user is a part of the dao if(sharesStorage.get(caller).Some === undefined){ return Result.Err<string, string>("you don't have any shares"); } // populate proposal information const proposal: Proposal = { id: nextProposalId, title: payload.title, amount: payload.amount, recipient: payload.recipient, votes: BigInt(0), ends: ic.time() + voteTime, executed: false, ended: false } // add proposal to the storage proposalStorage.insert(nextProposalId, proposal); // update variables availableFunds = availableFunds - payload.amount; lockedFunds = lockedFunds + payload.amount; nextProposalId = nextProposalId + 1; return Result.Ok<string, string>("proposal created succesfully") } // function to vote for a proposal $update export function voteProposal(proposal: QueryPayload): Result<string, string>{ // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let caller = ic.caller(); let proposalId = proposal.proposalId; // get user shares const shares = match(sharesStorage.get(caller), { Some: shares => shares, None: () => ic.trap("you don't have any shares") }) let address = caller.toString(); // create identifier with user address and proposal id let id = `${address + proposalId.toString()}` // check if investor has voted let hasVoted = match(votesMapping.get(id), { Some: hasVoted => hasVoted, None: () => false }) // check if user has voted before if(hasVoted){ return Result.Err<string, string>("you can only vote once"); } // get proposal information and add user vote match(proposalStorage.get(proposalId), { Some: proposal => { if(ic.time() > proposal.ends){ ic.trap("proposal has ended") }; const votes = proposal.votes + shares; const updatedProposal: Proposal = { ...proposal, votes }; proposalStorage.insert(proposalId, updatedProposal); }, None: () => ic.trap(`proposal with id ${proposalId} does not exist`) }) // set investor to hasVoted votesMapping.insert(id, true); return Result.Ok<string, string>("voted succesfully") } // function to execute a proposal, can only be called by the contract admin $update export function executeProposal(payload: QueryPayload): Promise<Result<string, string>> { // check if canister is already initialized if(!initialized){ ic.trap("canister not yet initialized") } let caller = ic.caller(); let proposalId = payload.proposalId; let executed: boolean; // check if caller is admin if(caller.toString() !== admin.toString()){ ic.trap("only admin can execute proposal"); } // get proposal information and update return match( proposalStorage.get(proposalId), { Some: async (proposal) => { if(ic.time() < proposal.ends){ ic.trap("cannot execute proposal before end date") }; if(proposal.ended){ ic.trap("cannot execute proposal already ended") } if(proposal.votes * 100n / totalShares >= quorum){ // initiate transfer // if network is set to local network use dummy tokens if(network == 0){ let status = (await tokenCanister.transfer(canisterAddress, proposal.recipient, proposal.amount).call()).Ok; if(!status){ ic.trap("failed to transfer") } } else { // mainnet function await transfer(proposal.recipient, proposal.amount); } executed = true; }else{ //release funds back to available funds availableFunds = availableFunds + proposal.amount; executed = false; } lockedFunds = lockedFunds - proposal.amount; const updatedProposal: Proposal = {...proposal, ended: true, executed: executed}; proposalStorage.insert(proposalId, updatedProposal); return Result.Ok<string, string>("proposal completed") }, None: async () => Result.Err<string, string>("Error") }) } $query; export function getProposals(): Result<Vec<Proposal>, string> { return Result.Ok(proposalStorage.values()); } $query; export function getProposal(proposalId: int32): Result<Proposal, string> { return match(proposalStorage.get(proposalId), { Some: (proposal) => Result.Ok<Proposal, string>(proposal), None: () => Result.Err<Proposal, string>(`proposal with id=${proposalId} not found`) }); } // Helper functions $update export async function getFaucetTokens(): Promise<Result<boolean, string>>{ const caller = ic.caller(); const returnVal = (await tokenCanister.balance(caller.toString()).call()).Ok; const balance = returnVal? returnVal : 0n; if(balance > 0n){ ic.trap("To prevent faucet drain, please utilize your existing tokens"); } return await tokenCanister.transfer(canisterAddress, caller.toString(), 100n).call(); } $update; export async function walletBalanceLocal(payload: AddressPayload): Promise<Result<nat64, string>> { let address = payload.address if(address == ""){ address = ic.caller().toString(); } return await tokenCanister.balance(address).call(); } async function getAccountBalance( address: Address ): Promise<Result<Tokens, string>> { return await icpCanister .account_balance({ account: binaryAddressFromAddress(address) }) .call(); } async function deposit( amount: nat64, ): Promise<Result<TransferResult, string>> { const balance = (await getAccountBalance(ic.caller().toText())).Ok?.e8s; const transfer_fee = (await getTransferFee()).Ok?.transfer_fee.e8s if(balance !== undefined && balance > amount){ return await icpCanister .transfer({ memo: 0n, amount: { e8s: amount }, fee: { e8s: transfer_fee? transfer_fee : 10000n }, from_subaccount: Opt.None, to: binaryAddressFromAddress(canisterAddress), created_at_time: Opt.None }) .call(); } else{ ic.trap("Fund your account first") } } async function transfer( to: Address, amount: nat64, ): Promise<Result<TransferResult, string>> { const balance = (await getAccountBalance(canisterAddress)).Ok?.e8s; const transfer_fee = (await getTransferFee()).Ok?.transfer_fee.e8s; if(balance !== undefined && balance > amount){ return await icpCanister .transfer({ memo: 0n, amount: { e8s: amount }, fee: { e8s: transfer_fee? transfer_fee : 10000n }, from_subaccount: Opt.None, to: binaryAddressFromAddress(to), created_at_time: Opt.None }) .call(); }else{ ic.trap("Account is empty") } } async function getTransferFee(): Promise<Result<TransferFee, string>> { return await icpCanister.transfer_fee({}).call(); }
// components/SearchImage.tsx import React, { useState, useEffect, useCallback } from 'react'; import { FaDownload, FaImage } from 'react-icons/fa'; import { query } from '../api/api'; import ApiSelector from './ApiSelector'; import { GiFallingStar } from "react-icons/gi"; interface SearchImageProps { setError: React.Dispatch<React.SetStateAction<string | null>>; selectedApi: string; } interface ImageData { url: string; id: number; } // const SearchImage: React.FC<SearchImageProps> = ({ setError, selectedApi }) => { const SearchImage: React.FC<SearchImageProps> = ({ setError }) => { const [selectedApi, setSelectedApi] = useState<string>('Hugging_face'); const [inputText, setInputText] = useState<string>(''); const [currentImage, setCurrentImage] = useState<ImageData | null>(null); const [previousImages, setPreviousImages] = useState<ImageData[]>([]); const [localError, setLocalError] = useState<string | null>(null); const [loading, setLoading] = useState<boolean>(false); const [progress, setProgress] = useState<number>(0); let intervalId: NodeJS.Timeout; <ApiSelector selectedApi={selectedApi} onApiChange={setSelectedApi} /> const loadDataFromDatabase = async () => { // Simulate fetching data from a database const response = await fetch('../data/images.json'); const data = await response.json(); setCurrentImage(data.currentImage); setPreviousImages(data.previousImages); }; const saveDataToDatabase = useCallback(() => { // Simulate saving data to a database const data = { currentImage, previousImages }; fetch('../data/images.json', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); }, [currentImage, previousImages]); const handleGenerateAI = async () => { try { setLoading(true); setProgress(0); intervalId = setInterval(() => { setProgress((prevProgress) => { const newProgress = prevProgress + 1; if (newProgress >= 95) { clearInterval(intervalId); } return newProgress; }); }, 50); const imageUrl = await query({ inputs: inputText, api: selectedApi, // Ensure that selectedApi is correctly set here onProgress: (loaded, total) => { const calculatedProgress = (loaded / total) * 95; setProgress(calculatedProgress); }, }); const newImage = { url: imageUrl, id: Date.now() }; setPreviousImages((prevImages) => { const updatedImages = [ newImage, ...(currentImage ? [currentImage, ...prevImages.slice(0, 2)] : prevImages.slice(0, 2)), ]; // Remove duplicate images based on id const uniqueImages = Array.from(new Set(updatedImages.map((image) => image.id))) .map((id) => updatedImages.find((image) => image.id === id)) .filter((image) => image !== undefined) as ImageData[]; return uniqueImages; }); setCurrentImage(newImage); setLocalError(null); } catch (error) { console.error('Error generating AI:', (error as Error).message); setCurrentImage(null); setLocalError('Failed to generate AI. Please try again later.'); } finally { setLoading(false); clearInterval(intervalId); setProgress(100); saveDataToDatabase(); } }; const handleDownload = (imageUrl: string) => { const downloadLink = document.createElement('a'); downloadLink.href = imageUrl; downloadLink.download = `generated_image_${Date.now()}.png`; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }; const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Enter') { handleGenerateAI(); } }; const handleApiChange = (newApi: string) => { setSelectedApi(newApi); }; useEffect(() => { loadDataFromDatabase(); }, []); useEffect(() => { saveDataToDatabase(); }, [currentImage, previousImages, saveDataToDatabase]); useEffect(() => { loadDataFromDatabase(); }, []); useEffect(() => { saveDataToDatabase(); }, [currentImage, previousImages, saveDataToDatabase]); useEffect(() => { if (!currentImage || localError) { setPreviousImages([]); } }, [currentImage, localError]); return ( <div className="min-h-screen bg-gray-800 text-white"> <div className="w-full max-w-3xl mx-auto p-8 rounded-md shadow-md bg-gray-900"> <ApiSelector selectedApi={selectedApi} onApiChange={setSelectedApi} /> {/* return ( <div className="min-h-screen bg-gray-800 text-white"> <div className="w-full max-w-3xl mx-auto p-8 rounded-md shadow-md bg-gray-900"> <ApiSelector selectedApi={selectedApi} onApiChange={setSelectedApi} /> */} <div className="flex flex-col md:flex-row justify-between items-center w-full md:space-x-8 mb-8"> <div className="flex-grow mb-4 md:mb-0"> <input type="text" placeholder="Generate AI" value={inputText} onChange={(e) => setInputText(e.target.value)} onKeyDown={handleKeyDown} className="w-full bg-gray-800 border-b-2 border-white text-white px-4 py-2 focus:outline-none" /> </div> <button className="text-blue-500 px-4 py-2 focus:outline-none rounded-md flex items-center bg-gray-700" onClick={handleGenerateAI} > <GiFallingStar size={20} className="mr-2"/> Generate </button> </div> {loading && ( <div className="relative pt-1"> <div className="flex mb-2 items-center justify-between"> <div> <span className="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-blue-600 bg-blue-200"> In Progress </span> </div> <div className="text-right"> <span className="text-xs font-semibold inline-block text-blue-600"> {progress.toFixed(1)}% </span> </div> </div> <div className="flex mb-2 items-center justify-start"> <div className="w-full bg-gray-300 rounded-full h-2"> <div className="rounded-full bg-blue-600 h-2" style={{ width: `${progress}%` }} ></div> </div> </div> </div> )} <div className="mt-4"> {currentImage ? ( <div className="relative overflow-hidden mb-4 flex items-center justify-center max-w-360 max-h-360 mx-auto"> <svg> <svg> <svg> <image xlinkHref={currentImage?.url} // Use xlinkHref instead of src for SVG images className="object-cover rounded-md" style={{ maxWidth: '100%', maxHeight: '300px' }} /> </svg> </svg> </svg> <div className="absolute bottom-0 left-0 right-0 flex justify-center items-center p-2 bg-gray-800 rounded-b-md"> <FaDownload size={20} className="text-white hover:text-blue-500 cursor-pointer" onClick={() => handleDownload(currentImage.url)} style={{ maxWidth: '300px'}} /> </div> </div> ) : ( <div className="flex items-center justify-center bg-gray-700 w-full h-64 rounded-md"> <FaImage size={50} className="text-white" /> </div> )} <div className="flex flex-wrap gap-4"> {previousImages.map((image) => ( <div key={image.id} className="relative overflow-hidden w-full md:w-1/4 h-48 md:h-1/4 rounded-md"> <img src={image.url} alt={`Generated AI Image - ${image.id}`} className="w-full h-full object-cover rounded-md" /> <div className="absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity rounded-md"> <FaDownload size={20} className="text-white hover:text-blue-500 cursor-pointer" onClick={() => handleDownload(image.url)} /> </div> </div> ))} </div> </div> </div> </div> ); }; export default SearchImage;
import json import numpy as np import sys import matplotlib.pyplot as plt sys.path.append("../Delaunay_Triangularization") from BowyerWatson import BowyerWatson from find_path import get_best_path_greedy, bfs def fit_curve(points): x = points[:, 0].reshape(-1, 1) y = points[:, 1].reshape(-1, 1) if x.shape[0] == 0: return None if x.shape[0] == 2: return [0, 0] + np.polyfit(x.flatten(), y.flatten(), 1).tolist() elif x.shape[0] >= 3: return [0] + np.polyfit(x.flatten(), y.flatten(), 2).tolist() # else: # return np.polyfit(x.flatten(), y.flatten(), 3).tolist() fig = plt.figure(1) ax1 = fig.add_subplot(111, aspect='equal') with open("hist_cone_list4.json", "r") as f: hist_cone_list = json.load(f) cone_list_idx = 122 print(len(hist_cone_list)) def plot(event): global cone_list_idx if event.key == 'j': cone_list_idx = max(cone_list_idx - 1, 0) sys.stdout.flush() if event.key == 'k': cone_list_idx = min(cone_list_idx + 1, len(hist_cone_list) - 1) print(f"Current index: {cone_list_idx}") ax1.cla() points = np.array(hist_cone_list[cone_list_idx]) print(points) triangulation = BowyerWatson(points) filtered_triangulation = [] for t in triangulation: # find the smallest angle in the triangle angles = [] for i in range(3): first_vector = t.points[(i+1)%3] - t.points[i] second_vector = t.points[(i+1)%3] - t.points[(i+2)%3] cos_theta = np.dot(first_vector, second_vector) / (np.linalg.norm(first_vector) * np.linalg.norm(second_vector)) theta = np.arccos(cos_theta) angles.append(theta) min_angle = max(angles) if min_angle < 120.0 * np.pi / 180: # print(min_angle, np.rad2deg(min_angle)) filtered_triangulation.append(t) paths = bfs(filtered_triangulation) print(paths) paths = np.array(paths) C = fit_curve(paths) # Sample 100 points from the curve x = points[:, 0].reshape(-1, 1) c_x = np.linspace(-0.5, max(x), 100) c_y = C[0] * c_x**3 + C[1] * c_x**2 + C[2] * c_x + C[3] curve_points = np.hstack((c_x.reshape(-1, 1), c_y.reshape(-1, 1))) # plot the curve_points ax1.plot(-curve_points[:, 1], curve_points[:, 0], 'ro') ax1.plot(-paths[:, 1], paths[:, 0], 'bo') ax1.plot(-paths[:, 1], paths[:, 0], 'b-') for t in triangulation: ax1.plot([-t.p1[1], -t.p2[1], -t.p3[1], -t.p1[1]], [t.p1[0], t.p2[0], t.p3[0], t.p1[0]], 'g-') for t in filtered_triangulation: ax1.plot([-t.p1[1], -t.p2[1], -t.p3[1], -t.p1[1]], [t.p1[0], t.p2[0], t.p3[0], t.p1[0]], 'b-') ax1.plot(-points[:, 1], points[:,0], 'ro') ax1.axis("equal") fig.canvas.draw() cid = fig.canvas.mpl_connect('key_press_event', plot) plt.show() exit() points = np.array(hist_cone_list[99]) triangulation = BowyerWatson(points) paths = get_best_path_greedy(triangulation)[1:] C = fit_curve(paths) # Sample 100 points from the curve x = points[:, 0].reshape(-1, 1) c_x = np.linspace(min(x), max(x), 100) c_y = C[0] * c_x**2 + C[1] * c_x + C[2] curve_points = np.hstack((c_x.reshape(-1, 1), c_y.reshape(-1, 1))) # plot the curve_points plt.plot(-curve_points[:, 1], curve_points[:, 0], 'ro') plt.plot(-paths[:, 1], paths[:, 0], 'bo') plt.plot(-paths[:, 1], paths[:, 0], 'b-') for t in triangulation: plt.plot([-t.p1[1], -t.p2[1], -t.p3[1], -t.p1[1]], [t.p1[0], t.p2[0], t.p3[0], t.p1[0]], 'b-') plt.plot(-points[:, 1], points[:,0], 'ro') plt.axis("equal") plt.show()
package assignments.dynamicmemory; import java.util.ArrayList; import java.util.List; public class MemoryAllocator implements IMemoryAllocator { private int totalSize; private IAllocationAlgorithm algorithm; private List<MemoryBlock> blocks; public MemoryAllocator(int totalSize, IAllocationAlgorithm algorithm) { this.totalSize = totalSize; this.algorithm = algorithm; blocks=new ArrayList<MemoryBlock>(); MemoryBlock block = new MemoryBlock(); block.setSize(totalSize); blocks.add(block); } @Override public void setAllocationStrategy(IAllocationAlgorithm newAlgorithm) { this.algorithm = newAlgorithm; } @Override public boolean Allocate(String objectName, int size) { MemoryBlock block = algorithm.GetMemoryBlock(blocks, size); if(size > totalSize) { System.out.println("Solicitud de memoria excede el tamaño total dispo"); return false; } if (block == null) { return false; } MemoryBlock newBlock = new MemoryBlock(); newBlock.setSize(size); newBlock.setObject(objectName); int idxBlock = blocks.indexOf(block); blocks.add(idxBlock, newBlock); block.setSize(block.getSize() - size); if (block.getSize() == 0) { blocks.remove(block); } return true; } @Override public boolean DeAllocate(String objectName) { MemoryBlock block = SearchByName(objectName); if (block == null) { System.out.println("No se encontró el objeto para desasignar."); return false; } block.setObject(null); mergeFreeBlocks(); return true; } private MemoryBlock SearchByName(String objectName) { for (MemoryBlock b : blocks) { if (objectName.equals(b.getObject())) { return b; } } return null; } @Override public boolean IsEmpty() { for (MemoryBlock block : blocks) { if (!block.IsFree()) { return false; } } return true; } @Override public boolean IsFull() { for (MemoryBlock block : blocks) { if (block.IsFree()) { return false; } } return true; } @Override public void ShowMemory() { for (MemoryBlock m : blocks) { System.out.println(m.getObject() + " " + m.getSize()); } System.out.println("-----------------------"); } private void mergeFreeBlocks() { for (int i = 0; i < blocks.size() - 1; i++) { MemoryBlock current = blocks.get(i); MemoryBlock next = blocks.get(i + 1); if (current.IsFree() && next.IsFree()) { current.setSize(current.getSize() + next.getSize()); blocks.remove(next); i--; } } } }
import React, { useState } from "react"; import MovieCard from "../components/MovieCard"; import { useGetMoviesQuery } from "../slices/MoviesApiSlice"; import Loader from "../components/Loader"; const Home = () => { const [page, setPage] = useState(1); let [disabled, setDisabled] = useState(false); const { data, refetch, isLoading, error } = useGetMoviesQuery({ page, }); console.log(data); const handleNext = (e) => { e.preventDefault(); setPage(page + 1); }; const handlePrev = (e) => { e.preventDefault(); if (page > 1) { setPage(page - 1); } else { setPage(1); e.currentTarget.disabled = setDisabled(true); } }; return ( <> {" "} {isLoading ? ( <Loader /> ) : error ? ( <p>Something went wrong</p> ) : ( <div> {" "} <div className="flex justify-between mb-3"> <h1 class="pl-2 mb-2 text-4xl font-bold leading-none tracking-tight text-slate-700 md:text-5xl lg:text-6xl dark:text-white"> Most Popular{" "} </h1> <nav aria-label=" Page navigation example"> <ul class="flex items-center justify-end -space-x-px h-10 text-base"> <li> <button disabled={page <= 1 ? true : false} class="flex items-center justify-center px-4 h-10 ml-0 leading-tight text-gray-500" onClick={handlePrev} > <span class="sr-only">Previous</span> <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 6 10" > <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 1 1 5l4 4" /> </svg> </button> </li> <p className="text-slate-700">{`Page ${page}`}</p> <li> <button disabled={page >= 500 ? true : false} class="flex items-center justify-center px-4 h-10 ml-0 leading-tight text-gray-500" onClick={handleNext} > <span class="sr-only">Next</span> <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 6 10" > <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 9 4-4-4-4" /> </svg> </button> </li> </ul> </nav> </div> <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 mx-3 lg:grid-cols-4 gap-4 items-center justify-center mb-3"> {data?.results?.map((Movie) => ( <MovieCard key={Movie.id} Movie={Movie} /> ))} </div> </div> )} </> ); }; export default Home;
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http' import { Observable } from 'rxjs'; import { environment } from '../../../environments/environment' import { ApiResponseEditTherapistI, ApiResponseGetTherapistDetailI, ApiResponseGetTherapistsI, ApiResponseRegisterTherapistI, ApiResponseStatusTherapist, RegisterTherapistI, bodyEditTherapistI } from '../interfaces/therapists.interface'; @Injectable({ providedIn: 'root' }) export class TherapistsService { /*Variables*/ urlApi = environment.urlApi; headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': '*/*', 'Access-Control-Request-Header': 'Content-type', 'Access-Control-Allow-Origin': '*' }); options = {} /*Constructor*/ constructor( private http: HttpClient, ) { } /*Método que obtiene los headers*/ public getHeaders(headers: Map<string, any> | undefined) { if (headers != null) { headers.forEach((value, key) => { this.headers = this.headers.append(key, value || ''); }); } this.headers = this.headers.delete('Authorization'); this.headers = this.headers.append('Authorization', `Bearer ${sessionStorage.getItem('token')}`); this.options = { headers: this.headers }; return this.options; } /*Método que obtiene el listado de todas las tareas de un terapeuta*/ getAllTherapists(headers: Map<string, any>, status: boolean): Observable<ApiResponseGetTherapistsI> { let queryParams = "?"; queryParams += `status=${status}`; this.options = this.getHeaders(headers); return this.http.get<ApiResponseGetTherapistsI>(this.urlApi + `/admin/terapists/${queryParams}`, this.options); } /*Método que obtiene el detalle de un terapeuta por su ID*/ getTherapistDetailById(headers: Map<string, any>, patientId: number): Observable<ApiResponseGetTherapistDetailI> { this.options = this.getHeaders(headers); return this.http.get<ApiResponseGetTherapistDetailI>(this.urlApi + `/user/by-id/${patientId}`, this.options); } /*Método que registra un nuevo terapeuta*/ registerTherapist(headers: Map<string, any>, body: RegisterTherapistI): Observable<ApiResponseRegisterTherapistI> { this.options = this.getHeaders(headers); return this.http.post<ApiResponseRegisterTherapistI>(this.urlApi + `/user/therapist`, body, this.options); } /*Método que cambia el estado de un terapeuta (Activar o desactivar)*/ activateOrDesactivateTherapist(headers: Map<string, any>, idTherapist: number): Observable<ApiResponseStatusTherapist> { this.options = this.getHeaders(headers); return this.http.patch<ApiResponseStatusTherapist>(this.urlApi + `/user/status/${idTherapist}`, null, this.options); } /*Método que editar la información de un terapeuta*/ editTherapist(headers: Map<string, any>, body: bodyEditTherapistI, idTherapist: number): Observable<ApiResponseEditTherapistI> { this.options = this.getHeaders(headers); return this.http.patch<ApiResponseEditTherapistI>(this.urlApi + `/user/update/${idTherapist}`, body, this.options); } }
from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.decomposition import PCA import pandas as pd import numpy as np def split_data(file_path='data/data_raw.csv', test_size=0.3, random_state=522117, delimiter=';'): """ Split the data into training set and test set. Parameters: file_path: str, path to the data file test_size: float, proportion of the dataset to include in the test split random_state: int, the seed used by the random number generator delimiter: str, the delimiter used in the data file Returns: train_data: pandas.DataFrame test_data: pandas.DataFrame """ # Manually specifying column names due to parsing issues column_names = ["fixed acidity", "volatile acidity", "citric acid", "residual sugar", "chlorides", "free sulfur dioxide", "total sulfur dioxide", "density", "pH", "sulphates", "alcohol", "quality"] # Load the data with the correct settings data = pd.read_csv(file_path, delimiter=delimiter, names=column_names, header=0) # Splitting the dataset into training and testing sets train_data, test_data = train_test_split(data, test_size=test_size, random_state=random_state) return train_data, test_data def save_split_data(train_data, test_data, train_file='data/train.csv', test_file='data/test.csv'): """save the split data to csv files Parameters: train_data: pandas.DataFrame test_data: pandas.DataFrame train_file: str, path to save the training data test_file: str, path to save the test data """ train_data.to_csv(train_file, index=False) test_data.to_csv(test_file, index=False) def load_training_data(train_file='data/train.csv', target='quality'): """ Load training data and split it into features and target. Parameters: train_file: str, path to the training data file target: str, the name of the target variable Returns: X: pandas.DataFrame, the features y: pandas.Series, the target variable """ data = pd.read_csv(train_file) X = data.drop(target, axis=1) y = data[target] return X, y def load_test_data(test_file='data/test.csv', target='quality'): """ Load test data and return it as features. Parameters: test_file: str, path to the test data file target: str, the name of the target variable Returns: X: pandas.DataFrame, the features y: pandas.Series, the target variable """ data = pd.read_csv(test_file) X = data.drop(target, axis=1) y = data[target] return X, y def normalize_features(X): """ Normalize all features Parameters: X: pandas.DataFrame, the features to normalize Returns: X_normalized: pandas.DataFrame, the normalized features """ scaler = StandardScaler() X_normalized = pd.DataFrame(scaler.fit_transform(X), columns=X.columns, index=X.index) return X_normalized def apply_pca(data, n_components): """ Apply PCA to the data and keep a fixed number of features. Parameters: data: pandas.DataFrame, the data to be transformed n_components: int, the number of features to keep Returns: transformed_data: pandas.DataFrame, the transformed data """ pca = PCA(n_components=n_components) transformed_data = pca.fit_transform(data) return pd.DataFrame(transformed_data) def select_features_by_importance(X, y, n_features): """ Select features based on their importance determined by a random forest. Parameters: X: pandas.DataFrame, the features y: pandas.Series, the target variable n_features: int, the number of features to keep Returns: X_selected: pandas.DataFrame, the selected features """ # Fit a random forest to the data forest = RandomForestClassifier(random_state=0) forest.fit(X, y) # Get the importance of each feature importances = forest.feature_importances_ # Sort the features by importance and select the top n_features indices = np.argsort(importances)[::-1] selected_features = X.columns[indices[:n_features]] # Return the selected features return X[selected_features] def remove_outliers(df, feature_names): ''' For each of the features from the dataset, remove the outliers. Parameters: df: DataFrame feature_names: feature names Returns: cleaned_df: cleaned dataframe ''' clean_df = df.copy() for feature in feature_names: Q1 = clean_df[feature].quantile(0.1) Q3 = clean_df[feature].quantile(0.9) IQR = Q3 - Q1 lower_bound = Q1 - 1.5 * IQR upper_bound = Q3 + 1.5 * IQR clean_df = clean_df[(clean_df[feature] >= lower_bound) & (clean_df[feature] <= upper_bound)] return clean_df if __name__ == '__main__': # Split the dataset train_data, test_data = split_data() # Save the split dataset save_split_data(train_data, test_data) # Load the training data X_train, y_train = load_training_data() print(X_train.head()) print('-'*50) print(y_train.head())
/***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * 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.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2002-2011 JRuby Community * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.embed.osgi.internal; import java.net.URL; import java.util.StringTokenizer; import org.jruby.Ruby; import org.jruby.RubyInstanceConfig.LoadServiceCreator; import org.jruby.embed.osgi.utils.OSGiFileLocator; import org.jruby.platform.Platform; import org.jruby.runtime.load.Library; import org.jruby.runtime.load.LibrarySearcher; import org.jruby.runtime.load.LoadService; import org.jruby.runtime.load.LoadServiceResource; import org.osgi.framework.Bundle; /** * Load scripts and java classes directly from the OSGi bundles. * bundle:/symbolic.name/ * * @author hmalphettes */ public class OSGiLoadService extends LoadService { public static final String OSGI_BUNDLE_CLASSPATH_SCHEME = "osgibundle:/"; public static final LoadServiceCreator OSGI_DEFAULT = runtime -> new OSGiLoadService(runtime); /** * Default constructor * Optional constructor (why?) * @param runtime */ public OSGiLoadService(Ruby runtime) { super(runtime); } // @Override protected LibrarySearcher.FoundLibrary searchForRequire(String searchFile) { String[] fileHolder = {searchFile}; SuffixType suffixType = LibrarySearcher.getSuffixTypeForRequire(fileHolder); String baseName = fileHolder[0]; LibrarySearcher.FoundLibrary[] library = {null}; char found = librarySearcher.findLibraryForRequire(baseName, library); if (found != 0) { return library[0]; } return findLibraryWithClassloaders(searchFile, suffixType); } @Override protected LibrarySearcher.FoundLibrary searchForLoad(String searchFile) { String[] fileHolder = {searchFile}; SuffixType suffixType = LibrarySearcher.getSuffixTypeForLoad(fileHolder); String baseName = fileHolder[0]; LibrarySearcher.FoundLibrary[] library = {null}; char found = librarySearcher.findLibraryForRequire(baseName, library); if (found != 0) { return library[0]; } return findLibraryWithClassloaders(searchFile, suffixType); } /** * Support for 'bundle:/' to look for libraries in osgi bundles * or classes or ruby files. * * <p>MRI: rb_find_file</p> * @param name the file to find, this is a path name * @return the correct file */ @Override protected LoadServiceResource findFileInClasspath(String name) { if (name.startsWith(OSGI_BUNDLE_CLASSPATH_SCHEME)) { name = cleanupFindName(name); StringTokenizer tokenizer = new StringTokenizer(name, "/", false); tokenizer.nextToken(); String symname = tokenizer.nextToken(); StringBuilder sb = new StringBuilder(); if (!tokenizer.hasMoreTokens()) { sb.append('/'); } else { while (tokenizer.hasMoreTokens()) { sb.append('/'); sb.append(tokenizer.nextToken()); } } Bundle bundle = OSGiFileLocator.getBundle(symname); if (bundle != null) { URL url = bundle.getEntry(sb.toString()); if (url != null) { return new LoadServiceResource( OSGiFileLocator.getLocalURL(url), name); } } } return super.findFileInClasspath(name); } /** * Support for 'bundle:/' to look for libraries in osgi bundles. */ @Override protected LibrarySearcher.FoundLibrary createLibrary(String baseName, String loadName, LoadServiceResource resource) { if (resource == null) { return null; } String file = loadName; if (file.startsWith(OSGI_BUNDLE_CLASSPATH_SCHEME)) { file = cleanupFindName(file); StringTokenizer tokenizer = new StringTokenizer(file, "/", false); tokenizer.nextToken(); String symname = tokenizer.nextToken(); Bundle bundle = OSGiFileLocator.getBundle(symname); if (bundle != null) { return new LibrarySearcher.FoundLibrary(baseName, loadName, new OSGiBundleLibrary(bundle)); } } return new LibrarySearcher.FoundLibrary(baseName, loadName, super.createLibrary(baseName, loadName, resource)); } /** * Remove the extension when they are misleading. * @param name * @return */ private String cleanupFindName(String name) { if (name.endsWith(".jar")) { return name.substring(0, name.length()-".jar".length()); } else if (name.endsWith(".class")) { return name.substring(0, name.length()-".class".length()); } else { return name; } } @Override protected String resolveLoadName(LoadServiceResource foundResource, String previousPath) { String path = foundResource.getAbsolutePath(); if (Platform.IS_WINDOWS) { path = path.replace('\\', '/'); } return path; } }
library(seqinr) library(dplyr) library(tidyr) get_binom_pval <- function(data, sex) { process_sample <- function (sample_data, sex) { sample_data <- sample_data %>% rowwise() %>% mutate( binom_pval = case_when( ( NV > 0 & NR > 0 & (sex == "female" | (sex == "male" & !is_XY_chromosomal) ) ) ~ binom.test(NV, NR, 0.5, alternative = "less")$p.value, ( NV > 0 & NR > 0 & sex == "male" & is_XY_chromosomal ) ~ binom.test(NV, NR, 0.95, alternative = "less")$p.value, TRUE ~ 1 ) ) %>% unnest(cols = c(binom_pval)) %>% mutate( binom_qval = p.adjust(binom_pval, method = "BH") ) %>% ungroup() return(sample_data) } # Split data by Sample data_split <- split(data, data$Sample) # Determine number of cores to use num_cores <- ifelse(is.null(params$ncores), 1, params$ncores) # Use mclapply for parallel processing if more than one core is specified if (num_cores > 1) { library(parallel) library(doParallel) cl <- makeCluster(params$ncores) registerDoParallel(cl) results <- mclapply( data_split, process_sample, sex, mc.cores = num_cores ) stopCluster(cl) } else { results <- lapply(data_split, process_sample, sex) } # Combine results data <- do.call(rbind, results) return(data) } create_binary_genotype <- function(data, sex, params) { print("Generating almost-dichotomous genotype representations") if (params$only_snvs) { data <- data %>% filter(Mutation_Type == "SNV") } if (params$genotype_conv_prob) { data <- get_binom_pval(data, sex) if (!is.null(params$min_variant_reads_shared)) { data <- data %>% mutate( has_sufficient_reads = ifelse( !is.null(params$min_variant_reads_shared), NV >= params$min_variant_reads_shared, TRUE ), is_true_somatic = ifelse( !is.null(params$min_pval_for_true_somatic_shared), binom_pval > params$min_pval_for_true_somatic_shared, TRUE ), has_sufficient_vaf = case_when( (!is.null(params$min_vaf_shared) & sex == "female") ~ VAF > params$min_vaf_shared, (!is.null(params$min_vaf_shared) & sex == "male" & !is_XY_chromosomal) ~ VAF > params$min_vaf_shared, (!is.null(params$min_vaf_shared) & sex == "male" & is_XY_chromosomal ) ~ VAF > (params$min_vaf_shared * 2), TRUE ~ TRUE ), binary_genotype = as.numeric(has_sufficient_reads & is_true_somatic & has_sufficient_vaf) ) %>% mutate( # Here a value of 0.5 is assigned to mutations which are # not confidently somatic, but have a p-value and number # of reads which suggests that they may be somatic. binary_genotype = case_when( binary_genotype == 1 ~ 1, ( binary_genotype == 0 & NV > 0 & binom_pval > 0.01 ) ~ 0.5, ( binary_genotype == 0 & NV > 2 & binom_pval > 0.001 ) ~ 0.5, ( binary_genotype == 0 & binom_pval > 0.05 ) ~ 0.5, TRUE ~ 0 ) ) %>% select( Sample, Muts, binary_genotype, Mutation_Type ) } } else { data <- data %>% mutate( binary_genotype = case_when( (sex == "male" & !is_XY_chromosomal & VAF < params$vaf_absent) ~ 0, (sex == "male" & !is_XY_chromosomal & VAF >= params$vaf_present) ~ 1, (sex == "male" & is_XY_chromosomal & VAF < (params$vaf_absent * 2)) ~ 0, (sex == "male" & is_XY_chromosomal & VAF >= (params$vaf_present * 2)) ~ 1, (sex == "female" & VAF < params$vaf_absent) ~ 0, (sex == "female" & VAF >= params$vaf_present) ~ 1, TRUE ~ 0.5 ) ) %>% select(Sample, Muts, binary_genotype, Mutation_Type) } return(data) } make_fasta <- function(binary_data, params) { # Function to generate a fasta file from a binary genotype matrix. dna_strings <- list() # Add inferred ancestor dna_strings[["Ancestral"]] <- paste( rep("A", length(unique(binary_data$Muts))), sep = "", collapse = "" ) # Add samples for (sample in unique(binary_data$Sample)) { dna_strings[[sample]] <- paste( binary_data %>% filter(Sample == sample) %>% mutate( bases = case_when( binary_genotype == 0 ~ "A", binary_genotype == 1 ~ "T", binary_genotype == 0.5 ~ "?" ) ) %>% pull(bases), sep = "", collapse = "" ) } # Write fasta file filename <- if (params$only_snvs) { paste0(params$output_dir, "/", params$donor_id, "_SNV_for_MPBoot.fa") } else { paste0(params$output_dir, "/", params$donor_id, "indel_for_MPBoot.fa") } write.fasta( dna_strings, names = names(dna_strings), file = filename ) }
#!/usr/bin/env python """ llm-stack efficient multi-platform stack for LLM-based UI applications. © 2023 hexis systems GmbH Licensed under the MIT License. """ import asyncio from pathlib import Path from llama_cpp import Llama from typing import AsyncGenerator, Callable, Iterable, Optional, Union, List, TypeVar, cast from langstream.core.stream import Stream, StreamOutput import flet as ft T = TypeVar('T') U = TypeVar('U') loop = None class LLamaCppStream(Stream[T, U]): # defaults cf. https://github.com/abetlen/llama-cpp-python/blob/4177ae6d3482bb8af57b85cc7183ca83bd1571c4/examples/low_level_api/common.py#L12 def __init__( self: 'LLamaCppStream[T, str]', call: Callable[ [T], str, ], model: str, n_ctx: int = 4096, # llama2: 4096 n_batch: int = 8, n_threads: Optional[int] = None, max_tokens: int = -1, # <0 = n_ctx temperature: float = 0.8, stop: Optional[Union[str, List[str]]] = [], top_k: float = 40, top_p: float = 0.1, tfs_z: float = 1.0, mirostat_mode: int = 0, mirostat_tau: float = 5.0, mirostat_eta: float = 0.1, frequency_penalty: float = 0.0, presence_penalty: float = 0.0, repeat_penalty: float = 1.18, ) -> None: llm = Llama(model_path=model, verbose=False, n_ctx=n_ctx, n_batch=n_batch, n_threads=n_threads) async def generate(prompt: str) -> AsyncGenerator[U, None]: global loop loop = asyncio.get_event_loop() def get_outputs() -> Iterable[str]: stream = llm.create_completion( prompt, stream=True, echo=False, max_tokens=max_tokens, temperature=temperature, stop=stop, top_k=top_k, top_p=top_p, tfs_z=tfs_z, mirostat_mode=mirostat_mode, mirostat_tau=mirostat_tau, mirostat_eta=mirostat_eta, frequency_penalty=frequency_penalty, presence_penalty=presence_penalty, repeat_penalty=repeat_penalty, ) for output in stream: yield output['choices'][0]['text'] outputs = await loop.run_in_executor(None, get_outputs) for output in outputs: yield cast(U, output) super().__init__('llm-stream', lambda input: generate(call(input))) async def stream_output(page, chat_stream, prompt): async for output in chat_stream(prompt): page.pubsub.send_all_on_topic('stream', output) def main(page: ft.Page): def listener_stream(topic, message: StreamOutput): page.controls[-1].value += message.data page.update() page.title = 'llm-stack' page.window_height = 200 page.window_width = 400 page.pubsub.subscribe_topic('stream', listener_stream) page.update() t = ft.Text(value='', color='green') page.controls.append(t) model_path = Path.home() / 'model.gguf' chat_stream = LLamaCppStream[str, str]( lambda prompt: prompt, model=str(model_path), n_ctx=4096 ) prompt = '''### System: You are a helpful assistant. ### User: Hello World. ### Assistant:''' asyncio.run(stream_output(page, chat_stream, prompt)) ft.app(target=main)
import React from "react"; export const useClickOutside = () => { const [closeMenu, setCloseMenu] = React.useState(false); const menuRef = React.useRef<any>(null); React.useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (menuRef.current && !menuRef.current.contains(event.target as Node)) { setCloseMenu(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); return { closeMenu, menuRef, setCloseMenu, }; };
import React from "react" import "./main-component.css" import AdddUser from "./AddUser" import UserList from "./UserList" class User extends React.Component{ constructor(){ super() this.state = { users: [] } this.addUser = this.addUser.bind(this) this.deleteUser = this.deleteUser.bind(this) } addUser(user){ let arr = this.state.users.concat([]) arr.push(user) this.setState({ users: arr }) } deleteUser(id){ let arr = this.state.users.concat([]) let index = null arr.find((el,ind)=>{ if( Number(el.id) === Number(id) ){ index = ind return true }else return false }) arr.splice(index,1) this.setState({ users: arr }) } shouldComponentUpdate(nextProps,nextState){ if(nextState.users.length != this.state.users.length){ return true }else return false } render(){ return( <div className="main-component"> <AdddUser addUser = {this.addUser}></AdddUser> <UserList users={this.state.users} delete={this.deleteUser}></UserList> </div> ) } } export default User
import { useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import './LoginPage.Styles.css'; import { loginUser } from "../../../api"; const LoginPage = () => { const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [error, setError] = useState('') const navigate = useNavigate(); const handleInputChange = (e) => { if (e.target.value !== '') { e.target.parentElement.classList.add('has-value'); } else { e.target.parentElement.classList.remove('has-value'); } }; const handleSubmit = async (e) => { e.preventDefault(); try { const data = await loginUser({ username, password }); console.log(data.message); navigate('/home'); // setTimeout(() => navigate('/home'), 1000); } catch (err) { setError("Failed to log in."); } }; return ( <div > <div className="login-box"> <form onSubmit={handleSubmit} > <div className="user-box"> <input type="username" name="username" id="username" value={username} onChange={(e) => setUsername(e.target.value)} onBlur={handleInputChange} onFocus={handleInputChange} /> <label htmlFor="username" >Username</label> </div> <div className="user-box"> <input type="password" name="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} onBlur={handleInputChange} onFocus={handleInputChange} /> <label htmlFor="password" >Password</label> </div> <div className="info"> <p>Don't have an account? Click sign up below.</p> </div> <div className="controls"> <button className="login-button" type="submit">Log In</button> <Link to='/signup' className="sign-up-button" >Sign Up</Link> </div> {error && <div className='error'>{error}</div>} </form> </div> </div> ) } export default LoginPage
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; // Assuming you are using React Router for routing const Navbar = () => { const [profile, setProfile] = useState(false); // Dummy function to toggle profile state const toggleProfile = () => { setProfile(!profile); }; return ( <div className='mx-5'> <div className="navbar bg-base-100"> <div className="flex-1 space-x-5 ml-5"> <a className='hover:text-teal-600 text-xl font-bold' href="#">Home</a> <a className='hover:text-teal-600 text-xl font-bold' href="#">Departments</a> <a className='hover:text-teal-600 text-xl font-bold' href="#">Doctors</a> <a className='hover:text-teal-600 text-xl font-bold' href="#">About us</a> </div> <div className="flex-none"> {profile ? ( <div className="dropdown dropdown-end"> <div tabIndex={0} role="button" className="btn btn-ghost btn-circle avatar" onClick={toggleProfile} // Toggle profile on avatar click > <div className="w-10 rounded-full"> <img alt="Avatar" src="https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.jpg" /> </div> </div> <ul className="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52"> <li> <a className="justify-between"> Profile <span className="badge">New</span> </a> </li> <li><a>Settings</a></li> <li><a>Logout</a></li> </ul> </div> ) : ( <div className="space-x-3"> <Link className="btn btn-error" to="/login"> <span className='text-xl font-bold'>Login</span> </Link> <Link className="btn btn-primary" to="/register"> <span className='text-xl font-bold'>Register</span> </Link> </div> )} </div> </div> </div> ); }; export default Navbar;
#include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <stdio.h> #include <unistd.h> using namespace std; void saveToFile(const string& filename, const string& content, bool append = false) { ofstream outfile; if (append) { outfile.open(filename, ios::app); } else { outfile.open(filename); } if (!outfile.is_open()) { cerr << "Unable to open file " << filename << endl; exit(EXIT_FAILURE); } outfile << content; outfile.close(); } void openFile(const string& filename, bool editMode) { if (editMode) { system(("notepad " + filename).c_str()); } else { ifstream infile(filename); if (!infile.is_open()) { cerr << "Unable to open file " << filename << endl; return; } string line; while (getline(infile, line)) { cout << line << endl; } infile.close(); } } void deleteFile(const string& filename) { if (remove(filename.c_str()) != 0) { cerr << "Unable to delete file " << filename << endl; exit(EXIT_FAILURE); } } void printMenu() { cout << "\n"; cout << "1. Create a new file and write to it\n"; cout << "2. Open an existing file in view mode\n"; cout << "3. Open an existing file in edit mode\n"; cout << "4. Delete a file\n"; cout << "5. Exit\n"; } int main() { int choice; string filename, content; do { system("clear"); printMenu(); cout << "Enter Your Choice : "; cin >> choice; system("clear"); switch (choice) { case 1: // Receive text input from the console cout << "Enter Some Text : "; cin.ignore(); getline(cin, content); // Save the text to a new file cout << "Enter The File Name : "; getline(cin, filename); saveToFile(filename, content); break; case 2: // Open an existing file in view mode cout << "Enter The File Name To Open : "; cin >> filename; openFile(filename, false); cout << "Press Enter to continue..... " << endl; cin>> filename; break; case 3: // Open an existing file in edit mode cout << "Enter The File Name To Open : "; cin >> filename; openFile(filename, true); sleep(5); break; case 4: // Delete a file cout << "Enter The File Name To Be Delete : "; cin >> filename; deleteFile(filename); break; case 5: // Exit the program cout << "Exiting Program...\n"; break; default: cerr << "Invalid Choice!" << endl; } } while (choice != 5); return 0; }
/** * @fileOverview * @author Brandon Alexander - baalexander@gmail.com */ var WebSocket = require('ws'); var WorkerSocket = require('../util/workerSocket'); var socketAdapter = require('./SocketAdapter.js'); var Service = require('./Service'); var ServiceRequest = require('./ServiceRequest'); var ServiceResponse = require('./ServiceResponse'); var assign = require('object-assign'); const Topic = require('./Topic'); const Param = require('./Param'); const { TFClient } = require('../tf'); const { ActionClient, SimpleActionServer } = require('../actionlib'); var EventEmitter2 = require('eventemitter2').EventEmitter2; /** * Manages connection to the server and all interactions with ROS. * * Emits the following events: * * 'error' - There was an error with ROS. * * 'connection' - Connected to the WebSocket server. * * 'close' - Disconnected to the WebSocket server. * * &#60;topicName&#62; - A message came from rosbridge with the given topic name. * * &#60;serviceID&#62; - A service response came from rosbridge with the given ID. */ class Ros extends EventEmitter2 { /** * @param {Object} [options] * @param {string} [options.url] - The WebSocket URL for rosbridge. Can be specified later with `connect`. * @param {boolean} [options.groovyCompatibility=true] - Don't use interfaces that changed after the last groovy release or rosbridge_suite and related tools. * @param {'websocket'|'workersocket'|RTCPeerConnection} [options.transportLibrary='websocket'] - One of 'websocket', 'workersocket', or RTCPeerConnection instance controlling how the connection is created in `connect`. * @param {Object} [options.transportOptions={}] - The options to use when creating a connection. Currently only used if `transportLibrary` is RTCPeerConnection. */ constructor(options) { super(); options = options || {}; var that = this; this.socket = null; this.idCounter = 0; this.isConnected = false; this.transportLibrary = options.transportLibrary || 'websocket'; this.transportOptions = options.transportOptions || {}; this._sendFunc = function (msg) { that.sendEncodedMessage(msg); }; if (typeof options.groovyCompatibility === 'undefined') { this.groovyCompatibility = true; } else { this.groovyCompatibility = options.groovyCompatibility; } // Sets unlimited event listeners. this.setMaxListeners(0); // begin by checking if a URL was given if (options.url) { this.connect(options.url); } } /** * Connect to the specified WebSocket. * * @param {string} url - WebSocket URL or RTCDataChannel label for rosbridge. */ connect(url) { if (this.transportLibrary.constructor.name === 'RTCPeerConnection') { this.socket = assign( // @ts-expect-error -- this is kinda wild. `this.transportLibrary` can either be a string or an RTCDataChannel. This needs fixing. this.transportLibrary.createDataChannel(url, this.transportOptions), socketAdapter(this) ); } else if (this.transportLibrary === 'websocket') { if (!this.socket || this.socket.readyState === WebSocket.CLOSED) { var sock = new WebSocket(url); sock.binaryType = 'arraybuffer'; this.socket = assign(sock, socketAdapter(this)); } } else if (this.transportLibrary === 'workersocket') { this.socket = assign(new WorkerSocket(url), socketAdapter(this)); } else { throw 'Unknown transportLibrary: ' + this.transportLibrary.toString(); } } /** * Disconnect from the WebSocket server. */ close() { if (this.socket) { this.socket.close(); } } /** * Send an authorization request to the server. * * @param {string} mac - MAC (hash) string given by the trusted source. * @param {string} client - IP of the client. * @param {string} dest - IP of the destination. * @param {string} rand - Random string given by the trusted source. * @param {Object} t - Time of the authorization request. * @param {string} level - User level as a string given by the client. * @param {Object} end - End time of the client's session. */ authenticate(mac, client, dest, rand, t, level, end) { // create the request var auth = { op: 'auth', mac: mac, client: client, dest: dest, rand: rand, t: t, level: level, end: end }; // send the request this.callOnConnection(auth); } /** * Send an encoded message over the WebSocket. * * @param {Object} messageEncoded - The encoded message to be sent. */ sendEncodedMessage(messageEncoded) { if (!this.isConnected) { this.once('connection', () => { this.socket.send(messageEncoded); }); } else { this.socket.send(messageEncoded); } } /** * Send the message over the WebSocket, but queue the message up if not yet * connected. * * @param {Object} message - The message to be sent. */ callOnConnection(message) { if (this.transportOptions.encoder) { this.transportOptions.encoder(message, this._sendFunc); } else { this._sendFunc(JSON.stringify(message)); } } /** * Send a set_level request to the server. * * @param {string} level - Status level (none, error, warning, info). * @param {number} [id] - Operation ID to change status level on. */ setStatusLevel(level, id) { var levelMsg = { op: 'set_level', level: level, id: id }; this.callOnConnection(levelMsg); } /** * @callback getActionServersCallback * @param {string[]} actionservers - Array of action server names. */ /** * @callback getActionServersFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of action servers in ROS as an array of string. * * @param {getActionServersCallback} callback - Function with the following params: * @param {getActionServersFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getActionServers(callback, failedCallback) { /** @satisfies {Service<any, any>} */ var getActionServers = new Service({ ros: this, name: '/rosapi/action_servers', serviceType: 'rosapi/GetActionServers' }); var request = new ServiceRequest({}); if (typeof failedCallback === 'function') { getActionServers.callService( request, function (result) { callback(result.action_servers); }, function (message) { failedCallback(message); } ); } else { getActionServers.callService(request, function (result) { callback(result.action_servers); }); } } /** * @callback getTopicsCallback * @param {Object} result - The result object with the following params: * @param {string[]} result.topics - Array of topic names. * @param {string[]} result.types - Array of message type names. */ /** * @callback getTopicsFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of topics in ROS as an array. * * @param {getTopicsCallback} callback - Function with the following params: * @param {getTopicsFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getTopics(callback, failedCallback) { var topicsClient = new Service({ ros: this, name: '/rosapi/topics', serviceType: 'rosapi/Topics' }); var request = new ServiceRequest(); if (typeof failedCallback === 'function') { topicsClient.callService( request, function (result) { callback(result); }, function (message) { failedCallback(message); } ); } else { topicsClient.callService(request, function (result) { callback(result); }); } } /** * @callback getTopicsForTypeCallback * @param {string[]} topics - Array of topic names. */ /** * @callback getTopicsForTypeFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of topics in ROS as an array of a specific type. * * @param {string} topicType - The topic type to find. * @param {getTopicsForTypeCallback} callback - Function with the following params: * @param {getTopicsForTypeFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getTopicsForType(topicType, callback, failedCallback) { var topicsForTypeClient = new Service({ ros: this, name: '/rosapi/topics_for_type', serviceType: 'rosapi/TopicsForType' }); var request = new ServiceRequest({ type: topicType }); if (typeof failedCallback === 'function') { topicsForTypeClient.callService( request, function (result) { callback(result.topics); }, function (message) { failedCallback(message); } ); } else { topicsForTypeClient.callService(request, function (result) { callback(result.topics); }); } } /** * @callback getServicesCallback * @param {string[]} services - Array of service names. */ /** * @callback getServicesFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of active service names in ROS. * * @param {getServicesCallback} callback - Function with the following params: * @param {getServicesFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getServices(callback, failedCallback) { var servicesClient = new Service({ ros: this, name: '/rosapi/services', serviceType: 'rosapi/Services' }); var request = new ServiceRequest(); if (typeof failedCallback === 'function') { servicesClient.callService( request, function (result) { callback(result.services); }, function (message) { failedCallback(message); } ); } else { servicesClient.callService(request, function (result) { callback(result.services); }); } } /** * @callback getServicesForTypeCallback * @param {string[]} topics - Array of service names. */ /** * @callback getServicesForTypeFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of services in ROS as an array as specific type. * * @param {string} serviceType - The service type to find. * @param {getServicesForTypeCallback} callback - Function with the following params: * @param {getServicesForTypeFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getServicesForType(serviceType, callback, failedCallback) { var servicesForTypeClient = new Service({ ros: this, name: '/rosapi/services_for_type', serviceType: 'rosapi/ServicesForType' }); var request = new ServiceRequest({ type: serviceType }); if (typeof failedCallback === 'function') { servicesForTypeClient.callService( request, function (result) { callback(result.services); }, function (message) { failedCallback(message); } ); } else { servicesForTypeClient.callService(request, function (result) { callback(result.services); }); } } /** * @callback getServiceRequestDetailsCallback * @param {Object} result - The result object with the following params: * @param {string[]} result.typedefs - An array containing the details of the service request. */ /** * @callback getServiceRequestDetailsFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve the details of a ROS service request. * * @param {string} type - The type of the service. * @param {getServiceRequestDetailsCallback} callback - Function with the following params: * @param {getServiceRequestDetailsFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getServiceRequestDetails(type, callback, failedCallback) { var serviceTypeClient = new Service({ ros: this, name: '/rosapi/service_request_details', serviceType: 'rosapi/ServiceRequestDetails' }); var request = new ServiceRequest({ type: type }); if (typeof failedCallback === 'function') { serviceTypeClient.callService( request, function (result) { callback(result); }, function (message) { failedCallback(message); } ); } else { serviceTypeClient.callService(request, function (result) { callback(result); }); } } /** * @callback getServiceResponseDetailsCallback * @param {ServiceResponse<{typedefs: string[]}>} result - The result object with the following params: */ /** * @callback getServiceResponseDetailsFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve the details of a ROS service response. * * @param {string} type - The type of the service. * @param {getServiceResponseDetailsCallback} callback - Function with the following params: * @param {getServiceResponseDetailsFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getServiceResponseDetails(type, callback, failedCallback) { /** @satisfies {Service<{},{typedefs: string[]}>} */ var serviceTypeClient = new Service({ ros: this, name: '/rosapi/service_response_details', serviceType: 'rosapi/ServiceResponseDetails' }); var request = new ServiceRequest({ type: type }); if (typeof failedCallback === 'function') { serviceTypeClient.callService( request, function (result) { callback(result); }, function (message) { failedCallback(message); } ); } else { serviceTypeClient.callService(request, function (result) { callback(result); }); } } /** * @callback getNodesCallback * @param {string[]} nodes - Array of node names. */ /** * @callback getNodesFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of active node names in ROS. * * @param {getNodesCallback} callback - Function with the following params: * @param {getNodesFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getNodes(callback, failedCallback) { var nodesClient = new Service({ ros: this, name: '/rosapi/nodes', serviceType: 'rosapi/Nodes' }); var request = new ServiceRequest(); if (typeof failedCallback === 'function') { nodesClient.callService( request, function (result) { callback(result.nodes); }, function (message) { failedCallback(message); } ); } else { nodesClient.callService(request, function (result) { callback(result.nodes); }); } } /** * @callback getNodeDetailsCallback * @param {string[]} subscriptions - Array of subscribed topic names. * @param {string[]} publications - Array of published topic names. * @param {string[]} services - Array of service names hosted. */ /** * @callback getNodeDetailsFailedCallback * @param {string} error - The error message reported by ROS. */ /** * @callback getNodeDetailsLegacyCallback * @param {Object} result - The result object with the following params: * @param {string[]} result.subscribing - Array of subscribed topic names. * @param {string[]} result.publishing - Array of published topic names. * @param {string[]} result.services - Array of service names hosted. */ /** * Retrieve a list of subscribed topics, publishing topics and services of a specific node. * <br> * These are the parameters if failedCallback is <strong>defined</strong>. * * @param {string} node - Name of the node. * @param {getNodeDetailsCallback} callback - Function with the following params: * @param {getNodeDetailsFailedCallback} [failedCallback] - The callback function when the service call failed with params: * * @also * * Retrieve a list of subscribed topics, publishing topics and services of a specific node. * <br> * These are the parameters if failedCallback is <strong>undefined</strong>. * * @param {string} node - Name of the node. * @param {getNodeDetailsLegacyCallback} callback - Function with the following params: * @param {getNodeDetailsFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getNodeDetails(node, callback, failedCallback) { var nodesClient = new Service({ ros: this, name: '/rosapi/node_details', serviceType: 'rosapi/NodeDetails' }); var request = new ServiceRequest({ node: node }); if (typeof failedCallback === 'function') { nodesClient.callService( request, function (result) { callback(result.subscribing, result.publishing, result.services); }, function (message) { failedCallback(message); } ); } else { nodesClient.callService(request, function (result) { // @ts-expect-error -- callback parameter polymorphism, see JSDoc comment above callback(result); }); } } /** * @callback getParamsCallback * @param {string[]} params - Array of param names. */ /** * @callback getParamsFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of parameter names from the ROS Parameter Server. * * @param {getParamsCallback} callback - Function with the following params: * @param {getParamsFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getParams(callback, failedCallback) { var paramsClient = new Service({ ros: this, name: '/rosapi/get_param_names', serviceType: 'rosapi/GetParamNames' }); var request = new ServiceRequest(); if (typeof failedCallback === 'function') { paramsClient.callService( request, function (result) { callback(result.names); }, function (message) { failedCallback(message); } ); } else { paramsClient.callService(request, function (result) { callback(result.names); }); } } /** * @callback getTopicTypeCallback * @param {string} type - The type of the topic. */ /** * @callback getTopicTypeFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve the type of a ROS topic. * * @param {string} topic - Name of the topic. * @param {getTopicTypeCallback} callback - Function with the following params: * @param {getTopicTypeFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getTopicType(topic, callback, failedCallback) { var topicTypeClient = new Service({ ros: this, name: '/rosapi/topic_type', serviceType: 'rosapi/TopicType' }); var request = new ServiceRequest({ topic: topic }); if (typeof failedCallback === 'function') { topicTypeClient.callService( request, function (result) { callback(result.type); }, function (message) { failedCallback(message); } ); } else { topicTypeClient.callService(request, function (result) { callback(result.type); }); } } /** * @callback getServiceTypeCallback * @param {string} type - The type of the service. */ /** * @callback getServiceTypeFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve the type of a ROS service. * * @param {string} service - Name of the service. * @param {getServiceTypeCallback} callback - Function with the following params: * @param {getServiceTypeFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getServiceType(service, callback, failedCallback) { var serviceTypeClient = new Service({ ros: this, name: '/rosapi/service_type', serviceType: 'rosapi/ServiceType' }); var request = new ServiceRequest({ service: service }); if (typeof failedCallback === 'function') { serviceTypeClient.callService( request, function (result) { callback(result.type); }, function (message) { failedCallback(message); } ); } else { serviceTypeClient.callService(request, function (result) { callback(result.type); }); } } /** * @callback getMessageDetailsCallback * @param {string} details - An array of the message details. */ /** * @callback getMessageDetailsFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve the details of a ROS message. * * @param {string} message - The name of the message type. * @param {getMessageDetailsCallback} callback - Function with the following params: * @param {getMessageDetailsFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getMessageDetails(message, callback, failedCallback) { var messageDetailClient = new Service({ ros: this, name: '/rosapi/message_details', serviceType: 'rosapi/MessageDetails' }); var request = new ServiceRequest({ type: message }); if (typeof failedCallback === 'function') { messageDetailClient.callService( request, function (result) { callback(result.typedefs); }, function (message) { failedCallback(message); } ); } else { messageDetailClient.callService(request, function (result) { callback(result.typedefs); }); } } /** * Decode a typedef array into a dictionary like `rosmsg show foo/bar`. * * @param {Object[]} defs - Array of type_def dictionary. */ decodeTypeDefs(defs) { var that = this; var decodeTypeDefsRec = function (theType, hints) { // calls itself recursively to resolve type definition using hints. var typeDefDict = {}; for (var i = 0; i < theType.fieldnames.length; i++) { var arrayLen = theType.fieldarraylen[i]; var fieldName = theType.fieldnames[i]; var fieldType = theType.fieldtypes[i]; if (fieldType.indexOf('/') === -1) { // check the fieldType includes '/' or not if (arrayLen === -1) { typeDefDict[fieldName] = fieldType; } else { typeDefDict[fieldName] = [fieldType]; } } else { // lookup the name var sub = false; for (var j = 0; j < hints.length; j++) { if (hints[j].type.toString() === fieldType.toString()) { sub = hints[j]; break; } } if (sub) { var subResult = decodeTypeDefsRec(sub, hints); if (arrayLen === -1) { typeDefDict[fieldName] = subResult; // add this decoding result to dictionary } else { typeDefDict[fieldName] = [subResult]; } } else { that.emit( 'error', 'Cannot find ' + fieldType + ' in decodeTypeDefs' ); } } } return typeDefDict; }; return decodeTypeDefsRec(defs[0], defs); } /** * @callback getTopicsAndRawTypesCallback * @param {Object} result - The result object with the following params: * @param {string[]} result.topics - Array of topic names. * @param {string[]} result.types - Array of message type names. * @param {string[]} result.typedefs_full_text - Array of full definitions of message types, similar to `gendeps --cat`. */ /** * @callback getTopicsAndRawTypesFailedCallback * @param {string} error - The error message reported by ROS. */ /** * Retrieve a list of topics and their associated type definitions. * * @param {getTopicsAndRawTypesCallback} callback - Function with the following params: * @param {getTopicsAndRawTypesFailedCallback} [failedCallback] - The callback function when the service call failed with params: */ getTopicsAndRawTypes(callback, failedCallback) { var topicsAndRawTypesClient = new Service({ ros: this, name: '/rosapi/topics_and_raw_types', serviceType: 'rosapi/TopicsAndRawTypes' }); var request = new ServiceRequest(); if (typeof failedCallback === 'function') { topicsAndRawTypesClient.callService( request, function (result) { callback(result); }, function (message) { failedCallback(message); } ); } else { topicsAndRawTypesClient.callService(request, function (result) { callback(result); }); } } Topic(options) { return new Topic({ ros: this, ...options }); } Param(options) { return new Param({ ros: this, ...options }); } Service(options) { return new Service({ ros: this, ...options }); } TFClient(options) { return new TFClient({ ros: this, ...options }); } ActionClient(options) { return new ActionClient({ ros: this, ...options }); } SimpleActionServer(options) { return new SimpleActionServer({ ros: this, ...options }); } } module.exports = Ros;
import { AppContext } from "../App"; import { useEffect, useState, useContext } from "react"; import { useNavigate, useParams } from "react-router-dom"; import jwt from "jwt-decode"; import { motion, AnimatePresence } from "framer-motion"; import { useForm } from "react-hook-form"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from "yup"; import Notification from "./Notification"; const schema = yup.object({ name: yup.string().min(3).max(300).required().label("Name"), email: yup.string().max(256).email().required().label("Email"), }).required(); const RouteCustomerUpdate = () => { const apiURL = useContext(AppContext); const navigate = useNavigate(); const [notification, setNotification] = useState({ message: "", display: false, bgColor: "" }); const { cId } = useParams(); const { register, handleSubmit, setValue, formState: { errors }, } = useForm({ resolver: yupResolver(schema) }); const token = localStorage.getItem("token"); const { uId } = jwt(token); useEffect(() => { const getCustomerInfo = async () => { const res = await fetch(`${apiURL}/api/customers/${cId}`, { headers: { "x-auth-token": token } }); const data = await res.json(); if (data.message === "success") { setValue("name", data.customer.name); setValue("email", data.customer.email); window.cusPostcode = data.customer.postcode; } else { alert(data.message); } } getCustomerInfo(); }, [cId, token, apiURL, setValue]); const onSubmit = async (formData) => { try { const res = await fetch(`${apiURL}/api/customers/${cId}`, { method: "PUT", headers: { "Content-Type": "application/json", "x-auth-token": token }, body: JSON.stringify({ userId: uId, ...formData, postcode: window.cusPostcode }) }); const data = await res.json(); if (res.status === 200) { navigate(-1); } else { setNotification({ message: data.message, display: true, bgColor: "#E2412E" }); } } catch (error) { setNotification({ message: error.message, display: true, bgColor: "#E2412E" }); } finally { setTimeout(() => { setNotification({ message: "", display: false, bgColor: "#E2412E" }); }, 3000); } } return ( <motion.div initial={{ opacity: 0, x: +200 }} animate={{ opacity: 1, x: 0 }} transition={{ ease: "easeOut", duration: 1.5 }} > <div className="cont"> <form onSubmit={handleSubmit(onSubmit)}> <div className="form-input-container"> <label> Name <br /> <input id="name" type="text" {...register("name")} /> </label> {errors.name?.message && ( <div className='cont-invalid'> <span className='invalid-text'>{errors.name?.message}</span> </div> )} </div> <div className="form-input-container"> <label> Email <br /> <input id="email" type="text" {...register("email")} /> </label> {errors.email?.message && ( <div className='cont-invalid'> <span className='invalid-text'>{errors.email?.message}</span> </div> )} </div> <div> <button className="btn btn-add" id="btn-update" type="submit">Update</button> </div> </form> <AnimatePresence> {notification.display && ( <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ ease: "easeOut", duration: 1.5 }} exit={{ opacity: 0 }} > <Notification message={notification.message} bgColor={notification.bgColor} /> </motion.div> )} </AnimatePresence> </div> </motion.div> ); } export default RouteCustomerUpdate;
import { styled } from "@mui/material/styles"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell, { tableCellClasses } from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import { useSelector } from "react-redux"; import { tableHeadCells } from "../../utils/commonData"; import { Link } from "react-router-dom"; const StyledTableCell = styled(TableCell)(({ theme }) => ({ [`&.${tableCellClasses.head}`]: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white, }, [`&.${tableCellClasses.body}`]: { fontSize: 14, }, })); const StyledTableRow = styled(TableRow)(({ theme }) => ({ "&:nth-of-type(odd)": { backgroundColor: theme.palette.action.hover, }, // hide last border "&:last-child td, &:last-child th": { border: 0, }, })); const cellStyle = { position: "relative", zIndex: 3, overflow: "hidden", }; const colorDegreFunc = (num) => { const n = num * 100 > 85 ? "#00FF08" : num * 100 > 80 ? "#33C237" : num * 100 > 75 ? "#EE400D" : num * 100 > 70 ? "red" : "#FF6F6F"; return n; }; const lineStyle = { position: "absolute", height: "5px", zIndex: -1, bottom: "0%", left: 0, transform: `translateY(-50%)`, borderRadius: "20px", }; export default function TeamHistoryTable() { const { teamNumbersMonthly } = useSelector((state) => state.teamNumbersSlice); return ( <TableContainer component={Paper} style={{ marginTop: "15px" }}> <Table sx={{ minWidth: 700 }} aria-label="customized table"> <TableHead> <TableRow> <StyledTableCell>Date</StyledTableCell> {tableHeadCells.map((cell, index) => { if (index === 0) return; return ( <StyledTableCell align="center" key={index}> {cell} </StyledTableCell> ); })} </TableRow> </TableHead> <TableBody> {teamNumbersMonthly?.map((number, index) => { return ( <StyledTableRow key={index}> {/* //!TODO when click navigate him to the day */} <StyledTableCell component="th" scope="row" align="center" style={{ fontWeight: "bold" }}> <Link to={`/`}>{number?.date}</Link> </StyledTableCell> <StyledTableCell align="center">{number?.total?.surveys}</StyledTableCell> <StyledTableCell align="center" style={cellStyle}> {(number?.total?.CSAT * 100).toFixed(2)}% <div style={{ ...lineStyle, backgroundColor: colorDegreFunc(number?.total?.CSAT), width: number?.total?.CSAT * 90 + "%", }}></div> </StyledTableCell>{" "} <StyledTableCell align="center">{number?.total?.KCSAT}</StyledTableCell> <StyledTableCell align="center">{number?.total?.PPH}</StyledTableCell> <StyledTableCell align="center">{number?.total?.PPD}</StyledTableCell> <StyledTableCell align="center">{number?.total?.PMTD}</StyledTableCell> <StyledTableCell align="center">{number?.total?.closedCases}</StyledTableCell> <StyledTableCell align="center">{number?.total?.responseRate}%</StyledTableCell> <StyledTableCell align="center">{number?.total?.QAEvaulations}</StyledTableCell> <StyledTableCell align="center">{number?.total?.QAScore}%</StyledTableCell> <StyledTableCell align="center">{number?.total?.IdleTime}</StyledTableCell> </StyledTableRow> ); })} </TableBody> </Table> </TableContainer> ); }
using Kysect.Zeya.LocalRepositoryAccess; using Kysect.Zeya.LocalRepositoryAccess.Github; using Kysect.Zeya.RepositoryValidationRules.Fixers.Github; using Kysect.Zeya.RepositoryValidationRules.Rules.Github; using Kysect.Zeya.Tests.Tools; using System.IO.Abstractions.TestingHelpers; namespace Kysect.Zeya.Tests.Domain.ValidationRuleFixers.Github; public class GithubWorkflowEnabledValidationRuleFixerTests { private readonly ValidationTestFixture _validationTestFixture; private readonly GithubWorkflowEnabledValidationRuleFixer _fixer; public GithubWorkflowEnabledValidationRuleFixerTests() { _validationTestFixture = new ValidationTestFixture(); _fixer = _validationTestFixture.GetRequiredService<GithubWorkflowEnabledValidationRuleFixer>(); } [Fact] public void Fix_NonGithubRepository_SkipFixing() { var masterFileContent = """ - name - run - step """; _validationTestFixture.SolutionFileStructureBuilderFactory .Create("Solution") .Save(_validationTestFixture.CurrentPath); _validationTestFixture.FileSystem.AddFile("build.yaml", new MockFileData(masterFileContent)); ILocalRepository nonGitRepository = _validationTestFixture.CreateLocalRepository(); _fixer.Fix(new GithubWorkflowEnabledValidationRule.Arguments(["build.yaml"]), nonGitRepository); } [Fact] public void Fix_SolutionWithoutWorkflow_CreateWorkflowFile() { var masterFileContent = """ - name - run - step """; _validationTestFixture.SolutionFileStructureBuilderFactory .Create("Solution") .Save(_validationTestFixture.CurrentPath); _validationTestFixture.FileSystem.AddFile("build.yaml", new MockFileData(masterFileContent)); LocalGithubRepository localGithubRepository = _validationTestFixture.CreateGithubRepository(); _fixer.Fix(new GithubWorkflowEnabledValidationRule.Arguments(["build.yaml"]), localGithubRepository); _validationTestFixture.FileSystemAsserts .File(_validationTestFixture.CurrentPath, ".github", "workflows", "build.yaml") .ShouldExists() .ShouldHaveContent(masterFileContent); } }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Home extends StatefulWidget { const Home({super.key}); @override State<Home> createState() => _homeState(); } class _homeState extends State<Home> { //var bool isFavorite = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Mission 1", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), ), backgroundColor: Colors.blue, ), body: Stack( children: [ SizedBox( height: double.infinity, width: double.infinity, child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [Colors.lightBlue.shade100, Colors.white], ), ), clipBehavior: Clip.antiAlias, ), ), Column( children: [ Flexible( flex: 2, child: Container( width: double.infinity, height: double.infinity, child: Image.asset( 'assets/images/image0.jpg', fit: BoxFit.cover, ), ), ), Flexible( flex: 1, child: Container( margin: const EdgeInsets.all(8), child: ListView( scrollDirection: Axis.horizontal, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ roundedImage('assets/images/image1.jpg'), const Padding( padding: EdgeInsets.symmetric(horizontal: 4)), roundedImage('assets/images/image2.jpg'), const Padding( padding: EdgeInsets.symmetric(horizontal: 4)), roundedImage('assets/images/image3.jpg'), const Padding( padding: EdgeInsets.symmetric(horizontal: 4)), roundedImage('assets/images/image4.jpg'), ], ), ], ), ), ), const Flexible( flex: 4, child: Column(children: [ Text( "Welcome to Golden Tulip Holland Batu", style: TextStyle( fontSize: 24.0, fontWeight: FontWeight.bold), textAlign: TextAlign.center, ), Expanded( child: SingleChildScrollView( clipBehavior: Clip.antiAlias, padding: const EdgeInsets.all(16.0), child: Text( "SkyDome Batu merupakan lounge dan bar ikonik dari Golden Tulip Holland Resort Batu. SkyDome Lounge & Bar menyajikan Masakan Steamboat otentik, Makanan Cina A’La Carte, Minuman Beralkohol & Non-alkohol. Dari makan siang terbaik, teh sore hari, minuman beralkohol dan santapan mewah di saat makan malam Anda. Gabungan pemandangan panorama kelas dunia dengan 3600 dan nikmati suasana malam di Kota Batu dengan instrumen Biola & Saksofon setiap akhir pekan.\n\n" "Dengan konsep interior design yang luxury dan exclusive berbentuk kubah, membuat instalasi AC yang di desain pada sisi samping berbentuk trox agar mendukung interior desain yang ada. Menggunakan unit Daikin VRV floor standing duct yang dapat diberdirikan di bawah dinding sehingga memudahkan untuk proses service & maintenance. kedepannya\n\n" "Selain itu, unit indoor floor standing Daikin VRV yang dapat disembunyikan tentunya mempermudah proses instalasi karena diperlukan fleksibilitas dalam penempatan unit nya. VRV HS juga salah satu unit Daikin VRV yang memiliki bentuk slim dan ringkas untuk tempat outdoor yang terbatas.", style: TextStyle(fontSize: 18.0), textAlign: TextAlign.justify, ), )) ])), ], ), Positioned( top: 20, right: 20, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.grey, border: Border.all( color: Colors.grey, width: 2.0, ), ), child: InkWell( onTap: () { setState(() { isFavorite = !isFavorite; }); }, child: Padding( padding: EdgeInsets.all(8.0), child: Icon( isFavorite ? Icons.favorite : Icons.favorite, color: isFavorite ? Colors.red : Colors.grey[800], ), ), ), ), ) ], ), ); } Widget roundedImage(String imagePath) { return ClipRRect( borderRadius: BorderRadius.circular(6), child: Image.asset( imagePath, width: 100.0, height: 100.0, fit: BoxFit.fill, ), ); } }
<?php namespace App\Domains\GroupType\Controllers; use App\Domains\GroupType\Models\GroupType; use App\Domains\GroupType\Models\EnumPermissionGroupType; use App\Domains\GroupType\Request\FilterGroupTypeRequest; use App\Domains\GroupType\Request\StoreGroupTypeRequest; use App\Domains\GroupType\Request\UpdateGroupTypeRequest; use App\Domains\GroupType\Resources\ChartOfAccountsResource; use App\Domains\GroupType\Resources\GroupTypeResource; use App\Domains\GroupType\Services\GroupTypeService; use App\Http\Controllers\Controller; use Symfony\Component\HttpFoundation\Response; use Illuminate\Http\Request; class GroupTypeController extends Controller { public function __construct(private GroupTypeService $groupTypeService) { } public function list(FilterGroupTypeRequest $request) { // abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::view_groupTypes->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return GroupTypeResource::collection($this->groupTypeService->list()); } public function getTreeView() { abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::view_groupTypes->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return ChartOfAccountsResource::collection($this->groupTypeService->getTreeView()); } public function treeViewPDF() { abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::view_groupTypes->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return $this->groupTypeService->treeViewPDF(); } public function delete($id) { abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::delete_groupType->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); if ($this->groupTypeService->delete($id)) { return response()->json([ 'message' => __('Deleted Successfully'), 'status' => true, ], Response::HTTP_OK); } return response()->json([ 'message' => __('Can not Deleted because it belong to Group'), 'status' => false, ], Response::HTTP_UNPROCESSABLE_ENTITY); } public function findById($id) { abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::view_groupTypes->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return GroupTypeResource::make($this->groupTypeService->findById($id)); } public function create(StoreGroupTypeRequest $request) { abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::create_groupType->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $this->groupTypeService->create($request); return response()->json([ 'message' => __('Created Successfully'), 'status' => true, ], Response::HTTP_OK); } public function update($id, UpdateGroupTypeRequest $request) { abort_if(!auth()->user()->hasPermissionTo(EnumPermissionGroupType::edit_groupType->value, 'api'), Response::HTTP_FORBIDDEN, '403 Forbidden'); if ($this->groupTypeService->update($id, $request)) { return response()->json([ 'message' => __('Updated Successfully'), 'status' => true, ], Response::HTTP_OK); } return response()->json([ 'message' => __('Can Not update this Group Type'), 'status' => false, ], Response::HTTP_UNPROCESSABLE_ENTITY); } }
import os from functools import lru_cache import pytest from cffconvert import Citation from cffconvert.lib.cff_1_3_x.zenodo import ZenodoObject @lru_cache def get_cffstr(): fixture = os.path.join(os.path.dirname(__file__), "CITATION.cff") with open(fixture, "rt", encoding="utf-8") as f: return f.read() def get_relation_types(): return [ "Cites", "Compiles", "Continues", "Describes", "Documents", "HasPart", "IsCitedBy", "IsCompiledBy", "IsContinuedBy", "IsDerivedFrom", "IsDescribedBy", "IsDocumentedBy", "IsIdenticalTo", "IsNewVersionOf", "IsObsoletedBy", "IsPartOf", "IsPreviousVersionOf", "IsPublishedIn", "IsReferencedBy", "IsRequiredBy", "IsReviewedBy", "IsSourceOf", "IsSupplementedBy", "IsSupplementTo", "Obsoletes", "References", "Requires", "Reviews" ] def get_relation_types_skip(): return [ "HasMetadata", "HasVersion", "IsMetadataFor", "IsOriginalFormOf", "IsVariantFormOf", "IsVersionOf" ] @pytest.mark.lib @pytest.mark.zenodo @pytest.mark.parametrize("expected", get_relation_types()) def test_with_relation(expected): cffstr = get_cffstr().replace("IsCompiledBy", expected) citation = Citation(cffstr) zenodo_object = ZenodoObject(citation.cffobj, initialize_empty=True) related_identifiers = zenodo_object.add_related_identifiers().related_identifiers assert related_identifiers is not None assert isinstance(related_identifiers, list) assert len(related_identifiers) > 0 # pylint: disable=unsubscriptable-object assert isinstance(related_identifiers[0], dict) # pylint: disable=unsubscriptable-object actual = related_identifiers[0].get("relation") assert actual[1:] == expected[1:] assert actual[0] == expected[0].lower() @pytest.mark.lib @pytest.mark.zenodo @pytest.mark.parametrize("expected", get_relation_types_skip()) def test_with_relation_unmapped(expected): cffstr = get_cffstr().replace("IsCompiledBy", expected) citation = Citation(cffstr) zenodo_object = ZenodoObject(citation.cffobj, initialize_empty=True) related_identifiers = zenodo_object.add_related_identifiers().related_identifiers assert related_identifiers is not None assert isinstance(related_identifiers, list) assert len(related_identifiers) > 0 # pylint: disable=unsubscriptable-object assert isinstance(related_identifiers[0], dict) # pylint: disable=unsubscriptable-object actual = related_identifiers[0].get("relation") assert actual == "isSupplementedBy" @pytest.mark.lib @pytest.mark.zenodo def test_without_relation(): cffstr = get_cffstr().replace("relation: IsCompiledBy\n ", "") citation = Citation(cffstr) zenodo_object = ZenodoObject(citation.cffobj, initialize_empty=True) related_identifiers = zenodo_object.add_related_identifiers().related_identifiers assert related_identifiers is not None assert isinstance(related_identifiers, list) assert len(related_identifiers) > 0 # pylint: disable=unsubscriptable-object assert isinstance(related_identifiers[0], dict) # pylint: disable=unsubscriptable-object relation = related_identifiers[0].get("relation") assert relation == "isSupplementedBy"
import { createContext, useCallback, useEffect, useState } from 'react' import { v4 as uuid } from 'uuid' type Task = { id: string; text: string; isDone: boolean; } type TasksContextType = { tasks: Task[]; totalTasks:number; doneTasks: number; onFinishTask: (id: string) => void; onDeleteTask: (name: string) =>void; onAddTask: (text: string) => void; } export const TaskContext = createContext({} as TasksContextType) export function TasksProvider({ children }: {children: React.ReactNode}) { const [taskList, setTaskList] = useState<Task[]>([]); const [totalTasks, setTotalTasks] = useState<number>(0); const [doneTasks, setDoneTasks] = useState<number>(0); const onAddTask = useCallback((text: string) => { const id = uuid() const newTask = { id, isDone: false, text } setTaskList(state => [...state, newTask]); }, []); const onFinishTask = useCallback((id: string) => { setTaskList(state => state.map(task => { if(task.id === id) { return { ...task, isDone: !task.isDone } } return task })) }, []); const onDeleteTask = useCallback((id: string) => { setTaskList(state => state.filter(task => task.id !== id)) }, []); useEffect(() => { setTotalTasks(taskList.length) setDoneTasks(taskList.filter(task => task.isDone).length) }, [taskList]); return ( <TaskContext.Provider value={{ tasks: taskList, onAddTask, onFinishTask, onDeleteTask, totalTasks, doneTasks, }} > {children} </TaskContext.Provider> ) }
// Copyright (c) 2012 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. // This defines helpful methods for dealing with Callbacks. Because Callbacks // are implemented using templates, with a class per callback signature, adding // methods to Callback<> itself is unattractive (lots of extra code gets // generated). Instead, consider adding methods here. // // ResetAndReturn(&cb) is like cb.Reset() but allows executing a callback (via a // copy) after the original callback is Reset(). This can be handy if Run() // reads/writes the variable holding the Callback. #ifndef BASE_CALLBACK_HELPERS_H_ #define BASE_CALLBACK_HELPERS_H_ #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" namespace base { template <typename Sig> base::Callback<Sig> ResetAndReturn(base::Callback<Sig>* cb) { base::Callback<Sig> ret(*cb); cb->Reset(); return ret; } // ScopedClosureRunner is akin to std::unique_ptr<> for Closures. It ensures // that the Closure is executed no matter how the current scope exits. class BASE_EXPORT ScopedClosureRunner { public: ScopedClosureRunner(); explicit ScopedClosureRunner(const Closure& closure); ~ScopedClosureRunner(); ScopedClosureRunner(ScopedClosureRunner&& other); // Calls the current closure if it's set and replaces it with the closure from // |other|. ScopedClosureRunner& operator=(ScopedClosureRunner&& other); // Calls the current closure and resets it, so it wont be called again. void Reset(); // Calls the current closure and replaces it with the new one. void Reset(const Closure& closure); // Releases the Closure without calling. Closure Release() WARN_UNUSED_RESULT; private: Closure closure_; DISALLOW_COPY_AND_ASSIGN(ScopedClosureRunner); }; } // namespace base #endif // BASE_CALLBACK_HELPERS_H_
package com.satellite.satellite.controller; import com.satellite.satellite.model.APIResponse; import com.satellite.satellite.model.CustomerSatellite; import com.satellite.satellite.service.CustomerSatelliteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/satellite") @CrossOrigin() public class CustomerSatelliteController { @Autowired CustomerSatelliteService customerSatelliteService; @PostMapping("/fetchSatellites") public void fetchSatellitesFromAPI() { customerSatelliteService.fetchSatellitesFromAPI(); } @GetMapping("/search") public ResponseEntity<APIResponse<List<CustomerSatellite>>> searchSatellites( @RequestParam(name = "id", required = false) String id, @RequestParam(name = "launchDate", required = false) String launchDate, @RequestParam(name = "country", required = false) String country, @RequestParam(name = "launcherId", required = false) String launcherId, @RequestParam(name = "mass", required = false) Double mass) { List<CustomerSatellite> searchResults = customerSatelliteService.searchSatellites(id, launchDate, country, launcherId, mass); if (searchResults.isEmpty()) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(APIResponse.<List<CustomerSatellite>>builder() .status(HttpStatus.NOT_FOUND.value()) .message("No satellites found matching the search criteria.") .build()); } else { return ResponseEntity.ok(APIResponse.<List<CustomerSatellite>>builder() .status(HttpStatus.OK.value()) .message("Satellites retrieved successfully.") .data(searchResults) .build()); } } @GetMapping("") public ResponseEntity<APIResponse<List<CustomerSatellite>>> getAllCustomerSatellites() { return customerSatelliteService.getAllCustomerSatellites(); } @PostMapping("") public ResponseEntity<APIResponse<CustomerSatellite>> addCustomerSatellites(@RequestBody CustomerSatellite customerSatellite) { return customerSatelliteService.createCustomerSatellite(customerSatellite); } @PutMapping("") public ResponseEntity<APIResponse<CustomerSatellite>> updateCustomerSatellites(@RequestBody CustomerSatellite customerSatellite) { return customerSatelliteService.updateCustomerSatellite(customerSatellite); } @DeleteMapping("") public ResponseEntity<APIResponse<Void>> deleteCustomerSatellites(@RequestParam("id") String id) { return customerSatelliteService.deleteCustomerSatellite(id); } @GetMapping("/id") public ResponseEntity<APIResponse<CustomerSatellite>> getCustomerSatellitesById(@RequestParam("id") String id) { return customerSatelliteService.getCustomerSatelliteById(id); } }
package sg.nus.edu.iss.vttp5a_ssf_day15l_mine.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import jakarta.validation.Valid; import sg.nus.edu.iss.vttp5a_ssf_day15l_mine.model.Person; import sg.nus.edu.iss.vttp5a_ssf_day15l_mine.service.PersonService; import sg.nus.edu.iss.vttp5a_ssf_day15l_mine.util.Utility; @Controller @RequestMapping("/persons") public class PersonCreateController { @Autowired PersonService personService; @GetMapping("/create") public String goToCreateForm(Model model){ model.addAttribute("person", new Person()); return "PersonCreate"; } @PostMapping("/create") public String createPerson(@Valid Person person, BindingResult bindingResult){ if(bindingResult.hasErrors()){ return "PersonCreate"; } Person p = new Person(person.getId(), person.getFullName(), person.getEmail()); personService.addPerson(Utility.REDISKEY, p); return "redirect:/persons"; } }
from flask import Flask, render_template, request, redirect, url_for import sqlite3 app = Flask(__name__) # SQLite database configuration DATABASE = 'database.db' def create_tables(): with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS department ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS student ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email_id TEXT NOT NULL, phoneNumber TEXT NOT NULL, deptId INTEGER NOT NULL, FOREIGN KEY (deptId) REFERENCES department (id) ) ''') connection.commit() # Create tables on startup create_tables() @app.route('/') def index(): with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() # Fetch all students with department names cursor.execute(''' SELECT student.id, student.name, student.email_id, student.phoneNumber, department.name FROM student JOIN department ON student.deptId = department.id ''') students = cursor.fetchall() # Fetch all departments cursor.execute('SELECT * FROM department') departments = cursor.fetchall() return render_template('index.html', students=students, departments=departments) @app.route('/add_student', methods=['POST']) def add_student(): name = request.form['name'] email_id = request.form['email_id'] phoneNumber = request.form['phoneNumber'] deptId = request.form['deptId'] with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute('INSERT INTO student (name, email_id, phoneNumber, deptId) VALUES (?, ?, ?, ?)', (name, email_id, phoneNumber, deptId)) connection.commit() return redirect(url_for('index')) @app.route('/edit_student/<int:student_id>', methods=['GET', 'POST']) def edit_student(student_id): if request.method == 'GET': with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() # Fetch student details cursor.execute('SELECT * FROM student WHERE id = ?', (student_id,)) student = cursor.fetchone() # Fetch all departments cursor.execute('SELECT * FROM department') departments = cursor.fetchall() return render_template('edit_student.html', student=student, departments=departments) elif request.method == 'POST': name = request.form['name'] email_id = request.form['email_id'] phoneNumber = request.form['phoneNumber'] deptId = request.form['deptId'] with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute(''' UPDATE student SET name=?, email_id=?, phoneNumber=?, deptId=? WHERE id=? ''', (name, email_id, phoneNumber, deptId, student_id)) connection.commit() return redirect(url_for('index')) @app.route('/delete_student/<int:student_id>') def delete_student(student_id): with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute('DELETE FROM student WHERE id = ?', (student_id,)) connection.commit() return redirect(url_for('index')) @app.route('/add_department', methods=['POST']) def add_department(): name = request.form['name'] with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute('INSERT INTO department (name) VALUES (?)', (name,)) connection.commit() return redirect(url_for('index')) @app.route('/edit_department/<int:dept_id>', methods=['GET', 'POST']) def edit_department(dept_id): if request.method == 'GET': with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() # Fetch department details cursor.execute('SELECT * FROM department WHERE id = ?', (dept_id,)) department = cursor.fetchone() return render_template('edit_department.html', department=department) elif request.method == 'POST': name = request.form['name'] with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute('UPDATE department SET name=? WHERE id=?', (name, dept_id)) connection.commit() return redirect(url_for('index')) @app.route('/delete_department/<int:dept_id>') def delete_department(dept_id): with sqlite3.connect(DATABASE) as connection: cursor = connection.cursor() cursor.execute('DELETE FROM department WHERE id = ?', (dept_id,)) connection.commit() return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)
#ifndef __STM32H7A3_GPIO_HPP__ #define __STM32H7A3_GPIO_HPP__ #include "AbstractGPIO.hpp" #include "stm32h7a3xxq.h" namespace Drivers { enum class GPIO_PIN { Pin0, Pin1, Pin2, Pin3, Pin4, Pin5, Pin6, Pin7, Pin8, Pin9, Pin10, Pin11, Pin12, Pin13, Pin14, Pin15 }; enum class GPIO_MODER { Input, GeneralOutput, AlternateFunction, Analog }; enum class GPIO_TYPER { PushPull, OpenDrain }; enum class GPIO_SPEEDR { LowSpeed, MediumSpeed, HighSpeed, VeryHighSpeed }; enum class GPIO_PULL_UP_DOWN { No_PullUp_PullDown, PullUp, PullDown }; enum class GPIO_ALTERNATE_FUNCTION { AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, AF10, AF11, AF12, AF13, AF14, AF15 }; using GPIO_Pin_t = uint32_t; class STM32H7A3_GPIO final : public AbstractGPIO { public: explicit STM32H7A3_GPIO(GPIO_TypeDef *port, GPIO_PIN pin, bool initState); virtual ~STM32H7A3_GPIO() {} inline void High(void) { portPtr->BSRR = (1UL << gpioPin); } inline void Low(void) { portPtr->BSRR = (1UL << (gpioPin + 16UL)); } inline void Toggle(void) { portPtr->ODR ^= (1UL << gpioPin); } inline bool getState(void) { return (portPtr->IDR & (1UL << gpioPin)); } void setMode(GPIO_MODER mode); void setType(GPIO_TYPER type); void setSpeed(GPIO_SPEEDR speed); void setPull_Up_Down(GPIO_PULL_UP_DOWN pull); void setAlternateFunction(GPIO_ALTERNATE_FUNCTION function); private: GPIO_TypeDef *portPtr; GPIO_Pin_t gpioPin; bool initState; uint32_t afrNumberRegister; }; } #endif /* __STM32H7A3_GPIO_HPP__ */
import React from 'react' import { Stack } from "@mui/material" import HomeIcon from '@mui/icons-material/Home'; // import the required icons import CodeIcon from '@mui/icons-material/Code'; import MusicNoteIcon from '@mui/icons-material/MusicNote'; import OndemandVideoIcon from '@mui/icons-material/OndemandVideo'; import SportsEsportsIcon from '@mui/icons-material/SportsEsports'; import LiveTvIcon from '@mui/icons-material/LiveTv'; import SchoolIcon from '@mui/icons-material/School'; import FitnessCenterIcon from '@mui/icons-material/FitnessCenter'; import CheckroomIcon from '@mui/icons-material/Checkroom'; import FaceRetouchingNaturalIcon from '@mui/icons-material/FaceRetouchingNatural'; import GraphicEqIcon from '@mui/icons-material/GraphicEq'; import DeveloperModeIcon from '@mui/icons-material/DeveloperMode'; import TheaterComedyIcon from '@mui/icons-material/TheaterComedy'; const categories = [ { name: 'New', icon: <HomeIcon /> }, { name: 'JS Mastery', icon: <CodeIcon /> }, { name: 'Music', icon: <MusicNoteIcon /> }, { name: 'Movie', icon: <OndemandVideoIcon /> }, { name: 'Gaming', icon: <SportsEsportsIcon /> }, { name: 'Live', icon: <LiveTvIcon /> }, { name: 'Education', icon: <SchoolIcon /> }, { name: 'Sport', icon: <FitnessCenterIcon /> }, { name: 'Fashion', icon: <CheckroomIcon /> }, { name: 'Beauty', icon: <FaceRetouchingNaturalIcon /> }, { name: 'Podcast', icon: <GraphicEqIcon /> }, { name: 'Crypto', icon: <DeveloperModeIcon /> }, { name: 'Comedy', icon: <TheaterComedyIcon /> }, // other categories ... ]; const Sidebar = ({ selectedCategory, setSelectedCategory }) => { return ( <Stack direction={'row'} sx={{ overflowY: "auto", height: { sx: 'auto', md: '92vh' }, flexDirection: { md: 'column' } }}> {categories.map((category) => { return <button className='category-btn' onClick={()=>setSelectedCategory(category.name)} key={category.name} style={{ background: category.name === selectedCategory && '#FC1503', color: 'white' }}><span style={{ color: category.name === selectedCategory ? "white" : "red", marginRight: '15px' }}>{category.icon}</span> <span style={{ opacity: category.name === selectedCategory ? '1' : '0.8' }}>{category.name}</span> </button> })} </Stack> ) } export default Sidebar
import { useLang } from '@/store/languageStore'; import { useEffect, useState } from 'react'; type Props = { createdAt: string; // ISO 8601 날짜 문자열 }; const TimeAgo = ({ createdAt }: Props) => { const [timeAgo, setTimeAgo] = useState(''); const { lang } = useLang(); useEffect(() => { const calculateTimeAgo = () => { const createdDate = new Date(createdAt); const now = new Date(); const diffMs = now.getTime() - createdDate.getTime(); // 밀리초 차이 계산 const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); // 일 단위로 변환 const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); // 시간 단위 const diffMinutes = Math.floor(diffMs / (1000 * 60)); // 분 단위 if (diffMinutes < 1) { return lang === "en" ? "Just now" : "방금 전"; } else if (diffHours < 1) { return lang === "en" ? `${diffMinutes} minutes ago` : `${diffMinutes}분 전`; } else if (diffDays < 1) { return lang === "en" ? `${diffHours} hours ago` : `${diffHours}시간 전`; } else { return lang === "en" ? `${diffDays} days ago` : `${diffDays}일 전`; } }; setTimeAgo(calculateTimeAgo()); }, [createdAt]); return <p className="text-[12px] text-[#797C80]">{timeAgo}</p>; }; export default TimeAgo;
package bp.sys; /** 导入模式 */ public enum ImpModel { /** 不执行导入 */ None(0), /** 表格模式 */ Table(1), /** 按照Excel文件模式 */ ExcelFile(2), /** 单据模式 */ BillModel(3); public static final int SIZE = java.lang.Integer.SIZE; private int intValue; private static java.util.HashMap<Integer, ImpModel> mappings; private static java.util.HashMap<Integer, ImpModel> getMappings() { if (mappings == null) { synchronized (ImpModel.class) { if (mappings == null) { mappings = new java.util.HashMap<Integer, ImpModel>(); } } } return mappings; } private ImpModel(int value) { intValue = value; getMappings().put(value, this); } public int getValue() { return intValue; } public static ImpModel forValue(int value) { return getMappings().get(value); } }
import { createRouter, createWebHistory } from "vue-router"; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: "/", name: "home", components: { default: async () => await import("../views/HomeView.vue"), header: async () => await import("../components/reusables/headers/landingPage.vue"), }, }, { path: "/login", name: "login", components: { default: async () => await import("../views/LoginView.vue"), header: async () => await import("../components/reusables/headers/login.vue"), }, }, { path: "/signup", name: "signup", components: { default: async () => await import("../views/SignupView.vue"), header: async () => await import("../components/reusables/headers/login.vue"), }, }, { path: "/placeOrder", name: "placeorder", components: { default: async () => await import("../views/PlaceOrderView.vue"), header: async () => await import("../components/reusables/headers/login.vue"), }, }, { path: "/dashboard", name: "dashboard", redirect: (to) => "dashboard/orders", components: { header: async () => await import("../components/reusables/headers/platform2.vue"), default: async () => await import("../views/DashboardView.vue"), }, children: [ { path: "orders", name: "orders", component: async () => await import("../components/common/ordersTable.vue"), }, { path: "users", name: "users", component: async () => await import("../components/admin/usersTable.vue"), }, { path: "items", name: "items", component: async () => await import("../components/admin/itemsEditor.vue"), }, { path: "deliveries", name: "deliveries", component: async () => await import("../components/admin/locationsTable.vue"), }, { path: "profile", name: "profile", component: async () => await import("../components/common/profile.vue"), }, { path: "catalogue", name: "catalogue", component: async () => await import("../components/user/itemsViewer.vue"), }, { path: "locations", name: "locations", component: async () => await import("../components/user/deliveryTable.vue"), }, ], }, ], }); export default router;
// Motor driver test // ----------------------------------------------------------- #include <RPC.h> // to support 2nd CPU core #include <LiquidCrystal.h> // LCD screen #include <Servo.h> // servo library #include <FastLED.h> //wiring: // (PWM) Encoder // speed direction A B // Motor 1 = 2 52,53 00 00 // Motor 2 = 3 50,51 00 00 // Motor 3 = 4 25,24 00 00 // Motor 4 = 5 23,22 00 00 // L298N Motor Driver speed control int driver1motor1enA = 2; // Speed control for motor 1 int driver1motor2enB = 3; int driver2motor3enA = 4; // Speed control for motor 3 int driver2motor4enB = 5; // L298N Motor Driver 2 encoder int driver1motor1in1 = 52; // Direction control for Motor 1 int driver1motor1in2 = 53; // Direction control for Motor 1 int driver1motor2in3 = 50; int driver1motor2in4 = 51; int driver2motor3in1 = 25; // Direction control for Motor 3 int driver2motor3in2 = 24; // Direction control for Motor 3 int driver2motor4in3 = 23; int driver2motor4in4 = 22; int potentiometer = A0; int speed = 0; #define M1_ENCODER_A 2 // Motor 1 Encoder A #define M1_ENCODER_B 3 // Motor 1 Encoder B #define M2_ENCODER_A 7 // Motor 2 Encoder A #define M2_ENCODER_B 8 // Motor 2 Encoder B // setup LED Lights #define NUM_LEDS 144 #define DATA_PIN 6 CRGB leds[NUM_LEDS]; // setup start/stop buttons int redButtonPin = 65; // stop motors int greenButtonPin = 64; // start motors int blueButtonPin = 57; // start arm // ultrasonic distances float distanceFront = 0; float distanceLeft = 0; float distanceRight = 0; float distanceBack = 0; // lcd screen setup LiquidCrystal lcd(59, 61, 63, 58, 60, 62); unsigned long messageDelay = 0; // used to update screen once per second bool delayRunning = false; unsigned long DELAY_TIME = 1500; //distance sensor pins const int trig1Pin = 28; const int echo1Pin = 29; const int trig2Pin = 30; const int echo2Pin = 31; const int trig3Pin = 32; const int echo3Pin = 33; const int trig4Pin = 34; const int echo4Pin = 35; const int FRONT = 1; const int BACK = 2; const int LEFT = 3; const int RIGHT = 4; bool runWheels = false; String message = ""; //create servo objects Servo servo1; Servo servo2; Servo servo3; Servo servo4; Servo servo5; Servo servo6; const int servo1Pin = 40; const int servo2Pin = 41; const int servo3Pin = 42; const int servo4Pin = 43; const int servo5Pin = 44; const int servo6Pin = 45; //----------------------------------------------------------------------------- void setup() { RPC.begin(); //tell the lcd the display is 16 wide by 2 characters high lcd.begin(16, 2); lcd.clear(); messageDelay = millis(); delayRunning = true; // init LED lights FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); // Serial.begin(9600); // Serial.write("Staring motor test"); // setup motor on/off buttons pinMode(redButtonPin, INPUT_PULLUP); pinMode(greenButtonPin, INPUT_PULLUP); pinMode(blueButtonPin, INPUT_PULLUP); // setup distance sensors pinMode(trig1Pin, OUTPUT); pinMode(echo1Pin, INPUT); pinMode(trig2Pin, OUTPUT); pinMode(echo2Pin, INPUT); pinMode(trig3Pin, OUTPUT); pinMode(echo3Pin, INPUT); pinMode(trig4Pin, OUTPUT); pinMode(echo4Pin, INPUT); // Set motor speed control pins outputs pinMode(driver1motor1enA, OUTPUT); pinMode(driver1motor2enB, OUTPUT); pinMode(driver2motor3enA, OUTPUT); pinMode(driver2motor4enB, OUTPUT); // Set the motor direction control pinMode(driver1motor1in1, OUTPUT); pinMode(driver1motor1in2, OUTPUT); pinMode(driver1motor2in3, OUTPUT); pinMode(driver1motor2in4, OUTPUT); pinMode(driver2motor3in1, OUTPUT); pinMode(driver2motor3in2, OUTPUT); pinMode(driver2motor4in3, OUTPUT); pinMode(driver2motor4in4, OUTPUT); // Turn off motors - Initial state digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, LOW); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, LOW); digitalWrite(driver2motor4in4, LOW); // set encoder pins // pinMode(M1_ENCODER_A, INPUT); // pinMode(M1_ENCODER_B, INPUT); // pinMode(M2_ENCODER_A, INPUT); // pinMode(M2_ENCODER_B, INPUT); showMessage("Press Blue"); while (digitalRead(blueButtonPin) == HIGH) {} servoTest(); } void loop() { potentiometer = analogRead(A0); //speed = round(potentiometer / 4); // potentiometer returns 0 to 1023 speed = map(potentiometer, 0, 1023, 0, 255); distanceFront = getDistance(FRONT); distanceBack = getDistance(BACK); distanceLeft = getDistance(LEFT); distanceRight = getDistance(RIGHT); if (digitalRead(redButtonPin) == LOW) { runWheels = false; stopAllWheels(); } else if (digitalRead(greenButtonPin) == LOW) { runWheels = true; } showCurrentStatus(); if (runWheels == false) return; setAllMotorSpeed(speed); // run all wheels //moveForward(); // return; //moveLeft(); strafeRight(); delay(1500); stopAllWheels(); delay(3000); strafeLeft(); delay(1500); stopAllWheels(); runWheels = false; // speedControl(); //delay(1000); // directionControl(); // int a = digitalRead(M1_ENCODER_A); // int b = digitalRead(M1_ENCODER_B); // Serial.print(a * 5); // Serial.print(" "); // Serial.print(b * 5); // Serial.println(); //delay(1000); } void setAllMotorSpeed(int speed) { // For PWM maximum possible values are 0 to 255 if (speed < 0 || speed > 255) { return; } analogWrite(driver1motor1enA, speed); analogWrite(driver1motor2enB, speed); analogWrite(driver2motor3enA, speed); analogWrite(driver2motor4enB, speed); } void moveForward() { digitalWrite(driver1motor1in1, HIGH); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, HIGH); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, HIGH); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, HIGH); digitalWrite(driver2motor4in4, LOW); } void moveLeft() { digitalWrite(driver1motor1in1, HIGH); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, HIGH); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, HIGH); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, HIGH); digitalWrite(driver2motor4in4, LOW); } void strafeRight() { //strafeRight FORWARD REVERSE REVERSE FORWARD digitalWrite(driver1motor1in1, HIGH); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver2motor3in1, LOW); digitalWrite(driver2motor3in2, HIGH); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, HIGH); digitalWrite(driver2motor4in3, HIGH); digitalWrite(driver2motor4in4, LOW); } void strafeLeft() { //strafeLeft REVERSE FORWARD FORWARD REVERSE digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, HIGH); digitalWrite(driver2motor3in1, HIGH); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver1motor2in3, HIGH); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor4in3, LOW); digitalWrite(driver2motor4in4, HIGH); } void stopAllWheels() { digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, LOW); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, LOW); digitalWrite(driver2motor4in4, LOW); } // This function lets you control spinning direction of motors void directionControl() { // Set motors to maximum speed // For PWM maximum possible values are 0 to 255 analogWrite(driver1motor1enA, 200); analogWrite(driver1motor2enB, 200); //// this crashes the giga analogWrite(driver2motor3enA, 200); analogWrite(driver2motor4enB, 200); // try digital instead // digitalWrite(driver2motor3enA, 255); // digitalWrite(driver2motor4enB, 255); // Turn on motor A & B digitalWrite(driver1motor1in1, HIGH); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, HIGH); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, HIGH); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, HIGH); digitalWrite(driver2motor4in4, LOW); delay(2000); // Now change motor directions digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, HIGH); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, HIGH); digitalWrite(driver2motor3in1, LOW); digitalWrite(driver2motor3in2, HIGH); digitalWrite(driver2motor4in3, LOW); digitalWrite(driver2motor4in4, HIGH); delay(2000); // Turn off motors digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, LOW); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, LOW); digitalWrite(driver2motor4in4, LOW); } // This function lets you control speed of the motors void speedControl() { // Turn on motors digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, HIGH); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, HIGH); // digitalWrite(driver2motor3in1, LOW); // digitalWrite(driver2motor3in2, HIGH); // digitalWrite(driver2motor4in3, LOW); // digitalWrite(driver2motor4in4, HIGH); // Accelerate from zero to maximum speed for (int i = 0; i < 256; i++) { analogWrite(driver1motor1enA, i); analogWrite(driver1motor2enB, i); // analogWrite(driver2motor3enA, i); // analogWrite(driver2motor4enB, i); delay(20); } // Decelerate from maximum speed to zero for (int i = 255; i >= 0; --i) { analogWrite(driver1motor1enA, i); analogWrite(driver1motor2enB, i); // analogWrite(driver2motor3enA, i); // analogWrite(driver2motor4enB, i); delay(20); } // Now turn off motors digitalWrite(driver1motor1in1, LOW); digitalWrite(driver1motor1in2, LOW); digitalWrite(driver1motor2in3, LOW); digitalWrite(driver1motor2in4, LOW); digitalWrite(driver2motor3in1, LOW); digitalWrite(driver2motor3in2, LOW); digitalWrite(driver2motor4in3, LOW); digitalWrite(driver2motor4in4, LOW); } void showMessage(String message) { lcd.clear(); lcd.setCursor(0, 0); lcd.print(message); } void showCurrentStatus() { // has one second passed? // see here: https://www.instructables.com/Coding-Timers-and-Delays-in-Arduino/ //if ((millis() - nextDisplay) > 3000) return; if (delayRunning && ((millis() - messageDelay) < DELAY_TIME)) return; lcd.clear(); message = "D:" + String(distanceFront, 0) + "," + String(distanceBack, 0) + "," + String(distanceLeft, 0) + "," + String(distanceRight, 0); lcd.setCursor(0, 0); lcd.print(message); //move the cursor to the first space of the bottom row lcd.setCursor(14, 1); lcd.print(millis() / 1000); lcd.setCursor(0, 1); String motorMessage = "M:" + String(runWheels) + ",S:" + String(speed); lcd.print(motorMessage); // set the next update for one second from now //nextDisplay = millis() + 3000; messageDelay += DELAY_TIME; /* /// CLEANUP - Unused //set the cursor to the 0,0 position (top left corner) lcd.setCursor(0, 0); lcd.print("S:"); lcd.setCursor(2, 0); lcd.print(speed); lcd.setCursor(6, 1); lcd.print(runWheels); */ } void waitForBlueButtonPress() { while (digitalRead(blueButtonPin) == HIGH) {} } //RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR int getDistance(int side) { // FROM SIK Circuit 3B - https://learn.sparkfun.com/tutorials/sparkfun-inventors-kit-experiment-guide---v41/all#circuit-3b-distance-sensor float echoTime; //variable to store the time it takes for a ping to bounce off an object int calculatedDistance; //variable to store the distance calculated from the echo time int trigPin = 0; int echoPin = 0; if (side == FRONT) { trigPin = trig1Pin; echoPin = echo1Pin; } else if (side == BACK) { trigPin = trig2Pin; echoPin = echo2Pin; } else if (side == LEFT) { trigPin = trig3Pin; echoPin = echo3Pin; } else if (side == RIGHT) { trigPin = trig4Pin; echoPin = echo4Pin; } if (trigPin == 0) return -1; // shouldnt get here //send out an ultrasonic pulse that's 10ms long digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); //use the pulsein command to see how long it takes for the //pulse to bounce back to the sensor echoTime = pulseIn(echoPin, HIGH); //calculate the distance of the object that reflected the pulse //(half the bounce time multiplied by the speed of sound) calculatedDistance = round(echoTime / 148.0); //send back the distance that was calculated return calculatedDistance; } void servoTest() { showMessage("Servo5 15deg"); servo5.write(15); // degs servo5.attach(servo5Pin); delay(500); waitForBlueButtonPress(); showMessage("Servo4 90deg"); servo4.write(90); // degs servo4.attach(servo4Pin); delay(500); for (int i = 90; i >= 0; i -= 5) { servo4.write(i); delay(100); } waitForBlueButtonPress(); showMessage("Servo5 90deg"); for (int i = 15; i <= 90; i += 5) { servo5.write(i); delay(100); } waitForBlueButtonPress(); showMessage("Servo4 90deg"); for (int i = 0; i <= 90; i += 5) { servo4.write(i); delay(100); } showMessage("Press Servo3"); waitForBlueButtonPress(); servo3.write(0); // degs servo3.attach(servo3Pin); // pin delay(2000); for (int i = 0; i <= 90; i += 5) { servo3.write(i); delay(100); } servo1.write(120); servo1.attach(servo1Pin); for (int i = 120; i <= 180; i += 5) { servo1.write(i); delay(100); } //------------------------------------------------------------------ Serial.println("Starting Shutdown routine."); for (int i = 90; i >= 0; i -= 5) { servo3.write(i); delay(100); } for (int i = 90; i <= 180; i += 5) { servo4.write(i); delay(100); } } //----------------------------------------------------------------------------- // LED LIGHTS void blackAllLeds() { for (int dot = 0; dot < NUM_LEDS; dot++) { leds[dot] = CRGB::Black; } FastLED.show(); } void showAllLeds() { for (int dot = 0; dot < NUM_LEDS; dot++) { leds[dot] = CRGB::Blue; } FastLED.show(); } void showSingleLED(int ledId) { leds[ledId] = CRGB::Red; FastLED.show(); delay(2000); } void initBlack() { // Set the first led back to black for 1 second leds[0] = CRGB::Black; FastLED.show(); delay(1000); } void initBlack2() { // Set the first led back to black for 1 second leds[0] = CRGB::Black; leds[5] = CRGB::Black; FastLED.show(); delay(1000); } void runXylon() { for (int dot = 0; dot < NUM_LEDS; dot++) { leds[dot] = CRGB::Blue; FastLED.show(); // clear this led for the next time around the loop leds[dot] = CRGB::Black; delay(30); } for (int dot = NUM_LEDS; dot >= 0; dot--) { leds[dot] = CRGB::Blue; FastLED.show(); // clear this led for the next time around the loop leds[dot] = CRGB::Black; delay(30); } } void runXylon2() { Serial.println("--------------------------------------------"); Serial.println("Xylon2 starting"); for (int dot = 0; dot < NUM_LEDS; dot++) { leds[dot - 1] = CRGB::Red; leds[dot] = CRGB::Blue; leds[dot + 5] = CRGB::Green; FastLED.show(); // clear this led for the next time around the loop leds[dot - 1] = CRGB::Black; leds[dot] = CRGB::Black; leds[dot + 5] = CRGB::Black; delay(30); } for (int dot = NUM_LEDS; dot >= 6; dot--) { leds[dot - 5] = CRGB::Green; leds[dot] = CRGB::Blue; leds[dot + 1] = CRGB::Red; FastLED.show(); // clear this led for the next time around the loop leds[dot - 5] = CRGB::Black; leds[dot] = CRGB::Black; leds[dot + 1] = CRGB::Black; delay(30); } Serial.println("Xylon2 done"); } ////
import * as React from "react"; import { render } from "react-dom"; import { test_backend } from "../../declarations/test_backend"; const MyHello = () => { const [num1, setNum1] = React.useState(0); const [num2, setNum2] = React.useState(0); const [result, setResult] = React.useState(0); async function doGreet() { const greeting = await test_backend.greet(name); setMessage(greeting); } function _num1(event){ setNum1(event.target.value); } function _num2(event){ setNum2(event.target.value); } // function _add(){ // setResult(num1+num2); // } async function _add() { var _result = await test_backend.add(num1,num2); setResult(_result); } async function _sub() { var _result = await test_backend.sub(num1,num2); setResult(_result); } async function _mul() { var _result = await test_backend.mul(num1,num2); setResult(_result); } async function _div() { var _result = await test_backend.div(num1,num2); setResult(_result); } return ( <div> <h3>Enter the first number : <input type="number" onChange={_num1} placeholder='Number 1'></input></h3><br/> <h3>Enter the second number : <input type="number" onChange={_num2} placeholder='Number 2'></input></h3><br/><br/> <button onClick={_add}>Addition</button> <button onClick={_sub}>Subtraction</button> <button onClick={_mul}>Multiplication</button> <button onClick={_div}>Division</button> <br/><br/> <h1>Output ::: {result}</h1> </div> ); }; render(<MyHello />, document.getElementById("app"));
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" type="image/x-icon" href="./favicon.ico"> <title> SIM - TP4 </title> <!-- CDN libreria tablas --> <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css"> <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-alpine.css"> <!-- CDN bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">SIM - TP 4 - grupo 2</a> </div> </nav> <button class="btn btn-primary mx-2 my-2" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">Integrantes</button> <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel"> <div class="offcanvas-header"> <h5 id="offcanvasRightLabel">Integrantes:</h5> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body"> <p> Cargnelutti, Gaston - 69519 </p> <p> Carracedo, Lautaro - 73143 </p> <p> Herrero, Marcos - 82617 </p> <p> Ledesma, Lisandro - 73153 </p> <p> Merlini Bravo, Francisco - 81211 </p> </div> </div> <hr> <a class="mx-2 btn btn-primary" data-bs-toggle="collapse" href="#collapseMontecarlo" role="button" aria-expanded="false" aria-controls="collapseExample"> Simulacion de Montercarlo </a> <div class="collapse" id="collapseMontecarlo"> <div class="container-fluid"> <hr> <label style="display: block;" for="time-sim">Cantidad de partidas (X)</label> <input id="time-sim" placeholder="Ej: 100" style="margin: 0.5em;" type="number" /> <label style="display: block;" for="n">Cantidad de rondas de una partida (N)</label> <input id="n" placeholder="Cantidad de números" style="margin: 0.5em;" type="number" /> <hr> <p><b> Distribucion de probabilidad de la primer tirada </b></p> <label style="display: block;" for="prob7-1tirada">Probabilidad de tirar 7 pinos:</label> <input id="prob7-1tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.12" /> <label style="display: block;" for="prob8-1tirada">Probabilidad de tirar 8 pinos:</label> <input id="prob8-1tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.15"/> <label style="display: block;" for="prob9-1tirada">Probabilidad de tirar 9 pinos:</label> <input id="prob9-1tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.18"/> <label style="display: block;" for="prob10-1tirada">Probabilidad de tirar 10 pinos:</label> <input id="prob10-1tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.55"/> <hr> <p><b> Distribucion de probabilidad de la segunda tirada </b></p> <table> <tr> <td><strong>Si en la primera tanda se tiraron 7...</strong></td> <td><strong>Si en la primera tanda se tiraron 8...</strong></td> <td><strong>Si en la primera tanda se tiraron 9...</strong></td> </tr> <tr> <td> <label style="display: block; margin-right: 60px;" for="prob0-7tirados-2tirada">Probabilidad de tirar 0 pinos en la segunda tirada:</label> <input id="prob0-7tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.02"/> </td> <td> <label style="display: block; margin-right: 60px;" for="prob0-8tirados-2tirada">Probabilidad de tirar 0 pinos en la segunda tirada:</label> <input id="prob0-8tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.04"/> </td> <td> <label style="display: block; margin-right: 60px;" for="prob0-9tirados-2tirada">Probabilidad de tirar 0 pinos en la segunda tirada:</label> <input id="prob0-9tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.06" /> </td> </tr> <tr> <td> <label style="display: block; margin-right: 60px;" for="prob1-7tirados-2tirada">Probabilidad de tirar 1 pinos en la segunda tirada:</label> <input id="prob1-7tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number"value="0.10" /></td> <td> <label style="display: block; margin-right: 60px;" for="prob1-8tirados-2tirada">Probabilidad de tirar 1 pinos en la segunda tirada:</label> <input id="prob1-8tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.20"/> </td> <td> <label style="display: block; margin-right: 60px;" for="prob1-9tirados-2tirada">Probabilidad de tirar 1 pinos en la segunda tirada:</label> <input id="prob1-9tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.94"/> </td> </tr> <tr> <td> <label style="display: block; margin-right: 60px;" for="prob2-7tirados-2tirada">Probabilidad de tirar 2 pinos en la segunda tirada:</label> <input id="prob2-7tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.45"/> </td> <td> <label style="display: block; margin-right: 60px;" for="prob2-8tirados-2tirada">Probabilidad de tirar 2 pinos en la segunda tirada:</label> <input id="prob2-8tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.76"/> </td> </tr> <tr> <td> <label style="display: block; margin-right: 60px;" for="prob3-7tirados-2tirada">Probabilidad de tirar 3 pinos en la segunda tirada:</label> <input id="prob3-7tirados-2tirada" placeholder="%" style="margin: 0.5em;" type="number" value="0.43"/> </tr> </table> <hr> <p><b> Puntajes </b></p> <label style="display: block;" for="puntaje-primertiro10">Puntaje por tirar 10 pinos en el primer tiro</label> <input id="puntaje-primertiro10" placeholder="Puntaje" style="margin: 0.5em;" type="number" value="20"/> <label style="display: block;" for="puntaje-dostiros10">Puntaje por tirar 10 pinos con dos tiros</label> <input id="puntaje-dostiros10" placeholder="Puntaje" style="margin: 0.5em;" type="number" value="15"/> <label style="display: block;" for="puntaje-a-alcanzar">Puntaje a obtener al cabo de N rondas</label> <input id="puntaje-a-alcanzar" placeholder="Puntaje" style="margin: 0.5em;" type="number" value="120"/> <hr> <p><b> Filas a mostrar </b></p> <label style="display: block;" for="sim-desde">Desde:</label> <input id="sim-desde" placeholder="Desde" style="margin: 0.5em;" type="number" /> <label style="display: block;" for="sim-hasta">Hasta:</label> <input id="sim-hasta" placeholder="Hasta" style="margin: 0.5em;" type="number" /> <hr> <button type="button" class="btn btn-success" id="btnSimular">Simular</button> <button type="button" class="btn btn-danger" id="btnSimDel">Reiniciar</button> <hr> </div> </div> <div class="row justify-content-center"> <div class="col-11"> <div id="gridVariable" class="ag-theme-alpine my-2" style="height: 500px; width: 100%;"></div> <button hidden="hidden" id="btnExportToExcelRandVar" class="btn btn-info" style="margin-bottom: 5px; font-weight: bold">Exportar a Excel</button> </div> </div> <script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.js"></script> <script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.noStyle.js"></script> <script src="https://unpkg.com/ag-grid-enterprise@27.1.0/dist/ag-grid-enterprise.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <script src="https://cdn.plot.ly/plotly-1.5.0.min.js"></script> <script src="https://cdn.plot.ly/plotly-latest.js" charset="utf-8"></script> <!--<script type="module" src="./Generadores/normal.js"></script> <script type="module" src="./Generadores/uniforme.js"></script> <script type="module" src="./Generadores/exponencial.js"></script>--> <script type="module" src="./montecarlo.js"></script> </body> </html>
<?php /** * General html rendering functions. * * SAM-4445: Apply TextFormatter * * @copyright 2021 Bidpath, Inc. * @author Igors Kotlevskis * @package com.swb.sam2 * @version SVN: $Id: $ * @since May 20, 2021 * file encoding UTF-8 * * Bidpath, Inc., 269 Mt. Hermon Road #102, Scotts Valley, CA 95066, USA * Phone: ++1 (415) 543 5825, &lt;info@bidpath.com&gt; */ namespace Sam\Core\Transform\Html; use Sam\Core\Service\CustomizableClass; use Sam\Core\Transform\Text\TextTransformer; /** * Class HtmlRenderer * @package Sam\Core\Transform\Text */ class HtmlRenderer extends CustomizableClass { public const CUT_WITH_CLARIFICATION_TPL = '<span title="%s">%s...</span>'; /** * Class instantiation method * @return $this */ public static function new(): static { return parent::_new(self::class); } /** * Replace all <br\> html tags with "\n" (new line symbol) * @param string $string * @return string */ public function br2nl(string $string): string { $newLineChar = chr(13) . chr(10); return preg_replace('/<br\s*\/?\s*>/i', $newLineChar, $string); } /** * Cut input length according limit and locate it in template, where the second placeholder is replaced by full input. * @param string $input * @param int $limit * @param string $template * @return string */ public function cutWithClarification( string $input, int $limit, string $template = self::CUT_WITH_CLARIFICATION_TPL ): string { if (mb_strlen($input) <= $limit) { return ee($input); } return sprintf( $template, ee($input), ee(TextTransformer::new()->cut($input, $limit)) ); } /** * Decode HTML entity. * See list of all HTML entities: https://www.freeformatter.com/html-entities.html * * @param string $string * @return string */ public function decodeHtmlEntity(string $string): string { return html_entity_decode($string, ENT_QUOTES | ENT_XML1 | ENT_HTML401 | ENT_XHTML | ENT_HTML5, 'UTF-8'); } /** * Convert all windows/linux line breaks into HTML line breaks * @param string $line string * @return string */ public function newlinesToHtmlBreaks(string $line): string { $pattern = mb_check_encoding($line, 'UTF-8') ? '/\R/u' : '/\R/'; return preg_replace($pattern, '<br/>', $line); } /** * Construct <img> html tag with attributes * @param string $tag - full url or relative path * @param array $attributes * @return string */ public function makeImgHtmlTag(string $tag, array $attributes = []): string { // no 'img' tag check if ($tag !== '' && $tag !== 'img') { return ''; } $output = ''; if ( $tag === 'img' && empty($attributes['src']) ) { // <img /> tag should contain "src" attribute return $output; } $props = []; ksort($attributes); foreach ($attributes as $key => $value) { $props[] = "{$key}=\"{$value}\""; } $attributeList = implode(' ', $props); $output = "<img {$attributeList} />"; return $output; } /** * Strip HTML tags, replace <br/> with new line char and decode HTML entities related to quotes. * See list of all HTML entities: https://www.freeformatter.com/html-entities.html * * @param string $string * @param string $charset * @return string */ public function replaceTags(string $string, string $charset = 'UTF-8'): string { return strip_tags(html_entity_decode($this->br2nl($string), ENT_QUOTES, $charset)); } }
package com.preran.BlogPost2.controllers; import com.preran.BlogPost2.entites.Comment; import com.preran.BlogPost2.exceptions.CustomResponse; import com.preran.BlogPost2.models.CommentDto; import com.preran.BlogPost2.services.CommentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.security.Principal; @RestController @RequestMapping("/api/comment") public class CommentController { @Autowired public CommentService commentService; @PostMapping("/add/{postId}") public ResponseEntity<CommentDto> createComment( @RequestBody CommentDto commentDto, @PathVariable long postId, Principal principal ) { String loggedInUsername = principal.getName(); commentDto.setCommenterName(loggedInUsername); CommentDto createdComment = this.commentService.createComment(commentDto, postId); return new ResponseEntity<>(createdComment, HttpStatus.CREATED); } @GetMapping("/delete/{commentId}") public ResponseEntity<?> deleteComment(@PathVariable long commentId, Principal principal) { String loggedInUsername = principal.getName(); Comment commentToBeDeleted = commentService.findById(commentId); String authorUsername = commentToBeDeleted.getCommenterName(); if (!loggedInUsername.equals(authorUsername)) { return new ResponseEntity<>( "You are not allowed to delete another user's comment", HttpStatus.FORBIDDEN ); } this.commentService.deleteComment(commentId); return new ResponseEntity<>( new CustomResponse("Deleted Successfully", true), HttpStatus.OK ); } }
#class to handle series(seasons) information and searching thereof class Series: def __init__(self, title: str, seasons: int, genres: list): self.title = title self.seasons = seasons self.genres = genres self.ratings = [] def __str__(self): if not self.ratings: ratings_string = "no ratings" else: ratings_string = f"{len(self.ratings)} ratings, average {(sum(self.ratings) / len(self.ratings)):.1f} points" genre_list = self.genres genre_string = ", ".join(genre_list) return f"{self.title} ({self.seasons} seasons)\ngenres: {genre_string}\n{ratings_string}" # Adds a rating between 0 and 5 to any series object. def rate(self, rating: int): self.ratings.append(rating) # Allows searching through a list of series. def minimum_grade(rating: float, series_list: list): results = [] for series in series_list: grade = sum(series.ratings) / len(series.ratings) if grade >= rating: results.append(series) return results # Allows searching through a list of series. def includes_genre(genre: str, series_list: list): results = [] for series in series_list: if genre in series.genres: results.append(series) return results
import { AccountComponent } from './components/account/account.component'; import { RoleGuard } from './guards/role.guard'; import { ReservationsComponent } from './components/reservations/reservations.component'; import { PlanningComponent } from './components/planning/planning.component'; import { ReservableComponent } from './components/reservable/reservable.component'; import { LoginComponent } from './components/auth/login/login.component'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { MainComponent } from './components/main/main.component'; import { MetaGuard } from './guards/meta-guard.guard'; const routes: Routes = [ { path:"login", component:LoginComponent, canActivate:[MetaGuard], data:{ auth:false }, }, { path:"", canActivate:[MetaGuard], data:{ auth:true, }, component:MainComponent, children:[ { path:"reservable/:type", component:ReservableComponent, canActivate:[RoleGuard], data:{ roles:[1,2] } }, { path:"planning", component:PlanningComponent, canActivate: [RoleGuard], data: { roles: [0,1, 2] } }, { path:"account", component:AccountComponent, canActivate:[RoleGuard], data:{ roles:[0,1,2] } }, { path:"reservation/:id", component:ReservationsComponent, canActivate:[RoleGuard], data:{ roles:[1,2] } }, { path:"", redirectTo:"planning", pathMatch:"full" } ] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import React, { useContext, useState } from "react"; import axios from "axios"; import { Link } from "react-router-dom"; import { toast } from "react-toastify"; import { UserContext } from "../context/userContext"; const Signup = () => { const { setLoggedInUser } = useContext(UserContext); const [loading, setLoading] = useState(false); const [foundUser, setFoundUser] = useState(null); const [userName, setUserName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [avatar, setAvatar] = useState(""); const handleVerify = async () => { try { setLoading(true); if (!email) return toast.error("Enter email address"); const data = { email }; const res = await axios.post("/user/email_verify", data); console.log(res); if (res.status === 220) { setFoundUser(res.data); } else { toast.error("Email already exsits"); } } catch (error) { console.error("error line:22", error); } setLoading(false); }; const handleSubmit = async (e) => { e.preventDefault(); setLoading(true); if (userName && email && avatar) { const reqData = new FormData(); reqData.set("userName", userName); reqData.set("email", email); reqData.set("password", password); reqData.set("avatar", avatar); const res = await axios.post("/user/signup", reqData); console.log(res.data); if (res.status === 224) { toast.success("User Created"); setLoggedInUser(res.data); } else { toast.warn(res.data.message); } } else { toast.error("Fill all fields"); } setLoading(false); }; return ( <> <div className="h-screen w-full grid place-items-center"> <form className="w-[320px] sm:w-[340px] p-5 mx-auto" onSubmit={handleSubmit} > <h2 className="text-4xl text-center font-bold mb-9"> Create your account </h2> {!foundUser && ( <> <div className="relative tracking-wide"> <input type="email" id="email" required className="peer border border-gray-300 focus:invalid:border-red-500 valid:border-green-500 rounded outline-0 block w-full h-[3rem] my-5 px-4 placeholder:text-transparent" placeholder="Email address" onChange={(e) => setEmail(e.target.value)} /> <label htmlFor="email" className="absolute left-3 -top-3 peer-focus:-top-3 peer-focus:left-3 peer-focus:text-sm bg-white px-1 peer-focus:peer-invalid:text-red-500 peer-valid:text-green-600 transition-all text-sm peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-3" > Email address </label> </div> </> )} {foundUser?.email ? ( <> <div className="relative tracking-wide"> <input type="email" id="email" required className="peer border invalid:border-red-500 valid:border-green-500 block w-full h-[3rem] rounded outline-0 my-5 px-4" placeholder="Email address" value={email} /> <label htmlFor="email" className="absolute left-3 -top-3 bg-white px-1 peer-invalid:text-red-500 text-green-600 text-sm" > Email address </label> </div> <div className="relative tracking-wide"> <input type="text" id="username" required className="peer border rounded valid:border-green-500 outline-0 block w-full h-[3rem] my-5 px-4 placeholder:text-transparent" placeholder="Username" onChange={(e) => setUserName(e.target.value)} /> <label htmlFor="username" className="absolute left-3 -top-3 peer-focus:-top-3 peer-focus:left-3 peer-focus:text-sm bg-white px-1 text-green-600 transition-all text-sm peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-3" > Username </label> </div> <div className="relative tracking-wide"> <input type="password" id="password" required minLength={8} className="peer border focus:invalid:border-red-500 valid:border-green-500 rounded outline-0 block w-full h-[3rem] my-5 px-4 placeholder:text-transparent" placeholder="Password" onChange={(e) => setPassword(e.target.value)} /> <label htmlFor="paassword" className="absolute left-3 -top-3 peer-focus:-top-3 peer-focus:left-3 peer-focus:text-sm bg-white px-1 peer-focus:peer-invalid:text-red-600 peer-valid:text-green-600 transition-all text-sm peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-placeholder-shown:top-3" > Password </label> </div> <input className="block w-full my-5 file:mr-5 file:px-4 file:py-1 file:rounded-full file:border-0 file:font-semibold file:bg-violet-50 file:text-violet-500 hover:file:bg-violet-100" type="file" required onChange={(e) => setAvatar(e.target.files[0])} /> <button type="submit" className="relative grid place-items-center w-full h-[3rem] rounded bg-green-500 text-white outline-0" > {loading ? ( <div className="absolute animate-ping w-9 h-6 rounded-full bg-green-700"></div> ) : ( <>Continue</> )} </button> </> ) : ( <> <Link onClick={handleVerify} className="relative grid place-items-center w-full h-[3rem] py-3 text-white bg-green-500 text-center rounded" > {loading ? ( <div className="absolute animate-ping w-9 h-6 rounded-full bg-green-700"></div> ) : ( <>Continue</> )} </Link> </> )} <p className="mt-5 py-2 text-center tracking-wide"> Alrady have an account?{" "} <Link className="text-green-600" to="/login"> Login </Link> </p> </form> </div> </> ); }; export default Signup;
const chai = require('chai'); const chaiHttp = require('chai-http'); chai.use(chaiHttp); const { expect } = chai; const request = require('supertest'); const app = require('../app.js'); const { reviewsValidationSchema } = require('../validations/checkReviews.js'); describe('Reviews CRUD Operations', () => { let reviewId; // Test for POST request to create a new review it('should create a new review', async () => { const newReview = { user_id: 1, event_id: 1, rating: 5, comment: 'Great event!', created_at: new Date().toISOString() }; const res = await request(app) .post('/reviews') .send(newReview); expect(res).to.have.status(201); expect(res.body).to.be.an('object'); reviewId = res.body.id; }); // Test for GET request to retrieve a review by ID it('should get a review by ID', async () => { const res = await request(app).get(`/reviews/${reviewId}`); expect(res).to.have.status(200); expect(res.body).to.be.an('object'); expect(res.body.id).to.equal(reviewId); }); // Test for PUT request to update a review it('should update a review', async () => { const updatedReview = { rating: 4, comment: 'Updated review comment.' }; const res = await request(app) .put(`/reviews/${reviewId}`) .send(updatedReview); expect(res).to.have.status(200); expect(res.body).to.be.an('object'); expect(res.body.id).to.equal(reviewId); }); // Test for DELETE request to delete a review it('should delete a review', async () => { const res = await request(app).delete(`/reviews/${reviewId}`); expect(res).to.have.status(200); expect(res.body).to.be.an('object'); expect(res.body.id).to.equal(reviewId); }); // Test for GET request to retrieve all reviews it('should get all reviews', async () => { const res = await request(app).get('/reviews'); expect(res).to.have.status(200); expect(res.body).to.be.an('array'); }); });
import numpy as np import matplotlib.pyplot as plt class MLP: def __init__(self, hidden_node=3): self.input_node = 1 self.hidden_node = hidden_node self.output_node = 1 self.w1 = np.random.rand(self.hidden_node, self.input_node) self.b1 = np.random.rand(self.hidden_node, 1) self.w2 = np.random.rand(self.output_node, self.hidden_node) self.b2 = np.random.rand(self.output_node, 1) def sigmoid(self, x): return 1 / (1 + np.exp(-x)) def d_sigmoid(self, x): return self.sigmoid(x) * (1 - self.sigmoid(x)) def train(self, train_x, train_y, alpha=0.1, max_iter=500): np.random.seed(0) input_node = self.input_node hidden_node = self.hidden_node output_node = self.output_node alpha = alpha max_iter = max_iter for iter in range(1, max_iter): for i in range(n_train): z1 = np.dot(self.w1, train_x[i].reshape(1, 1)) + self.b1 a1 = self.sigmoid(z1) z2 = np.dot(self.w2, a1) + self.b2 y_hat = z2 y_hat_list[i] = y_hat e = 0.5 * (train_y[i] - y_hat)**2 dy = -(train_y[i] - y_hat) dz2 = 1 dw2 = a1.T delta_w2 = dy * dz2 * dw2 delta_b2 = dy * dz da1 = self.w2.T dz1 = self.d_sigmoid(z1) dw1 = train_x[i].T delta_w1 = dy * dz2 * da1 * dz1 * dw1 delta_b1 = dy * dz2 * da1 * dz1 self.w2 -= alpha * delta_w2 self.b2 -= alpha * delta_b2 self.w1 -= alpha * delta_w1 self.b1 -= alpha * delta_b1 def predict(self, test_x): for i in range(n_test): z1 = np.dot(self.w1, test_x[i].reshape(1, 1)) + self.b1 a1 = self.sigmoid(z1) z2 = np.dot(self.w2, a1) + self.b2 y_hat = z2 y_hat_list[i] = y_hat return y_hat_list n_train = 20 train_x = np.linspace(0, np.pi * 2, n_train) train_y = np.sin(train_x) n_test = 60 test_x = np.linspace(0, np.pi * 2, n_test) test_y = np.sin(test_x) y_hat_list = np.zeros(n_test) mlp = MLP(hidden_node=4) mlp.train(train_x, train_y, max_iter=600) plt.plot(test_x, test_y, label='ground truth') y_hat_list = mlp.predict(test_x) plt.plot(test_x, y_hat_list, '-r', label='prediction') plt.legend() plt.show()
import { Transform, Type } from 'class-transformer'; import { toNumber } from '@credebl/common/cast.helper'; import { ApiProperty } from '@nestjs/swagger'; import { IsOptional, IsString } from 'class-validator'; import { Invitation } from '@credebl/enum/enum'; export class GetAllSentEcosystemInvitationsDto { @ApiProperty({ required: false }) @IsOptional() @Type(() => String) search = ''; @ApiProperty({ required: false }) @IsOptional() @Type(() => Number) @Transform(({ value }) => toNumber(value)) pageNumber = 1; @ApiProperty({ required: false }) @IsOptional() @Type(() => Number) @Transform(({ value }) => toNumber(value)) pageSize = 10; @ApiProperty({ required: false }) @IsOptional() @IsString() status = Invitation.PENDING; }
import React from 'react' import {RenderOptions, render } from '@testing-library/react' import { Provider } from 'react-redux'; import { BrowserRouter } from 'react-router-dom'; import { RootState, rootReducer } from '../Store/rootReducer'; import { createStore } from 'redux'; import { CATEGORIES_INITIAL_STATE } from '../Store/categories/categories.reducer'; import { USER_INITIAL_STATE } from '../Store/user/user.types'; import { CART_INITIAL_STATE } from '../Store/cart/cart.reducer'; interface WrapperProps { children: React.ReactNode } interface RenderWithProvidersOptions { preloadedState?: RootState; store?: any; renderOptions?: RenderOptions; } export function renderWithProviders( ui: React.ReactElement, { preloadedState = { user: USER_INITIAL_STATE, categories: CATEGORIES_INITIAL_STATE, cart: CART_INITIAL_STATE }, // Automatically create a store instance if no store was passed in store = createStore(rootReducer, preloadedState), ...renderOptions }: RenderWithProvidersOptions = {} ) { const Wrapper: React.FC<WrapperProps> = ({ children }) => { return ( <Provider store={store}> <BrowserRouter>{children}</BrowserRouter> </Provider> ); } // Return an object with the store and all of RTL's query functions return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }; }
import 'package:intl/intl.dart'; class HumanFormats { static String number( double number, [ int decimals = 0 ] ) { final formatterNumber = NumberFormat.compactCurrency( decimalDigits: decimals, symbol: '', locale: 'en' ).format(number); return formatterNumber; } static String shortDate( DateTime date ) { final format = DateFormat.yMMMEd('es'); return format.format(date); } }
# frozen_string_literal: true module Fights class Execute attr_reader :fight, :error_message def initialize(fight:) @fight = fight end def call raise 'Fight already started' unless fight.status_planned? ActiveRecord::Base.transaction do fight.status_in_progress! execute_fight_steps fight.status_ended! end true rescue StandardError => error @error_message = error.message false end private def execute_fight_steps gladiators = fight.gladiators the_winner = ChooseWinner.new(gladiators: gladiators).call the_loosers = gladiators - [the_winner] Finalize.new(fight: fight, the_winner: the_winner, the_loosers: the_loosers).call end end end
import { useState } from "react"; import { useParams } from 'react-router-dom'; import { FifteenthClassItem } from "../../components/FifteenthClassItem"; import { useTheme } from "../../hooks/useTheme"; import "./style.scss"; export function FifteenthClass() { /** REACT HOOKS **/ // (1) useState const [locations, setLocations] = useState([]); const [cep, setCep] = useState(""); // (2) useTheme const { theme } = useTheme(); // (3) useParams // const { id } = useParams() /** FUNCTIONS **/ function searchCep(cepReceived) { if (cepReceived.length === 8) { fetch(`https://viacep.com.br/ws/${cepReceived}/json`) .then(response => response.json() .then(address => { if (address.erro !== undefined) { console.log("Error!"); } else { // console.log("Success!"); registerAddress(address); } }) ) } } function registerAddress(address) { setLocations([...locations, address]); } function deleteLocation(currentLocation) { const locationList = locations.filter(location => location.cep != currentLocation.cep); setLocations(locationList); } return ( <div className={`fouteenth-class-component ${theme}`}> <form onSubmit={(cep) => searchCep(cep)}> <h1>Register addresses</h1> <div> <label htmlFor="">CEP</label> <input type="number" value={cep} aria-label="cep" onChange={event => setCep(event.target.value)} /> </div> <button aria-label="submit-button">Register</button> </form> <section className="locations"> { locations.map( (location, index) => ( <FifteenthClassItem key={index} data={location} onDeleteLocation={currentLocation => deleteLocation(currentLocation)} /> ) ) } </section> </div> ); }
import 'swiper/css'; import { Swiper } from 'swiper'; import { Controller, Manipulation, Navigation, Pagination } from 'swiper/modules'; export const swiper = function () { const listElements = Array.from(document.querySelectorAll('[swiper="component"]')); if (listElements.length === 0) return; // Make each instance unique const swiperElements = listElements.map((component, i) => { const instance = component.querySelector('.swiper'); if (!instance) return; instance.classList.add(`is-swiper-${i + 1}`); const btnNext = component.querySelector('.swiper-next'); const btnPrev = component.querySelector('.swiper-prev'); return { componentEl: component, instance: instance, btnNext: btnNext, btnPrev: btnPrev, }; }); const swiperInstances = []; const getSwiperTitles = function (componentEl) { const slides = componentEl.querySelectorAll('.swiper-slide'); if (!slides) return; const titles = []; slides.forEach((slide) => { const { title } = slide.dataset; if (!title) return; titles.push(title); }); return titles; }; // Create swiper swiperElements.forEach((component) => { swiperInstances.push(newSwiper(component)); }); function newSwiper(component) { const options = component.componentEl.getAttribute('swiper-options') || 1; const titles = getSwiperTitles(component.componentEl); const optionVariants = [ { modules: [Navigation, Manipulation, Controller], speed: 800, loop: false, grabCursor: true, spaceBetween: 24, centeredSlides: false, slidesPerView: 2, preventClicksPropagation: false, navigation: { nextEl: component.btnNext, prevEl: component.btnPrev, }, breakpoints: { // when window width is >= 320px 320: { slidesPerView: 1.125, spaceBetween: 24, }, // when window width is >= 480px 768: { slidesPerView: 1.5, spaceBetween: 24, }, // when window width is >= 992px 992: { slidesPerView: 1.5, spaceBetween: 24, }, }, slideActiveClass: 'swiper-active', }, { modules: [Pagination, Controller], speed: 800, loop: false, spaceBetween: 24, centeredSlides: false, slidesPerView: 2, pagination: { el: component.componentEl.querySelector('.tabs-1_pagination'), clickable: true, bulletClass: 'tabs-1_bullet', bulletActiveClass: 'tabs-1_bullet-active', renderBullet: function (index, className) { return `<div class="${className}">${titles[index]}</div>`; }, }, breakpoints: { // when window width is >= 320px 320: { slidesPerView: 1.125, spaceBetween: 24, }, // when window width is >= 480px 768: { slidesPerView: 1.5, spaceBetween: 24, }, // when window width is >= 992px 992: { slidesPerView: 1.5, spaceBetween: 24, }, }, slideActiveClass: 'swiper-active', slideToClickedSlide: true, }, ]; const swiper = new Swiper(component.instance, optionVariants[options - 1]); return swiper; } };
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ /** * Helper class for working with Workflow objects and processing the email messages that are triggered on a model */ class WorkflowEmailMessagesUtil { /** * @param Workflow $workflow * @param RedBeanModel $model * @param User $triggeredByUser */ public static function processAfterSave(Workflow $workflow, RedBeanModel $model, User $triggeredByUser) { foreach ($workflow->getEmailMessages() as $emailMessage) { try { if ($emailMessage->getEmailMessageRecipientFormsCount() > 0) { self::processEmailMessageAfterSave($workflow, $emailMessage, $model, $triggeredByUser); } } catch (Exception $e) { WorkflowUtil::handleProcessingException($e, 'application.modules.workflows.utils.WorkflowEmailMessagesUtil.processAfterSave'); } } } /** * @param EmailMessageForWorkflowForm $emailMessageForWorkflowForm * @param RedBeanModel $model * @param User $triggeredByUser */ public static function processOnWorkflowMessageInQueueJob(EmailMessageForWorkflowForm $emailMessageForWorkflowForm, RedBeanModel $model, User $triggeredByUser) { try { if ($emailMessageForWorkflowForm->getEmailMessageRecipientFormsCount() > 0) { $helper = new WorkflowEmailMessageProcessingHelper($emailMessageForWorkflowForm, $model, $triggeredByUser); $helper->process(); } } catch (Exception $e) { WorkflowUtil::handleProcessingException($e, 'application.modules.workflows.utils.WorkflowEmailMessagesUtil.processOnWorkflowMessageInQueueJob'); } } /** * @param Workflow $workflow * @param EmailMessageForWorkflowForm $emailMessage * @param RedBeanModel $model * @param User $triggeredByUser * @throws FailedToSaveModelException */ protected static function processEmailMessageAfterSave(Workflow $workflow, EmailMessageForWorkflowForm $emailMessage, RedBeanModel $model, User $triggeredByUser) { if ($emailMessage->sendAfterDurationInterval == 0) { $helper = new WorkflowEmailMessageProcessingHelper($emailMessage, $model, $triggeredByUser); $helper->process(); } else { $emailMessageData = SavedWorkflowToWorkflowAdapter:: makeArrayFromEmailMessageForWorkflowFormAttributesData(array($emailMessage)); $workflowMessageInQueue = new WorkflowMessageInQueue(); $workflowMessageInQueue->processDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($emailMessage->resolveNewTimeStampForDuration(time())); $workflowMessageInQueue->savedWorkflow = SavedWorkflow::getById((int)$workflow->getId()); $workflowMessageInQueue->modelClassName = get_class($model); $workflowMessageInQueue->modelItem = $model; $workflowMessageInQueue->serializedData = serialize($emailMessageData); $workflowMessageInQueue->triggeredByUser = $triggeredByUser; $saved = $workflowMessageInQueue->save(); if (!$saved) { throw new FailedToSaveModelException(); } } } /** * @param WorkflowMessageInQueue $workflowMessageInQueue * @param Workflow $workflow * @return EmailMessageForWorkflowForm */ public static function makeEmailMessageForWorkflowFormByQueueModelAndWorkflow( WorkflowMessageInQueue $workflowMessageInQueue, Workflow $workflow) { $moduleClassName = $workflow->getModuleClassName(); $emailMessageForWorkflowForm = new EmailMessageForWorkflowForm($moduleClassName::getPrimaryModelName(), $workflow->getType(), 0); $unserializedData = unserialize($workflowMessageInQueue->serializedData); $emailMessageForWorkflowForm->setAttributes(reset($unserializedData)); return $emailMessageForWorkflowForm; } } ?>
# PowerShell one-liner: Get eventlog Posted on [October 28, 2017October 30, 2017](https://www.powershellbros.com/powershell-one-liner-get-eventlog/) by [Pawel Janowicz](https://www.powershellbros.com/author/pawel-janowicz/) Use PowerShell one-liner to get eventlog details quickly and easily. In this article you will find several useful examples which will help you in daily operational tasks. ## Get-Eventlog The **Get-EventLog** cmdlet actually serves two purposes: it enables you to manage your event logs, and it also enables you to get at the events contained within those event logs. To get lognames list we just have to use parameter ` -list `: ```powershell # Get all lognames details and properties Get-Eventlog -List # Get "System" log details and properties Get-EventLog -List | Where-Object {$_.logdisplayname -eq "System"} ``` [![Get-EventLog](https://i0.wp.com/www.powershellbros.com/wp-content/uploads/2017/10/Get-EventLog-1.png?resize=589%2C279)](https://i0.wp.com/www.powershellbros.com/wp-content/uploads/2017/10/Get-EventLog-1.png)Get-EventLog Now when we know our **lognames** we can scan them using command parameters: ```powershell Get-EventLog -LogName System Get-EventLog -LogName Application -Newest 3 Get-EventLog -LogName System -Newest 3 | Format-List Get-EventLog -LogName System -Newest 3 | Select-Object * Get-EventLog -LogName System -Source Disk Get-EventLog -LogName System -Source NetLogon -Newest 3 | Out-GridView ``` During daily tasks we often need to specify time frames to search for specific log entry. To do this we can use the following examples: ```powershell # Time frame and entry type Get-EventLog -LogName System -After "09/28/2017" -Before "10/28/2017" Get-EventLog -LogName System -After "09/28/2017" -Before "10/28/2017" -EntryType Error Get-EventLog -LogName System -After "09/28/2017" -Before "10/28/2017" | Where-Object {$_.EntryType -like 'Error' -or $_.EntryType -like 'Warning'} # Last 1 hour Get-EventLog -LogName Application | Where-Object { $_.TimeGenerated -gt ((Get-Date).AddHours(-1)) } ``` Using ` Where-Object ` you can search for specific event id: ```powershell Get-EventLog -LogName "Windows PowerShell" | Where-Object {$_.EventID -eq 403} Get-EventLog -LogName Application -Source MSIInstaller | Where-Object {$_.EventID -eq '1034'} Get-EventLog -LogName System -Newest 100 | Where-Object {$_.EventId -eq 6006} | Select-Object -first 5 ``` [![Get-EventLog](https://i0.wp.com/www.powershellbros.com/wp-content/uploads/2017/10/Get-EventLog.png?resize=690%2C128)](https://i0.wp.com/www.powershellbros.com/wp-content/uploads/2017/10/Get-EventLog.png)Get-EventLog Great thing about Get-EventLog command is that we can also scan remote machines: ```powershell Get-EventLog -ComputerName DC01 -LogName System -Source Disk Get-EventLog -ComputerName DC01,DC02,DC03 -LogName System -Source Disk | Format-Table -Wrap -AutoSize Get-EventLog -ComputerName (Get-Content -path "c:\temp\servers.txt") -LogName System -Source Disk | select-object -first 1 | Out-GridView -Title "Scan results" ``` ## Get-WinEvent Apart from ` Get-EventLog ` command you can also use ` Get-WinEvent `. The **Get-WinEvent** cmdlet gets events from event logs, including classic logs, such as the System and Application logs, and the event logs that are generated by the Windows Event Log technology introduced in Windows Vista. It also gets events in log files generated by Event Tracing for Windows (ETW). You can get all the providers for some logname on your local computer: ```powershell #Get Application event log providers (Get-WinEvent -ListLog Application).providernames #Get Application event log providers where name match "WMI" (Get-WinEvent -ListLog Application).providernames | Where-Object {$_ -like "*WMI*"} #Get events for providers "Microsoft-Windows-WMI" an format table (Get-WinEvent -ListProvider "Microsoft-Windows-WMI").events | Format-Table id, description -auto ``` Below you can find another great example how to find first 5 events about reboot information. This time ` FilterHashtable ` has been used to provide logname and id: ```powershell Get-WinEvent -FilterHashtable @{logname='System'; id=1074} | Select-Object timecreated,message -First 5 | Out-GridView ``` You can also use ` invoke-command ` to scan remote servers for some specific event id. In this example we will check failed logon attempts logs for user pawel.janowicz and we will scan events only from last 24hours – `(Get-Date).AddDays(-1)`. **EventID 4625:** An account failed to log on. ```powershell # Using -Computername parameter Get-WinEvent -ComputerName DC01 -FilterHashTable @{ LogName = ”Security”; ID = "4625"; StartTime = (Get-Date).AddDays(-1) } | Where-Object { ($_.Message -like "*pawel.janowicz*") } # Using invoke command Invoke-Command -ComputerName DC01 -ScriptBlock{Get-WinEvent -FilterHashTable @{ LogName = ”Security”; ID = "4625"; StartTime = (Get-Date).AddDays(-1) } | Where-Object { ($_.Message -like "*pawel.janowicz*") } } ``` There is a possibility to scan also custom event log like in this case – ADFS. In ` Where-Object ` you can specify multiple event ids and time frame for scanning: ```powershell # Max events 10000 and 247 event id Get-WinEvent -ProviderName 'ADFS' -MaxEvents 10000 | Where-Object { $_.ID -eq '247' } # Multiple event ids and time frame Get-WinEvent -ProviderName 'ADFS' | Where-Object { $_.ID -eq '247' -or $_.ID -eq '305' -or $_.ID -eq '306' -or $_.ID -eq '246' -and $_.TimeCreated -gt ((Get-Date).AddHours(-"8")) } ``` I hope that this was informative for you 🙂 See you in next articles.
/* * 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 servelet; import dao.ImagemDao; import dao.ProdutoDao; import entidade.Imagem; import entidade.Produto; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author marce */ public class VisualizarProduto extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet VisualizarProduto</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet VisualizarProduto at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // String nome = "novo"; // String nome = "Maquina de lavar3"; // teste para pegar variavel String nome = request.getParameter("nome"); // fim teste Produto produto = ProdutoDao.getProdutoPP(nome); request.setAttribute("produto",produto); request.setAttribute("nomeProduto",nome); List<Imagem> listaImagens = ImagemDao.getImagem(nome); Imagem imagens = listaImagens.get(0); request.setAttribute("produtoI",imagens); request.setAttribute("listaImagens",listaImagens); RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/visualizarProduto.jsp"); requestDispatcher.forward(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
// Copyright 2019 Google LLC // // 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. package com.google.codelab.currentplace; import android.Manifest; import android.text.SpannableString; import android.view.View.OnClickListener; import android.widget.AdapterView.OnItemClickListener; import android.widget.SearchView; import android.widget.SearchView.OnQueryTextListener; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.AutocompletePrediction; import com.google.android.libraries.places.api.model.LocationBias; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.model.PlaceLikelihood; import com.google.android.libraries.places.api.net.FetchPlaceRequest; import com.google.android.libraries.places.api.net.FetchPlaceResponse; import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest; import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse; import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest; import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse; import com.google.android.libraries.places.api.net.PlacesClient; import java.util.Arrays; import java.util.List; public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback { private GoogleMap mMap; // New variables for Current Place Picker private static final String TAG = "MapsActivity"; ListView lstPlaces; private PlacesClient mPlacesClient; private FusedLocationProviderClient mFusedLocationProviderClient; // The geographical location where the device is currently located. That is, the last-known // location retrieved by the Fused Location Provider. private Location mLastKnownLocation; // A default location (Sydney, Australia) and default zoom to use when location permission is // not granted. private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085); private static final int DEFAULT_ZOOM = 15; private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; private boolean mLocationPermissionGranted; // Used for selecting the current place. private static final int M_MAX_ENTRIES = 5; private Place[] mPlaces; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); // // PASTE THE LINES BELOW THIS COMMENT // // Set up the action toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Set up the views lstPlaces = findViewById(R.id.listPlaces); // Initialize the Places client String apiKey = getString(R.string.google_maps_key); Places.initialize(getApplicationContext(), apiKey); mPlacesClient = Places.createClient(this); mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); } /** * Populates the app bar with the menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); final SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (TextUtils.isEmpty(query)) { return false; } getAutoCompleteResults(query); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return super.onCreateOptionsMenu(menu); } private void getAutoCompleteResults(String query) { if (!mLocationPermissionGranted) { Log.w(TAG, "Permission is not yet granted."); return; } if (mLastKnownLocation == null) { Log.w(TAG, "Last location not known."); return; } // Build request FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder() .setOrigin(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude())) .setQuery(query) .build(); Task<FindAutocompletePredictionsResponse> task = mPlacesClient.findAutocompletePredictions(request); task.addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() { @Override public void onComplete(@NonNull Task<FindAutocompletePredictionsResponse> task) { FindAutocompletePredictionsResponse response = task.getResult(); if (!task.isSuccessful() || response == null) { Log.w(TAG, "Could not fetch predictions."); return; } List<AutocompletePrediction> predictions = response.getAutocompletePredictions(); fillPredictionsList(predictions); } }); } /** * Handles user clicks on menu items. */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_geolocate) { // COMMENTED OUT UNTIL WE DEFINE THE METHOD // Present the current place picker pickCurrentPlace(); return true; } // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } /** * Prompts the user for permission to use the device location. */ private void getLocationPermission() { /* * Request location permission, so that we can get the location of the * device. The result of the permission request is handled by a callback, * onRequestPermissionsResult. */ mLocationPermissionGranted = false; if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); } } /** * Handles the result of the request for location permissions. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { mLocationPermissionGranted = false; if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; } } } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); // // PASTE THE LINES BELOW THIS COMMENT // // Enable the zoom controls for the map mMap.getUiSettings().setZoomControlsEnabled(true); // Prompt the user for permission. getLocationPermission(); } private void fillPredictionsList(final List<AutocompletePrediction> predictions) { SpannableString[] items = new SpannableString[predictions.size()]; for (int i = 0; i < items.length; i++) { items[i] = predictions.get(i).getPrimaryText(null); } ArrayAdapter<SpannableString> placesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); lstPlaces.setAdapter(placesAdapter); lstPlaces.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AutocompletePrediction prediction = predictions.get(position); displayMarker(prediction); } }); } private void displayMarker(final AutocompletePrediction prediction) { String placeId = prediction.getPlaceId(); List<Place.Field> placeFields = Arrays.asList(Place.Field.NAME, Place.Field.LAT_LNG); FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields).build(); Task<FetchPlaceResponse> response = mPlacesClient.fetchPlace(request); response.addOnCompleteListener(new OnCompleteListener<FetchPlaceResponse>() { @Override public void onComplete(@NonNull Task<FetchPlaceResponse> task) { FetchPlaceResponse placeResponse = task.getResult(); if (!task.isSuccessful() || placeResponse == null) { Log.w(TAG, "Could not fetch place."); return; } Place place = placeResponse.getPlace(); // Add a marker for the selected place, with an info window // showing information about that place. mMap.addMarker(new MarkerOptions() .title(place.getName()) .position(place.getLatLng()) .snippet(prediction.getSecondaryText(null).toString())); // Position the map's camera at the location of the marker. mMap.moveCamera(CameraUpdateFactory.newLatLng(place.getLatLng())); } }); } /** * Calls the findCurrentPlace method in Google Maps Platform Places API. * Response contains a list of placeLikelihood objects. * Takes the most likely places and extracts the place details for access in other methods. */ private void getCurrentPlaceLikelihoods() { // Use fields to define the data types to return. List<Place.Field> placeFields = Arrays.asList(Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG); // Get the likely places - that is, the businesses and other points of interest that // are the best match for the device's current location. @SuppressWarnings("MissingPermission") final FindCurrentPlaceRequest request = FindCurrentPlaceRequest.builder(placeFields).build(); Task<FindCurrentPlaceResponse> placeResponse = mPlacesClient.findCurrentPlace(request); placeResponse.addOnCompleteListener(this, new OnCompleteListener<FindCurrentPlaceResponse>() { @Override public void onComplete(@NonNull Task<FindCurrentPlaceResponse> task) { FindCurrentPlaceResponse response = task.getResult(); if (task.isSuccessful() && response != null) { // Set the count, handling cases where less than 5 entries are returned. int count = Math.min(response.getPlaceLikelihoods().size(), M_MAX_ENTRIES); int i = 0; mPlaces = new Place[count]; for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) { Place currPlace = placeLikelihood.getPlace(); mPlaces[i] = currPlace; String currLatLng = (currPlace.getLatLng() == null) ? "" : currPlace.getLatLng().toString(); Log.i(TAG, "Place " + currPlace.getName() + " has likelihood: " + placeLikelihood.getLikelihood() + " at " + currLatLng); i++; if (i > (count - 1)) { break; } } // COMMENTED OUT UNTIL WE DEFINE THE METHOD // Populate the ListView fillPlacesList(); } else { Exception exception = task.getException(); if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; Log.e(TAG, "Place not found: " + apiException.getStatusCode()); } } } }); } /** * Get the current location of the device, and position the map's camera */ private void getDeviceLocation() { /* * Get the best and most recent location of the device, which may be null in rare * cases when a location is not available. */ try { if (mLocationPermissionGranted) { Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation(); locationResult.addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { // Set the map's camera position to the current location of the device. mLastKnownLocation = location; Log.d(TAG, "Latitude: " + mLastKnownLocation.getLatitude()); Log.d(TAG, "Longitude: " + mLastKnownLocation.getLongitude()); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM)); } else { Log.d(TAG, "Current location is null. Using defaults."); mMap.moveCamera(CameraUpdateFactory .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM)); } getCurrentPlaceLikelihoods(); } }); } } catch (Exception e) { Log.e("Exception: %s", e.getMessage()); } } /** * Fetch a list of likely places, and show the current place on the map - provided the user * has granted location permission. */ private void pickCurrentPlace() { if (mMap == null) { return; } if (mLocationPermissionGranted) { getDeviceLocation(); } else { // The user has not granted permission. Log.i(TAG, "The user did not grant location permission."); // Add a default marker, because the user hasn't selected a place. mMap.addMarker(new MarkerOptions() .title(getString(R.string.default_info_title)) .position(mDefaultLocation) .snippet(getString(R.string.default_info_snippet))); // Prompt the user for permission. getLocationPermission(); } } /** * When user taps an item in the Places list, add a marker to the map with the place details */ private AdapterView.OnItemClickListener listClickedHandler = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // position will give us the index of which place was selected in the array Place place = mPlaces[position]; String markerSnippet = place.getAddress(); if (place.getAttributions() != null) { markerSnippet += "\n" + TextUtils.join(" ", place.getAttributions()); } // Add a marker for the selected place, with an info window // showing information about that place. mMap.addMarker(new MarkerOptions() .title(place.getName()) .position(place.getLatLng()) .snippet(markerSnippet)); // Position the map's camera at the location of the marker. mMap.moveCamera(CameraUpdateFactory.newLatLng(place.getLatLng())); } }; /** * Display a list allowing the user to select a place from a list of likely places. */ private void fillPlacesList() { // Set up an ArrayAdapter to convert likely places into TextViews to populate the ListView String[] items = new String[mPlaces.length]; for (int i = 0; i < mPlaces.length; i++) { items[i] = mPlaces[i].getName(); } ArrayAdapter<String> placesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); lstPlaces.setAdapter(placesAdapter); lstPlaces.setOnItemClickListener(listClickedHandler); } }
package oauth import ( "context" "encoding/json" "fmt" "github.com/mohsenabedy91/polyglot-sentences/internal/core/config" "github.com/mohsenabedy91/polyglot-sentences/pkg/logger" "github.com/mohsenabedy91/polyglot-sentences/pkg/serviceerror" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "io" "net/http" ) type GoogleUserInfo struct { Id *string `json:"id"` Email string `json:"email"` FirstName *string `json:"given_name"` LastName *string `json:"family_name"` AvatarURL *string `json:"picture"` VerifiedEmail bool `json:"verified_email"` } type GoogleService interface { UserGoogleInfo(ctx context.Context, accessToken string) (*GoogleUserInfo, error) } type OAuth struct { log logger.Logger config config.Oauth } func New(log logger.Logger, config config.Oauth) *OAuth { return &OAuth{config: config, log: log} } func (r *OAuth) UserGoogleInfo(ctx context.Context, accessToken string) (*GoogleUserInfo, error) { var oauthCfg = oauth2.Config{ ClientID: r.config.Google.ClientId, ClientSecret: r.config.Google.ClientSecret, RedirectURL: r.config.Google.CallbackURL, Endpoint: google.Endpoint, } client := oauthCfg.Client( ctx, &oauth2.Token{ AccessToken: accessToken, }, ) response, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo") if err != nil { r.log.Error(logger.Google, logger.ExternalService, err.Error(), nil) return nil, serviceerror.NewServerError() } defer func(Body io.ReadCloser) { err = Body.Close() if err != nil { r.log.Error(logger.Google, logger.ExternalService, err.Error(), nil) } }(response.Body) if response.StatusCode == http.StatusOK { var userInfo *GoogleUserInfo body, _ := io.ReadAll(response.Body) if err = json.Unmarshal(body, &userInfo); err != nil { r.log.Error(logger.Google, logger.ExternalService, fmt.Sprintf("Error unmarshalling message, error: %v", err), nil) return nil, serviceerror.NewServerError() } return userInfo, nil } r.log.Error(logger.Google, logger.ExternalService, fmt.Sprintf("error: Unable to fetch user info. Status Code: %s", response.Status), nil) return nil, serviceerror.NewServerError() }
Some Notes on the abc2midi Code ------------------------------- written by Seymour Shlien Abc2midi.txt - last updated 29 November 1999. This file provides an algorithmic description of the program abc2midi which converts an abc file into a midi file. The sources of abc2midi now comprising of 6700 lines of C code are contained in the following five files. parseabc.c is the front end which scans the abc file and invokes the appropriate event handler for each element it encounters (eg. bar lines, notes, chords etc.) It happens to be the front end for other programs such as abc2ps, yaps and abc2abc. store.c contains all the event handlers which are invoked from parseabc. It converts the abc file into an internal representation described later in this file. genmidi.c converts this internal representation in an output midi file. queues.c are some utilities needed by genmidi. midifile.c is a library of public domain routines to read and write midifiles. In order to handle the multiple voices, parts, repeats and accompaniments which occur in abc files, the program performs multiple passes. The midi file stores the different voices, accompaniment and lyrics in individual tracks, so it is necessary to separates these parts prior to writing it to the midi file. If there are repeats in the music, something which appears only once in the abc file may be invoked twice when creating the output midi file. Parseabc.c ---------- The parser has been written so that it should be possible to write your own utility to handle the interpreted abc and link it with the parser code. This is very similar to the way that the midifilelib utilities work. The parser is designed so that it can write out almost exactly what it reads in. This means that in some cases the level of parsing is fairly primitive and it may be necessary to make use of routines in store.c which perform further processing on an item. In the first phase of parsing, the abc file is read and when, say, a note is encountered, the routine event_note() is called. The code for event_note is in the file store.c. Encountering an X in the abc generally causes a routine called event_X() to be called. An internal representation of the tune is built up and when the end of an abc tune is reached, a little bit of processing is done on the internal representation before the routine mywritetrack() is called to actually write out the MIDI file. The main program to abc2midi is contained in this file. Since this main program is used to start other programs such as yaps, it is fairly simple. It calls event_init defined in store.c which obtains all the user parameters (eg. input filename) and then executes the top level procedure, parsefile. The procedure parsefile (filename), opens the specified file (or stdin) and processes it one character at a time. The characters fill a line buffer which is passed to the procedure parseline whenever a linebreak character (eg. linefeed) is encountered. By doing it in this fashion, abc2midi is able to eliminate the extra carriage return which occurs in DOS files. The procedure parseline first checks for blank lines and comments. A blank line signals the end of the tune and the event_blankline is called to initiate the next stage in processing. If it is neither a comment or blank line, the procedure must decide whether the line is a a field line (eg."X:2") or part of a music body (eg. "|:C>DGz|..."). This is decided using the following rule. If the first letter begins with one of the field letter commands and is immediately followed by a ":", then it is treated as a field line and parsefield is called. Otherwise if a K: field line was already encountered (variable inbody set to 1), then it is treated as a line of music. If neither case is satisfied, then the line is intepreted as plain text. The procedure parsefield identifies the particular field line type and invokes the appropriate support function or event handler. If the field command occurs after the first K: line, then only certain field lines are legal. (For example it is illegal to place a T: (title) line after the K: (key signature) line.) The procedure parsemusic is the most complex procedure in the file and recognizes the musical notes, chords, guitar chord names, bar lines, repeats, slurs, ties, graces etc. Appropriate event handlers and support functions are called to complete the tasks of parsing the information. The parsenote function, for example, must check for decorations, accidentals, octave shifts as well as identifying the note and its determining its duration. Unlike the other software modules, parseabc.c contains few global variables. The global variables linenum, inhead, inbody, parsing, slur, parserinchord indicate which lexical component of the abc tune is being processed. store.c ------- This is the most complex module consisting of almost 3000 lines of source code. This module contains all of the event handlers which may be invoked in the file parseabc.c. The main purpose of these handlers are to build up an internal representation of the abc file in the global memory arrays. This is a complete representation which allows the regeneration of the abc file (eg. abc2abc) or the creation of a midi file. The internal representation is used by the genmidi.c software to create the midi file. Global variables The internal representation is stored in global variables defined at the beginning of the file. A description of the most important variables is given here. The music is stored in the four arrays, feature, pitch, num, denom. These arrays contains a list of the lexical components in the order that they have been encountered or created. The array "feature" identifies the type of component which can be one of the following enum features. SINGLE_BAR, DOUBLE_BAR, BAR_REP, REP_BAR, REP1, REP2, BAR1, REP_BAR2, DOUBLE_REP, THICK_THIN, THIN_THICK, PART, TEMPO, TIME, KEY, REST, TUPLE, NOTE, NONOTE, OLDTIE, TEXT, SLUR_ON, SLUR_OFF, TIE, TITLE, CHANNEL, TRANSPOSE, RTRANSPOSE, GRACEON, GRACEOFF, SETGRACE, SETC, GCHORD, GCHORDON, GCHORDOFF, VOICE, CHORDON, CHORDOFF, SLUR_TIE, TNOTE, LT, GT, DYNAMIC, LINENUM, MUSICLINE, MUSICSTOP, WORDLINE, WORDSTOP The array pitch[] mainly stores the pitch of a musical note, represented in the same manner as in a midi file. Thus middle C has a value of 60. The array has other uses, for example in a LINENUM feature it stores the line number relative to the X: reference command where the lexical feature has been detected. The LINENUM feature is useful when reporting warnings or errors in the input file. Duration of the notes are represented as a fraction, where the standard unit is defined by the L: command. If feature[n] is a NOTE, then num[n] and denom[n] contain the numerator and denominator of this fraction. Here is an example of the contents of these arrays for the following small file in the same order that they are stored in these arrays. X: 1 T: sample M: 2/4 L: 1/8 K: G |: C>D[EF]G |C4:| Feature Pitch Num Denom LINENUM 2 0 0 TITLE 0 0 0 LINENUM 3 0 0 LINENUM 4 0 0 LINENUM 5 0 0 DOUBLE_BAR 0 0 0 LINENUM 6 0 0 MUSICLINE 0 0 0 BAR_REP 0 0 0 NOTE 60 2 3 NOTE 62 1 3 CHORDON 0 0 0 NOTE 64 1 2 NOTE 66 1 2 CHORDOFF 0 1 2 NOTE 67 1 2 SINGLE_BAR 0 0 0 NOTE 60 2 1 REP_BAR 0 0 0 MUSIC_STOP 0 0 0 LINENUM 7 0 0 In order to support multivoice abc files in the form V:1 | ...| ...|.... V:2 | ...| ...|.... % V:1 | ...| ...|.... V:2 | ...| ...|.... etc. abc2midi maintains a voicecontext structure for each voice. This allows each voice to define its own key signature, default note length using internal field commands. There is a head voicecontext which is used when no voice field commands are defined in the abc file. The v[] array maintains a set of all voices active in the abc file and voicecount keeps track of the number of voices. Similarly, abcmidi maintains a list of all the part stored in the feature[], pitch[], num[] and denom[] arrays. All text items (eg. title and some other fields) are stored in char atext[][] arrays, so that they can be included in the midi output file. The textual information is repeated in each track of the output midi file. Following the conventions in the midi file, the program uses the quarter note as the standard unit of time instead of the whole note. In contrast, the standard length in the abc file is based on the whole note. For example in L:1/8, the fraction refers to a whole note. In order to convert time units to quarter notes, the numerator of the time specifications for note lengths is multiplied by 4 when it is added to the feature list. Table of contents of procedures in store.c getarg(option, argc, argv) - gets run time arguments. newvoice(n) - creates a new voice context. getvoicecontext() - finds or makes a voice context. clearvoicecontexts() - frees up the memory of the voice context event_init() - called by main program event_text(s) - called when a line of text is encountered. event_reserved(p) - handles reserved character codes H-Z. event_tex(s) - called whenever a TeX command is encountered. event_linebreak() - called whenever a newline character is encountered. event_startmusicline() - called for each new music line. event_endmusicline() - called at the end of each music line. event_eof() - end of abc file encountered. event_fatal_error(s) - reports fatal error. event_error(s) - reports an error. event_warning(s) - reports a potential problem. event_comment(s) - called whenever a comment is encountered. event_specific(package, s) - recognizes %%package s. event_startinline() - beginning of an in-music field command. event_closeinline() - finishes an in-music field command. event_field(k,f) - for R:, T: and any other unprocessed field commands. event_words(p) - processes a w: field command. char_out(list,out,ch) - for building up a parts list in a P: command. read_spec() - converts P:A(AB)3 to P:AABABAB etc. event_part(s) - handles a P: field. char_break() - reports error for improper voice change. event_voice(n,s) - processes a V: field. event_length(n) - recognizes L: field event_blankline - starts finishfile() procedure. event_refno(n) - recognizes X: event_tempo(n, a, b, rel) - recognizes Q: event_timesig(n, m) - recognizes M: event_key(sharps, s, minor, modmap, modmul) - recognizes K: event_graceon() - start of grace notes, "{" encountered. event_graceoff() - end of grace notes, "}" encountered. event_rep1() - handles first repeat indicated by [1. event_rep2() - handles second repeat indicated by [2. event_slur(t) -called when s encountered in abc. event_sluron(t) called when "(" is encountered in abc. event_sluroff(t) called when ")" is encountered in abc. slurtotie() - converts slur into tied notes. event_tie() - handles tie indication "-". event_rest(n,m) - processes rest indication Z or z. event_bar(type) - processes various types of bar lines. event_space() - space character encountered. Ignored here. event_linend(ch,n) - handles line continuation at end of line (eg. \). event_broken(type, mult) - handles >, <, >> etc. in abc. event_tuple(n,q,r) - handles triplets and general tuplets. event_chord() - called whenever + is encountered. marknotestart() - remembers last few notes in voice context. marknoteend() - this is used to process broken rhythms (eg. >). marknote() - called for single note (as opposed to chord). event_chordon() - called whenever [ is encountered. event_chordoff() - called whenever ] is encountered. splitstring(s,sep,handler) - splits string with separator sep. event_instuction(s) - handles !...! event. getchordnumber(s) - searches known chords for chord s. addchordname(s, len, notes) - adds chord name to known chord list. event_gchord(s) - handles guitar chords. event_handle_gchord(s) - handler for guitar chords. event_handle_instruction(s) - handles dynamic indications (eg. !ppp!). event_finger(p) - handles 1,2,...5 in guitar chord field (does nothing). hornp(num,denom) - modifies rhythm to hornpipe. event_note(roll, staccato, updown, accidental, mult, note, octave, n, m) doroll(note,octave,n,m,pitch) - applies roll to note. dotrill(note,octave,n,m,pitch) - applies trill to note. pitchof(note,accidental,mult,octave) -finds MIDI pitch value setmap(sf,map,mult) - converts key signature to accidental map. altermap(v,modmap,modmul) - modifies accidental map. copymap(v) - sets up working accidental map at beginning of bar. addfeature(f,p,n,d) - places feature in internal tables. autoextend(maxnotes) - increase memory limits for feature arrays. textextend(maxstrings, stringarray) - resize array pointers to strings. myputc(c) - workaround for problems with PCC compiler. tiefix() - connect up tied notes. dotie(j,xinchord) - called in preprocessing stage to handle ties. addfrac(xnum,xdenom,a,b) - add a/b to the number of units in bar. applybroken(place, type, n) - adjust length of broken notes. brokenadjust() -adjust length of broken notes. applygrace() - assign lengths to grace notes. dograce() - assign lengths to grace notes. lenmul(n, a, b) - multiply num(n),denom(n) by a/b. zerobar() - start a new count of beats in the bar. delendrep() - remove bogus repeat. placeendrep(j) - patch up missing repeat. placestartrep(j) - patch up missing repeat. fixreps() - find and correct missing repeats in music. startfile() - initialization performed after an event_refno. tempounits(t_num, t_denom) - interprets Q: field. setbeat() - sets default gchord command for time signature. headerprocess() - called after the first K: field in tune. finishfile() - starts next stage of processing when end of tune is encountered. All the functions in this file respond to event calls from parseabc. Once the internal representation of the abc file is completed, the procedure finishfile is called to perform some clean up and create the midi file. An internal representation of the midi file is first created and then it is written onto the designated output file. As finishfile provides the link to the next module, genmidi.c, here is a brief description of what it does. proc finishfile performs several passes through the internal representation to clean up the graces (dograce), the tied notes (tiefix) and any unbalanced repeats. It then calls writetrack(i) for each midi track to create the internal midi representation and finally the midi representation is recorded in the output file. genmidi.c --------- The procedure finishfile described above, creates each midi track by calling the function writetrack which is defined here. To create a track from the internal representation, the program must find all the parts and put them in order with all the repeats. In addition, if it contains karaoke text, this too must be placed in a separate track. Any chordal accompaniment is generated from the guitar chord indications and placed in another track. For multivoice and multipart music, a voice may be missing in a particular part. If the voice is missing, the procedure fillvoice ensures that all voices remain properly aligned when the voice reappears in another part. Here is a simple road map to the important procedures included in this file. dodeferred is here used to handle any dynamic indications (eg. !ppp!) which may be contained in the file. The %%MIDI messages are stored in a atext string which is pointed to by the contents of the pitch[] array. checkbar is called each time a bar line is encountered and reports a warning if the wrong number of beats occur. Transitions between parts are handled by the procedure partbreak. There are a number of procedures for handling karoake text -- karaokestarttrack(), findwline(startline), getword(place,w), write_syllable(place) and checksyllables(). For the first track, the meter, tempo and key signature are recorded using the functions set_meter(n,m), write_meter(n,m), write_keysig(sf,mi). Chordal accompaniment is produced by the procedure dogchords(i). queues.c -------- For each midi note, it is necessary to send a note-on and a note-off instruction. When polyphonic music is played on the same track, keeping track of the time to issue a note-off instruction may get complicated. The procedures in this file are used to maintain a linked list for the notes to be turned off. The notes are put into the list in the order that they are encountered but the order in which to issue note-off commands is maintained by the links. As many as 50 notes playing simultaneously can be handled by the list. Addendum -------- The following section contains clarifications on various components of abc2midi. 29 June 2003 Treatment of octave shifts. The key signature field command K: has provision for shifting a note using either transpose= or octave= subcommands. Both of these functions operate quite differently and deserve some description especially for multivoiced tunes. The octave shift, is performed in event_note in store.c, using the cached value v.octaveshift which is stored in the global voicecontext structure, v. There is a structure for each voice in the abc file. Whenever a new V: command is encountered, event_voice (store.c) is invoked, which swaps the appropriate voices structure into the global v array using the function getvoicecontext(n). If getvoicecontext cannot find a cached structure for that voice, then a new voice structure is created and added to the linked list of voice structures. The v.octaveshift variable is updated by event_octave which is called by event_key (store.c) which is called by parsekey in parseabc.c (Comment: it is not too clear how an octave switch is handled in the middle of a repeat section. i.e. does the old value get restored when repeating.) (Description of transpose shift is in CHANGES July 1 2003.)
package com.green.di.diBasic4; import com.google.common.reflect.ClassPath; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Set; @Component class Car { @Resource Engine engine; @Resource Door door; @Override public String toString() { return "Car{" + "engine=" + engine + ", door=" + door + '}'; } } @Component class SportsCar extends Car {} @Component class Truck extends Car {} @Component class Engine {} @Component class Door {} class AppContext { Map map; // 객체 저장소 AppContext() { map = new HashMap(); doComponentScan(); doAutowired(); doResource(); } private void doResource() { // map에 저장된 객체의 iv 중에서 @Resource가 붙어있으면 map에서 iv의 타입에 맞는 객체를 찾아서 연결(객체의 주소를 iv에 저장) try { for(Object bean : map.values()) { for(Field fld : bean.getClass().getDeclaredFields()) { if(fld.getAnnotation(Resource.class) != null) { fld.set(bean, getBean(fld.getName())); } } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private void doAutowired() { // map에 저장된 객체의 iv 중에서 @Autowired가 붙어있으면 map에서 iv의 타입에 맞는 객체를 찾아서 연결(객체의 주소를 iv에 저장) try { for(Object bean : map.values()) { for(Field fld : bean.getClass().getDeclaredFields()) { if(fld.getAnnotation(Autowired.class) != null) { fld.set(bean, getBean(fld.getType())); } } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private void doComponentScan() { // 1. 패키지 내의 클래스 목록을 가져옴 // 2. 반복문으로 클래스를 하나씩 읽어와서 @Component가 붙어있는지 확인 // 3. @Component가 붙어있으면 객체를 생성해서 map에 저장 try { // 클래스의 정보를 확인 ClassLoader classLoader = AppContext.class.getClassLoader(); ClassPath classPath = ClassPath.from(classLoader); // 클래스의 목록을 가져옴 // getTopLevelClasses를 이용하여 패키지 이름을 적어주고 set으로 받음 Set<ClassPath.ClassInfo> set = classPath.getTopLevelClasses("com.green.di.diBasic4"); // for문을 이용하여 @Component가 있는지를 확인 for(ClassPath.ClassInfo classInfo : set) { Class clazz = classInfo.load(); Component component = (Component) clazz.getAnnotation(Component.class); // 만약 component가 null이 아니면 == @Component가 있음 if(component != null) { // uncapitalize를 이용하여 첫글자를 소문자로 변경하여 클래스 이름을 가져옴 String id = StringUtils.uncapitalize(classInfo.getSimpleName()); // map에 객체를 만들어서 저장 map.put(id, clazz.newInstance()); } } } catch (Exception e) { throw new RuntimeException(e); } } Object getBean(String key) { return map.get(key); } // key로 찾기 Object getBean(Class clazz) { for(Object obj : map.values()) { if(clazz.isInstance(obj)) { return obj; } } return null; } // type으로 찾기 } public class Main4 { public static void main(String[] args) throws Exception { AppContext ac = new AppContext(); Car car = (Car) ac.getBean("car"); Door door = (Door) ac.getBean(Door.class); Engine engine = (Engine) ac.getBean("engine"); // 수동 연결 // car.engine = engine; // car.door = door; System.out.println("car = " + car); System.out.println("engine = " + engine); System.out.println("door = " + door); } }
import React from 'react'; import { Easing } from 'react-native'; import PropTypes from 'prop-types'; import { SymbolLayer } from '../SymbolLayer'; import Animated from '../../utils/animated/Animated'; import { AnimatedPoint } from '../../classes'; class Annotation extends React.Component { static propTypes = { id: PropTypes.string.isRequired, animated: PropTypes.bool, animationDuration: PropTypes.number, animationEasingFunction: PropTypes.func, coordinates: PropTypes.arrayOf(PropTypes.number), onPress: PropTypes.func, children: PropTypes.any, style: PropTypes.any, icon: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]) }; static defaultProps = { animated: false, animationDuration: 1000, animationEasingFunction: Easing.linear }; constructor(props) { super(props); const shape = this._getShapeFromProps(props); this.state = { shape: props.animated ? new AnimatedPoint(shape) : shape }; this.onPress = this.onPress.bind(this); } componentDidUpdate(prevProps) { if (!Array.isArray(this.props.coordinates)) { this.setState({ shape: null }); return; } const hasCoordChanged = prevProps.coordinates[0] !== this.props.coordinates[0] || prevProps.coordinates[1] !== this.props.coordinates[1]; if (prevProps.animated !== this.props.animated || hasCoordChanged && (!this.state.shape || !this.props.animated)) { const shape = this._getShapeFromProps(this.props); this.setState({ shape: this.props.animated ? new AnimatedPoint(shape) : shape }); } else if (hasCoordChanged && this.props.animated && this.state.shape) { // flush current animations this.state.shape.stopAnimation(); this.state.shape.timing({ coordinates: this.props.coordinates, easing: this.props.animationEasingFunction, duration: this.props.animationDuration }).start(); } } onPress() { if (this.props.onPress) { this.props.onPress(); } } _getShapeFromProps() { let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; const lng = props.coordinates[0] || 0; const lat = props.coordinates[1] || 0; return { type: 'Point', coordinates: [lng, lat] }; } get symbolStyle() { if (!this.props.icon) { return undefined; } return Object.assign({}, this.props.style, { iconImage: this.props.icon }); } render() { if (!this.props.coordinates) { return null; } return /*#__PURE__*/React.createElement(Animated.ShapeSource, { id: this.props.id, ref: "source", onPress: this.onPress, shape: this.state.shape }, this.symbolStyle && /*#__PURE__*/React.createElement(SymbolLayer, { id: `${this.props.id}-symbol`, style: this.symbolStyle }), this.props.children); } } export default Annotation; //# sourceMappingURL=Annotation.js.map