row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
37,045
Rewrite this: When I was looking for a simple and free way to send transactional emails, I came across the option of sending emails via MailChannels with Cloudflare Workers. Since I send emails from various applications, I developed a simple application, worker-mailchannels, to simplify the setup and implement email sending via an API.
61f703151fbb3c386adbf4f7a127b7ca
{ "intermediate": 0.5052950382232666, "beginner": 0.3076643943786621, "expert": 0.1870405673980713 }
37,046
2)Нужно отсортировать введённую строку по длине слов, а затем вывести отсортированную строку. Напиши алгоритм и программу, можно использовать только такие команды ассемблера: add, sub, mul, imul, jmp, jne, jcxz, jecxz, jg, jnle, jge, jnl, jl, jnge, jle, jng, ja, jnbe, jae, jnb, jb, jnae, jbe, jna, jz, jnz, jc, jnc, jo, jno, js, jns, jp, jnp и особенно: movsb, movsw, movsd, cmpsb, cmpsw, cmpsd, scasb, scasw, scasd, stosb, stows, stosd, lodsb, lodsw, lodsd При этом сама программа начинается так: #include<stdio.h> #include"conio.h" #include <iostream> using namespace std; int main() { char ch; char source[28] = "send string", dest[28] = " "; int ln1; short cch; int i; _asm {
fde0e2635ea69228b237e696d6107faa
{ "intermediate": 0.2927298843860626, "beginner": 0.5173740386962891, "expert": 0.1898961067199707 }
37,047
hi
6513f34c7965bea80716ac35f9cc20b9
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,048
export default class CompresseurImage{ // taille max en mb private static MAX_SIZE = 4; private static MAX_WIDTH = 1000; private static MAX_HEIGHT = 1000; public static compress(file: File) : Promise<File>{ } } complètes mon code
589d12323d354234149b8245af17c146
{ "intermediate": 0.32465341687202454, "beginner": 0.36042359471321106, "expert": 0.31492307782173157 }
37,049
I want to design a website with the name Adidas using HTML, CSS, and JS. I want the site logo with the site name on the left side, knowing that I want the site logo clearly and in writing. I want the site menu to be in the middle of the site, and I want the site background to be black, and there is a glass shape in the middle of the page. Content with the addition of a footer at the end of the site with data such as mobile number, address, work hours, and social media sites.
ed2f5fbd798c2f6c21dbb4604fc20406
{ "intermediate": 0.44190508127212524, "beginner": 0.2835245430469513, "expert": 0.27457040548324585 }
37,050
HTML: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Adidas</title> <link rel=“stylesheet” href=“styles.css”> </head> <body> <header> <div class=“logo”> <img src=“logo.png” alt=“Adidas Logo”> <h1>Adidas</h1> </div> <nav> <ul> <li><a href=“#”>Home</a></li> <li><a href=“#”>Products</a></li> <li><a href=“#”>About</a></li> <li><a href=“#”>Contact</a></li> </ul> </nav> </header> <main> <div class=“glass-shape”></div> <!-- Add your content here --> </main> <footer> <div class=“footer-content”> <ul> <li><strong>Phone:</strong> 123-456-7890</li> <li><strong>Address:</strong> 123 Street, City, Country</li> <li><strong>Working Hours:</strong> Mon-Fri: 9AM-6PM</li> </ul/> <div class=“social-media”> <a href=“#”><img src=“facebook.png” alt=“Facebook”></a> <a href=“#”><img src=“instagram.png” alt=“Instagram”></a> <a href=“#”><img src=“twitter.png” alt=“Twitter”></a> </div> </div> </footer> </body> </html> اريد ان اعرف ما الخطأ
948279f416b76670af68ea830dddeeeb
{ "intermediate": 0.13370637595653534, "beginner": 0.7270475029945374, "expert": 0.13924603164196014 }
37,051
Are you live?
c09018787a466295c832c8dece601aca
{ "intermediate": 0.402188241481781, "beginner": 0.29503166675567627, "expert": 0.3027801215648651 }
37,052
When import something in angular, example: @import '…/…/…/shared/variables'; But shared folder in the root folder (src folder), how can I just @import '@/shared/variables';
eb2c85007a157b5b0a8ea8a941584de9
{ "intermediate": 0.5063455700874329, "beginner": 0.3875180184841156, "expert": 0.10613645613193512 }
37,053
hi, write a script in unity for a very smart enemy with self-learning in unity 3d
256541f5568d0c2fcb336ff7418b5770
{ "intermediate": 0.1804133802652359, "beginner": 0.18131110072135925, "expert": 0.6382755041122437 }
37,054
hi
d53500c235ef043aba8043baefdb5c75
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
37,055
Hi
792f86ad8a18491d0944ab14b01c9a50
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
37,056
IN this contract // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.19; import {LibTWAPOracle} from "../libraries/LibTWAPOracle.sol"; import {Modifiers} from "../libraries/LibAppStorage.sol"; import {ITWAPOracleDollar3pool} from "../../dollar/interfaces/ITWAPOracleDollar3pool.sol"; /** * @notice Facet used for Curve TWAP oracle in the Dollar MetaPool */ contract TWAPOracleDollar3poolFacet is Modifiers, ITWAPOracleDollar3pool { /** * @notice Sets Curve MetaPool to be used as a TWAP oracle * @param _pool Curve MetaPool address, pool for 2 tokens [Dollar, 3CRV LP] * @param _curve3CRVToken1 Curve 3Pool LP token address */ function setPool( address _pool, address _curve3CRVToken1 ) external onlyOwner { return LibTWAPOracle.setPool(_pool, _curve3CRVToken1); } /** * @notice Updates the following state variables to the latest values from MetaPool: * - Dollar / 3CRV LP quote * - 3CRV LP / Dollar quote * - cumulative prices * - update timestamp */ function update() external { LibTWAPOracle.update(); } /** * @notice Returns the quote for the provided `token` address * @notice If the `token` param is Dollar then returns 3CRV LP / Dollar quote * @notice If the `token` param is 3CRV LP then returns Dollar / 3CRV LP quote * @dev This will always return 0 before update has been called successfully for the first time * @param token Token address * @return amountOut Token price, Dollar / 3CRV LP or 3CRV LP / Dollar quote */ function consult(address token) external view returns (uint256 amountOut) { return LibTWAPOracle.consult(token); } } in the function consult is contain a vulneability that is need a check that should compare the current block timestamp with the timestamp of the last update and revert the transaction if the data is considered stale explain details if valid or invalid
b20f8b06267b0bdc5eacd8eab47ae262
{ "intermediate": 0.4872725307941437, "beginner": 0.25346869230270386, "expert": 0.2592587471008301 }
37,057
hi, write a script in unity for a very smart enemy with self-learning in unity3d, without using the ML-Agent toolkit, make the enemy try to catch up with the player, bypassing obstacles and hiding behind obstacles if the player does not see it
7a227e3ee1c8f794388bf1cf3c060d34
{ "intermediate": 0.2975483536720276, "beginner": 0.09807556122541428, "expert": 0.6043760776519775 }
37,058
Bonjour
0503cd719e86f7668ffef9ca20592f1c
{ "intermediate": 0.3596824109554291, "beginner": 0.28452569246292114, "expert": 0.3557918965816498 }
37,059
I am trying to use fastify with typescript. I have installed fastify and @types/node globally but when I try to import fastify using the "import" syntax, typescript-language server does not infer the correct types. What am I doing wrong?
552cd2636a2d0b16fe5c7aea1cbb0ca3
{ "intermediate": 0.5388375520706177, "beginner": 0.25620192289352417, "expert": 0.20496055483818054 }
37,060
import os import subprocess import numpy as np import uuid from moviepy.editor import VideoFileClip from scipy.io import wavfile import random video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output' def calculate_loudness(audio_data): if audio_data.ndim == 1: volume = audio_data ** 2 else: volume = np.mean(audio_data ** 2, axis=1) return np.sqrt(volume) def find_loudest_moments(audio_filename, num_moments, segment_duration, video_duration, starting_offset, ending_offset): rate, audio_data = wavfile.read(audio_filename) if audio_data.ndim == 2: audio_data = np.mean(audio_data, axis=1) volume = calculate_loudness(audio_data.astype('float32')) start_index = int(starting_offset * rate) end_index = int((video_duration - ending_offset) * rate) moments = [] while len(moments) < num_moments: index = np.argmax(volume[start_index:end_index]) moment = (start_index + index) / rate # Skip moments too close to the start or end if moment - segment_duration / 2 < starting_offset or moment + segment_duration / 2 > video_duration - ending_offset: volume[start_index + index] = 0 continue moments.append(moment) # Clear out the volume data around the found moment to avoid overlap clear_margin = int(segment_duration * rate / 2) clear_start = max(start_index, start_index + index - clear_margin) clear_end = min(end_index, start_index + index + clear_margin) volume[clear_start:clear_end] = 0 return sorted(moments) def ask_peak_position(): print("Choisissez le positionnement du pic sonore dans le segment vidéo :") print("1 - En début de vidéo (à un tiers)") print("2 - Au milieu de la vidéo") print("3 - En fin de vidéo (aux deux tiers)") print("4 - Aléatoire (à un tiers, au milieu, ou aux deux tiers)") choice = input("Entrez le numéro de votre choix : ") while choice not in ('1', '2', '3', '4'): print("Entrée invalide. Veuillez choisir une option valide.") choice = input("Entrez le numéro de votre choix : ") return int(choice) def extract_segments(video_path, moments, segment_duration, peak_position_choice, video_duration): if not os.path.exists(output_folder): os.makedirs(output_folder) base_name = os.path.splitext(os.path.basename(video_path))[0] for i, moment in enumerate(moments): if peak_position_choice == 1: # Start of video start_time = max(moment - segment_duration / 3, 0) elif peak_position_choice == 2: # Middle of video start_time = max(moment - segment_duration / 2, 0) elif peak_position_choice == 3: # End of video start_time = max(moment - 2 * segment_duration / 3, 0) elif peak_position_choice == 4: # Random start_time = max(moment - segment_duration * random.choice([1/3, 1/2, 2/3]), 0) else: raise ValueError("Invalid peak position choice") end_time = min(start_time + segment_duration, video_duration) output_filename = f"{base_name}_moment{i + 1}.mp4" output_path = os.path.join(output_folder, output_filename) command = [ "ffmpeg", "-y", "-ss", str(start_time), "-i", video_path, "-t", str(min(segment_duration, video_duration - start_time)), "-c:v", "libx264", "-preset", "medium", "-crf", "23", "-c:a", "aac", "-strict", "-2", "-b:a", "192k", output_path ] subprocess.run(command, check=True, stderr=subprocess.PIPE) print(f"Extracted and re-encoded {output_filename}") def process_video_files(starting_offset_seconds, ending_offset_seconds, num_moments, segment_duration, peak_position_choice): temporary_audio_files = [] for root, _, files in os.walk('.'): for file in files: if file.lower().endswith(tuple(video_extensions)): video_path = os.path.join(root, file) unique_id = str(uuid.uuid4()) audio_path = f'temp_audio{unique_id}.wav' temporary_audio_files.append(audio_path) try: video_clip = VideoFileClip(video_path) video_duration = video_clip.duration video_clip.audio.write_audiofile(audio_path, codec='pcm_s16le', fps=44100, nbytes=2, buffersize=2000) video_clip.close() moments = find_loudest_moments(audio_path, num_moments, segment_duration, video_duration, starting_offset_seconds, ending_offset_seconds) extract_segments(video_path, moments, segment_duration, peak_position_choice, video_duration) finally: if os.path.exists(audio_path): os.remove(audio_path) print(f"Finished processing video {video_path}") # Cleanup temporary audio files created during processing for audio_file in temporary_audio_files: if os.path.exists(audio_file): os.remove(audio_file) if __name__ == "__main__": starting_offset_seconds = float(input("Combien de secondes à ignorer au début pour l'analyse ? ")) ending_offset_seconds = float(input("Combien de secondes à ignorer à la fin pour l'analyse ? ")) num_moments = int(input("Combien de moments forts souhaitez-vous extraire de chaque vidéo ? ")) segment_duration = float(input("Quelle est la durée (en secondes) de chaque segment vidéo à extraire ? ")) peak_position_choice = ask_peak_position() process_video_files(starting_offset_seconds, ending_offset_seconds, num_moments, segment_duration, peak_position_choice) print("All temporary audio files have been cleaned up.") print("All videos have been processed.")
0e6de78c79741c9835d5aad2d167978d
{ "intermediate": 0.3887156844139099, "beginner": 0.47522488236427307, "expert": 0.13605941832065582 }
37,061
review this contract line by line for issues // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.19; import {IUbiquityPool} from "../interfaces/IUbiquityPool.sol"; import {Modifiers} from "../libraries/LibAppStorage.sol"; import {LibUbiquityPool} from "../libraries/LibUbiquityPool.sol"; /** * @notice Ubiquity pool facet * @notice Allows users to: * - deposit collateral in exchange for Ubiquity Dollars * - redeem Ubiquity Dollars in exchange for the earlier provided collateral */ contract UbiquityPoolFacet is IUbiquityPool, Modifiers { //===================== // Views //===================== /// @inheritdoc IUbiquityPool function allCollaterals() external view returns (address[] memory) { return LibUbiquityPool.allCollaterals(); } /// @inheritdoc IUbiquityPool function collateralInformation( address collateralAddress ) external view returns (LibUbiquityPool.CollateralInformation memory returnData) { return LibUbiquityPool.collateralInformation(collateralAddress); } /// @inheritdoc IUbiquityPool function collateralUsdBalance() external view returns (uint256 balanceTally) { return LibUbiquityPool.collateralUsdBalance(); } /// @inheritdoc IUbiquityPool function freeCollateralBalance( uint256 collateralIndex ) external view returns (uint256) { return LibUbiquityPool.freeCollateralBalance(collateralIndex); } /// @inheritdoc IUbiquityPool function getDollarInCollateral( uint256 collateralIndex, uint256 dollarAmount ) external view returns (uint256) { return LibUbiquityPool.getDollarInCollateral( collateralIndex, dollarAmount ); } /// @inheritdoc IUbiquityPool function getDollarPriceUsd() external view returns (uint256 dollarPriceUsd) { return LibUbiquityPool.getDollarPriceUsd(); } //==================== // Public functions //==================== /// @inheritdoc IUbiquityPool function mintDollar( uint256 collateralIndex, uint256 dollarAmount, uint256 dollarOutMin, uint256 maxCollateralIn ) external returns (uint256 totalDollarMint, uint256 collateralNeeded) { return LibUbiquityPool.mintDollar( collateralIndex, dollarAmount, dollarOutMin, maxCollateralIn ); } /// @inheritdoc IUbiquityPool function redeemDollar( uint256 collateralIndex, uint256 dollarAmount, uint256 collateralOutMin ) external returns (uint256 collateralOut) { return LibUbiquityPool.redeemDollar( collateralIndex, dollarAmount, collateralOutMin ); } /// @inheritdoc IUbiquityPool function collectRedemption( uint256 collateralIndex ) external returns (uint256 collateralAmount) { return LibUbiquityPool.collectRedemption(collateralIndex); } /// @inheritdoc IUbiquityPool function updateChainLinkCollateralPrice(uint256 collateralIndex) external { LibUbiquityPool.updateChainLinkCollateralPrice(collateralIndex); } //========================= // AMO minters functions //========================= /// @inheritdoc IUbiquityPool function amoMinterBorrow(uint256 collateralAmount) external { LibUbiquityPool.amoMinterBorrow(collateralAmount); } //======================== // Restricted functions //======================== /// @inheritdoc IUbiquityPool function addAmoMinter(address amoMinterAddress) external onlyAdmin { LibUbiquityPool.addAmoMinter(amoMinterAddress); } /// @inheritdoc IUbiquityPool function addCollateralToken( address collateralAddress, address chainLinkPriceFeedAddress, uint256 poolCeiling ) external onlyAdmin { LibUbiquityPool.addCollateralToken( collateralAddress, chainLinkPriceFeedAddress, poolCeiling ); } /// @inheritdoc IUbiquityPool function removeAmoMinter(address amoMinterAddress) external onlyAdmin { LibUbiquityPool.removeAmoMinter(amoMinterAddress); } /// @inheritdoc IUbiquityPool function setCollateralChainLinkPriceFeed( address collateralAddress, address chainLinkPriceFeedAddress, uint256 stalenessThreshold ) external onlyAdmin { LibUbiquityPool.setCollateralChainLinkPriceFeed( collateralAddress, chainLinkPriceFeedAddress, stalenessThreshold ); } /// @inheritdoc IUbiquityPool function setFees( uint256 collateralIndex, uint256 newMintFee, uint256 newRedeemFee ) external onlyAdmin { LibUbiquityPool.setFees(collateralIndex, newMintFee, newRedeemFee); } /// @inheritdoc IUbiquityPool function setPoolCeiling( uint256 collateralIndex, uint256 newCeiling ) external onlyAdmin { LibUbiquityPool.setPoolCeiling(collateralIndex, newCeiling); } /// @inheritdoc IUbiquityPool function setPriceThresholds( uint256 newMintPriceThreshold, uint256 newRedeemPriceThreshold ) external onlyAdmin { LibUbiquityPool.setPriceThresholds( newMintPriceThreshold, newRedeemPriceThreshold ); } /// @inheritdoc IUbiquityPool function setRedemptionDelayBlocks( uint256 newRedemptionDelayBlocks ) external onlyAdmin { LibUbiquityPool.setRedemptionDelayBlocks(newRedemptionDelayBlocks); } /// @inheritdoc IUbiquityPool function toggleCollateral(uint256 collateralIndex) external onlyAdmin { LibUbiquityPool.toggleCollateral(collateralIndex); } /// @inheritdoc IUbiquityPool function toggleMintRedeemBorrow( uint256 collateralIndex, uint8 toggleIndex ) external onlyAdmin { LibUbiquityPool.toggleMintRedeemBorrow(collateralIndex, toggleIndex); } } start with the main components such as the UbiquityPoolFacet contract, here is the LibUbiquityPool library// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.19; import {AggregatorV3Interface} from "@chainlink/interfaces/AggregatorV3Interface.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IDollarAmoMinter} from "../interfaces/IDollarAmoMinter.sol"; import {IERC20Ubiquity} from "../interfaces/IERC20Ubiquity.sol"; import {UBIQUITY_POOL_PRICE_PRECISION} from "./Constants.sol"; import {LibAppStorage} from "./LibAppStorage.sol"; import {LibTWAPOracle} from "./LibTWAPOracle.sol"; /** * @notice Ubiquity pool library * @notice Allows users to: * - deposit collateral in exchange for Ubiquity Dollars * - redeem Ubiquity Dollars in exchange for the earlier provided collateral */ library LibUbiquityPool { using SafeERC20 for IERC20; using SafeMath for uint256; /// @notice Storage slot used to store data for this library bytes32 constant UBIQUITY_POOL_STORAGE_POSITION = bytes32( uint256(keccak256("ubiquity.contracts.ubiquity.pool.storage")) - 1 ); /// @notice Struct used as a storage for this library struct UbiquityPoolStorage { //======== // Core //======== // minter address -> is it enabled mapping(address amoMinter => bool isEnabled) isAmoMinterEnabled; //====================== // Collateral related //====================== // available collateral tokens address[] collateralAddresses; // collateral address -> collateral index mapping(address collateralAddress => uint256 collateralIndex) collateralIndex; // collateral index -> chainlink price feed addresses address[] collateralPriceFeedAddresses; // collateral index -> threshold in seconds when chainlink answer should be considered stale uint256[] collateralPriceFeedStalenessThresholds; // collateral index -> collateral price uint256[] collateralPrices; // array collateral symbols string[] collateralSymbols; // collateral address -> is it enabled mapping(address collateralAddress => bool isEnabled) isCollateralEnabled; // Number of decimals needed to get to E18. collateral index -> missing decimals uint256[] missingDecimals; // Total across all collaterals. Accounts for missing_decimals uint256[] poolCeilings; //==================== // Redeem related //==================== // user -> block number (collateral independent) mapping(address => uint256) lastRedeemedBlock; // 1010000 = $1.01 uint256 mintPriceThreshold; // 990000 = $0.99 uint256 redeemPriceThreshold; // address -> collateral index -> balance mapping(address user => mapping(uint256 collateralIndex => uint256 amount)) redeemCollateralBalances; // number of blocks to wait before being able to collectRedemption() uint256 redemptionDelayBlocks; // collateral index -> balance uint256[] unclaimedPoolCollateral; //================ // Fees related //================ // minting fee of a particular collateral index, 1_000_000 = 100% uint256[] mintingFee; // redemption fee of a particular collateral index, 1_000_000 = 100% uint256[] redemptionFee; //================= // Pause related //================= // whether borrowing collateral by AMO minters is paused for a particular collateral index bool[] isBorrowPaused; // whether minting is paused for a particular collateral index bool[] isMintPaused; // whether redeeming is paused for a particular collateral index bool[] isRedeemPaused; } /// @notice Struct used for detailed collateral information struct CollateralInformation { uint256 index; string symbol; address collateralAddress; address collateralPriceFeedAddress; uint256 collateralPriceFeedStalenessThreshold; bool isEnabled; uint256 missingDecimals; uint256 price; uint256 poolCeiling; bool isMintPaused; bool isRedeemPaused; bool isBorrowPaused; uint256 mintingFee; uint256 redemptionFee; } /** * @notice Returns struct used as a storage for this library * @return uPoolStorage Struct used as a storage */ function ubiquityPoolStorage() internal pure returns (UbiquityPoolStorage storage uPoolStorage) { bytes32 position = UBIQUITY_POOL_STORAGE_POSITION; assembly { uPoolStorage.slot := position } } //=========== // Events //=========== /// @notice Emitted when new AMO minter is added event AmoMinterAdded(address amoMinterAddress); /// @notice Emitted when AMO minter is removed event AmoMinterRemoved(address amoMinterAddress); /// @notice Emitted on setting a chainlink's collateral price feed params event CollateralPriceFeedSet( uint256 collateralIndex, address priceFeedAddress, uint256 stalenessThreshold ); /// @notice Emitted on setting a collateral price event CollateralPriceSet(uint256 collateralIndex, uint256 newPrice); /// @notice Emitted on enabling/disabling a particular collateral token event CollateralToggled(uint256 collateralIndex, bool newState); /// @notice Emitted when fees are updated event FeesSet( uint256 collateralIndex, uint256 newMintFee, uint256 newRedeemFee ); /// @notice Emitted on toggling pause for mint/redeem/borrow event MintRedeemBorrowToggled(uint256 collateralIndex, uint8 toggleIndex); /// @notice Emitted when new pool ceiling (i.e. max amount of collateral) is set event PoolCeilingSet(uint256 collateralIndex, uint256 newCeiling); /// @notice Emitted when mint and redeem price thresholds are updated (1_000_000 = $1.00) event PriceThresholdsSet( uint256 newMintPriceThreshold, uint256 newRedeemPriceThreshold ); /// @notice Emitted when a new redemption delay in blocks is set event RedemptionDelayBlocksSet(uint256 redemptionDelayBlocks); //===================== // Modifiers //===================== /** * @notice Checks whether collateral token is enabled (i.e. mintable and redeemable) * @param collateralIndex Collateral token index */ modifier collateralEnabled(uint256 collateralIndex) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); require( poolStorage.isCollateralEnabled[ poolStorage.collateralAddresses[collateralIndex] ], "Collateral disabled" ); _; } /** * @notice Checks whether a caller is the AMO minter address */ modifier onlyAmoMinter() { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); require( poolStorage.isAmoMinterEnabled[msg.sender], "Not an AMO Minter" ); _; } //===================== // Views //===================== /** * @notice Returns all collateral addresses * @return All collateral addresses */ function allCollaterals() internal view returns (address[] memory) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); return poolStorage.collateralAddresses; } /** * @notice Returns collateral information * @param collateralAddress Address of the collateral token * @return returnData Collateral info */ function collateralInformation( address collateralAddress ) internal view returns (CollateralInformation memory returnData) { // load the storage UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); // validation require( poolStorage.isCollateralEnabled[collateralAddress], "Invalid collateral" ); // get the index uint256 index = poolStorage.collateralIndex[collateralAddress]; returnData = CollateralInformation( index, poolStorage.collateralSymbols[index], collateralAddress, poolStorage.collateralPriceFeedAddresses[index], poolStorage.collateralPriceFeedStalenessThresholds[index], poolStorage.isCollateralEnabled[collateralAddress], poolStorage.missingDecimals[index], poolStorage.collateralPrices[index], poolStorage.poolCeilings[index], poolStorage.isMintPaused[index], poolStorage.isRedeemPaused[index], poolStorage.isBorrowPaused[index], poolStorage.mintingFee[index], poolStorage.redemptionFee[index] ); } /** * @notice Returns USD value of all collateral tokens held in the pool, in E18 * @return balanceTally USD value of all collateral tokens */ function collateralUsdBalance() internal view returns (uint256 balanceTally) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); uint256 collateralTokensCount = poolStorage.collateralAddresses.length; balanceTally = 0; for (uint256 i = 0; i < collateralTokensCount; i++) { balanceTally += freeCollateralBalance(i) .mul(10 ** poolStorage.missingDecimals[i]) .mul(poolStorage.collateralPrices[i]) .div(UBIQUITY_POOL_PRICE_PRECISION); } } /** * @notice Returns free collateral balance (i.e. that can be borrowed by AMO minters) * @param collateralIndex collateral token index * @return Amount of free collateral */ function freeCollateralBalance( uint256 collateralIndex ) internal view returns (uint256) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); return IERC20(poolStorage.collateralAddresses[collateralIndex]) .balanceOf(address(this)) .sub(poolStorage.unclaimedPoolCollateral[collateralIndex]); } /** * @notice Returns Dollar value in collateral tokens * @param collateralIndex collateral token index * @param dollarAmount Amount of Dollars * @return Value in collateral tokens */ function getDollarInCollateral( uint256 collateralIndex, uint256 dollarAmount ) internal view returns (uint256) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); return dollarAmount .mul(UBIQUITY_POOL_PRICE_PRECISION) .div(10 ** poolStorage.missingDecimals[collateralIndex]) .div(poolStorage.collateralPrices[collateralIndex]); } /** * @notice Returns Ubiquity Dollar token USD price (1e6 precision) from Curve Metapool (Ubiquity Dollar, Curve Tri-Pool LP) * @return dollarPriceUsd USD price of Ubiquity Dollar */ function getDollarPriceUsd() internal view returns (uint256 dollarPriceUsd) { // get Dollar price from Curve Metapool (18 decimals) uint256 dollarPriceUsdD18 = LibTWAPOracle.getTwapPrice(); // convert to 6 decimals dollarPriceUsd = dollarPriceUsdD18 .mul(UBIQUITY_POOL_PRICE_PRECISION) .div(1e18); } //==================== // Public functions //==================== /** * @notice Mints Dollars in exchange for collateral tokens * @param collateralIndex Collateral token index * @param dollarAmount Amount of dollars to mint * @param dollarOutMin Min amount of dollars to mint (slippage protection) * @param maxCollateralIn Max amount of collateral to send (slippage protection) * @return totalDollarMint Amount of Dollars minted * @return collateralNeeded Amount of collateral sent to the pool */ function mintDollar( uint256 collateralIndex, uint256 dollarAmount, uint256 dollarOutMin, uint256 maxCollateralIn ) internal collateralEnabled(collateralIndex) returns (uint256 totalDollarMint, uint256 collateralNeeded) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); require( poolStorage.isMintPaused[collateralIndex] == false, "Minting is paused" ); // update Dollar price from Curve's Dollar Metapool LibTWAPOracle.update(); // prevent unnecessary mints require( getDollarPriceUsd() >= poolStorage.mintPriceThreshold, "Dollar price too low" ); // update collateral price updateChainLinkCollateralPrice(collateralIndex); // get amount of collateral for minting Dollars collateralNeeded = getDollarInCollateral(collateralIndex, dollarAmount); // subtract the minting fee totalDollarMint = dollarAmount .mul( UBIQUITY_POOL_PRICE_PRECISION.sub( poolStorage.mintingFee[collateralIndex] ) ) .div(UBIQUITY_POOL_PRICE_PRECISION); // check slippages require((totalDollarMint >= dollarOutMin), "Dollar slippage"); require((collateralNeeded <= maxCollateralIn), "Collateral slippage"); // check the pool ceiling require( freeCollateralBalance(collateralIndex).add(collateralNeeded) <= poolStorage.poolCeilings[collateralIndex], "Pool ceiling" ); // take collateral first IERC20(poolStorage.collateralAddresses[collateralIndex]) .safeTransferFrom(msg.sender, address(this), collateralNeeded); // mint Dollars IERC20Ubiquity ubiquityDollarToken = IERC20Ubiquity( LibAppStorage.appStorage().dollarTokenAddress ); ubiquityDollarToken.mint(msg.sender, totalDollarMint); } /** * @notice Burns redeemable Ubiquity Dollars and sends back 1 USD of collateral token for every 1 Ubiquity Dollar burned * @dev Redeem process is split in two steps: * @dev 1. `redeemDollar()` * @dev 2. `collectRedemption()` * @dev This is done in order to prevent someone using a flash loan of a collateral token to mint, redeem, and collect in a single transaction/block * @param collateralIndex Collateral token index being withdrawn * @param dollarAmount Amount of Ubiquity Dollars being burned * @param collateralOutMin Minimum amount of collateral tokens that'll be withdrawn, used to set acceptable slippage * @return collateralOut Amount of collateral tokens ready for redemption */ function redeemDollar( uint256 collateralIndex, uint256 dollarAmount, uint256 collateralOutMin ) internal collateralEnabled(collateralIndex) returns (uint256 collateralOut) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); require( poolStorage.isRedeemPaused[collateralIndex] == false, "Redeeming is paused" ); // update Dollar price from Curve's Dollar Metapool LibTWAPOracle.update(); // prevent unnecessary redemptions that could adversely affect the Dollar price require( getDollarPriceUsd() <= poolStorage.redeemPriceThreshold, "Dollar price too high" ); uint256 dollarAfterFee = dollarAmount .mul( UBIQUITY_POOL_PRICE_PRECISION.sub( poolStorage.redemptionFee[collateralIndex] ) ) .div(UBIQUITY_POOL_PRICE_PRECISION); // update collateral price updateChainLinkCollateralPrice(collateralIndex); // get collateral output for incoming Dollars collateralOut = getDollarInCollateral(collateralIndex, dollarAfterFee); // checks require( collateralOut <= (IERC20(poolStorage.collateralAddresses[collateralIndex])) .balanceOf(address(this)) .sub(poolStorage.unclaimedPoolCollateral[collateralIndex]), "Insufficient pool collateral" ); require(collateralOut >= collateralOutMin, "Collateral slippage"); // account for the redeem delay poolStorage.redeemCollateralBalances[msg.sender][ collateralIndex ] = poolStorage .redeemCollateralBalances[msg.sender][collateralIndex].add( collateralOut ); poolStorage.unclaimedPoolCollateral[collateralIndex] = poolStorage .unclaimedPoolCollateral[collateralIndex] .add(collateralOut); poolStorage.lastRedeemedBlock[msg.sender] = block.number; // burn Dollars IERC20Ubiquity ubiquityDollarToken = IERC20Ubiquity( LibAppStorage.appStorage().dollarTokenAddress ); ubiquityDollarToken.burnFrom(msg.sender, dollarAmount); } /** * @notice Used to collect collateral tokens after redeeming/burning Ubiquity Dollars * @dev Redeem process is split in two steps: * @dev 1. `redeemDollar()` * @dev 2. `collectRedemption()` * @dev This is done in order to prevent someone using a flash loan of a collateral token to mint, redeem, and collect in a single transaction/block * @param collateralIndex Collateral token index being collected * @return collateralAmount Amount of collateral tokens redeemed */ function collectRedemption( uint256 collateralIndex ) internal returns (uint256 collateralAmount) { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); require( poolStorage.isRedeemPaused[collateralIndex] == false, "Redeeming is paused" ); require( ( poolStorage.lastRedeemedBlock[msg.sender].add( poolStorage.redemptionDelayBlocks ) ) <= block.number, "Too soon to collect redemption" ); bool sendCollateral = false; if ( poolStorage.redeemCollateralBalances[msg.sender][collateralIndex] > 0 ) { collateralAmount = poolStorage.redeemCollateralBalances[msg.sender][ collateralIndex ]; poolStorage.redeemCollateralBalances[msg.sender][ collateralIndex ] = 0; poolStorage.unclaimedPoolCollateral[collateralIndex] = poolStorage .unclaimedPoolCollateral[collateralIndex] .sub(collateralAmount); sendCollateral = true; } // send out the tokens if (sendCollateral) { IERC20(poolStorage.collateralAddresses[collateralIndex]) .safeTransfer(msg.sender, collateralAmount); } } /** * @notice Updates collateral token price in USD from ChainLink price feed * @param collateralIndex Collateral token index */ function updateChainLinkCollateralPrice(uint256 collateralIndex) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); AggregatorV3Interface priceFeed = AggregatorV3Interface( poolStorage.collateralPriceFeedAddresses[collateralIndex] ); // fetch latest price ( , // roundId int256 answer, // startedAt , uint256 updatedAt, ) = // answeredInRound priceFeed.latestRoundData(); // fetch number of decimals in chainlink feed uint256 priceFeedDecimals = priceFeed.decimals(); // validation require(answer > 0, "Invalid price"); require( block.timestamp - updatedAt < poolStorage.collateralPriceFeedStalenessThresholds[ collateralIndex ], "Stale data" ); // convert chainlink price to 6 decimals uint256 price = uint256(answer).mul(UBIQUITY_POOL_PRICE_PRECISION).div( 10 ** priceFeedDecimals ); poolStorage.collateralPrices[collateralIndex] = price; emit CollateralPriceSet(collateralIndex, price); } //========================= // AMO minters functions //========================= /** * @notice Allows AMO minters to borrow collateral to make yield in external * protocols like Compound, Curve, erc... * @dev Bypasses the gassy mint->redeem cycle for AMOs to borrow collateral * @param collateralAmount Amount of collateral to borrow */ function amoMinterBorrow(uint256 collateralAmount) internal onlyAmoMinter { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); // checks the collateral index of the minter as an additional safety check uint256 minterCollateralIndex = IDollarAmoMinter(msg.sender) .collateralIndex(); // checks to see if borrowing is paused require( poolStorage.isBorrowPaused[minterCollateralIndex] == false, "Borrowing is paused" ); // ensure collateral is enabled require( poolStorage.isCollateralEnabled[ poolStorage.collateralAddresses[minterCollateralIndex] ], "Collateral disabled" ); // transfer IERC20(poolStorage.collateralAddresses[minterCollateralIndex]) .safeTransfer(msg.sender, collateralAmount); } //======================== // Restricted functions //======================== /** * @notice Adds a new AMO minter * @param amoMinterAddress AMO minter address */ function addAmoMinter(address amoMinterAddress) internal { require(amoMinterAddress != address(0), "Zero address detected"); // make sure the AMO Minter has collateralDollarBalance() uint256 collatValE18 = IDollarAmoMinter(amoMinterAddress) .collateralDollarBalance(); require(collatValE18 >= 0, "Invalid AMO"); UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); poolStorage.isAmoMinterEnabled[amoMinterAddress] = true; emit AmoMinterAdded(amoMinterAddress); } /** * @notice Adds a new collateral token * @param collateralAddress Collateral token address * @param chainLinkPriceFeedAddress Chainlink's price feed address * @param poolCeiling Max amount of available tokens for collateral */ function addCollateralToken( address collateralAddress, address chainLinkPriceFeedAddress, uint256 poolCeiling ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); uint256 collateralIndex = poolStorage.collateralAddresses.length; // add collateral address to all collaterals poolStorage.collateralAddresses.push(collateralAddress); // for fast collateral address -> collateral idx lookups later poolStorage.collateralIndex[collateralAddress] = collateralIndex; // set collateral initially to disabled poolStorage.isCollateralEnabled[collateralAddress] = false; // add in the missing decimals poolStorage.missingDecimals.push( uint256(18).sub(ERC20(collateralAddress).decimals()) ); // add in the collateral symbols poolStorage.collateralSymbols.push(ERC20(collateralAddress).symbol()); // initialize unclaimed pool collateral poolStorage.unclaimedPoolCollateral.push(0); // initialize paused prices to $1 as a backup poolStorage.collateralPrices.push(UBIQUITY_POOL_PRICE_PRECISION); // set fees to 0 by default poolStorage.mintingFee.push(0); poolStorage.redemptionFee.push(0); // handle the pauses poolStorage.isMintPaused.push(false); poolStorage.isRedeemPaused.push(false); poolStorage.isBorrowPaused.push(false); // set pool ceiling poolStorage.poolCeilings.push(poolCeiling); // set price feed address poolStorage.collateralPriceFeedAddresses.push( chainLinkPriceFeedAddress ); // set price feed staleness threshold in seconds poolStorage.collateralPriceFeedStalenessThresholds.push(1 days); } /** * @notice Removes AMO minter * @param amoMinterAddress AMO minter address to remove */ function removeAmoMinter(address amoMinterAddress) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); poolStorage.isAmoMinterEnabled[amoMinterAddress] = false; emit AmoMinterRemoved(amoMinterAddress); } /** * @notice Sets collateral ChainLink price feed params * @param collateralAddress Collateral token address * @param chainLinkPriceFeedAddress ChainLink price feed address * @param stalenessThreshold Threshold in seconds when chainlink answer should be considered stale */ function setCollateralChainLinkPriceFeed( address collateralAddress, address chainLinkPriceFeedAddress, uint256 stalenessThreshold ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); uint256 collateralIndex = poolStorage.collateralIndex[ collateralAddress ]; // set price feed address poolStorage.collateralPriceFeedAddresses[ collateralIndex ] = chainLinkPriceFeedAddress; // set staleness threshold in seconds when chainlink answer should be considered stale poolStorage.collateralPriceFeedStalenessThresholds[ collateralIndex ] = stalenessThreshold; emit CollateralPriceFeedSet( collateralIndex, chainLinkPriceFeedAddress, stalenessThreshold ); } /** * @notice Sets mint and redeem fees, 1_000_000 = 100% * @param collateralIndex Collateral token index * @param newMintFee New mint fee * @param newRedeemFee New redeem fee */ function setFees( uint256 collateralIndex, uint256 newMintFee, uint256 newRedeemFee ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); poolStorage.mintingFee[collateralIndex] = newMintFee; poolStorage.redemptionFee[collateralIndex] = newRedeemFee; emit FeesSet(collateralIndex, newMintFee, newRedeemFee); } /** * @notice Sets max amount of collateral for a particular collateral token * @param collateralIndex Collateral token index * @param newCeiling Max amount of collateral */ function setPoolCeiling( uint256 collateralIndex, uint256 newCeiling ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); poolStorage.poolCeilings[collateralIndex] = newCeiling; emit PoolCeilingSet(collateralIndex, newCeiling); } /** * @notice Sets mint and redeem price thresholds, 1_000_000 = $1.00 * @param newMintPriceThreshold New mint price threshold * @param newRedeemPriceThreshold New redeem price threshold */ function setPriceThresholds( uint256 newMintPriceThreshold, uint256 newRedeemPriceThreshold ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); poolStorage.mintPriceThreshold = newMintPriceThreshold; poolStorage.redeemPriceThreshold = newRedeemPriceThreshold; emit PriceThresholdsSet(newMintPriceThreshold, newRedeemPriceThreshold); } /** * @notice Sets a redemption delay in blocks * @dev Redeeming is split in 2 actions: * @dev 1. `redeemDollar()` * @dev 2. `collectRedemption()` * @dev `newRedemptionDelayBlocks` sets number of blocks that should be mined after which user can call `collectRedemption()` * @param newRedemptionDelayBlocks Redemption delay in blocks */ function setRedemptionDelayBlocks( uint256 newRedemptionDelayBlocks ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); poolStorage.redemptionDelayBlocks = newRedemptionDelayBlocks; emit RedemptionDelayBlocksSet(newRedemptionDelayBlocks); } /** * @notice Toggles (i.e. enables/disables) a particular collateral token * @param collateralIndex Collateral token index */ function toggleCollateral(uint256 collateralIndex) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); address collateralAddress = poolStorage.collateralAddresses[ collateralIndex ]; poolStorage.isCollateralEnabled[collateralAddress] = !poolStorage .isCollateralEnabled[collateralAddress]; emit CollateralToggled( collateralIndex, poolStorage.isCollateralEnabled[collateralAddress] ); } /** * @notice Toggles pause for mint/redeem/borrow methods * @param collateralIndex Collateral token index * @param toggleIndex Method index. 0 - toggle mint pause, 1 - toggle redeem pause, 2 - toggle borrow by AMO pause */ function toggleMintRedeemBorrow( uint256 collateralIndex, uint8 toggleIndex ) internal { UbiquityPoolStorage storage poolStorage = ubiquityPoolStorage(); if (toggleIndex == 0) poolStorage.isMintPaused[collateralIndex] = !poolStorage .isMintPaused[collateralIndex]; else if (toggleIndex == 1) poolStorage.isRedeemPaused[collateralIndex] = !poolStorage .isRedeemPaused[collateralIndex]; else if (toggleIndex == 2) poolStorage.isBorrowPaused[collateralIndex] = !poolStorage .isBorrowPaused[collateralIndex]; emit MintRedeemBorrowToggled(collateralIndex, toggleIndex); } }, and the IUbiquityPool interface// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.8.19; import {LibUbiquityPool} from "../libraries/LibUbiquityPool.sol"; /** * @notice Ubiquity pool interface * @notice Allows users to: * - deposit collateral in exchange for Ubiquity Dollars * - redeem Ubiquity Dollars in exchange for the earlier provided collateral */ interface IUbiquityPool { //===================== // Views //===================== /** * @notice Returns all collateral addresses * @return All collateral addresses */ function allCollaterals() external view returns (address[] memory); /** * @notice Returns collateral information * @param collateralAddress Address of the collateral token * @return returnData Collateral info */ function collateralInformation( address collateralAddress ) external view returns (LibUbiquityPool.CollateralInformation memory returnData); /** * @notice Returns USD value of all collateral tokens held in the pool, in E18 * @return balanceTally USD value of all collateral tokens */ function collateralUsdBalance() external view returns (uint256 balanceTally); /** * @notice Returns free collateral balance (i.e. that can be borrowed by AMO minters) * @param collateralIndex collateral token index * @return Amount of free collateral */ function freeCollateralBalance( uint256 collateralIndex ) external view returns (uint256); /** * @notice Returns Dollar value in collateral tokens * @param collateralIndex collateral token index * @param dollarAmount Amount of Dollars * @return Value in collateral tokens */ function getDollarInCollateral( uint256 collateralIndex, uint256 dollarAmount ) external view returns (uint256); /** * @notice Returns Ubiquity Dollar token USD price (1e6 precision) from Curve Metapool (Ubiquity Dollar, Curve Tri-Pool LP) * @return dollarPriceUsd USD price of Ubiquity Dollar */ function getDollarPriceUsd() external view returns (uint256 dollarPriceUsd); //==================== // Public functions //==================== /** * @notice Mints Dollars in exchange for collateral tokens * @param collateralIndex Collateral token index * @param dollarAmount Amount of dollars to mint * @param dollarOutMin Min amount of dollars to mint (slippage protection) * @param maxCollateralIn Max amount of collateral to send (slippage protection) * @return totalDollarMint Amount of Dollars minted * @return collateralNeeded Amount of collateral sent to the pool */ function mintDollar( uint256 collateralIndex, uint256 dollarAmount, uint256 dollarOutMin, uint256 maxCollateralIn ) external returns (uint256 totalDollarMint, uint256 collateralNeeded); /** * @notice Burns redeemable Ubiquity Dollars and sends back 1 USD of collateral token for every 1 Ubiquity Dollar burned * @dev Redeem process is split in two steps: * @dev 1. `redeemDollar()` * @dev 2. `collectRedemption()` * @dev This is done in order to prevent someone using a flash loan of a collateral token to mint, redeem, and collect in a single transaction/block * @param collateralIndex Collateral token index being withdrawn * @param dollarAmount Amount of Ubiquity Dollars being burned * @param collateralOutMin Minimum amount of collateral tokens that'll be withdrawn, used to set acceptable slippage * @return collateralOut Amount of collateral tokens ready for redemption */ function redeemDollar( uint256 collateralIndex, uint256 dollarAmount, uint256 collateralOutMin ) external returns (uint256 collateralOut); /** * @notice Used to collect collateral tokens after redeeming/burning Ubiquity Dollars * @dev Redeem process is split in two steps: * @dev 1. `redeemDollar()` * @dev 2. `collectRedemption()` * @dev This is done in order to prevent someone using a flash loan of a collateral token to mint, redeem, and collect in a single transaction/block * @param collateralIndex Collateral token index being collected * @return collateralAmount Amount of collateral tokens redeemed */ function collectRedemption( uint256 collateralIndex ) external returns (uint256 collateralAmount); //========================= // AMO minters functions //========================= /** * @notice Allows AMO minters to borrow collateral to make yield in external * protocols like Compound, Curve, erc... * @dev Bypasses the gassy mint->redeem cycle for AMOs to borrow collateral * @param collateralAmount Amount of collateral to borrow */ function amoMinterBorrow(uint256 collateralAmount) external; //======================== // Restricted functions //======================== /** * @notice Adds a new AMO minter * @param amoMinterAddress AMO minter address */ function addAmoMinter(address amoMinterAddress) external; /** * @notice Adds a new collateral token * @param collateralAddress Collateral token address * @param chainLinkPriceFeedAddress Chainlink's price feed address * @param poolCeiling Max amount of available tokens for collateral */ function addCollateralToken( address collateralAddress, address chainLinkPriceFeedAddress, uint256 poolCeiling ) external; /** * @notice Removes AMO minter * @param amoMinterAddress AMO minter address to remove */ function removeAmoMinter(address amoMinterAddress) external; /** * @notice Sets collateral ChainLink price feed params * @param collateralAddress Collateral token address * @param chainLinkPriceFeedAddress ChainLink price feed address * @param stalenessThreshold Threshold in seconds when chainlink answer should be considered stale */ function setCollateralChainLinkPriceFeed( address collateralAddress, address chainLinkPriceFeedAddress, uint256 stalenessThreshold ) external; /** * @notice Updates collateral token price in USD from ChainLink price feed * @param collateralIndex Collateral token index */ function updateChainLinkCollateralPrice(uint256 collateralIndex) external; /** * @notice Sets mint and redeem fees, 1_000_000 = 100% * @param collateralIndex Collateral token index * @param newMintFee New mint fee * @param newRedeemFee New redeem fee */ function setFees( uint256 collateralIndex, uint256 newMintFee, uint256 newRedeemFee ) external; /** * @notice Sets max amount of collateral for a particular collateral token * @param collateralIndex Collateral token index * @param newCeiling Max amount of collateral */ function setPoolCeiling( uint256 collateralIndex, uint256 newCeiling ) external; /** * @notice Sets mint and redeem price thresholds, 1_000_000 = $1.00 * @param newMintPriceThreshold New mint price threshold * @param newRedeemPriceThreshold New redeem price threshold */ function setPriceThresholds( uint256 newMintPriceThreshold, uint256 newRedeemPriceThreshold ) external; /** * @notice Sets a redemption delay in blocks * @dev Redeeming is split in 2 actions: * @dev 1. `redeemDollar()` * @dev 2. `collectRedemption()` * @dev `newRedemptionDelayBlocks` sets number of blocks that should be mined after which user can call `collectRedemption()` * @param newRedemptionDelayBlocks Redemption delay in blocks */ function setRedemptionDelayBlocks( uint256 newRedemptionDelayBlocks ) external; /** * @notice Toggles (i.e. enables/disables) a particular collateral token * @param collateralIndex Collateral token index */ function toggleCollateral(uint256 collateralIndex) external; /** * @notice Toggles pause for mint/redeem/borrow methods * @param collateralIndex Collateral token index * @param toggleIndex Method index. 0 - toggle mint pause, 1 - toggle redeem pause, 2 - toggle borrow by AMO pause */ function toggleMintRedeemBorrow( uint256 collateralIndex, uint8 toggleIndex ) external; }. include the interactions with external entities like users and AMO minters. start with the contract and its main functions. What are the key operations that you would like to highlight
a8c321b54b88d08386a344edda7c724b
{ "intermediate": 0.4159628748893738, "beginner": 0.35860708355903625, "expert": 0.22543011605739594 }
37,062
Format each line into format: wordsArray500[index] = "text of line"; and increase the index for each row by 1 (index starts from 0). Also put "-" symbol after each ] in line. 사람들 [saramdil] people 남자 [namja] man 여자 [yoja] woman 아이 [ai] child 남자 아이 [namja ai] boy 여자 아이 [yoja ai] girl 친구 [chingu] friend 손님 [sonnim] guest 승객 [singek] passenger 가족 [kajok] family 아버지 [aboji] father 어머니 [omoni] mother 부모 [pumo] parents 남편 [namphyon] husband 아내 [ane] wife 아들 [adil] son 딸 [ttal] daughter 할아버지 [haraboji] grandpa 할머 [halmoni] grandmother 형제 [hyonje] brother 자매 [chame] sister 직업 [chigop] work, job 선생님 [sonsennim] teacher 운전사 [unjonsa] driver 기사 [kisa] engineer 의사 [iysa] doctor 판매원 [phanmewon] shop assistent 대학생 [tehaksen] student 통역원 [thonyogwon] translator 작가 [chakka] writer 경찰관 [kyonchalgwan] policeman 사업가 [saopka] businessman 대통령 [tetonyon] president 나라 [nara] country 한국 [hangu] Korea 미국 [migu] America 영국 [yongu] England 수도 [sudo] capital 동물 [tonmul] animal 고양이 [koyanyi] cat 개 [ke] dog 말 [mal] horse 새 [se] bird 늑대 [nikte] wolf 도시 [tosi] city 학교 [hakkyo] school 거리 [kori] street 집 [chip] house 길, 도리 [kil, tori] road 교회 [kyohve] church 강 [kan] river 레스토랑 [restoran] restaurant 시장 [sijan] market 동물원 [tonmurwon] zoo 공원 [konwon] park 버스 정류장 [posi chonnujan] bus station 영화관 [yonhwagwan] cinema 사거리 [sagori] crossroads 숲 [sup] forest 병원 [pyonwon] hospital 경찰 [kyonchal] police 우체국 [uchegu] post office 정거장 [chongojan] station 가게 [kage] shop 전철 [chonchol] metro 도서관 [tosogwan] library 은행 [inhen] bank 바 [pa] bar 교회 [kyohwe] church 아파트 [apati] apartment, flat 방 [pan] room 문 [mun] door 부엌 [puok] kitchen 화장실 [hwajansil] toilet 침실 [chimsil] bedroom 층 [chin] floor 창문 [chanmun] window
129f24ea15f15c930a3363fd5090d124
{ "intermediate": 0.4452097713947296, "beginner": 0.42218342423439026, "expert": 0.13260677456855774 }
37,063
Format each line into format: wordsArray500[index] = "text of line"; and increase the index for each row by 1 (index starts from 0). Also put " - " symbol after each ] in line. 사람들 [saramdil] people 남자 [namja] man 여자 [yoja] woman 아이 [ai] child 남자 아이 [namja ai] boy 여자 아이 [yoja ai] girl 친구 [chingu] friend 손님 [sonnim] guest 승객 [singek] passenger 가족 [kajok] family 아버지 [aboji] father 어머니 [omoni] mother 부모 [pumo] parents 남편 [namphyon] husband 아내 [ane] wife 아들 [adil] son 딸 [ttal] daughter 할아버지 [haraboji] grandpa 할머 [halmoni] grandmother 형제 [hyonje] brother 자매 [chame] sister 직업 [chigop] work, job 선생님 [sonsennim] teacher 운전사 [unjonsa] driver 기사 [kisa] engineer 의사 [iysa] doctor 판매원 [phanmewon] shop assistent 대학생 [tehaksen] student 통역원 [thonyogwon] translator 작가 [chakka] writer 경찰관 [kyonchalgwan] policeman 사업가 [saopka] businessman 대통령 [tetonyon] president 나라 [nara] country 한국 [hangu] Korea 미국 [migu] America 영국 [yongu] England 수도 [sudo] capital 동물 [tonmul] animal 고양이 [koyanyi] cat 개 [ke] dog 말 [mal] horse 새 [se] bird 늑대 [nikte] wolf 도시 [tosi] city 학교 [hakkyo] school 거리 [kori] street 집 [chip] house 길, 도리 [kil, tori] road 교회 [kyohve] church 강 [kan] river 레스토랑 [restoran] restaurant 시장 [sijan] market 동물원 [tonmurwon] zoo 공원 [konwon] park 버스 정류장 [posi chonnujan] bus station 영화관 [yonhwagwan] cinema 사거리 [sagori] crossroads 숲 [sup] forest 병원 [pyonwon] hospital 경찰 [kyonchal] police 우체국 [uchegu] post office 정거장 [chongojan] station 가게 [kage] shop 전철 [chonchol] metro 도서관 [tosogwan] library 은행 [inhen] bank 바 [pa] bar 교회 [kyohwe] church 아파트 [apati] apartment, flat 방 [pan] room 문 [mun] door 부엌 [puok] kitchen 화장실 [hwajansil] toilet 침실 [chimsil] bedroom 층 [chin] floor 창문 [chanmun] window
447cc832f542e46dec032ca967f5d208
{ "intermediate": 0.4452589452266693, "beginner": 0.4218248128890991, "expert": 0.13291628658771515 }
37,064
Format each line into format: wordsArray500[index] = “text of line”; and increase the index for each row by 1 (index starts from 385). Also put " - " symbol after each ] in line. 둘 [tul] two 세 [set] three 넷 [net] four 다섯 [tasot] five 여섯 [yosot] six 일곱 [ilgop] seven 여덟 [yodol] eight 아홉 [ahop] nine 열 [yol] ten 열한 [yolhan] eleven 열두 [yoltu] twelve 열셋 [yolse] thirteen 십사 [sipsa] fourteen 십오 [sip-o] fifteen 열 여섯 [yolyosa] sixteen 십칠 [sipchil] seventeen 십팔 [sippal] eighteen 열 아홉 [yol ahop] nineteen 스물 [simul] twenty 낡은 [nalgin] old 젊은 [cholmin] young 새 [se] new 큰 [kin] big 작은 [chagin] small 좋은 [choin] good 나쁜 [nappin] bad 차가운 [chagaun] cold 뜨거운 [ttigoun] hot 높은 [nopin] high 낮은 [najin] low 좁은 [chobin] narrow 두꺼운 [tukkoun] thick 얇은 [yalbin] thin 오른 [orin] right 왼 [wen] left 가벼운 [kabyoun] light (not heavy) 비싼 [pissan] expensive 싼 [ssan] cheap 빨리 [ppalli] quickly 어두운 [oduun] dark 예쁜, 아름다운 [yeppin, arimdau] beautiful 예 [ye] yes 아니 [aniyo] no 아주 [aju] very 여기에 [yogiye] here 거기에 [kogie] there 누구? [nugu] who? 어디에? [odiye] where? 무엇 [muot] what? 안녕하세요. [annyon haseyo] hello 안녕히 가세요 [annyonyi kaseyo ] goodbye 죄송합니다 [chwesonhamnida] sorry 감사합니다 [kamsahamnida] thanks 천만에요 [chanman-eo] please 달리다 [tallida] run 무서워하다 [musowohada] fear 가지고 가다 [kajigo kada] take 던지다 [tonjida] throw 있다 [itta] be (be located) L이다 [ида] be 끓이다 [kkirida] cook 운반하다 [unbanhada] carry 보다 [poda] see 주의를 주다 [chuiril chuda] pay attention 돌아오다 [toraoda] return, come back ‎기억나다 [kionnada] recall ‎만나다 [mannada] meet ‎들어가다 [tirogada] enter 나가다 [nagada] exit 말하다 [marhada] talk 식사를 준비하다 [siksaril chunbihada] cook 주다 [chuda] give 하다, 만들다 [hada, mandilda] do 나누다 [nanuda] share, split, divide 생각하다 [sengakhada] think 먹다 [mokta] eat 가다 [kada] go
bd1c07eea687b619eaca719274fdf6ad
{ "intermediate": 0.3333013355731964, "beginner": 0.42805400490760803, "expert": 0.23864467442035675 }
37,065
I want to make an http server in node. I know I need to pass in a function "requestListener" to the function http.createServer but am not sure what the type of the function needs to be. Can you tell me the type signature of the function I need to pass in, using jsdoc?
0b1d0176be08d323d88bea4da77853ff
{ "intermediate": 0.547267496585846, "beginner": 0.2749691307544708, "expert": 0.17776332795619965 }
37,066
Can you write a short wrapper for OpenGL VAOs, VBOs and EBOs, perhaps making it possible to port to Vulkan?
83907935d7ca1207469181050d4d1d5c
{ "intermediate": 0.702799916267395, "beginner": 0.1392141878604889, "expert": 0.15798594057559967 }
37,067
Hello
42ed49d6a418a2b64fdfdc86315a8b3d
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
37,068
Où se trouve le pic d'amplitude sonore dans les fichiers extraits par ce script ? import os import subprocess import numpy as np import uuid from moviepy.editor import VideoFileClip from scipy.io import wavfile # Define video file extensions and the output folder video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output' def calculate_loudness(audio_data, rate): """Calculate loudness using ITU-R BS.1770-4 method.""" if audio_data.ndim == 2: audio_data = np.mean(audio_data, axis=1) # convert to mono by averaging channels # Normalization constants for the ITU-R BS.1770-4 method pre_filter = np.array([1.53512485958697, -2.69169618940638, 1.19839281085285]) pre_gain = 1.0 power = 10.0 # Pre-filter audio_data = np.convolve(audio_data, pre_filter) * pre_gain # Calculate power and then LUFS mean_square = np.mean(audio_data ** 2) mean_power = mean_square ** (0.5) loudness = (1 / rate) * np.sum(mean_power ** power) lufs = -0.691 + 10 * np.log10(loudness) return lufs def find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset): """Find the segments with the highest loudness in the audio data.""" # Calculate the loudness of the audio file and loop over to find top segments loudness = np.array([calculate_loudness(audio_data[max(0, idx - int(rate * segment_duration)):min(len(audio_data), idx + int(rate * segment_duration))], rate) for idx in range(0, len(audio_data), int(rate * segment_duration))]) sorted_indices = np.argsort(loudness)[::-1] segments = [] for idx in sorted_indices: if len(segments) >= num_segments: break segment_start_time = idx * segment_duration if segment_start_time < starting_offset or segment_start_time + segment_duration > video_duration - ending_offset: continue segments.append(segment_start_time) return segments def extract_segment(video_path, start_time, duration, output_path): """Use ffmpeg to extract a segment from a video.""" command = [ "ffmpeg", "-y", # Overwrite output files without asking "-ss", str(start_time), # Start time "-i", video_path, # Input file "-t", str(duration), # Duration "-c", "copy", # Copy the streams without re-encoding output_path # Output path ] try: subprocess.run(command, check=True, stderr=subprocess.PIPE) except subprocess.CalledProcessError as e: print(f"ffmpeg command failed: {e.stderr.decode()}") def process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration): """Process a single video file to find and extract the loudest segments.""" unique_id = str(uuid.uuid4()) audio_filename = f'temp_audio_{unique_id}.wav' try: video_clip = VideoFileClip(video_path) video_duration = video_clip.duration video_clip.audio.write_audiofile(audio_filename) rate, audio_data = wavfile.read(audio_filename) segments = find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset) if not os.path.exists(output_folder): os.makedirs(output_folder) for i, start_time in enumerate(segments): output_filename = f"{os.path.splitext(os.path.basename(video_path))[0]}_segment{i+1}.mp4" output_path = os.path.join(output_folder, output_filename) extract_segment(video_path, start_time, segment_duration, output_path) print(f"Extracted segment to {output_path}") finally: os.unlink(audio_filename) # Clean up the temporary file # Main if __name__ == "__main__": starting_offset = float(input("Start offset (sec)? ")) ending_offset = float(input("End offset (sec)? ")) num_segments = int(input("How many segments to extract? ")) segment_duration = float(input("Duration of each segment (sec)? ")) for root, dirs, files in os.walk('.'): for file in files: if any(file.lower().endswith(ext) for ext in video_extensions): video_path = os.path.join(root, file) print(f"Processing video {video_path}…") process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration) print("All videos have been processed.")
38400a23499bd95f3cccbd3515f8273d
{ "intermediate": 0.31758004426956177, "beginner": 0.47774192690849304, "expert": 0.204678013920784 }
37,069
"ffmpeg -framerate 60 -i %d.png -c:v prores_ks -profile:v 4 -tune:v animation -pix_fmt yuva444p10le -vendor ap10 -compression_level 0 z.mov". The PNGS are in 1980x1080, I want the final video to be 1280x720. How do I change the command to let that happen
7d5ec54e25edcaef4de2b6ab0bf26440
{ "intermediate": 0.5968194007873535, "beginner": 0.1784021407365799, "expert": 0.2247784435749054 }
37,070
Please write me a python file that implements a grammar.
50a42ba9789f726fc328e644e86ae8fc
{ "intermediate": 0.39539533853530884, "beginner": 0.3925679624080658, "expert": 0.21203674376010895 }
37,071
How to remove grass in area in Unity
fa6d2d37488ce26c794b8656aa8b1fd3
{ "intermediate": 0.3524782359600067, "beginner": 0.32277441024780273, "expert": 0.32474738359451294 }
37,072
How do I set a source as visible or invisible in OBS websocket
e79ef77070151141dd0518bd7911baba
{ "intermediate": 0.5500949621200562, "beginner": 0.17154933512210846, "expert": 0.2783556878566742 }
37,073
How do I smooth update text in OBS? Like when I need to change some text, it will maybe fade between old and new values? FreeType2
da47bf605b18a5a6f5f4b1d244fafa2e
{ "intermediate": 0.49561822414398193, "beginner": 0.16305847465991974, "expert": 0.34132328629493713 }
37,074
#include <stdio.h> #include <stdlib.h> #define MEMORY_SIZE 1024 // Total memory size #define PARTITION_SIZE 256 // Size of each partition int partitions[MEMORY_SIZE / PARTITION_SIZE]; int partitionCount = MEMORY_SIZE / PARTITION_SIZE; void initializeMemory() { for (int i = 0; i < partitionCount; i++) { partitions[i] = -1; // Initialize all partitions as unallocated } } int allocateMemory(int processSize) { for (int i = 0; i < partitionCount; i++) { if (partitions[i] == -1 && (i + 1) * PARTITION_SIZE >= processSize) { partitions[i] = processSize; return i; // Return the partition number } } return -1; // Memory allocation failed } void deallocateMemory(int partitionNumber) { partitions[partitionNumber] = -1; // Mark the partition as unallocated } int main() { initializeMemory(); // Example processes with different sizes int process1Size = 200; int process2Size = 400; int process3Size = 300; // Allocate memory for processes int partition1 = allocateMemory(process1Size); int partition2 = allocateMemory(process2Size); int partition3 = allocateMemory(process3Size); if (partition1 == -1 ⠺⠵⠞⠵⠵⠺⠵⠞⠞⠞⠞⠵⠟⠺⠵⠺⠵⠺ partition3 == -1) { printf("Memory allocation failed.\n"); } else { printf("Memory allocated for Process 1 in Partition %d\n", partition1); printf("Memory allocated for Process 2 in Partition %d\n", partition2); printf("Memory allocated for Process 3 in Partition %d\n", partition3); // Deallocate memory after process termination deallocateMemory(partition1); deallocateMemory(partition2); deallocateMemory(partition3); } return 0; } correct this code
71a360d4e261e71b6b43a5d547371daa
{ "intermediate": 0.30711793899536133, "beginner": 0.42097559571266174, "expert": 0.27190640568733215 }
37,075
show difference between how attention is implemented in code and in self attention also in code
b49e5d0dfa296d75c05d148e0beca891
{ "intermediate": 0.2587302327156067, "beginner": 0.1580553948879242, "expert": 0.5832143425941467 }
37,076
playwright python
82d1a56100737387cddc717862f11ea6
{ "intermediate": 0.369186133146286, "beginner": 0.3753456771373749, "expert": 0.2554682195186615 }
37,077
Ce script ne s'arrête pas une fois le nombre décidé par l'utilisateur atteint : import os import subprocess import numpy as np import uuid from moviepy.editor import VideoFileClip from scipy.io import wavfile # Define video file extensions and the output folder video_extensions = ['.mp4', '.mkv', '.wmv', '.avi'] output_folder = 'Output' def calculate_loudness(audio_data, rate): """Calculate loudness using ITU-R BS.1770-4 method.""" if audio_data.ndim == 2: audio_data = np.mean(audio_data, axis=1) # convert to mono by averaging channels # Normalization constants for the ITU-R BS.1770-4 method pre_filter = np.array([1.53512485958697, -2.69169618940638, 1.19839281085285]) pre_gain = 1.0 power = 10.0 # Pre-filter audio_data = np.convolve(audio_data, pre_filter) * pre_gain # Calculate power and then LUFS mean_square = np.mean(audio_data ** 2) mean_power = mean_square ** (0.5) loudness = (1 / rate) * np.sum(mean_power ** power) lufs = -0.691 + 10 * np.log10(loudness) return lufs def find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset): """Find the segments with the highest loudness in the audio data.""" # Calculate the loudness of each segment in the audio file segment_loudness = [ calculate_loudness( audio_data[max(0, i * int(rate * segment_duration)) : min(len(audio_data), (i + 1) * int(rate * segment_duration))], rate) for i in range(0, int(video_duration / segment_duration)) ] # Combine segment start times with their corresponding loudness loudness_and_segments = [ (segment_loudness[i], i * segment_duration) for i in range(len(segment_loudness)) if i * segment_duration >= starting_offset and (i + 1) * segment_duration <= video_duration - ending_offset ] # Sort the loudness and segments based on loudness loudness_and_segments.sort(key=lambda x: x[0], reverse=True) # Return the top num_segments segments sorted by loudness return loudness_and_segments[:num_segments] def find_sound_amplitude_peak(audio_data): """Find the position of the highest sound amplitude peak.""" peak_position = np.argmax(np.abs(audio_data)) return peak_position def sort_segments(segments_with_loudness, preference): if preference == 1: return sorted(segments_with_loudness, key=lambda x: x[1]) elif preference == 2: return sorted(segments_with_loudness, key=lambda x: x[1], reverse=True) elif preference == 3: return sorted(segments_with_loudness, key=lambda x: x[0]) elif preference == 4: return sorted(segments_with_loudness, key=lambda x: x[0], reverse=True) def extract_segment(video_path, start_time, duration, output_path): """Use ffmpeg to extract a segment from a video with x264 encoding.""" command = [ "ffmpeg", "-y", # Overwrite output files without asking "-ss", str(start_time), # Start time "-i", video_path, # Input file "-t", str(duration), # Duration "-c:v", "libx264", # Use x264 video codec "-c:a", "aac", # AAC audio codec "-strict", "experimental", # Allow experimental codecs (if necessary for AAC) output_path # Output path ] try: subprocess.run(command, check=True, stderr=subprocess.PIPE) except subprocess.CalledProcessError as e: print(f"ffmpeg command failed: {e.stderr.decode()}") def extract_adjusted_segment(video_path, start_time, duration, output_path, rate, audio_data, peak_position_preference, segment_duration): """Adjust the start time of the segment to position the sound peak where the user wants it.""" peak_position = find_sound_amplitude_peak(audio_data) desired_peak_position = int(segment_duration * peak_position_preference / 6 * rate) adjusted_start_time = max(start_time + (peak_position - desired_peak_position) / rate, 0) extract_segment(video_path, adjusted_start_time, duration, output_path) def process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration, preference, peak_position_preference): """Process a single video file to find and extract the loudest segments.""" unique_id = str(uuid.uuid4()) audio_filename = f'temp_audio_{unique_id}.wav' try: video_clip = VideoFileClip(video_path) video_duration = video_clip.duration video_clip.audio.write_audiofile(audio_filename) rate, audio_data = wavfile.read(audio_filename) segments_with_loudness = find_loudest_segments(audio_data, rate, num_segments, segment_duration, video_duration, starting_offset, ending_offset) # Trier les segments en fonction de la préférence de l'utilisateur sorted_segments = sort_segments(segments_with_loudness, preference) # Anticiper si les noms de fichiers doivent correspondre à l'ordre initial if preference in [1, 2]: initial_order_index = {start_time: i for i, (loudness, start_time) in enumerate(segments_with_loudness)} if not os.path.exists(output_folder): os.makedirs(output_folder) for segment in sorted_segments: loudness, start_time = segment segment_index = initial_order_index[start_time] if preference in [1, 2] else sorted_segments.index(segment) output_filename = f"{os.path.splitext(os.path.basename(video_path))[0]}_segment{segment_index+1}.mp4" output_path = os.path.join(output_folder, output_filename) segment_audio = audio_data[int(start_time*rate):int((start_time+segment_duration)*rate)] extract_adjusted_segment(video_path, start_time, segment_duration, output_path, rate, segment_audio, peak_position_preference, segment_duration) print(f"Extracted and adjusted segment to {output_path}") finally: if os.path.exists(audio_filename): os.unlink(audio_filename) # Clean up the temporary file # Main if __name__ == "__main__": starting_offset = float(input("Start offset (sec)? ")) ending_offset = float(input("End offset (sec)? ")) num_segments = int(input("How many segments to extract? ")) segment_duration = float(input("Duration of each segment (sec)? ")) print("Choose your sorting preference for the extracted files:") print("1 - In order of appearance in the video") print("2 - In reverse order of appearance") print("3 - By increasing loudness") print("4 - By decreasing loudness") preference = int(input("Enter the number of your preference: ")) # Validate the user's preference if preference not in [1, 2, 3, 4]: print("Invalid preference. Please enter a valid number.") exit(1) # Nouveau prompt pour la position du pic sonore print("Choose the position for the maximum sound amplitude peak:") print("1 - at 1/6 of the segment playback time") print("2 - at 2/6 of the segment playback time") print("3 - at 3/6 of the segment playback time") print("4 - at 4/6 of the segment playback time") print("5 - at 5/6 of the segment playback time") peak_position_preference = int(input("Enter the number of your preference (1-6): ")) # Validate the user’s preference if peak_position_preference not in range(1, 7): print("Invalid preference. Please enter a number between 1 and 6.") exit(1) for root, dirs, files in os.walk('.'): for file in files: if any(file.lower().endswith(ext) for ext in video_extensions): video_path = os.path.join(root, file) print(f"Processing video {video_path}…") process_video_file(video_path, starting_offset, ending_offset, num_segments, segment_duration, preference, peak_position_preference) print("All videos have been processed.")
896a76ca2223d93d8419f5df6408203b
{ "intermediate": 0.299064964056015, "beginner": 0.44028475880622864, "expert": 0.26065030694007874 }
37,078
Try to create a realistic face out of letters.
29fab3827db97e3a316e28e4f10b6374
{ "intermediate": 0.4100341200828552, "beginner": 0.265054851770401, "expert": 0.32491105794906616 }
37,079
HI
af3125b47c72ce3507e37981cb5e9b99
{ "intermediate": 0.32988452911376953, "beginner": 0.2611807882785797, "expert": 0.40893468260765076 }
37,080
How can I write the following boolean logic in a single expression? if (completeConditions.isAllMatchRequired() && !checkMatchingConditionsWith(Stream::allMatch)) return false; return envelope.getAdaptationContext().checkCondition(completeConditions);
dc6d0c13ee25b2557ac3f77060e54cc0
{ "intermediate": 0.5106136202812195, "beginner": 0.280582070350647, "expert": 0.20880432426929474 }
37,081
hy please help me with commands for installing mitm tools using powershell
59805aebd5d19e996745faeaced7d62e
{ "intermediate": 0.5324019193649292, "beginner": 0.13018785417079926, "expert": 0.33741018176078796 }
37,082
make a quick python script that scrap the images of an url but also sort out icons and ads
56890f6ecdfc22eec2111d99d255cc1e
{ "intermediate": 0.40905505418777466, "beginner": 0.2028275430202484, "expert": 0.38811740279197693 }
37,083
safely close the threads again: def download_image(image_url, destination_folder, session): if not is_likely_ad_or_icon(image_url): try: with session.get(image_url, stream=True) as r: r.raise_for_status() img_name = os.path.basename(urlparse(image_url).path) img_path = os.path.join(destination_folder, img_name) with open(img_path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) print(f"Downloaded {img_name} to {destination_folder}") except Exception as e: print(f"Could not download {image_url}: {e}") # Function to download images using multithreading def download_images(url, destination_folder, session): # Create the folder path if it doesn't exist if not os.path.isdir(destination_folder): os.makedirs(destination_folder) response = session.get(url) soup = BeautifulSoup(response.text, "html.parser", parse_only=SoupStrainer("img")) images = [ urljoin(url, img.get("src") or img.get("data-src")) for img in soup if img.get("src") or img.get("data-src") ] # Use ThreadPoolExecutor to download images in parallel with ThreadPoolExecutor(max_workers=10) as executor: for image_url in images: executor.submit(download_image, image_url, destination_folder, session) def remove_files(): for files in os.listdir("downloaded_images"): os.remove(os.path.join("downloaded_images", files)) def get_images(links): fixed_urls = [BeautifulSoup(tag, "html.parser").a["href"] for tag in links if tag] session = requests.Session() # Using session object for connection pooling destination_dir = "downloaded_images" # Download images from all links using multithreading with ThreadPoolExecutor(max_workers=10) as executor: for link in fixed_urls: executor.submit(download_images, link, destination_dir, session)
f82b9981b57374e5feb623b9dddc51df
{ "intermediate": 0.3441447913646698, "beginner": 0.42781656980514526, "expert": 0.22803860902786255 }
37,084
What is top-p (nucleus sampling) in AI chat settings?
a61abaca9c4ed363cbb49ebd72b4eee8
{ "intermediate": 0.09690132737159729, "beginner": 0.11174584180116653, "expert": 0.7913528084754944 }
37,085
tell me what's wrong with this post: async get_images() { const response = await fetch(`${this.host}api/get_prepareItem_image`, { method: 'POST', }); if (!response.ok) { this.$toast.add({ severity: 'info', summary: 'Error', detail: 'Lyckades inte hämta bilderna.', life: 3000 }); return }; response = await response.json(); console.log(response.body) this.images = response; }, @app.post("/api/get_prepareItem_image") async def get_prepareItem_images(): images = [] for image in os.listdir("downloaded_images"): image_path = os.path.join("downloaded_images", image) with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) images.append(encoded_string) return {"images": images}
17d106340c67cc19f0cf818378f97b03
{ "intermediate": 0.456308513879776, "beginner": 0.4053799510002136, "expert": 0.13831156492233276 }
37,086
fix this so it adds the images from the response correctly so I can render them out: async get_images() { const response = await fetch(`${this.host}api/get_prepareItem_image`, { method: 'GET', }); if (!response.ok) { this.$toast.add({ severity: 'Error', summary: 'Error', detail: 'Lyckades inte hämta bilderna.', life: 3000 }); return }; response = await response.json(); console.log(response.body) this.images = response; }, @app.post("/api/get_prepareItem_image") async def get_prepareItem_images(): images = [] for image in os.listdir("downloaded_images"): image_path = os.path.join("downloaded_images", image) with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) images.append(encoded_string) return {"images": images}
2f94cef121ff92c82896a2d079a1eb0b
{ "intermediate": 0.42805275321006775, "beginner": 0.39593470096588135, "expert": 0.17601244151592255 }
37,087
render this an array like this here: <template> <Dialog v-model:visible="choosing_picture" header="Information" :style="{ width: '70%' }" :modal="true"> <div style="text-align: center;"> <label for="name" style="display: inline-block; margin-bottom: 10px; font-weight: bold;">Bilder: </label> </div> <div style="text-align: center;"> <Button label="Stäng" style="display: inline-block; margin-bottom: 10px; font-weight: bold;" @click="choosing_picture = false" /> </div> </Dialog> the array is a list of pictures in base64 format jpg
54fa7891293501f28fce049579b208f8
{ "intermediate": 0.4319235384464264, "beginner": 0.23746243119239807, "expert": 0.33061403036117554 }
37,088
my initial email: Good day, I trust this message finds you in good health and spirits. I am writing to kindly seek clarification regarding the payment status of my Practicum Fee for course COA.220626.0001 (CPE199R) for the term 3T 22-23. As per my records, I have settled the amount of PHP 1,200, but it appears that my payment has not yet been reflected in your system. For your convenience and verification purposes, please find attached an image of the official receipt. The details are as follows - Student ID: - Official Receipt (OR) Number: - Course: COA.220626.0001 - PRACTICUM FEE 3T 22-23 (CPE199R) - Amount Paid: I kindly request that the payment be verified and the necessary adjustments be made to my account to reflect the correct payment status. The prompt resolution of this matter is crucial for me to ensure that my enrollment and academic responsibilities continue without any hindrances. I sincerely appreciate your time and assistance in resolving this issue. Should there be any further information or documentation required, please do not hesitate to let me know, and I will promptly provide it. Thank you in advance for your attention to this matter. I look forward to your confirmation of the payment update. Warm regards,
2d947a77db6167980add07a84efe2e5b
{ "intermediate": 0.3524458408355713, "beginner": 0.27957338094711304, "expert": 0.3679807484149933 }
37,089
how to extract google alert in python
47554d2509625663419c00d4e5a8d1e3
{ "intermediate": 0.3543270528316498, "beginner": 0.14628654718399048, "expert": 0.49938637018203735 }
37,090
make sure it use the check for ads and also don't save svgs: import os import requests from bs4 import BeautifulSoup, SoupStrainer from concurrent.futures import ThreadPoolExecutor from urllib.parse import urljoin, urlparse # Function to determine if the image is likely an ad or icon def is_likely_ad_or_icon(image_url, minimum_size_kb=10): # Define common ad and icon indicator keywords common_ad_indicators = ["ad", "banner", "sponsor"] common_icon_indicators = ["favicon", "logo", "icon"] # Check for ad indicators in the URL if any(indicator in image_url.lower() for indicator in common_ad_indicators): return True # Try to fetch the image content size try: response = requests.head(image_url, timeout=5) content_length = response.headers.get("content-length", None) if content_length and int(content_length) < minimum_size_kb * 1024: return True except Exception as e: print(f"Could not fetch head for {image_url}: {e}") return any(indicator in image_url.lower() for indicator in common_icon_indicators) def download_image(image_url, destination_folder, session): if not is_likely_ad_or_icon(image_url): try: with session.get(image_url, stream=True) as r: r.raise_for_status() img_name = os.path.basename(urlparse(image_url).path) img_path = os.path.join(destination_folder, img_name) with open(img_path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) print(f"Downloaded {img_name} to {destination_folder}") except Exception as e: print(f"Could not download {image_url}: {e}") # Function to download images using multithreading def download_images(url, destination_folder, session): # Create the folder path if it doesn't exist if not os.path.isdir(destination_folder): os.makedirs(destination_folder) response = session.get(url) soup = BeautifulSoup(response.text, "html.parser", parse_only=SoupStrainer("img")) images = [ urljoin(url, img.get("src") or img.get("data-src")) for img in soup if img.get("src") or img.get("data-src") ] # Use ThreadPoolExecutor to download images in parallel with ThreadPoolExecutor(max_workers=10) as executor: for image_url in images: executor.submit(download_image, image_url, destination_folder, session) def remove_files(): for files in os.listdir("downloaded_images"): os.remove(os.path.join("downloaded_images", files)) def get_images(links): fixed_urls = [BeautifulSoup(tag, "html.parser").a["href"] for tag in links if tag] with requests.Session() as session: # Now using the context manager for the session destination_dir = "downloaded_images" with ThreadPoolExecutor(max_workers=10) as executor: for link in fixed_urls: executor.submit(download_images, link, destination_dir, session)
dad3abd70164b83dc6dc6ff3d4e31ec4
{ "intermediate": 0.43905431032180786, "beginner": 0.3917458653450012, "expert": 0.1691998541355133 }
37,091
{% block styles %} <link rel="stylesheet" href="{{ url_for('static', filename='admin_evenements.css') }}"> {% endblock %} {% block content %} <a id="retour" href="{{ url_for('menu_admin') }}" class="btn-retour">Retour</a> <h1>Les événements du festival</h1> <table> <thead> <tr> <th>id Evenement</th> <th>id Groupe</th> <th>nom Evenement</th> <th>heure de début</th> <th>heure de fin</th> <th>Date de début</th> <th>Date de fin</th> <th>Actions</th> </tr> </thead> <tbody> {% for evenement in liste_evenements %} <tr> <td>{{ evenement.get_idE() }}</td> <td>{{ evenement.get_idG() }}</td> <td>{{ evenement.get_nomE() }}</td> <td>{{ evenement.get_heureDebutE() }}</td> <td>{{ evenement.get_heureFinE() }}</td> <td>{{ evenement.get_dateDebutE() }}</td> <td>{{ evenement.get_dateFinE() }}</td> <td> <button class="btn-modifier" data-id="{{ evenement.get_idE() }}" data-nom = "{{ evenement.get_nomE() }}" data-heureDebut = "{{ evenement.get_heureDebutE() }}" data-heureFin = "{{ evenement.get_heureFinE() }}" data-dateDebut = "{{ evenement.get_dateDebutE() }}" data-dateFin = "{{ evenement.get_dateFinE() }}">Modifier</button> <button class="btn-supprimer" data-id="{{ evenement.get_idE() }}">Supprimer</button> </td> </tr> {% endfor %} </tbody> </table> <div id="modal-modifier" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="/modifier_evenement" method="post"> <!-- ID Evenement (caché) --> <input type="hidden" name="id_evenement" id="id_evenement_modifier" value=""> <!-- Champs pour la modification --> <input type="text" name="nom_evenement" id="nom_evenement_modifier" placeholder="Nom de l'événement"> </form> </div> </div> <button id="ajouter">Ajouter</button> <script> document.addEventListener("DOMContentLoaded", function() { var modalModifier = document.getElementById("modal-modifier"); var btnClose = document.querySelectorAll(".close-button"); btnClose.forEach(function(btn) { btn.onclick = function() { modalModifier.style.display = "none"; }; }); document.querySelectorAll(".btn-modifier").forEach(function(btn) { btn.onclick = function() { document.getElementById("id_evenement_modifier").value = btn.getAttribute("data-id"); document.getElementById("nom_evenement_modifier").value = btn.getAttribute("data-nom"); modalModifier.style.display = "block"; }; }); }); </script> {% endblock %} j'aimerais dans mon modal modifier ajouter un menu déroulant pour choisir les horaires, et aussi de quoi choisir les dates
3f434bfec581615dbd9c12f95e13161b
{ "intermediate": 0.32542526721954346, "beginner": 0.5041908025741577, "expert": 0.17038396000862122 }
37,092
explain to me like im 10 the difference between empathy and sympathy and give example
40e9dbeeab9a591bf16a82e6959140d4
{ "intermediate": 0.352898508310318, "beginner": 0.33406007289886475, "expert": 0.31304144859313965 }
37,093
store the name of the picture too before sending back the array, @app.post("/api/get_prepareItem_image") async def get_prepareItem_images(): images = [] for image in os.listdir("downloaded_images"): image_path = os.path.join("downloaded_images", image) with open(image_path, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) # Assuming the images are in JPEG format images.append("data:image/jpg;base64," + encoded_string.decode("utf-8")) return JSONResponse({"images": images})
885ed7a142cc4ea0c30dc26d0ec48064
{ "intermediate": 0.46353310346603394, "beginner": 0.3490239381790161, "expert": 0.18744294345378876 }
37,094
select * top(100) from db
9e676174e0ab8bda535bddf04db848f6
{ "intermediate": 0.2913600206375122, "beginner": 0.3086675703525543, "expert": 0.39997240900993347 }
37,095
Please, edit the text: To simplify your work with views you can use **Dataverse view** block during page editing. Here you can choose table and view name in dropdowns. Also you can set cache time in seconds or change language for the view. Page size manages the quantity of records on each page. Number of pages shows the digital quantity of pages at the bottom of the screen (Note in your work that the value to be set in the text field must be an odd number.). You can also choose fetchXML template in the dropdown to filter view. To filter view according lookup set similar value in the lookups substitution textbox: {% raw %}
c8d8527d025868aa94528894ff14ca21
{ "intermediate": 0.3825272023677826, "beginner": 0.2149573713541031, "expert": 0.40251538157463074 }
37,096
<el-button type="text" icon="el-icon-edit" class="arfa-button" @click="handleProEdit(scope.$index, scope.row)"></el-button> <el-button type="text" icon="el-icon-video-play" class="arfa-button" :loading="scope.row.prop_state === 1" @click="createProp(scope.$index, scope.row)"></el-button> <el-button type="text" icon="el-icon-view" class="arfa-button" @click="goToDetail(scope.$index, scope.row)"></el-button> <el-button type="text" icon="el-icon-view" class="arfa-button" @click="goToDetail(scope.$index, scope.row)"></el-button> <el-button type="text" icon="el-icon-document" class="arfa-button" :disabled="scope.row.job_state === 0 || scope.row.job_state === 4" @click="fetchSubmitLog(scope.$index, scope.row)"></el-button> <el-button type="text" icon="el-icon-video-play" class="arfa-button" :loading="scope.row.job_state === 4" :disabled="scope.row.job_state === 1" @click="submitTask(scope.$index, scope.row)"></el-button>
40ba39d42102e205ec0fe1b0497ed018
{ "intermediate": 0.3251481354236603, "beginner": 0.36425846815109253, "expert": 0.3105933964252472 }
37,097
//±-----------------------------------------------------------------+ //| ZZ_EA.mq4 | //| Copyright © 2023, Gabriele Bassi | //±-----------------------------------------------------------------+ #property strict // External input parameters for the EA input double TakeProfitPips = 400; // Take profit in pips input double StopLossPips = 150; // Stop loss in pips input double TrailingStopPips = 10; // Trailing stop in pips // External input parameters for the indicator input int CCI_Period = 12; input int Momentum_Period = 21; input int RSI_Period = 14; input double SAR_Step = 0.01; input double SAR_Maximum = 0.2; // OnInit is called when the expert is loaded onto a chart int OnInit() { // Initialization code here return INIT_SUCCEEDED; } // OnTick is called on every new tick void OnTick() { // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // If there are no current orders, check for a buy or sell signal if(OrdersTotal() == 0) { if(arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order. double sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); double tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_BUY, 0.1, Ask, 2, sl, tp, "Buy order based on ZZZZZ", 0, 0, clrGreen); if(ticket < 0) { Print("An error occurred while sending a buy order: ", GetLastError()); } } if(arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order. double sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); double tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_SELL, 0.1, Bid, 2, sl, tp, "Sell order based on ZZZZZ", 0, 0, clrRed); if(ticket < 0) { Print("An error occurred while sending a sell order: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); } } // TrailingStopFunc adjusts the stop loss to enable a trailing stop void TrailingStopFunc() { for(int i = OrdersTotal() - 1; i >= 0; i--) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { // Verify that the selected order is for the current symbol if(OrderSymbol() == Symbol() && OrderMagicNumber() == 0) { if(OrderType() == OP_BUY) { // Current price is far enough from the opening price to move stop loss if(Bid - OrderOpenPrice() > TrailingStopPips * Point) { double newStopLoss = Bid - TrailingStopPips * Point; // Update the stop loss if it is less than the current stop loss if(newStopLoss > OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrGreen); } } } else if(OrderType() == OP_SELL) { // Current price is far enough from the opening price to move stop loss if(OrderOpenPrice() - Ask > TrailingStopPips * Point) { double newStopLoss = Ask + TrailingStopPips * Point; // Update the stop loss if it is greater than the current stop loss if(newStopLoss < OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrRed); } } } } } } } //±-----------------------------------------------------------------+ aggiungi la gestione del lotto
ec3ade43b61e2578139c64c355b9943d
{ "intermediate": 0.3004589378833771, "beginner": 0.49867647886276245, "expert": 0.20086458325386047 }
37,098
Привет! У меня есть бот telegram для смены фона фото и его уникализации. Я хочу добавить функцию, которая позволит пользователям загружать свои "пресеты", то есть несколько фотографий, у которых потом по кнопке бот будет менять фон и уникализировать. Вот код моего бота: import logging from PIL import Image, ImageOps, ImageFilter, ImageEnhance, ImageDraw import random from io import BytesIO import aiohttp from aiogram import Bot, Dispatcher, executor, types from aiogram.types import ReplyKeyboardMarkup, KeyboardButton from aiogram.contrib.middlewares.logging import LoggingMiddleware from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.filters import CommandStart from aiogram.contrib.fsm_storage.memory import MemoryStorage import aiosqlite import asyncio import time import datetime import math import os API_TOKEN = '6796504222:AAFpaCTHBnBwtnLcSMW371gGNmPiWDVPp6U' ADMIN_ID = 989037374 # Замените на ваш телеграм ID админа logging.basicConfig(level=logging.INFO) bot = Bot(token=API_TOKEN) dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup(LoggingMiddleware()) # Состояния для загрузки фото class UploadState(StatesGroup): waiting_for_photo = State() class PhotoState(StatesGroup): waiting_for_user_photo = State() # Подключаемся к БД async def create_db_tables(): conn = await get_db_connection() await conn.execute("""CREATE TABLE IF NOT EXISTS whitelist ( user_id INTEGER PRIMARY KEY, subscription_end INTEGER, backgrounds_changed INTEGER DEFAULT 0 ); """) await conn.execute("""CREATE TABLE IF NOT EXISTS photos ( id INTEGER PRIMARY KEY AUTOINCREMENT, photo_id TEXT NOT NULL ); """) await conn.execute(""" CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT ); """) await conn.execute(""" CREATE TABLE IF NOT EXISTS templates ( user_id INTEGER NOT NULL, photo_ids TEXT, UNIQUE(user_id) ); """) await conn.commit() await conn.close() async def get_db_connection(): conn = await aiosqlite.connect('bot.db') await conn.execute('PRAGMA busy_timeout = 15000') return conn # Инициализируем БД @dp.message_handler(commands=['init'], state="*") async def init_db(message: types.Message): if message.from_user.id == ADMIN_ID: conn = await get_db_connection() await conn.execute("CREATE TABLE IF NOT EXISTS whitelist (user_id INTEGER PRIMARY KEY)") await conn.execute( "CREATE TABLE IF NOT EXISTS photos (id INTEGER PRIMARY KEY AUTOINCREMENT, photo_id TEXT NOT NULL)") await conn.commit() await conn.close() await message.answer("БД инициализирована.") else: await message.answer("Недостаточно прав.") @dp.message_handler(commands=['count'], user_id=ADMIN_ID) async def count_backgrounds(message: types.Message): conn = await get_db_connection() cur = await conn.execute("SELECT COUNT(*) FROM photos") count = await cur.fetchone() await conn.close() if count is not None: await message.answer(f"Количество доступных фонов в БД: **{count[0]}**",parse_mode='MarkdownV2') else: await message.answer("Не удалось получить количество фонов.") # Добавляем пользователя в whitelist @dp.message_handler(commands=['add'], state="*") async def add_to_whitelist(message: types.Message): if message.from_user.id == ADMIN_ID: args = message.get_args().split() if len(args) == 1 and args[0].isdigit(): user_id = int(args[0]) conn = await get_db_connection() subscription_end = int(time.time()) + 30 * 86400 # 30 days in seconds await conn.execute( "INSERT OR IGNORE INTO whitelist (user_id, subscription_end) VALUES (?, ?)", (user_id, subscription_end) ) await conn.commit() await conn.close() await message.answer(f"Пользователь {user_id} добавлен в whitelist на 30 дней.") else: await message.answer("Неверный формат команды. Используйте /add user_id.") else: await message.answer("Недостаточно прав.") @dp.message_handler(commands=['info'], user_id=ADMIN_ID) async def info_subscription(message: types.Message): args = message.get_args().split() if len(args) == 1 and args[0].isdigit(): user_id = int(args[0]) conn = await get_db_connection() cur = await conn.execute( "SELECT subscription_end, backgrounds_changed FROM whitelist WHERE user_id = ?", (user_id,) ) user_info = await cur.fetchone() if user_info: subscription_end = datetime.datetime.fromtimestamp(user_info[0]) await message.answer( f"Пользователь {user_id} имеет подписку до {subscription_end} и сменил фон {user_info[1]} раз." ) else: await message.answer("Пользователь не найден в whitelist.") await conn.close() else: await message.answer("Неверный аргумент команды. Используйте /info user_id.") @dp.message_handler(commands=['plus'], user_id=ADMIN_ID) async def add_subscription_days(message: types.Message): args = message.get_args().split() if len(args) == 2 and args[0].isdigit() and args[1].isdigit(): user_id = int(args[0]) days_to_add = int(args[1]) conn = await get_db_connection() # Добавляем дни к существующей подписке await conn.execute(""" UPDATE whitelist SET subscription_end = subscription_end + (? * 86400) WHERE user_id = ? """, (days_to_add, user_id)) await conn.commit() await conn.close() await message.answer(f"Пользователю {user_id} продлена подписка на {days_to_add} дней.") else: await message.answer("Неверный формат команды. Используйте /plus user_id days.") @dp.message_handler(commands=['minus'], user_id=ADMIN_ID) async def subtract_subscription_days(message: types.Message): args = message.get_args().split() if len(args) == 2 and args[0].isdigit() and args[1].isdigit(): user_id = int(args[0]) days_to_subtract = int(args[1]) conn = await get_db_connection() # Отнимаем дни от существующей подписки await conn.execute(""" UPDATE whitelist SET subscription_end = subscription_end - (? * 86400) WHERE user_id = ? AND subscription_end - (? * 86400) >= strftime('%s', 'now') """, (days_to_subtract, user_id, days_to_subtract)) affected_rows = conn.total_changes await conn.commit() await conn.close() if affected_rows: await message.answer(f"У пользователя {user_id} убрано {days_to_subtract} дней подписки.") else: await message.answer(f"Не удалось убрать дни подписки у пользователя {user_id}. " "Проверьте базу данных или аргументы команды.") else: await message.answer("Неверный формат команды. Используйте /minus user_id days.") @dp.message_handler(commands=['delete'], user_id=ADMIN_ID) async def delete_from_whitelist(message: types.Message): args = message.get_args().split() if len(args) == 1 and args[0].isdigit(): user_id = int(args[0]) conn = await get_db_connection() # Удаляем пользователя из whitelist await conn.execute("DELETE FROM whitelist WHERE user_id = ?", (user_id,)) await conn.commit() await conn.close() await message.answer(f"Пользователь {user_id} удален из whitelist.") else: await message.answer("Неверный формат команды. Используйте /delete user_id.") @dp.message_handler(commands=['list'], user_id=ADMIN_ID) async def list_whitelisted_users(message: types.Message): conn = await get_db_connection() # Получаем список всех пользователей с активной подпиской cur = await conn.execute(""" SELECT user_id, subscription_end FROM whitelist WHERE subscription_end > strftime('%s', 'now') """) users = await cur.fetchall() await conn.close() # Формируем и отправляем ответ if users: user_list = [] for user_id, subscription_end in users: subscription_end_date = datetime.datetime.fromtimestamp(int(subscription_end)).strftime('%Y-%m-%d %H:%M:%S') user_list.append(f"ID: {user_id}, подписка до: {subscription_end_date}") users_info = '\n'.join(user_list) await message.answer(f"Пользователи с активной подпиской:\n{users_info}") else: await message.answer("Нет пользователей с активной подпиской.") @dp.message_handler(commands=['post'], user_id=ADMIN_ID) async def post_to_all_users(message: types.Message): args = message.get_args() if not args: await message.answer("Пожалуйста, укажите текст сообщения после команды /post.") return conn = await get_db_connection() # Предполагаем, что в таблице users есть столбец user_id cur = await conn.execute("SELECT user_id FROM users") users = await cur.fetchall() await conn.close() for user_id_tuple in users: try: # Отправляем сообщение каждому пользователю await bot.send_message(user_id_tuple[0], args) except Exception as e: # Возможно, следует обработать исключения, например, если пользователь заблокировал бота logging.exception(e) await message.answer("Сообщения отправлены.") # Старт загрузки фото @dp.message_handler(commands=['upload'], state="*") async def start_upload(message: types.Message): if message.from_user.id == ADMIN_ID: await UploadState.waiting_for_photo.set() await message.answer("Загрузите фото одним сообщением. Когда закончите, введите /ustop") else: await message.answer("Недостаточно прав.") # Обработка загружаемых фото @dp.message_handler(content_types=['photo'], state=UploadState.waiting_for_photo) async def handle_photo(message: types.Message, state: FSMContext): if message.from_user.id == ADMIN_ID: photo_id = message.photo[-1].file_id conn = await get_db_connection() await conn.execute("INSERT INTO photos (photo_id) VALUES (?)", (photo_id,)) await conn.commit() await conn.close() # Остановка загрузки фото @dp.message_handler(commands=['ustop'], state=UploadState.waiting_for_photo) async def stop_upload(message: types.Message, state: FSMContext): if message.from_user.id == ADMIN_ID: await state.finish() await message.answer("Загрузка фотографий завершена.") else: await message.answer("Недостаточно прав.") # Очистка базы данных фотографий @dp.message_handler(commands=['clear'], state="*") async def clear_photos(message: types.Message): if message.from_user.id == ADMIN_ID: conn = await get_db_connection() await conn.execute("DELETE FROM photos") await conn.commit() await conn.close() await message.answer("Все фотографии удалены.") else: await message.answer("Недостаточно прав.") keyboard = ReplyKeyboardMarkup(resize_keyboard=True) keyboard.add(KeyboardButton("🖼 Поменять фон")) keyboard.add(KeyboardButton("🧑‍💻 Профиль")) # Отправляем клавиатуру пользователю @dp.message_handler(CommandStart(), state="*") async def send_welcome(message: types.Message): user_id = message.from_user.id chat_id = '-1001904990371' conn = await get_db_connection() # Добавляем пользователя в таблицу users, если его там еще нет await conn.execute(""" INSERT OR IGNORE INTO users (user_id) VALUES (?) """, (user_id,)) # Проверяем, есть ли пользователь в whitelist cur = await conn.execute(""" SELECT user_id FROM whitelist WHERE user_id = ? """, (user_id,)) user_info = await cur.fetchone() if user_info: await message.reply("👋 **Привет\!** Нажми на кнопку ниже для смены фона\.", reply_markup=keyboard, parse_mode='MarkdownV2') else: await message.reply("😭 **Вы не находитесь в whitelist.** Для приобретения доступа напишите @ih82seeucry",parse_mode='MarkdownV2') await conn.commit() await conn.close() # Функция для изменения размера фотографии пользователя def resize_user_photo(user_photo, base_width, base_height, padding=70): new_width = base_width - padding * 2 new_height = base_height - padding * 2 user_photo.thumbnail((new_width, new_height), Image.Resampling.LANCZOS) return user_photo async def download_photo(file_id): async with aiohttp.ClientSession() as session: file_path = await bot.get_file(file_id) photo_url = f"https://api.telegram.org/file/bot{API_TOKEN}/{file_path.file_path}" async with session.get(photo_url) as response: if response.status == 200: return await response.read() response.raise_for_status() class TemplateState(StatesGroup): waiting_for_template_photos = State() @dp.message_handler(lambda message: message.text == "🧑‍💻 Профиль", state="*") async def user_profile(message: types.Message): user_id = message.from_user.id conn = await get_db_connection() # Получаем информацию о подписке пользователя cur = await conn.execute(""" SELECT subscription_end FROM whitelist WHERE user_id = ? """, (user_id,)) subscription_info = await cur.fetchone() await conn.close() if subscription_info: # Пользователь в whitelist, преобразуем timestamp в читаемый формат subscription_end = datetime.datetime.fromtimestamp( int(subscription_info[0]) ).strftime('%Y-%m-%d %H:%M:%S') escaped_end = subscription_end.replace('-', '\-').replace('.', '\.') await message.answer(f"**🧑‍💻 Ваш профиль**\n\n**Ваш user id:** `{user_id}`\n**Время окончания подписки:** {escaped_end}", parse_mode='MarkdownV2') else: # Пользователь не в whitelist await message.answer(f"Ваш user id: `{user_id}`\n**У вас нет активной подписки**\. Для приобретения напишите @ih82seeucry", parse_mode='MarkdownV2') @dp.message_handler(commands=['admin'], user_id=ADMIN_ID) async def admin_help(message: types.Message): admin_commands = ( "/init - Инициализировать базу данных бота", "/count - Узнать количество фонов в базе данных", "/add [user_id] - Добавить пользователя в whitelist на 30 дней", "/info [user_id] - Получить информацию о подписке пользователя", "/plus [user_id] [days] - Добавить дополнительные дни к подписке пользователя", "/minus [user_id] [days] - Убавить дни подписки пользователя", "/delete [user_id] - Удалить пользователя из whitelist", "/list - Показать список всех пользователей с их подписками", "/post - Отправить сообщение всем пользователям", "/clear - Удалить все фотографии из базы данных", "/upload - Начать загрузку фотографий для фона", "/ustop - Закончить загрузку фотографий для фона", ) await message.answer("\n".join(admin_commands)) # Начало процесса смены фона @dp.message_handler(lambda message: message.text == "🖼 Поменять фон", state="*") async def change_background(message: types.Message, state: FSMContext): await PhotoState.waiting_for_user_photo.set() # Отправляем сообщение и ждем пользовательское фото await message.reply("**Загрузите ваши фото одним сообщением\.** Если бот не ответил, пропишите /start", reply_markup=types.ReplyKeyboardRemove(),parse_mode='MarkdownV2') # Запоминаем, что пользователь начал процесс смены фона await state.update_data(changing_background=True) # Обновленная функция накладывания фотографий @dp.message_handler(content_types=['photo'], state=PhotoState.waiting_for_user_photo) async def overlay_photo_on_background(message: types.Message, state: FSMContext): await message.reply("**Обрабатываю фотографии\.** Подождите, пожалуйста\.", parse_mode='MarkdownV2') user_photo_id = message.photo[-1].file_id conn = await get_db_connection() # Получаем случайное фото фона из БД cur = await conn.execute("SELECT id, photo_id FROM photos ORDER BY RANDOM() LIMIT 1") photo_info = await cur.fetchone() if photo_info is None: await message.answer("Нет доступных фоновых изображений.") await state.finish() return background_photo_id = photo_info[1] # Скачиваем фото фона и пользовательское фото background_data = await download_photo(background_photo_id) user_photo_data = await download_photo(user_photo_id) with Image.open(BytesIO(background_data)) as background, Image.open(BytesIO(user_photo_data)) as user_photo: # Пропорции и размеры для пользовательского фото с учетом отступов padding = 70 new_user_width = user_photo.width + padding * 2 new_user_height = user_photo.height + padding * 2 user_photo.thumbnail((new_user_width, new_user_height), Image.Resampling.LANCZOS) background = background.convert("RGBA") # Рассчитываем новые пропорции для фона new_background_width = max(background.width, new_user_width) new_background_height = max(background.height, new_user_height) # Растягиваем фон до новых размеров background = background.resize((new_background_width, new_background_height), Image.Resampling.LANCZOS) # Применяем размытие Гаусса на 20% к фону background = background.filter(ImageFilter.GaussianBlur(radius=background.size[0] * 0.006)) # Если пользовательское изображение не в формате RGBA, конвертируем его if user_photo.mode != 'RGBA': user_photo = user_photo.convert("RGBA") # Создаем маску прозрачности для альфа-канала mask = user_photo.split()[3] # Позиционируем пользовательское изображение по центру растянутого и размытого фона position = ((background.width - user_photo.width) // 2, (background.height - user_photo.height) // 2) background.paste(user_photo, position, user_photo) enhancer = ImageEnhance.Brightness(background) factor = random.uniform(0.7, 1.25) background = enhancer.enhance(factor) # Создание серых полос draw = ImageDraw.Draw(background) num_lines = random.randint(10, 20) # Случайное число полос от 10 до 20 for _ in range(num_lines): # Используем num_lines для случайного количества полос # Определяем длину полосы length = random.randint(150, 300) # Определяем угол наклона в радианах angle = random.uniform(0, 2 * math.pi) # Определяем произвольное начальное положение для полосы start_x = random.randint(0, background.width) start_y = random.randint(0, background.height) # Вычисляем конечное положение для полосы end_x = start_x + int(length * math.cos(angle)) end_y = start_y + int(length * math.sin(angle)) # Рисуем линию с полупрозрачностью draw.line((start_x, start_y, end_x, end_y), fill=(128, 128, 128, 60), width=1) del draw draw = ImageDraw.Draw(background) num_color_lines = random.randint(30, 45) # Случайное число разноцветных полос for _ in range(num_color_lines): # Итерации для разноцветных полос # Генерируем случайные RGB-значения для цвета r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) # Определяем длину полосы length = random.randint(5, 7) # Определяем угол наклона в радианах angle = random.uniform(0, 2 * math.pi) # Определяем произвольное начальное положение для полосы starty_x = random.randint(0, background.width) starty_y = random.randint(0, background.height) # Вычисляем конечное положение для полосы endy_x = starty_x + int(length * math.cos(angle)) endy_y = starty_y + int(length * math.sin(angle)) # Рисуем разноцветную линию с полупрозрачностью draw.line((starty_x, starty_y, endy_x, endy_y), fill=(r, g, b, 165), width=4) # Удаляем объект рисования, так как он больше не нужен del draw # Создание белого шума noise_image = Image.new('RGB', background.size) noise_pixels = [ (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for _ in range(background.width * background.height) ] noise_image.putdata(noise_pixels) # Конвертируем изображение шума в формат 'RGBA' и изменяем альфа-канал noise_image = noise_image.convert('RGBA') noise_alpha = Image.new('L', noise_image.size, color=55) # Альфа-канал с 10% непрозрачности (25 из 255) noise_image.putalpha(noise_alpha) # Накладываем белый шум на изображение background = Image.alpha_composite(background, noise_image) # Сохраняем результат в объект BytesIO result_image_io = BytesIO() background.save(result_image_io, format='PNG') result_image_io.seek(0) # Отправляем пользователю новое изображение await bot.send_photo(message.chat.id, photo=result_image_io) # Удаляем использованный фон из БД await conn.execute("DELETE FROM photos WHERE id = ?", (photo_info[0],)) await conn.commit() await conn.close() await state.finish() await message.answer("Фото обработано.", reply_markup=keyboard) async def subscription_check(): while True: # Бесконечный цикл try: conn = await get_db_connection() # Удаляем подписки, которые истекли await conn.execute(""" DELETE FROM whitelist WHERE subscription_end < strftime('%s', 'now') """) await conn.commit() await conn.close() except Exception as e: # Логгируем возможные ошибки при работе с базой данных logging.exception("Ошибка при проверке подписок: ", e) finally: # Задержка перед следующей проверкой - один час (3600 секунд) await asyncio.sleep(3600) async def main(): await create_db_tables() asyncio.create_task(subscription_check()) await dp.start_polling() if __name__ == '__main__': asyncio.run(main())
032910870e81c3b5352a3e60033a90b4
{ "intermediate": 0.36086469888687134, "beginner": 0.5165213942527771, "expert": 0.12261389940977097 }
37,099
super slow and keep reaching full pool: import os import requests from bs4 import BeautifulSoup, SoupStrainer from concurrent.futures import ThreadPoolExecutor from urllib.parse import urljoin, urlparse ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "gif", "bmp", "tiff"} def has_allowed_extension(image_url): return any(image_url.lower().endswith("." + ext) for ext in ALLOWED_EXTENSIONS) def is_likely_ad_or_icon(image_url, image_headers, minimum_size_kb=10): common_ad_indicators = ["ad", "banner", "sponsor"] common_icon_indicators = ["favicon", "logo", "icon"] # Check if image URL contains ad or icon indicators if any( indicator in image_url.lower() for indicator in common_ad_indicators + common_icon_indicators ): return True # Fetch image content size from the headers and check if it is smaller than the minimum size content_length = image_headers.get("content-length", None) if content_length and int(content_length) < minimum_size_kb * 1024: return True return False def download_image(image_url, destination_folder, session): try: image_ext = os.path.splitext(urlparse(image_url).path)[1][1:].strip().lower() if image_ext not in ALLOWED_EXTENSIONS: print(f"Skipping {image_url}: Unsupported extension {image_ext}") return response = session.head(image_url, timeout=5) if not is_likely_ad_or_icon( image_url, response.headers ) and has_allowed_extension(image_url): with session.get(image_url, stream=True) as r: r.raise_for_status() img_name = os.path.basename(urlparse(image_url).path) img_path = os.path.join(destination_folder, img_name) with open(img_path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) print(f"Downloaded {img_name} to {destination_folder}") except Exception as e: print(f"Could not download {image_url}: {e}") def download_images(url, destination_folder, session): if not os.path.isdir(destination_folder): os.makedirs(destination_folder) response = session.get(url) soup = BeautifulSoup(response.text, "html.parser", parse_only=SoupStrainer("img")) images = [ urljoin(url, img.get("src") or img.get("data-src")) for img in soup if img.get("src") or img.get("data-src") ] with ThreadPoolExecutor(max_workers=15) as executor: for image_url in images: executor.submit(download_image, image_url, destination_folder, session) def remove_files(directory): for file_name in os.listdir(directory): file_path = os.path.join(directory, file_name) if os.path.isfile(file_path): os.remove(file_path) def get_images(links): fixed_urls = [BeautifulSoup(tag, "html.parser").a["href"] for tag in links if tag] with requests.Session() as session: destination_dir = "downloaded_images" remove_files( destination_dir ) # Ensure directory is empty before downloading new images with ThreadPoolExecutor(max_workers=15) as executor: for link in fixed_urls: executor.submit(download_images, link, destination_dir, session)
ec690baed4778c3b70644425060b042f
{ "intermediate": 0.3701426088809967, "beginner": 0.4578762650489807, "expert": 0.17198118567466736 }
37,100
can a tor user's ip address be tracked back from the tor exit node ip address?
7d67185320da73e39f540a8b5088064b
{ "intermediate": 0.3639896810054779, "beginner": 0.28109538555145264, "expert": 0.35491493344306946 }
37,101
im in university and i need to write in french as to how im sick and i wont be able to make it to tp today, and that il have a pdf attached showing my preparation work, his name is wissam jenkal and mine is charif kati
7b178ccccd055a8f0afc154871760fce
{ "intermediate": 0.3614996075630188, "beginner": 0.3284991979598999, "expert": 0.3100011646747589 }
37,102
@app.route("/ajouter_evenement", methods=["POST"]) def ajouter_evenement(): connexionbd = ConnexionBD() evenementbd = EvenementBD(connexionbd) nom_evenement = request.form["nom_nouvel_evenement"] date_debut = request.form["date_debut_ajouter"] date_fin = request.form["date_fin_ajouter"] heure_debut = request.form["heure_debut_ajouter"] heure_fin = request.form["heure_fin_ajouter"] evenement = Evenement(None, None, nom_evenement, heure_debut, heure_fin, date_debut, date_fin) evenementbd.insert_evenement(evenement) return redirect(url_for("evenements_festival")) {% block styles %} <link rel="stylesheet" href="{{ url_for('static', filename='admin_evenements.css') }}"> {% endblock %} {% block content %} <a id="retour" href="{{ url_for('menu_admin') }}" class="btn-retour">Retour</a> <h1>Les événements du festival</h1> <table> <thead> <tr> <th>id Evenement</th> <th>id Groupe</th> <th>nom Evenement</th> <th>heure de début</th> <th>heure de fin</th> <th>Date de début</th> <th>Date de fin</th> <th>Actions</th> </tr> </thead> <tbody> {% for evenement in liste_evenements %} <tr> <td>{{ evenement.get_idE() }}</td> <td>{{ evenement.get_idG() }}</td> <td>{{ evenement.get_nomE() }}</td> <td>{{ evenement.get_heureDebutE() }}</td> <td>{{ evenement.get_heureFinE() }}</td> <td>{{ evenement.get_dateDebutE() }}</td> <td>{{ evenement.get_dateFinE() }}</td> <td> <button class="btn-modifier" data-id="{{ evenement.get_idE() }}" data-nom = "{{ evenement.get_nomE() }}" data-heureDebut = "{{ evenement.get_heureDebutE() }}" data-heureFin = "{{ evenement.get_heureFinE() }}" data-dateDebut = "{{ evenement.get_dateDebutE() }}" data-dateFin = "{{ evenement.get_dateFinE() }}">Modifier</button> <button class="btn-supprimer" data-id="{{ evenement.get_idE() }}">Supprimer</button> </td> </tr> {% endfor %} </tbody> </table> <!-- Modale pour modifier un évènement --> <div id="modal-modifier" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="/modifier_evenement" method="post"> <!-- ID Evenement (caché) --> <input type="hidden" name="id_evenement" id="id_evenement_modifier" value=""> <!-- Nom de l'événement --> <label for="nom_evenement_modifier">Nom de l'événement:</label> <input type="text" name="nom_evenement" id="nom_evenement_modifier" placeholder="Nom de l'événement"> <!-- Horaire de début --> <label for="heure_debut_modifier">Heure de début:</label> <input type="time" name="heure_debut" id="heure_debut_modifier"> <!-- Horaire de fin --> <label for="heure_fin_modifier">Heure de fin:</label> <input type="time" name="heure_fin" id="heure_fin_modifier"> <!-- Date de début --> <label for="date_debut_modifier">Date de début:</label> <input type="date" name="date_debut" id="date_debut_modifier" max="2023-07-23" min="2023-07-21"> <!-- Date de fin --> <label for="date_fin_modifier">Date de fin:</label> <input type="date" name="date_fin" id="date_fin_modifier" max="2023-07-23" min="2023-07-21"> <button id="modifier" type="submit">Modifier</button> </form> </div> </div> <!-- Modale pour supprimer un évènement --> <div id="modal-supprimer" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="/supprimer_evenement" method="post"> <!-- ID Evenement (caché) --> <input type="hidden" name="id_evenement" id="id_evenement_supprimer" value=""> <p>Êtes-vous sûr de vouloir supprimer cet évènement ?</p> <button id="supprimer" type="submit">Supprimer</button> </form> </div> </div> <!-- Modale pour ajouter un groupe --> <div id="modal-ajouter" class="modal"> <div class="modal-content"> <span class="close-button">x</span> <form action="/ajouter_evenement" method="post"> <!-- Nom de l'événement --> <label for="nom_evenement_ajouter">Nom de l'événement:</label> <input type="text" name="nom_nouvel_evenement" id="nom_evenement_ajouter" placeholder="Nom de l'événement"> <!-- Horaire de début --> <label for="heure_debut_ajouter">Heure de début:</label> <input type="time" name="heure_debut_ajouter" id="heure_debut_ajouter"> <!-- Horaire de fin --> <label for="heure_fin_ajouter">Heure de fin:</label> <input type="time" name="heure_fin_ajouter" id="heure_fin_ajouter"> <!-- Date de début --> <label for="date_debut_ajouter">Date de début:</label> <input type="date" name="date_debut_ajouter" id="date_debut_ajouter" max="2023-07-23" min="2023-07-21"> <!-- Date de fin --> <label for="date_fin_ajouter">Date de fin:</label> <input type="date" name="date_fin_ajouter" id="date_fin_ajouter" max="2023-07-23" min="2023-07-21"> <button class="btn-ajouter" type="submit">Ajouter</button> </form> </div> </div> <button id="ajouter">Ajouter</button> <script> document.addEventListener("DOMContentLoaded", function() { var modalModifier = document.getElementById("modal-modifier"); var modalSupprimer = document.getElementById("modal-supprimer"); var modalAjouter = document.getElementById("modal-ajouter"); var btnClose = document.querySelectorAll(".close-button"); btnClose.forEach(function(btn) { btn.onclick = function() { btn.closest(".modal").style.display = "none"; }; }); document.querySelectorAll(".btn-modifier").forEach(function(btn) { btn.onclick = function() { document.getElementById("id_evenement_modifier").value = btn.getAttribute("data-id"); document.getElementById("nom_evenement_modifier").value = btn.getAttribute("data-nom"); document.getElementById("heure_debut_modifier").value = btn.getAttribute("data-heureDebut"); document.getElementById("heure_fin_modifier").value = btn.getAttribute("data-heureFin"); document.getElementById("date_debut_modifier").value = btn.getAttribute("data-dateDebut"); document.getElementById("date_fin_modifier").value = btn.getAttribute("data-dateFin"); modalModifier.style.display = "block"; }; }); document.querySelectorAll(".btn-supprimer").forEach(function(btn) { btn.onclick = function() { document.getElementById("id_evenement_supprimer").value = btn.getAttribute("data-id"); modalSupprimer.style.display = "block"; }; }); document.getElementById("ajouter").onclick = function() { modalAjouter.style.display = "block"; }; window.onclick = function(event) { if (event.target.classList.contains("modal")) { event.target.style.display = "none"; } } }); </script> {% endblock %} corrige cette erreur : werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'nom_nouvel_evenement'
9ac931271857483c92d9acdcbacfab3f
{ "intermediate": 0.3241429328918457, "beginner": 0.5596935749053955, "expert": 0.11616349220275879 }
37,103
Let's create a loop to replace all of this inefficient code! Delete all the code after the second comment. In LOGIC, drag out Loop with Range. Change the range() to 9 so the loop runs 9 times. Move the code that is between the comments into the loop instead! The commands should be indented once. You've refactored the code! Notice that the outcome is the same, but the code is much and more efficient. this is the loop with range for counter in range(5): pass # delete after adding indented code # add code here
27c5e8f374f521f2ee2c2d2948721ea5
{ "intermediate": 0.28315919637680054, "beginner": 0.49117767810821533, "expert": 0.22566312551498413 }
37,104
Sql
2117c49e3a3233517572cb5e78457bd6
{ "intermediate": 0.2310624122619629, "beginner": 0.26643508672714233, "expert": 0.5025025010108948 }
37,105
Let’s create a loop to replace all of this inefficient code! Delete all the code after the second comment. In LOGIC, drag out Loop with Range. Change the range() to 9 so the loop runs 9 times. Move the code that is between the comments into the loop instead! The commands should be indented once. You’ve refactored the code! Notice that the outcome is the same, but the code is much and more efficient. this is the loop with range for counter in range(5): pass # delete after adding indented code # add code here stage.set_background("jupiter") sprite = codesters.Sprite("ufo", -125, 0) sprite.set_size(.7) sprite.set_color("gold") sprite.pen_down() #start sprite.move_forward(250) sprite.turn_left(160) #end sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160) sprite.move_forward(250) sprite.turn_left(160)
f10cc0d0cf740ee2928f7f6c9219e3f2
{ "intermediate": 0.2740383744239807, "beginner": 0.5379921197891235, "expert": 0.18796949088573456 }
37,106
hello
ed33571297274898a752bcb50d257257
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
37,107
translate latex doc into russian: \documentclass[12pt, a4paper]{article} \usepackage{vmargin} \usepackage{amsmath} \setpapersize{USletter} \setmarginsrb{1in}{1in}{1in}{1in}{0pt}{0mm}{0pt}{30pt} \begin{document} \title{Free Form Fitting With Restrictions} \author{Andrei Vermel} %\author{} \maketitle \section{Problem overview} The measured points from the CMM $\left\{p_m^i\right\}_{i=0...N}$ need to be matched to the CAD model optimally by finding the proper isometric transformation (rotation matrix $\bf R$ + translation vector $t$), that would minimize the mean square distance from the CAD model. The transformation may be subject to certain user defined restrictions. The solution of this type of problem (also known as {\em registration problem}) is often obtained via an iterative algorithm, which in turn projects measured points onto a CAD model, updates the transformation on base of the results of projection and applies the transformation to the measured points. A popular type of such an algorithm is an {\em Iterative Closest Point} algorithm (ICP) [1], which calculates the transformation that provides the best fit of measured points to their projections $\left\{p_n^i\right\}_{i=0...N}$. It is easy to see that the ICP algorithm always converges monotonically to the nearest local minimum. An advantage of ICP is that a closed form solution to find the transformation matrix on each iteration exists. Thus the performance of a single iteration is entirely determined by the performance of projection on CAD model. It will be shown below that the the closed form solution with some modifications is still applicable to certain types of restrictions on the transformation, while others would require an iteration method to be fulfiled. An improvement over ICP is an accelerated ICP method [1], which achieves faster convergence. It makes use of the notice that the transformation with iterations usually drifts in the same direction and applies linear and quadratic prediction. A good alternative to ICP turned out to be a method described in [6]. Instead of fitting measured points to their projection points we can fit them to the tangent planes passing through the projection points. An advantage is a significantly better convergence rate. Unfortunately no known closed form solution exist, so an iterative method is necessary. The method is based on a simple linearization, which reduces the least squares problem to a system of 6 linear equations. The general approach to the registration problem is also studied in literature. If CAD model consists of parametric suraces (which in practice is anything except STL model), it is possible to make use of surface derivatives to fit the points to surfaces directly by performing a Newton method optimization in 7D parametric space [3], avoiding the point projection. Due to reportedly not very good reliability intrinsic to multidimentional nonlinear optimization problem, I do not consider the said approach in this paper.
eb3b0c52aba43625d4d92d978183756c
{ "intermediate": 0.3140760362148285, "beginner": 0.2670263648033142, "expert": 0.4188976287841797 }
37,108
I wanna make a duck animation of a duck walking around that will play while you are waiting for an answer from a bot in a chatbox, how can I do to achive this?
0e959d298102a5d5a2f161001bfb9a67
{ "intermediate": 0.3715682923793793, "beginner": 0.2529464066028595, "expert": 0.37548530101776123 }
37,109
do you know about the hero ling Yes, Ling is a hero in Mobile Legends: Bang Bang (MLBB), an assassin known for his agility and ability to traverse walls, giving him unique mobility compared to other heroes in the game. Here are some key aspects of Ling: Finesse and Agility: Ling can leap on walls and remain there for an extended period of time. This allows him to bypass obstacles, escape, or ambush enemies. His wall-traversing ability makes him a highly mobile hero who can quickly reposition in battles and skirmishes. Energy System: Instead of Mana, Ling uses Energy to cast his skills. This allows him to be less dependent on Mana regeneration items, but it means he must manage his Energy carefully during fights to maximize his skill usage. Assassination Potential: Ling’s abilities allow him to quickly jump to target an enemy hero’s back, dealing significant burst damage. He excels in picking off isolated targets or finishing off low-health enemies, making him a potent threat in 1v1 situations. Ultimate Skill: His ultimate grants him a brief period of invulnerability, during which he can leap between enemies within the area of effect, dealing critical hits. This skill is very effective for both engaging in team fights and rapidly taking down enemy heroes. Ling’s playstyle is unique and requires good map awareness and positioning to utilize his wall-traversing skills effectively. Players need to exercise careful judgment when engaging or disengaging with Ling, as his high mobility can sometimes lead into danger if not used wisely. Please note that in competitive games like Mobile Legends, heroes are often subject to adjustments and re-balancing in updates, so Ling’s abilities and effectiveness may change over time. Always refer to the latest patch notes or in-game information for the most current details about any hero. > as his high mobility can sometimes lead into danger if not used wisely. Explain
302107f28c06ce9303eb4624f372bd4e
{ "intermediate": 0.36212217807769775, "beginner": 0.33866772055625916, "expert": 0.29921016097068787 }
37,110
in c declare a null pointer named ptr of type 't_toto'
9b973dcf9e967c8a9853510de24492f6
{ "intermediate": 0.45870769023895264, "beginner": 0.23774151504039764, "expert": 0.3035507798194885 }
37,111
using UnityEngine; using System.Collections; using UnityEngine.UI; using com.ootii.Actors.AnimationControllers; using com.ootii.Cameras; using com.ootii.Input; using AIBehavior; using BreadcrumbAi; using UnityEngine.EventSystems; using JetBrains.Annotations; using System.Collections.Generic; //using NUnit.Framework; using com.ootii.Actors; using com.ootii.Actors.LifeCores; using BeautifyEffect; using FIMSpace.FLook; using com.ootii.Helpers; using com.ootii.Utilities.Debug; using com.ootii.Geometry; public class PlayerVitals : MonoBehaviour, IDataPersistence { public Transform debugTransform; public GameObject bulletProjectile; public Transform bulletParent; public GameObject currentHitObject; public List<GameObject> currentHitObjects = new List<GameObject>(); public float sphereRadius; public float knifeRadius; public float maxDistance; public LayerMask aimLayerMask; public LayerMask layerMask; public LayerMask obstacleMask; private Vector3 origin; private Vector3 direction; private float currentHitDistance; float damageTime = 1.0f; // every 1 second float currentDamageTime; float timePainSoundPlayed; public float reloadtime; public float fireRate = 0.8f; private float nextTimetoFire = 0f; private bool isReloading; private int bulletPerShot = 15; private float inaccuracyDistance = 0.1f; public Transform firePoint; public Transform knifeHitPoint; public ParticleSystem muzzleFlash; public GameObject TentacleFxParent; public ParticleSystem[] TentaclesFX; public GameObject muzzleLight; public GameObject shotgun; public int maxAmmo; public int currentAmmo; public int damage; public int headshotDamage; public int knifeDamage = 2; public float aimSpeed = 1f; public Slider staminaSlider; public float Stamina; public float minStamina; public float currentStamina; private float StaminaRegenTimer = 0.0f; private const float StaminaDecreasePerFrame = 3.5f; private const float StaminaIncreasePerFrame = 3.0f; private const float StaminaTimeToRegen = 1.5f; public Slider healthSlider; public float Health; public float currentHealth; public bool isInjured; public GameObject bloodPrefab; public bool isCrouching; public Slider flashlightSlider; public float maxFlashlight = 100; public float flashlightFallRate; public float currentFlashlight; public float flashlightDistance; public float flashlightRadius; public Light LightSource; public bool LightOn; public bool GlowStickON; public AudioClip TurnOn; public AudioClip TurnOff; public AudioClip Healsound; public AudioClip Aiming; public AudioClip FireShot; public AudioClip ReloadSound; public AudioClip GunEmpty; public AudioClip BulletReloadSound; public AudioClip GasolineSound; public AudioClip DeathSound; public AudioClip DeathTragicMusic; public AudioClip GameOverUIMusic; public AudioClip Heartbeat; public AudioClip FrySound; public AudioClip headshotSound; public AudioClip knifeSound; public AudioClip knifeHitSound; public AudioSource weaponAudioSource; public AudioSource HeartbeatAudioSource; [SerializeField] AudioClip[] Painsounds; [SerializeField] AudioClip[] Hitsounds; private AudioSource audioSource; public GameObject Inventory; public CameraController camRig; public UnityInputSource InputSource; public GameObject Player; public GameObject Gameover; public Animator m_Animator; public Animator BloodScreenFx; public Animator stealthFX; public bool isDead; public bool isSuiciding; public MotionController motionController; public ActorController actorController; protected MotionController mMotionController = null; public CameraShake CamShake; public bool isAiming; public bool isSettingTrap; public bool isSliding; public bool isRunning; public Transform Bullet1, Bullet2, Bullet3, Bullet4, Bullet5, Bullet6, Bullet7, Bullet8; public Transform AmmoText; public GameObject ShotgunUI; public GameObject PlayerVitalsUI; public GameObject QuestUI; public GameObject GasolineUI; public GameObject KnifeUI; public GameObject Reticle; public GameObject RedReticle; public GameObject GasCan; public GameObject gasolineTrap; public GameObject GlowStick; public GameObject CharacterHead; public GameObject FlashlightPoint; public Slider gasolineSlider; public float maxGasoline = 100; public float currentGasoline; public int trainDestroyed; public int deathCount; public int fatalHeadShot; [HideInInspector] public NotificationUI MsgUI; private BreadcrumbAi.Ai ai; private GameObject[] zombies; private Transform closestZombie; private DemoEnemyControls zombieHealth; private CrawlerControls crawlerControls; private SpreadFire spreadFire; private EasterEgg easterEgg; private Beautify beautify; private InventoryManager InvManager; private CameraFilterPack_AAA_BloodOnScreen camBlood; private FLookAnimator fLook; private FearSystem fearSystem; private bool tentacleIsPlaying; private string BaseLayer; private Quaternion _lookRotation; private Vector3 _direction; private bool _1stPerson; private Camera mainCamera; private void Awake() { if (menuScript1.PlayerSelected == 0) { Health = 100; maxAmmo = 5; damage = 2; headshotDamage = 4; maxDistance = 8; Stamina = 100; } if (menuScript1.PlayerSelected == 1) { //Has Shotgun //Normal Health (100) //Normal Stamina (100) //Normal Sanity (20) //Low Damage (1-3) Health = 100; maxAmmo = 5; damage = 1; headshotDamage = 3; maxDistance = 8; Stamina = 100; } if (menuScript1.PlayerSelected == 2) { //Has Pistol //High Health (125) //Low Stamina (75) //High Sanity (30) //Medium Damage (3-5) Health = 125; maxAmmo = 8; damage = 3; headshotDamage = 5; maxDistance = 15; Stamina = 75; } if (menuScript1.PlayerSelected == 3) { //Has Pistol //Low Health (50) //High Stamina (125) //Low Sanity (20) //High Damage (5-7) Health = 50; maxAmmo = 8; damage = 5; headshotDamage = 7; maxDistance = 6; Stamina = 125; } } void Start() { Cursor.visible = false; isCrouching = false; //currentAmmo = 0; AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / " + maxAmmo; healthSlider.interactable = false; healthSlider.maxValue = Health; //currentHealth = Health; healthSlider.value = currentHealth; staminaSlider.interactable = false; staminaSlider.maxValue = Stamina; //currentStamina = Stamina; staminaSlider.value = currentStamina; flashlightSlider.interactable = false; flashlightSlider.maxValue = maxFlashlight; flashlightSlider.value = currentFlashlight; //currentFlashlight = maxFlashlight; LightOn = false; LightSource.intensity = 0f; isInjured = false; LightSource = GetComponentInChildren<Light>(); audioSource = GetComponent<AudioSource>(); beautify = FindObjectOfType(typeof(Beautify)) as Beautify; Inventory.SetActive(false); Gameover.SetActive(false); CameraController camRig = gameObject.GetComponent<CameraController>(); UnityInputSource InputSource = GetComponent<UnityInputSource>(); m_Animator = gameObject.GetComponent<Animator>(); m_Animator.SetBool("isDead", false); m_Animator.SetBool("isInjured", false); motionController = GetComponent<MotionController>(); mMotionController = gameObject.GetComponent<MotionController>(); CameraController lController = gameObject.GetComponent<CameraController>(); CamShake = gameObject.GetComponent<CameraShake>(); InvManager = FindObjectOfType(typeof(InventoryManager)) as InventoryManager; camBlood = Camera.main.GetComponent<CameraFilterPack_AAA_BloodOnScreen>(); fLook = gameObject.GetComponent<FLookAnimator>(); fearSystem = GetComponent<FearSystem>(); //tentacleIsPlaying = false; TentaclesFX = TentacleFxParent.GetComponentsInChildren<ParticleSystem>(); closestZombie = null; BaseLayer = "Base Layer"; _1stPerson = false; mainCamera = Camera.main; //set weapon for (int t = 0; t < InvManager.Items; t++) //Starting a loop in the slots of the inventory: { if (InvManager.Slots[t].IsTaken == true) //Checking if there's an item in this slot. { Item ItemScript = InvManager.Slots[t].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag. if (ItemScript.Name == "Shotgun" || ItemScript.Name == "Colt 1911") //Checking if the type of the new item matches with another item already in the bag. { shotgun.SetActive(true); ShotgunUI.SetActive(true); } } } } void Update() { //TENTACLES FX if (fearSystem.isInsane || isSuiciding) { if (!tentacleIsPlaying) { foreach (ParticleSystem tentacle in TentaclesFX) { tentacle.Play(); tentacle.loop = true; tentacleIsPlaying = true; } } } if (!fearSystem.isInsane) { if (tentacleIsPlaying) { foreach (ParticleSystem tentacle in TentaclesFX) { tentacleIsPlaying = false; tentacle.loop = false; } } } //GUN RELOAD if (shotgun.activeInHierarchy == true && !isSettingTrap && Input.GetKeyDown(KeyCode.R) || Input.GetKeyDown(KeyCode.JoystickButton3)) { if (!isReloading) { StartCoroutine(Reload()); } } //BULLET UI STRING AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / " + maxAmmo; //BULLET UI SECTION if (currentAmmo > 0) { Bullet1.GetComponent<Image>().enabled = true; } else { Bullet1.GetComponent<Image>().enabled = false; } if (currentAmmo > 1) { Bullet2.GetComponent<Image>().enabled = true; } else { Bullet2.GetComponent<Image>().enabled = false; } if (currentAmmo > 2) { Bullet3.GetComponent<Image>().enabled = true; } else { Bullet3.GetComponent<Image>().enabled = false; } if (currentAmmo > 3) { Bullet4.GetComponent<Image>().enabled = true; } else { Bullet4.GetComponent<Image>().enabled = false; } if (currentAmmo > 4) { Bullet5.GetComponent<Image>().enabled = true; } else { Bullet5.GetComponent<Image>().enabled = false; } if (menuScript1.PlayerSelected == 2 || menuScript1.PlayerSelected == 3) { if (currentAmmo > 5) { Bullet6.GetComponent<Image>().enabled = true; } else { Bullet6.GetComponent<Image>().enabled = false; } if (currentAmmo > 6) { Bullet7.GetComponent<Image>().enabled = true; } else { Bullet7.GetComponent<Image>().enabled = false; } if (currentAmmo > 7) { Bullet8.GetComponent<Image>().enabled = true; } else { Bullet8.GetComponent<Image>().enabled = false; } } //AMMO LOCK if (currentAmmo > maxAmmo) { currentAmmo = maxAmmo; } //AIMING SECTION if (Input.GetMouseButton(1) && !m_Animator.GetCurrentAnimatorStateInfo(1).IsName("IdleBandage") && shotgun.activeInHierarchy == true && !isSettingTrap) { m_Animator.SetBool("isAiming", true); isAiming = true; fLook.enabled = false; if (mainCamera != null) { Ray ray = mainCamera.ViewportPointToRay(Vector3.one * 0.5f); //Debug.DrawRay (ray.origin, ray.direction * maxDistance, Color.magenta, 2f); RaycastHit hit; if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity, layerMask)) { zombieHealth = hit.collider.GetComponentInParent<DemoEnemyControls>(); crawlerControls = hit.collider.GetComponentInParent<CrawlerControls>(); easterEgg = hit.collider.GetComponent<EasterEgg>(); bool gasoline = hit.transform.gameObject.CompareTag("Gas"); if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity, obstacleMask)) //White Reticle If Obstacles { Reticle.SetActive(true); RedReticle.SetActive(false); } else if (zombieHealth != null || crawlerControls != null || easterEgg != null || gasoline) { //Red Reticle If Available Target RedReticle.SetActive(true); Reticle.SetActive(false); } } else { //White Reticle If Nothing Reticle.SetActive(true); RedReticle.SetActive(false); } } } else { m_Animator.SetBool("isAiming", false); isAiming = false; fLook.enabled = true; Reticle.SetActive(false); RedReticle.SetActive(false); } //AIMING SOUND if (Input.GetMouseButtonDown(1) && shotgun.activeInHierarchy == true) { AudioClip clip = Aiming; weaponAudioSource.PlayOneShot(clip); } //GUN FIRE if (Input.GetMouseButtonDown(0) && m_Animator.GetBool("isAiming") == true && Time.time >= nextTimetoFire && !isReloading && shotgun.activeInHierarchy == true && !isSettingTrap) { if (currentAmmo >= 1) { nextTimetoFire = Time.time + 1f / fireRate; //StartCoroutine(Fire()); StartCoroutine(Shoot()); } else { MsgUI = FindObjectOfType(typeof(NotificationUI)) as NotificationUI; MsgUI.SendMsg("No Ammo! Press R to reload."); AudioClip clip = GunEmpty; weaponAudioSource.PlayOneShot(clip); } } //STATS LOCK healthSlider.value = currentHealth; staminaSlider.value = currentStamina; flashlightSlider.value = currentFlashlight; if (currentHealth > Health) { currentHealth = Health; } if (currentStamina > Stamina) { currentStamina = Stamina; } if (currentHealth < minStamina) { currentStamina = minStamina; } //SHOW&HIDE STAMINA SLIDER if (currentStamina < Stamina) { staminaSlider.gameObject.SetActive(true); } else { staminaSlider.gameObject.SetActive(false); } SwitchState(); //FLASHLIGHT CONTROL SECTION //currentFlashlight = flashlightSlider.value; if (LightOn && flashlightSlider.value >= 0) { //flashlightSlider.value -= Time.deltaTime / flashlightFallRate; currentFlashlight -= Time.deltaTime / flashlightFallRate; LightSource.intensity = 5f; } if (LightOn && flashlightSlider.value <= 75) { LightSource.intensity = 4f; } if (LightOn && flashlightSlider.value <= 50) { LightSource.intensity = 3; } if (LightOn && flashlightSlider.value <= 25) { LightSource.intensity = 1.5f; } if (LightOn && flashlightSlider.value <= 0) { flashlightSlider.value = 0; LightSource.intensity = 0f; currentFlashlight = 0f; } else if (flashlightSlider.value >= maxFlashlight) { flashlightSlider.value = maxFlashlight; } //HEALING CHEAT /*if(Input.GetKeyDown(KeyCode.H)) { MotionControllerMotion bandage = mMotionController.GetMotion(1, "IdleBandage"); mMotionController.ActivateMotion(bandage); currentHealth += 10; audioSource.PlayOneShot(Healsound); if (healthSlider.value >= 100) { currentHealth = Health; } }*/ /*if (Input.GetKeyDown(KeyCode.Space) && m_Animator.GetFloat("InputMagnitude") >= 1) { StartCoroutine(Slide()); }*/ /*if (Input.GetMouseButton(1) && Input.GetMouseButtonDown(0) && !m_Animator.GetCurrentAnimatorStateInfo(1).IsName("IdleBandage") && shotgun.activeInHierarchy == false && !isSettingTrap && !isReloading && !isSliding) { StartCoroutine(Knife()); }*/ StartCoroutine(ToggleCrouch()); StartCoroutine(CheckGasoline()); //FLASHLIGHT DOUBLE WALKERS VISION if (LightOn) { currentHitObjects.Clear(); RaycastHit[] hits = new RaycastHit[1]; int numberOfHits = Physics.SphereCastNonAlloc(FlashlightPoint.transform.position, flashlightRadius, FlashlightPoint.transform.forward, hits, flashlightDistance, layerMask, QueryTriggerInteraction.UseGlobal); if (numberOfHits >= 1) { for (int i = 0; i < numberOfHits; i++) { currentHitObjects.Add(hits[i].transform.gameObject); currentHitDistance = hits[i].distance; foreach (GameObject zombie in currentHitObjects) { ai = hits[i].collider.GetComponentInParent<BreadcrumbAi.Ai>(); if (ai != null) { ai.visionDistance = ai.visionDistance * 2f; } } } } } //FLASHLIGHT TOGGLE if (Input.GetKeyDown(KeyCode.F) || DPadButtons.IsLeft) { toggleFlashlight(); toggleFlashlightSFX(); if (LightOn) { LightOn = false; } else if (!LightOn && flashlightSlider.value >= 0) { LightOn = true; } } //STAMINA CONTROL SECTION bool _isRunning = IsRunning(); bool _canRun = CanRun(); if (_isRunning && _canRun) { currentStamina = Mathf.Clamp(currentStamina - (StaminaDecreasePerFrame * Time.deltaTime), 0.0f, Stamina); StaminaRegenTimer = 0.0f; } else { if (currentStamina < Stamina) { if (StaminaRegenTimer >= StaminaTimeToRegen) currentStamina = Mathf.Clamp(currentStamina + (StaminaIncreasePerFrame * Time.deltaTime), 0.0f, Stamina); else StaminaRegenTimer += Time.deltaTime; } } if (!_canRun) { StartCoroutine(StopRunMotion()); } else { MotionControllerMotion walkOnlyMotion = mMotionController.GetMotion(0, "Walk Only Motion"); walkOnlyMotion._IsEnabled = false; } //FIRST PERSON FEATURE if (Input.GetKeyDown(KeyCode.Tab)) { if (!_1stPerson) { camRig.ActivateMotor(5); _1stPerson = true; motionController.SetAnimatorMotionPhase(0, 1130); motionController.ActivateMotion("Strafe", 0); } else if (_1stPerson) { camRig.ActivateMotor(6); _1stPerson = false; } } } IEnumerator StopRunMotion() { m_Animator.SetFloat("InputMagnitude", 0.5f, 0.1f, 0.5f); m_Animator.SetFloat("InputMagnitudeAvg", 0.5f, 1f, 0.5f); m_Animator.SetFloat("InputY", 0.5f, 1f, 0.5f); yield return new WaitForSeconds(0.1f); MotionControllerMotion walkOnlyMotion = mMotionController.GetMotion(0, "Walk Only Motion"); walkOnlyMotion.IsEnabled = true; } public bool IsRunning() { if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W)) { return (true); } else { return (false); } } public bool CanRun() { if (currentStamina > 1f) { return (true); } else { return (false); } } /*IEnumerator Slide() { isSliding = true; AnimationClip slide = m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Slide"); actorController.AddForce(actorController._Transform.forward * 10, m_Animator.GetCurrentAnimatorStateInfo(0).length); yield return new WaitForSeconds(1); Debug.Log("Sliding"); }*/ IEnumerator Knife() { isSliding = true; m_Animator.SetBool("isSliding", true); fLook.enabled = false; AudioClip clip = knifeSound; weaponAudioSource.PlayOneShot(clip); Collider[] hitEnemies = Physics.OverlapSphere(knifeHitPoint.position, knifeRadius, layerMask); foreach (Collider enemies in hitEnemies) { if (isSliding && enemies != null) { if (enemies.transform.tag == "Easter") { easterEgg = enemies.GetComponent<EasterEgg>(); easterEgg.DestroyTrain(); DestroyObject(enemies.transform.gameObject, 8); } if (enemies.transform.tag == "Body" || enemies.transform.tag == "Enemy") { zombieHealth = enemies.GetComponentInParent<DemoEnemyControls>(); crawlerControls = enemies.GetComponentInParent<CrawlerControls>(); if (zombieHealth != null || crawlerControls != null) { zombieHealth.GotHit(knifeDamage); crawlerControls.GotHit(knifeDamage); AudioClip hit = knifeHitSound; weaponAudioSource.PlayOneShot(hit); } } } } yield return new WaitForSeconds(1f); isSliding = false; m_Animator.SetBool("isSliding", false); //mMotionController.enabled = true; fLook.enabled = true; } public void KnifeHit() { /*RaycastHit hit; if (Physics.SphereCast(knifeHitPoint.transform.position, 4f, knifeHitPoint.transform.forward, out hit, 4f, layerMask, QueryTriggerInteraction.UseGlobal)) { currentHitObject = hit.transform.gameObject; currentHitDistance = hit.distance; zombieHealth = hit.collider.GetComponentInParent<DemoEnemyControls>(); easterEgg = hit.collider.GetComponent<EasterEgg>(); if (hit.collider.transform.tag == "Easter") { easterEgg.DestroyTrain(); DestroyObject(hit.transform.gameObject, 8); } if (zombieHealth != null) { if (hit.collider.transform.tag == "Body" || hit.collider.transform.tag == "Enemy") { zombieHealth.GotHit(damage); } } } else { currentHitDistance = maxDistance; currentHitObject = null; }*/ } public IEnumerator CharacterSuicide() { if (isSuiciding) { float timeElapsed = 1f; float lerpDuration = 14; float startValue = 0; float endValue = 1.6f; fearSystem.currentFear = fearSystem.maxFear; //Keeping Anomaly FX //DISABLING CAM&INPUT camRig.enabled = false; camRig._IsCollisionsEnabled = false; InputSource.IsEnabled = false; fLook.enabled = false; if (_1stPerson) { camRig.ActivateMotor(6); } //DISABLING UI LightSource.enabled = false; QuestUI.SetActive(false); ShotgunUI.SetActive(false); GasolineUI.SetActive(false); PlayerVitalsUI.SetActive(false); Inventory.SetActive(false); KnifeUI.SetActive(false); //ON KNEE ANIMATION motionController.SetAnimatorMotionPhase(0, 3400, true); Player.tag = "Dead"; m_Animator.SetBool("isSuiciding", true); isInjured = false; //Disabling Injured Sounds //STOP BLOOD m_Animator.SetBool("isInjured", false); BloodScreenFx.SetBool("50Health", false); BloodScreenFx.SetBool("100Health", true); yield return new WaitForSeconds(5f); //SUICIDE ANIMATION m_Animator.SetBool("isSuiciding2", true); yield return new WaitForSeconds(0.8f); //PLAY AUDIO audioSource.PlayOneShot(FireShot); audioSource.PlayOneShot(DeathTragicMusic); audioSource.PlayOneShot(headshotSound); if (HeartbeatAudioSource.isPlaying) { HeartbeatAudioSource.Stop(); } //HEADSHOT&FALLING ANIMATION CharacterHead.SetActive(false); m_Animator.SetBool("isSuiciding3", true); //NEW BLOOD FX while (timeElapsed < lerpDuration) { camBlood.Blood_On_Screen = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration); timeElapsed += Time.deltaTime; yield return null; } camBlood.Blood_On_Screen = endValue; //ENABLING GAMEOVER UI + DEATH MUSIC + HEARTBEAT STOP Gameover.SetActive(true); Cursor.visible = true; audioSource.clip = GameOverUIMusic; audioSource.Play(); audioSource.loop = true; deathCount++; } } public IEnumerator CharacterDeath() { float timeElapsed = 1f; float lerpDuration = 14; float startValue = 0; float endValue = 1.6f; if (isDead) { //PLAY AUDIO audioSource.PlayOneShot(DeathSound); audioSource.PlayOneShot(DeathTragicMusic); //DISABLING CAM&INPUT camRig.enabled = false; camRig._IsCollisionsEnabled = false; InputSource.IsEnabled = false; fLook.enabled = false; if (_1stPerson) { camRig.ActivateMotor(6); } //DEATH ANIMATION motionController.SetAnimatorMotionPhase(0, 3375, true); Player.tag = "Dead"; m_Animator.SetBool("isDead", true); //DISABLING UI LightSource.enabled = false; QuestUI.SetActive(false); ShotgunUI.SetActive(false); GasolineUI.SetActive(false); PlayerVitalsUI.SetActive(false); Inventory.SetActive(false); KnifeUI.SetActive(false); //STOP BLOOD m_Animator.SetBool("isInjured", false); BloodScreenFx.SetBool("50Health", false); BloodScreenFx.SetBool("100Health", true); //SEND ZOMBIES ANIMATION zombies = GameObject.FindGameObjectsWithTag("Enemy"); closestZombie = null; foreach (GameObject zombie in zombies) { float curDistance; curDistance = Vector3.Distance(transform.position, zombie.transform.position); zombieHealth = zombie.gameObject.transform.GetComponent<DemoEnemyControls>(); crawlerControls = zombie.gameObject.transform.GetComponent<CrawlerControls>(); if (curDistance < 1f) { if (zombieHealth != null) { zombieHealth.EatPlayer(); zombieHealth.transform.LookAt(transform); transform.LookAt(zombieHealth.transform); } if (crawlerControls != null) { crawlerControls.EatPlayer(); crawlerControls.transform.LookAt(transform); transform.LookAt(crawlerControls.transform); } } } yield return closestZombie; //NEW BLOOD FX while (timeElapsed < lerpDuration) { camBlood.Blood_On_Screen = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration); timeElapsed += Time.deltaTime; yield return null; } camBlood.Blood_On_Screen = endValue; //ENABLING GAMEOVER UI + DEATH MUSIC Gameover.SetActive(true); Cursor.visible = true; audioSource.clip = GameOverUIMusic; audioSource.Play(); audioSource.loop = true; deathCount++; if (HeartbeatAudioSource.isPlaying) { HeartbeatAudioSource.Stop(); } } } void SwitchState() { if (healthSlider.value <= 0 && !isDead) { isDead = true; beautify.sepiaIntensity = 1f; StartCoroutine(CharacterDeath()); } else if (healthSlider.value > 0 && healthSlider.value < (Health / 5.5f)) { beautify.sepiaIntensity = 1f; isInjured = true; } else if (healthSlider.value > (Health / 5.5f) && healthSlider.value < (Health / 4)) { beautify.sepiaIntensity = 0.90f; isInjured = true; } else if (healthSlider.value > (Health / 4) && healthSlider.value < (Health / 2)) { beautify.sepiaIntensity = 0.65f; isInjured = true; } else if (healthSlider.value > (Health / 2) && healthSlider.value < (Health / 1.3f)) { beautify.sepiaIntensity = 0.35f; isInjured = false; } else if (healthSlider.value > (Health / 1.3f)) { beautify.sepiaIntensity = 0f; isInjured = false; } if (isInjured && !isDead && !isSuiciding) { m_Animator.SetBool("isInjured", true); BloodScreenFx.SetBool("50Health", true); BloodScreenFx.SetBool("100Health", false); if (Time.time - timePainSoundPlayed < 4f) return; HeartbeatAudioSource.clip = Heartbeat; HeartbeatAudioSource.Play(); int n = Random.Range(1, Painsounds.Length); AudioClip painSounds = Painsounds[n]; if (!audioSource.isPlaying) { audioSource.PlayOneShot(painSounds); Painsounds[n] = Painsounds[0]; Painsounds[0] = painSounds; timePainSoundPlayed = Time.time; } } if (!isInjured || isDead || isSuiciding) { m_Animator.SetBool("isInjured", false); BloodScreenFx.SetBool("50Health", false); BloodScreenFx.SetBool("100Health", true); HeartbeatAudioSource.clip = Heartbeat; HeartbeatAudioSource.Stop(); } } IEnumerator ToggleCrouch() { for (int i = 0; i < m_Animator.layerCount; i++) { if (m_Animator.GetLayerName(i) == BaseLayer) { AnimatorStateInfo stateInfo = m_Animator.GetCurrentAnimatorStateInfo(i); if (stateInfo.IsName("Base Layer.Sneak v2-SM.Move Tree")) { isCrouching = true; stealthFX.SetBool("Stealth", true); yield return new WaitForSeconds(2); } if (stateInfo.IsName("Base Layer.WalkRunPivot v2-SM.Move Tree")) { isCrouching = false; stealthFX.SetBool("Stealth", false); yield return new WaitForSeconds(2); } } } yield return new WaitForSeconds(2); } public void Bleed(Quaternion rot) { GameObject blood = Instantiate(bloodPrefab, transform.position, rot) as GameObject; Destroy(blood, 5); } public void TakeDamage(float damage) { //PLAY PAIN SOUND int n = Random.Range(1, Hitsounds.Length); AudioClip clip = Hitsounds[n]; audioSource.PlayOneShot(clip); //DAMAGE currentHealth -= damage; //StartCoroutine(HitAnimation()); } public void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("Fire")) { currentHealth -= Time.deltaTime / 3; if (!audioSource.isPlaying) { AudioClip clip = FrySound; audioSource.PlayOneShot(clip); } } } public void OnTriggerEnter(Collider other) { /*if (isSliding && other != null) { Debug.Log("Knife Damage"); Debug.Log(other.name); if (other.transform.tag == "Easter") { easterEgg = other.GetComponent<EasterEgg>(); easterEgg.DestroyTrain(); DestroyObject(other.transform.gameObject, 8); } if (other.transform.tag == "Body" || other.transform.tag == "Enemy") { zombieHealth = other.GetComponentInParent<DemoEnemyControls>(); if (zombieHealth != null) { zombieHealth.GotHit(knifeDamage); Debug.Log(knifeDamage); } } }*/ } /*private IEnumerator HitAnimation() { //GET NEARBY ZOMBIE THAT ATTACKS zombies = GameObject.FindGameObjectsWithTag("Enemy"); foreach (GameObject zombie in zombies) { float curDistance; curDistance = Vector3.Distance(transform.position, zombie.transform.position); // Determine which direction to rotate towards Vector3 targetPosition = zombie.transform.position; Vector3 targetDirection = transform.position - zombie.transform.position; Quaternion desiredRotation = Quaternion.LookRotation(targetDirection, transform.up); //IF ONE IS NEAR if (curDistance < 1f) { //LOOK AT THIS ZOMBIE Debug.Log("OUCH"); Debug.DrawRay(transform.position, targetPosition * maxDistance, Color.blue, 2f); zombie.transform.LookAt(transform); transform.LookAt(targetPosition, transform.up); //DISABLING CAM&INPUT camRig.enabled = false; camRig._IsCollisionsEnabled = false; InputSource.IsEnabled = false; fLook.enabled = false; yield return new WaitForSeconds(1.5f); //ENABLING CAM&INPUT camRig.enabled = true; camRig._IsCollisionsEnabled = true; InputSource.IsEnabled = true; fLook.enabled = true; } } }*/ void toggleFlashlight() { if (LightOn) { LightSource.enabled = false; } else { LightSource.enabled = true; } } void toggleFlashlightSFX() { if (LightSource.enabled) { audioSource.clip = TurnOn; audioSource.Play(); } else { audioSource.clip = TurnOff; audioSource.Play(); } } private IEnumerator CheckGasoline() { //Toggle UI If Gas In Inventory for (int i = 0; i < InvManager.MaxItems; i++) { if (InvManager.Slots[i].IsTaken == true) //Checking if there's an item in this slot. { Item ItemScript = InvManager.Slots[i].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag. //ItemScript.Name = PlayerPrefs.GetString("Name" + i.ToString()); //Loading the item's name. if (ItemScript.Name == "Gasoline" && !isDead) //Checking if the type of the new item matches with another item already in the bag. { GasolineUI.SetActive(true); gasolineSlider.value = ItemScript.AmountPercent; if (gasolineSlider.value <= 0) { gasolineSlider.value = 0; } if (gasolineSlider.value >= ItemScript.AmountPercent) { gasolineSlider.value = ItemScript.AmountPercent; } if (Input.GetKeyDown(KeyCode.Q) && ItemScript.AmountPercent >= 20 && !isAiming && !isReloading) { ItemScript.AmountPercent -= 20; StartCoroutine(SetTrap()); } } else { GasolineUI.SetActive(false); } } } yield return new WaitForSeconds(1); } private IEnumerator SetTrap() { isSettingTrap = true; AudioClip clip = GasolineSound; audioSource.PlayOneShot(clip); shotgun.SetActive(false); GasCan.SetActive(true); m_Animator.SetBool("isSettingTrap", true); yield return new WaitForSeconds(0.01f); m_Animator.SetBool("isSettingTrap", false); mMotionController.enabled = false; camRig.EnableMotor<TransitionMotor>(false, "Targeting"); camRig.EnableMotor<TransitionMotor>(false, "Targeting In"); camRig.EnableMotor<TransitionMotor>(false, "Targeting Out"); GameObject gas = Instantiate(gasolineTrap, transform.position + transform.forward, Quaternion.Euler(-90, 0, 0)) as GameObject; yield return new WaitForSeconds(4); mMotionController.enabled = true; camRig.EnableMotor<TransitionMotor>(true, "Targeting"); camRig.EnableMotor<TransitionMotor>(true, "Targeting In"); camRig.EnableMotor<TransitionMotor>(true, "Targeting Out"); shotgun.SetActive(true); GasCan.SetActive(false); isSettingTrap = false; } private IEnumerator Fire() { //Debug.DrawRay(firePoint.transform.position, firePoint.transform.forward * 12, Color.red, 2f); //currentHitDistance = maxDistance; //currentHitObjects.Clear(); //RaycastHit[] hits = new RaycastHit[1]; Ray ray = Camera.main.ViewportPointToRay(Vector3.one * 0.5f); Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.green, 2f); RaycastHit hit; //if (Physics.SphereCast(firePoint.transform.position, sphereRadius, firePoint.transform.forward, out hit, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal)) //if (Physics.SphereCast(ray.origin, sphereRadius, ray.direction, out hit, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal)) //if (!Physics.Raycast(ray.origin, ray.direction, out hit, maxDistance, obstacleMask, QueryTriggerInteraction.UseGlobal)) //Fix to hide enemies behind obstacles if (Physics.Raycast(ray.origin, ray.direction, out hit, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal)) //int numberOfHits = Physics.SphereCastNonAlloc(firePoint.position, sphereRadius, firePoint.transform.forward, hits, maxDistance, layerMask, QueryTriggerInteraction.UseGlobal); //for (int i = 0; i < numberOfHits; i++) { //currentHitObjects.Add(hits[i].transform.gameObject); //currentHitDistance = hits[i].distance; currentHitObject = hit.transform.gameObject; currentHitDistance = hit.distance; //zombieHealth = hits[i].collider.GetComponentInParent<DemoEnemyControls>(); zombieHealth = hit.collider.GetComponentInParent<DemoEnemyControls>(); crawlerControls = hit.collider.GetComponentInParent<CrawlerControls>(); spreadFire = hit.collider.GetComponent<SpreadFire>(); easterEgg = hit.collider.GetComponent<EasterEgg>(); if (hit.collider.transform.tag == "Gas") { spreadFire.SetFire(); DestroyObject(hit.transform.gameObject, 3); } if (hit.collider.transform.tag == "Easter") { trainDestroyed++; easterEgg.DestroyTrain(); DestroyObject(hit.transform.gameObject, 8); } //if (hits[i].collider.transform.tag == "Head") if (hit.collider.transform.tag == "Head") { if (zombieHealth != null) { zombieHealth.HeadShot(headshotDamage); } else if (crawlerControls != null) { crawlerControls.HeadShot(headshotDamage); } } //else if (hits[i].collider.transform.tag == "Body" || hits[i].collider.transform.tag == "Enemy") else if (hit.collider.transform.tag == "Body" || hit.collider.transform.tag == "Enemy") { if (zombieHealth != null) { zombieHealth.GotHit(damage); } else if (crawlerControls != null) { crawlerControls.GotHit(damage); } } } else { currentHitDistance = maxDistance; currentHitObject = null; } m_Animator.SetBool("isFire", true); MotionControllerMotion fire = mMotionController.GetMotion(1, "Fire"); mMotionController.ActivateMotion(fire); AudioClip clip = FireShot; weaponAudioSource.PlayOneShot(clip); muzzleFlash.Play(); muzzleLight.SetActive(true); yield return new WaitForSeconds(0.1f); muzzleLight.SetActive(false); currentAmmo--; CameraShake.Shake(0.25f, 0.08f); AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / 5"; if (currentAmmo > 0) { Bullet1.GetComponent<Image>().enabled = true; } else { Bullet1.GetComponent<Image>().enabled = false; } if (currentAmmo > 1) { Bullet2.GetComponent<Image>().enabled = true; } else { Bullet2.GetComponent<Image>().enabled = false; } if (currentAmmo > 2) { Bullet3.GetComponent<Image>().enabled = true; } else { Bullet3.GetComponent<Image>().enabled = false; } if (currentAmmo > 3) { Bullet4.GetComponent<Image>().enabled = true; } else { Bullet4.GetComponent<Image>().enabled = false; } if (currentAmmo > 4) { Bullet5.GetComponent<Image>().enabled = true; } else { Bullet5.GetComponent<Image>().enabled = false; } yield return new WaitForSeconds(1 - .25f); m_Animator.SetBool("isFire", false); yield return new WaitForSeconds(2); } private IEnumerator Shoot() { if (menuScript1.PlayerSelected == 2 || menuScript1.PlayerSelected == 3) { /*GameObject bullet = GameObject.Instantiate(bulletProjectile, firePoint.position, Quaternion.identity, bulletParent); BulletController bulletController = bullet.GetComponent<BulletController>();*/ GameObject pooledBullet = ObjectPool.instance.GetPooledObjects(); if (pooledBullet == null) { yield break; } BulletController bulletController = pooledBullet.GetComponent<BulletController>(); RaycastHit hit; if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hit, Mathf.Infinity, aimLayerMask)) { //debugTransform.position = hit.point; //bulletController.target = hit.point; //bulletController.hit = true; bulletController.target = hit.point; bulletController.hit = true; pooledBullet.transform.position = firePoint.position; pooledBullet.transform.LookAt(mainCamera.transform.forward); pooledBullet.SetActive(true); } else { //debugTransform.position = hit.point; //bulletController.target = mainCamera.transform.position + mainCamera.transform.forward * 25f; //bulletController.hit = false; bulletController.target = mainCamera.transform.position + mainCamera.transform.forward * 25f; bulletController.hit = false; pooledBullet.transform.position = firePoint.position; pooledBullet.transform.LookAt(mainCamera.transform.forward); pooledBullet.SetActive(true); } m_Animator.SetBool("isFire", true); MotionControllerMotion fire = mMotionController.GetMotion(1, "Fire"); mMotionController.ActivateMotion(fire); AudioClip clip = FireShot; weaponAudioSource.PlayOneShot(clip); muzzleFlash.Play(); muzzleLight.SetActive(true); yield return new WaitForSeconds(0.1f); muzzleLight.SetActive(false); currentAmmo--; CameraShake.Shake(0.25f, 0.08f); AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / 5"; if (currentAmmo > 0) { Bullet1.GetComponent<Image>().enabled = true; } else { Bullet1.GetComponent<Image>().enabled = false; } if (currentAmmo > 1) { Bullet2.GetComponent<Image>().enabled = true; } else { Bullet2.GetComponent<Image>().enabled = false; } if (currentAmmo > 2) { Bullet3.GetComponent<Image>().enabled = true; } else { Bullet3.GetComponent<Image>().enabled = false; } if (currentAmmo > 3) { Bullet4.GetComponent<Image>().enabled = true; } else { Bullet4.GetComponent<Image>().enabled = false; } if (currentAmmo > 4) { Bullet5.GetComponent<Image>().enabled = true; } else { Bullet5.GetComponent<Image>().enabled = false; } yield return new WaitForSeconds(1 - .25f); m_Animator.SetBool("isFire", false); yield return new WaitForSeconds(2); } else if (menuScript1.PlayerSelected == 0 || menuScript1.PlayerSelected == 1) // IF ARTHUR { for (int i = 0; i < bulletPerShot; i++) { Vector3 shootDirection = mainCamera.transform.forward; shootDirection.x += Random.Range(-inaccuracyDistance * 2, inaccuracyDistance * 2); shootDirection.y += Random.Range(-inaccuracyDistance, inaccuracyDistance); GameObject pooledBullet = ObjectPool.instance.GetPooledObjects(); if (pooledBullet == null) { yield break; } BulletController bulletController = pooledBullet.GetComponent<BulletController>(); RaycastHit hit; if (Physics.Raycast(mainCamera.transform.position, shootDirection, out hit, Mathf.Infinity, aimLayerMask)) { //debugTransform.position = hit.point; bulletController.target = hit.point; bulletController.hit = true; pooledBullet.transform.position = firePoint.position; pooledBullet.transform.LookAt(shootDirection); pooledBullet.SetActive(true); } else { //debugTransform.position = hit.point; bulletController.target = mainCamera.transform.position + shootDirection; bulletController.hit = false; pooledBullet.transform.position = firePoint.position; pooledBullet.transform.LookAt(shootDirection); pooledBullet.SetActive(true); } } m_Animator.SetBool("isFire", true); MotionControllerMotion fire = mMotionController.GetMotion(1, "Fire"); mMotionController.ActivateMotion(fire); AudioClip clip = FireShot; weaponAudioSource.PlayOneShot(clip); muzzleFlash.Play(); muzzleLight.SetActive(true); yield return new WaitForSeconds(0.1f); muzzleLight.SetActive(false); currentAmmo--; CameraShake.Shake(0.25f, 0.08f); AmmoText.GetComponent<Text>().text = currentAmmo.ToString() + " / 5"; if (currentAmmo > 0) { Bullet1.GetComponent<Image>().enabled = true; } else { Bullet1.GetComponent<Image>().enabled = false; } if (currentAmmo > 1) { Bullet2.GetComponent<Image>().enabled = true; } else { Bullet2.GetComponent<Image>().enabled = false; } if (currentAmmo > 2) { Bullet3.GetComponent<Image>().enabled = true; } else { Bullet3.GetComponent<Image>().enabled = false; } if (currentAmmo > 3) { Bullet4.GetComponent<Image>().enabled = true; } else { Bullet4.GetComponent<Image>().enabled = false; } if (currentAmmo > 4) { Bullet5.GetComponent<Image>().enabled = true; } else { Bullet5.GetComponent<Image>().enabled = false; } yield return new WaitForSeconds(1 - .25f); m_Animator.SetBool("isFire", false); yield return new WaitForSeconds(2); } } Vector3 GetShootingDirection() { Vector3 targetPos = Camera.main.transform.position + Camera.main.transform.forward * Mathf.Infinity; targetPos = new Vector3( targetPos.x = Random.Range(-inaccuracyDistance, inaccuracyDistance), targetPos.y = Random.Range(-inaccuracyDistance, inaccuracyDistance), targetPos.z = Random.Range(-inaccuracyDistance, inaccuracyDistance) ); direction = targetPos - Camera.main.transform.position; return direction.normalized; } private IEnumerator Reload() { for (int i = 0; i < InvManager.MaxItems; i++) { if (InvManager.Slots[i].IsTaken == true) //Checking if there's an item in this slot. { Item ItemScript = InvManager.Slots[i].Item.GetComponent<Item>(); //Getting the item script from the items inside the bag. //ItemScript.Name = PlayerPrefs.GetString("Name" + i.ToString()); //Loading the item's name. if (ItemScript.Name == "Ammunition" && ItemScript.Amount >= 1) //Checking if the type of the new item matches with another item already in the bag. { isReloading = true; m_Animator.SetBool("isReloading", true); MotionControllerMotion reload = mMotionController.GetMotion(1, "Reload"); mMotionController.ActivateMotion(reload); int ammoToRemove = (maxAmmo - currentAmmo); if (ammoToRemove > ItemScript.Amount) { ammoToRemove = ItemScript.Amount; } InvManager.RemoveItem(InvManager.Slots[i].Item, (maxAmmo - currentAmmo)); for (int b = 0; b < ammoToRemove; b++) { weaponAudioSource.PlayOneShot(BulletReloadSound); currentAmmo++; yield return new WaitForSeconds(reloadtime); if (currentAmmo == maxAmmo) { AudioClip clip = ReloadSound; weaponAudioSource.PlayOneShot(clip); m_Animator.SetBool("isReloading", false); isReloading = false; } } m_Animator.SetBool("isReloading", false); isReloading = false; } } } } public IEnumerator ActivateGlowStick() { GlowStick.SetActive(true); GlowStickON = true; yield return new WaitForSeconds(30); GlowStick.SetActive(false); GlowStickON = false; } private void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; if (knifeHitPoint == null) return; //Debug.DrawLine(FlashlightPoint.transform.position, FlashlightPoint.transform.position + FlashlightPoint.transform.forward * currentHitDistance); //Gizmos.DrawWireSphere(FlashlightPoint.transform.position + FlashlightPoint.transform.forward * currentHitDistance, flashlightRadius); Gizmos.DrawWireSphere(knifeHitPoint.transform.position, knifeRadius); } public void LoadData(GameData data) { this.currentHealth = data.health; this.currentStamina = data.stamina; this.currentFlashlight = data.flashlightAmount; this.currentAmmo = data.ammo; this.trainDestroyed = data.trainDestroyed; this.deathCount = data.deathCount; this.fatalHeadShot= data.fatalHeadShot; this.transform.position = data.playerPosition; } public void SaveData(GameData data) { data.health = this.currentHealth; data.stamina = this.currentStamina; data.flashlightAmount = this.currentFlashlight; data.ammo = this.currentAmmo; data.trainDestroyed = this.trainDestroyed; data.deathCount= this.deathCount; data.fatalHeadShot= this.fatalHeadShot; data.playerPosition = this.transform.position; } }
fae7fdc1cbb7ef6e67364fbb9e09505a
{ "intermediate": 0.31067320704460144, "beginner": 0.492021381855011, "expert": 0.19730542600154877 }
37,112
I want disable refresh browser after a scenario
699373d0eafda9168fe7754c1097987b
{ "intermediate": 0.2753458619117737, "beginner": 0.31083202362060547, "expert": 0.41382211446762085 }
37,113
I am trying to use node with typescript. I have installed @types/node globally, and trying to import the http module using "import * as http from 'http'". However, typescript-language server says that it cannot find module 'http' or its corresponding type declarations. Why is this happening?
ebecbf223b088edbaffbb5a60d62403a
{ "intermediate": 0.46941718459129333, "beginner": 0.2995445430278778, "expert": 0.23103827238082886 }
37,114
help me create a duck component for my tsx nux file that will do so you can add a duck to the current page that chasing the cursor
78eebe125e7b3d1b8ad13cb3e4292ae5
{ "intermediate": 0.5066767930984497, "beginner": 0.13084834814071655, "expert": 0.3624747693538666 }
37,115
ajoute maintenant un Client : import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Serveur { public static void main(String[] args) throws IOException { Calculatrice calculatrice = new Calculatrice(); BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Serveur de calculatrice - taper l'operation (ex: 2 + 3) ou tapez 'exit' pour fermer."); String ligneEntrer = null; while (true) { System.out.print("Entrez l'opération: "); ligneEntrer = consoleReader.readLine(); if ("exit".equalsIgnoreCase(ligneEntrer)) { break; } else{ try { String[] parts = ligneEntrer.split(" "); System.out.println("parts: " + parts); double a = Double.parseDouble(parts[0]); String operation = parts[1]; double b = Double.parseDouble(parts[2]); double result = calculatrice.calculer(a, b, operation); System.out.println("Résultat: " + result); } catch (Exception e) { System.out.println("Erreur: " + e.getMessage()); } } } } }public class Calculatrice { public double calculer(double a, double b, String operation) { switch (operation) { case "+": return a + b; case "-": return a - b; case "": return a * b; case "/": if (b != 0) { return a / b; } else { throw new IllegalArgumentException("divisions par zero!"); } } } }
bee2fa1a84d03c948e9d22d454472873
{ "intermediate": 0.4003651738166809, "beginner": 0.48059597611427307, "expert": 0.11903885006904602 }
37,116
addEventListener("beforeunload", (event) => { window.close(); }); fix this code
76be62d74975a5c874de3b98106f9e56
{ "intermediate": 0.5049759745597839, "beginner": 0.2765257954597473, "expert": 0.21849825978279114 }
37,117
pourquoi sur le client je ne vois le résulat du serveur ? import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Serveur { private Calculatrice calculatrice; private ServerSocket serverSocket; public Serveur(int port) throws IOException { this.calculatrice = new Calculatrice(); this.serverSocket = new ServerSocket(port); } public void start() throws IOException { System.out.println("Serveur démarré attends la connect."); Socket clientSocket = serverSocket.accept(); System.out.println("le client se connecte!"); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); String inputLine; while ((inputLine = in.readLine()) != null) { try { String[] parts = inputLine.split(" "); double a = Double.parseDouble(parts[0]); String operation = parts[1]; double b = Double.parseDouble(parts[2]); double resultat = calculatrice.calculer(a, b, operation); } catch (Exception e) { System.out.println("Erreur côté serveur: " + e.getMessage()); } } } }import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Client { private BufferedReader consoleReader; private Socket socket; private PrintWriter out; BufferedReader in; public Client(String host, int port) throws IOException { this.consoleReader = new BufferedReader(new InputStreamReader(System.in)); this.socket = new Socket(host, port); this.out = new PrintWriter(socket.getOutputStream(), true); this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } public void envoyerOperations() throws IOException { String inputLine; while (true) { System.out.print("Client: Entrez l'opération (ex: 2 + 3) ou 'exit' pour sortir: "); inputLine = consoleReader.readLine(); if ("exit".equalsIgnoreCase(inputLine)) { break; } else { String response = in.readLine(); System.out.println(response); } } } }
eb0adff177a2c81192335b76b479f7c1
{ "intermediate": 0.31938567757606506, "beginner": 0.5848273634910583, "expert": 0.09578697383403778 }
37,118
I want you to modify the simulate projectile function: *Start the parabolic movement at the initial transform. position *The maximum height is reached at the middle of the trajectory *End the movement in currentTarget *the longer the distance the arrow goes up, the shorter the distance the arrow goes down, the minimum height is a straight line with the target using System.Collections; using Game.Systems; using UnityEngine.UIElements; namespace Game.ImprovedAI { using System.Collections; using UnityEngine; public class Arrow : MonoBehaviour { public float speed = 10f; // Velocidad constante de la flecha public float maxHeightFactor = 0.25f; // Factor de la distancia que afecta la altura máxima public float chaseDistance; public float damageRange; public GameObject target; // Posición del objetivo private Vector3 startPoint; private float travelTime; private UnitHealth unitHealth; private float damage; public void Init(GameObject target, UnitHealth unitHealth, float damage) { this.target = target; this.unitHealth = unitHealth; this.damage = damage; startPoint = transform.position; InitiateFlight(); } void InitiateFlight() { // Calcular la altura máxima basada en la distancia al objetivo float distance = Vector3.Distance(startPoint, target.transform.position); float maxHeight = distance * maxHeightFactor; // Calcular el tiempo de vuelo basado en la velocidad constante travelTime = distance / speed; // Iniciar la simulación de la trayectoria StartCoroutine(SimulateProjectile(maxHeight)); } IEnumerator SimulateProjectile(float maxHeight) { float elapsed_time = 0; Vector3 currentTarget = target.transform.position; while (Vector3.Distance(transform.position, currentTarget) > damageRange) { elapsed_time += Time.deltaTime; float progress = elapsed_time / travelTime; // Interpolar la posición horizontal Vector3 horizontalPosition = Vector3.Lerp(startPoint, currentTarget, progress); // Calcular la posición vertical con una función parabólica basada en el progreso float height = (-4 * maxHeight * progress * (progress - 1)); // Calcular la próxima posición Vector3 nextPosition = new Vector3(horizontalPosition.x, height, horizontalPosition.z); // Rotar la flecha hacia la dirección de movimiento RotateTowardsMovement(nextPosition); // Mover la flecha transform.position = nextPosition; if(Vector3.Distance(transform.position, target.transform.position) < chaseDistance) { currentTarget = gameObject.transform.position; } if(Vector3.Distance(transform.position, target.transform.position) < damageRange) { if (unitHealth != null) { unitHealth.TakeDamage(damage); } } yield return null; } OnReachTarget(); } void RotateTowardsMovement(Vector3 nextPosition) { Vector3 directionOfMovement = nextPosition - transform.position; if (directionOfMovement != Vector3.zero) { Quaternion rotation = Quaternion.LookRotation(directionOfMovement.normalized); transform.rotation = rotation; } } void OnReachTarget() { // Aquí se maneja el impacto o llegada al objetivo Destroy(gameObject); // Por ejemplo, destruir la flecha cuando impacta el objetivo } } }
f7be881b2f24a9f001a1dbcae5e70a80
{ "intermediate": 0.33221718668937683, "beginner": 0.41930174827575684, "expert": 0.24848102033138275 }
37,119
I want you to modify the simulate projectile function: *Start the parabolic movement at the initial transform. position *The maximum height is reached at the middle of the trajectory *End the movement in target, take into account target will move so the end destination is dynamic *the longer the distance the arrow goes up, the shorter the distance the arrow goes down, the minimum height is a straight line with the target using System.Collections; using Game.Systems; using UnityEngine; namespace Game.ImprovedAI { public class Arrow : MonoBehaviour { public float speed = 10f; public float maxHeightFactor = 0.5f; // Adjust the height of the projectile public float damageRange; public float chaseRange; public GameObject target; private Vector3 startPoint; private Vector3 currentTarget; private float travelTime; private UnitHealth unitHealth; private float damage; public void Init(GameObject target, UnitHealth unitHealth, float damage) { this.target = target; this.unitHealth = unitHealth; this.damage = damage; startPoint = transform.position; currentTarget = target.transform.position; InitiateFlight(); } void InitiateFlight() { float distance = Vector3.Distance(startPoint, currentTarget); float maxHeight = Mathf.Max(distance * maxHeightFactor, 0.01f); // Ensure some height travelTime = distance / speed; StartCoroutine(SimulateProjectile(maxHeight)); } IEnumerator SimulateProjectile(float maxHeight) { float time = 0; // Calculate the vertex of the parabola (the highest point) Vector3 vertex = (startPoint + currentTarget) / 2 + Vector3.up * maxHeight; bool updatedTarget = false; while (time < travelTime) { time += Time.deltaTime; // Calculate the lerp parameter in [0, 1] float lerpParameter = time / travelTime; float heightParameter = 4 * (-lerpParameter * lerpParameter + lerpParameter); Vector3 parabolaPoint = Vector3.Lerp(startPoint, currentTarget, lerpParameter) + Vector3.up * maxHeight * heightParameter; // Rotate the arrow to face the next position RotateTowardsMovement(parabolaPoint); // Move the arrow to the next calculated position transform.position = parabolaPoint; if (Vector3.Distance(transform.position, currentTarget) < damageRange) { unitHealth?.TakeDamage(damage); break; } yield return null; } OnReachTarget(); } void RotateTowardsMovement(Vector3 nextPosition) { Vector3 directionOfMovement = nextPosition - transform.position; if (directionOfMovement != Vector3.zero) { Quaternion rotation = Quaternion.LookRotation(directionOfMovement.normalized); transform.rotation = rotation; } } void OnReachTarget() { Destroy(gameObject); } } }
f4ceb9a59509a031fb6630a90d5f8b31
{ "intermediate": 0.364562451839447, "beginner": 0.3971559405326843, "expert": 0.23828160762786865 }
37,120
voglio che il mio EA integri lindicatore ZZZZZ senza doverlo richiamare. ecco i codici //±-----------------------------------------------------------------+ //| ZZ_EA.mq4 | //| Copyright © 2023, Gabriele Bassi | CON LOT SIZE //±-----------------------------------------------------------------+ #property strict // External input parameters for the EA input double LotSize = 0.1; // Fixed lot size for each trade input double TakeProfitPips = 400; // Take profit in pips input double StopLossPips = 150; // Stop loss in pips input double TrailingStopPips = 10; // Trailing stop in pips // External input parameters for the indicator input int CCI_Period = 12; input int Momentum_Period = 21; input int RSI_Period = 14; input double SAR_Step = 0.01; input double SAR_Maximum = 0.2; // OnInit is called when the expert is loaded onto a chart int OnInit() { // Initialization code here return INIT_SUCCEEDED; } // OnTick is called on every new tick void OnTick() { // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // If there are no current orders, check for a buy or sell signal if(OrdersTotal() == 0) { if(arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order double sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); double tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy order based on ZZZZZ", 0, 0, clrGreen); if(ticket < 0) { Print("An error occurred while sending a buy order: ", GetLastError()); } } if(arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order double sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); double tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell order based on ZZZZZ", 0, 0, clrRed); if(ticket < 0) { Print("An error occurred while sending a sell order: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); } } // TrailingStopFunc adjusts the stop loss to enable a trailing stop void TrailingStopFunc() { for(int i = OrdersTotal() - 1; i >= 0; --i) { if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { // Verify that the selected order is for the current symbol if(OrderSymbol() == Symbol() && OrderMagicNumber() == 0) { if(OrderType() == OP_BUY) { // Current price is far enough from the opening price to move stop loss if(Bid - OrderOpenPrice() > TrailingStopPips * Point) { double newStopLoss = Bid - TrailingStopPips * Point; // Update the stop loss if it is less than the current stop loss if(newStopLoss > OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrGreen); } } } else if(OrderType() == OP_SELL) { // Current price is far enough from the opening price to move stop loss if(OrderOpenPrice() - Ask > TrailingStopPips * Point) { double newStopLoss = Ask + TrailingStopPips * Point; // Update the stop loss if it is greater than the current stop loss if(newStopLoss < OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrRed); } } } } } } } //±-----------------------------------------------------------------+ //±-----------------------------------------------------------------+ //| ZZZZZ.mq4 | //| Copyright © 2023, Gabriele Bassi | //±-----------------------------------------------------------------+ #property strict #property indicator_chart_window #property indicator_buffers 2 // Define property constants for arrow symbols #property indicator_type1 DRAW_ARROW #property indicator_type2 DRAW_ARROW #property indicator_color1 LimeGreen #property indicator_color2 Red #property indicator_width1 1 #property indicator_width2 1 // Indicator arrow codes from the Wingdings font #define UP_ARROW_SYMBOL 233 #define DOWN_ARROW_SYMBOL 234 // Indicator buffers (arrays) for storing values double ArrowUpBuffer[]; double ArrowDownBuffer[]; // Input parameters for indicator formula input int CCI_Period = 12; input int Momentum_Period = 5; input int RSI_Period = 14; input double SAR_Step = 0.02; input double SAR_Maximum = 0.2; //±-----------------------------------------------------------------+ //| Custom indicator initialization function | //±-----------------------------------------------------------------+ int OnInit() { // Set up indicator buffers for storing arrow data SetIndexBuffer(0, ArrowUpBuffer); SetIndexBuffer(1, ArrowDownBuffer); // Set up arrow symbols for display SetIndexArrow(0, UP_ARROW_SYMBOL); SetIndexArrow(1, DOWN_ARROW_SYMBOL); // Prepare indicator buffers for data manipulation ArraySetAsSeries(ArrowUpBuffer, true); ArraySetAsSeries(ArrowDownBuffer, true); // Clear all buffers first (initialize with empty values) for (int i = 0; i < ArraySize(ArrowUpBuffer); i++) { ArrowUpBuffer[i] = EMPTY_VALUE; } for (int i = 0; i < ArraySize(ArrowDownBuffer); i++) { ArrowDownBuffer[i] = EMPTY_VALUE; } return(INIT_SUCCEEDED); } //±-----------------------------------------------------------------+ //| Custom indicator iteration function called by the MetaTrader | //| platform every tick or price change | //±-----------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long &tick_volume[], const long &volume[], const int &spread[]) { // Loop through the bars and calculate the CCI for each for (int i = 1; i < rates_total; i++) { // Do not repaint the last bar if(i == rates_total - 1) { ArrowUpBuffer[i] = EMPTY_VALUE; ArrowDownBuffer[i] = EMPTY_VALUE; continue; } // Get the CCI, Momentum, RSI and SAR values double cci = iCCI(NULL, 0, CCI_Period, PRICE_TYPICAL, i); double cci_prev = iCCI(NULL, 0, CCI_Period, PRICE_TYPICAL, i + 1); double momentum = iMomentum(NULL, 0, Momentum_Period, PRICE_CLOSE, i); double rsi = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, i); double sar = iSAR(NULL, 0, SAR_Step, SAR_Maximum, i); // Condition for the up arrow (green): CCI crossover from below if (cci >= 100 && cci_prev < 100 && momentum >= 100 && rsi >= 50 && sar < low[i]) { ArrowUpBuffer[i] = low[i] - (4 * _Point); } else { ArrowUpBuffer[i] = EMPTY_VALUE; } // Condition for the down arrow (red): CCI crossover from above if (cci <= -100 && cci_prev > -100 && momentum < 100 && rsi < 50 && sar > high[i]) { ArrowDownBuffer[i] = high[i] + (4 * _Point); } else { ArrowDownBuffer[i] = EMPTY_VALUE; } } return(rates_total); } //±-----------------------------------------------------------------+ scrivi il codice completo del nuovo EA
12ffc41d5176ee6d5f294376b7961825
{ "intermediate": 0.3605829179286957, "beginner": 0.3581874966621399, "expert": 0.28122958540916443 }
37,121
Here's my enum class: public enum Enumlol { GetRecordStatus() { @Override public void assemble(JsonNode node) { } }; private Enumlol() { } protected abstract void assemble(JsonNode node); } How do I force the enums to have an abstract method in them, but each enum can define its own number of parameters it takes in the method?
ba4753760f564515af92898ac13b0caf
{ "intermediate": 0.26253095269203186, "beginner": 0.5886059999465942, "expert": 0.1488630771636963 }
37,122
Here's my enum class: public enum Enumlol { GetRecordStatus() { @Override public void assemble(JsonNode node) { } }; private Enumlol() { } protected abstract void assemble(JsonNode node); } How do I force the enums to have an abstract method in them, but each enum can define its own number of parameters it takes in the method?
3c3c2f089b9d31c27decea157a96bc03
{ "intermediate": 0.3085887134075165, "beginner": 0.5504372715950012, "expert": 0.1409740298986435 }
37,123
How do I force a subclass to have method, but that method can have any number of variables that it wants in the subclass, it just has to have the method?
64d07d546f12a555116927e80a51c70c
{ "intermediate": 0.4504470229148865, "beginner": 0.25885289907455444, "expert": 0.2907000482082367 }
37,124
In java, "How do I force a subclass to have method, but that method can have any number of variables that it wants in the subclass, it just has to have the method?"
332266b0fadfcd91184e2f64ba59ff16
{ "intermediate": 0.5059434175491333, "beginner": 0.3620896339416504, "expert": 0.1319669485092163 }
37,125
"How do I force a subclass to have method, but that method can have any number of variables that it wants in the subclass, it just has to have the method?"
441da9ffaf0c41f48d0900e81eee32d0
{ "intermediate": 0.42888203263282776, "beginner": 0.262990266084671, "expert": 0.30812767148017883 }
37,126
"How do I force a subclass to have method, but that method can have any number of variables that it wants in the subclass, it just has to have the method?"
b800793eed2b10fb02a455e079297ea8
{ "intermediate": 0.42888203263282776, "beginner": 0.262990266084671, "expert": 0.30812767148017883 }
37,127
In Java, "How do I force a subclass to have method, but that method can have any number of variables that it wants in the subclass, it just has to have the method?"
de671c56cd7e52e40749a43c6c20aa01
{ "intermediate": 0.3858025372028351, "beginner": 0.453288733959198, "expert": 0.16090872883796692 }
37,128
Consumer with an infinite number of arguments but one return type in java
42500c55ea975f02510302e9192a82ec
{ "intermediate": 0.3162585198879242, "beginner": 0.5201388001441956, "expert": 0.16360269486904144 }
37,129
Make a go program that logs into smtp server and sends emails to every email in an emails.txt
532f296eadc065630de4d1ef69330f9b
{ "intermediate": 0.5100569725036621, "beginner": 0.13906638324260712, "expert": 0.3508766293525696 }
37,130
Make a python program to send emails using smtp server login details. It will send html emails, the html will be an index.html. the emails in an emails.txt
acbc2dc3be1f15f1f70446c4b14049d6
{ "intermediate": 0.41919320821762085, "beginner": 0.23534007370471954, "expert": 0.3454667031764984 }
37,131
python if has attr then true
84427c314005ea0e88fdeca1c7bec845
{ "intermediate": 0.2737967371940613, "beginner": 0.4066087007522583, "expert": 0.31959450244903564 }
37,132
print attr of class in python
cec2ea44232e573508c94e1274c39cb7
{ "intermediate": 0.14729377627372742, "beginner": 0.6012076735496521, "expert": 0.25149857997894287 }
37,133
how to add an element to the end of an arraylist
9fb783f8d36c6baadd517cbca253365d
{ "intermediate": 0.3923962414264679, "beginner": 0.3459923565387726, "expert": 0.2616114020347595 }
37,134
package alternativa.tanks.gui { import alternativa.engine3d.alternativa3d; import alternativa.engine3d.containers.KDContainer; import alternativa.engine3d.core.Face; import alternativa.engine3d.core.MipMapping; import alternativa.engine3d.core.Object3D; import alternativa.engine3d.core.Object3DContainer; import alternativa.engine3d.core.Vertex; import alternativa.engine3d.core.View; import alternativa.engine3d.core.Wrapper; import alternativa.engine3d.materials.TextureMaterial; import alternativa.engine3d.objects.Decal; import alternativa.engine3d.objects.Mesh; import alternativa.engine3d.objects.SkyBox; import alternativa.init.Main; import alternativa.osgi.service.locale.ILocaleService; import alternativa.resource.StubBitmapData; import alternativa.tanks.Tank3D; import alternativa.tanks.Tank3DPart; import alternativa.tanks.bg.IBackgroundService; import alternativa.tanks.camera.GameCamera; import alternativa.types.Long; import controls.TankWindow2; import controls.TankWindowHeader; import controls.TankWindowInner; import forms.TankWindowWithHeader; import flash.display.BitmapData; import flash.display.BlendMode; import flash.display.Shape; import flash.display.Sprite; import flash.events.Event; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TimerEvent; import flash.filters.BitmapFilterQuality; import flash.filters.BlurFilter; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import flash.geom.Vector3D; import flash.ui.Keyboard; import flash.utils.Timer; import flash.utils.clearInterval; import flash.utils.getTimer; import flash.utils.setInterval; import scpacker.resource.ResourceType; import scpacker.resource.ResourceUtil; import scpacker.resource.images.ImageResource; import scpacker.resource.tanks.TankResource; import specter.utils.Logger; use namespace alternativa3d; public class TankPreview extends Sprite { private static const INITIAL_CAMERA_DIRECTION:Number = -150; private static const SHADOW_ALPHA:Number = 0.7; private static const SHADOW_BLUR:Number = 13; private static const SHADOW_RESOLUTION:Number = 2.5; private static const SHADOW_DIRECTION:Vector3D = new Vector3D(0, 0, -1); protected var shadow:Mesh; private var shadowMaterial:TextureMaterial; private var window:TankWindow2; private var windowHeader:TankWindowWithHeader; private const windowMargin:int = 11; private var inner:TankWindowInner; private var rootContainer:Object3DContainer; private var cameraContainer:Object3DContainer; private var camera:GameCamera; private var timer:Timer; private var tank:Tank3D; private var rotationSpeed:Number; private var lastTime:int; private var loadedCounter:int = 0; private var holdMouseX:int; private var lastMouseX:int; private var prelastMouseX:int; private var rate:Number; private var startAngle:Number = -150; private var holdAngle:Number; private var slowdownTimer:Timer; private var resetRateInt:uint; private var autoRotationDelay:int = 10000; private var autoRotationTimer:Timer; public var overlay:Shape; private var firstAutoRotation:Boolean = true; private var first_resize:Boolean = true; private var dot : Number = Math.PI / 180; private var dot1:Number = dot * 0.001; protected var backgroundEraserTimer:Timer; protected var backgroundEraser:Shape; /// public function TankPreview(garageBoxId:Long, rotationSpeed:Number = 5) { this.windowHeader = new TankWindowWithHeader("МОЙ ТАНК"); addChild(this.windowHeader); var box:Mesh = null; var material:TextureMaterial = null; this.overlay = new Shape(); super(); this.rotationSpeed = rotationSpeed; this.window = new TankWindow2(400,300); var localeService:ILocaleService = ILocaleService(Main.osgi.getService(ILocaleService)); addChild(this.window); this.rootContainer = new Object3DContainer(); this.tank = new Tank3D(null, null, null); this.rootContainer.addChild(this.tank); this.tank.matrix.appendTranslation(0, 0, 0);//(-17, 0, 0) initGarage(); this.camera = new GameCamera(); this.camera.view = new View(100, 100); this.camera.view.hideLogo(); addChild(this.camera.view); addChild(this.overlay); this.camera.view.visible = false; this.overlay.x = 0; this.overlay.y = 9; this.overlay.width = 1500; this.overlay.height = 1300; this.overlay.graphics.clear(); this.cameraContainer = new Object3DContainer(); this.rootContainer.addChild(this.cameraContainer); this.cameraContainer.addChild(this.camera); this.cameraContainer.z = 225; //this.camera.z = -850; //this.cameraContainer.rotationX = -115 * dot; //this.cameraContainer.rotationZ = this.startAngle * dot; this.cameraContainer.rotationX = -110 * Math.PI / 180; //this.camera.y = garageService.getCameraAltitude(); this.camera.z = -910; //this.camera.fov = garageService.getCameraFieldOfView(); this.camera.x = -20; this.camera.y = 80; this.cameraContainer.rotationZ = INITIAL_CAMERA_DIRECTION * Math.PI / 180; this.inner = new TankWindowInner(0, 0, TankWindowInner.TRANSPARENT); addChild(this.inner); this.inner.mouseEnabled = true; this.autoRotationTimer = new Timer(this.autoRotationDelay,1); this.autoRotationTimer.addEventListener(TimerEvent.TIMER_COMPLETE,this.start); this.timer = new Timer(50); this.slowdownTimer = new Timer(20,1000000); this.slowdownTimer.addEventListener(TimerEvent.TIMER,this.slowDown); this.inner.addEventListener(MouseEvent.MOUSE_DOWN,this.onMouseDown); Main.stage.addEventListener(Event.ENTER_FRAME, this.onRender); // this.backgroundEraser = new Shape(); this.backgroundEraser.blendMode = BlendMode.ERASE; /// this.backgroundEraserTimer = new Timer(1000,1); this.backgroundEraserTimer.addEventListener(TimerEvent.TIMER_COMPLETE,this.onBackgroundEraserTimerComplete); this.backgroundEraserTimer.start(); // this.start(); } private function onBackgroundEraserTimerComplete(param1:TimerEvent) : void { addChild(this.backgroundEraser); this.backgroundEraserTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.onBackgroundEraserTimerComplete); this.backgroundEraserTimer = null; } public function hide() : void { var bgService:IBackgroundService = Main.osgi.getService(IBackgroundService) as IBackgroundService; if(bgService != null) { bgService.drawBg(); } this.stopAll(); this.window = null; this.inner = null; for(var i:int = 0; i < rootContainer.numChildren; i++) { //rootContainer.getChildAt(i).destroy(); rootContainer.removeChildAt(i); } this.rootContainer = null; this.cameraContainer = null; this.camera.view.clear(); this.camera = null; this.timer = null; this.tank.destroy(); this.tank = null; this.backgroundEraser = null; this.backgroundEraserTimer = null; Main.stage.removeEventListener(Event.ENTER_FRAME,this.onRender); } private function onMouseDown(e:MouseEvent) : void { if(this.autoRotationTimer.running) { this.autoRotationTimer.stop(); } if(this.timer.running) { this.stop(); } if(this.slowdownTimer.running) { this.slowdownTimer.stop(); } this.resetRate(); this.holdMouseX = Main.stage.mouseX; this.lastMouseX = this.holdMouseX; this.prelastMouseX = this.holdMouseX; this.holdAngle = this.cameraContainer.rotationZ; Main.writeToConsole("TankPreview onMouseMove holdAngle: " + this.holdAngle.toString()); Main.stage.addEventListener(MouseEvent.MOUSE_UP,this.onMouseUp); Main.stage.addEventListener(MouseEvent.MOUSE_MOVE,this.onMouseMove); } private function onMouseMove(e:MouseEvent) : void { this.cameraContainer.rotationZ = this.holdAngle - (Main.stage.mouseX - this.holdMouseX) * 0.01; //this.camera.render(); this.rate = (Main.stage.mouseX - this.prelastMouseX) * 0.5; this.prelastMouseX = this.lastMouseX; this.lastMouseX = Main.stage.mouseX; clearInterval(this.resetRateInt); this.resetRateInt = setInterval(this.resetRate,50); } private function resetRate() : void { this.rate = 0; } private function onMouseUp(e:MouseEvent) : void { clearInterval(this.resetRateInt); Main.stage.removeEventListener(MouseEvent.MOUSE_UP,this.onMouseUp); Main.stage.removeEventListener(MouseEvent.MOUSE_MOVE,this.onMouseMove); if(Math.abs(this.rate) > 0) { this.slowdownTimer.reset(); this.slowdownTimer.start(); } else { this.autoRotationTimer.reset(); this.autoRotationTimer.start(); } } private function slowDown(e:TimerEvent) : void { this.cameraContainer.rotationZ = this.cameraContainer.rotationZ - this.rate * 0.01; //this.camera.render(); this.rate = this.rate * Math.exp(-0.02); if(Math.abs(this.rate) < 0.1) { this.slowdownTimer.stop(); this.autoRotationTimer.reset(); this.autoRotationTimer.start(); } } public function resize(width:Number, height:Number, i:int = 0, j:int = 0) : void { this.window.width = width; this.window.height = height; this.window.alpha = 1; this.inner.width = width - this.windowMargin * 2; this.inner.height = height - this.windowMargin * 2; this.inner.x = this.windowMargin; this.inner.y = this.windowMargin; var bgService:IBackgroundService = Main.osgi.getService(IBackgroundService) as IBackgroundService; if(Main.stage.stageWidth >= 800 && !this.first_resize) { if(bgService != null) { bgService.drawBg(new Rectangle(Math.round(int(Math.max(1000,Main.stage.stageWidth)) / 3) + this.windowMargin,60 + this.windowMargin,this.inner.width,this.inner.height)); } } this.first_resize = false; this.camera.view.width = width - this.windowMargin * 2 - 2; this.camera.view.height = height - this.windowMargin * 2 - 2; this.camera.view.x = this.windowMargin; this.camera.view.y = this.windowMargin; this.adjustBackgroundEraser(); this.camera.render(); } private function adjustBackgroundEraser() : void { if(true) { this.backgroundEraser.x = this.camera.view.x; this.backgroundEraser.y = this.camera.view.y; this.backgroundEraser.graphics.clear(); this.backgroundEraser.graphics.beginFill(16711680); this.backgroundEraser.graphics.drawRect(0,0,this.camera.view.width,this.camera.view.height); this.backgroundEraser.graphics.endFill(); } } public function start(e:TimerEvent = null) : void { if(this.loadedCounter < 3) { this.autoRotationTimer.reset(); this.autoRotationTimer.start(); } else { this.firstAutoRotation = false; this.timer.addEventListener(TimerEvent.TIMER,this.onTimer); this.timer.reset(); this.lastTime = getTimer(); this.timer.start(); } } public function onRender(e:Event) : void { this.camera.render(); } public function stop() : void { this.timer.stop(); this.timer.removeEventListener(TimerEvent.TIMER,this.onTimer); } public function stopAll() : void { this.timer.stop(); this.timer.removeEventListener(TimerEvent.TIMER,this.onTimer); this.slowdownTimer.stop(); this.slowdownTimer.removeEventListener(TimerEvent.TIMER,this.slowDown); this.autoRotationTimer.stop(); this.slowdownTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, this.start); } private function onTimer(e:TimerEvent) : void { var time:int = this.lastTime; this.lastTime = getTimer(); this.cameraContainer.rotationZ = this.cameraContainer.rotationZ - this.rotationSpeed * (this.lastTime - time) * 0.001 * (Math.PI / 180); } } } как сделать чтобы windowHeader не перекрывал показ танка
705bb8fb2e1cdb8d8295529fcfa06d53
{ "intermediate": 0.31751227378845215, "beginner": 0.37508487701416016, "expert": 0.3074028491973877 }
37,135
if there are 10 books in room if i take 2 books for reading then how many books still in room
b2663571ba406e6404a02281d907fdeb
{ "intermediate": 0.37428101897239685, "beginner": 0.36375924944877625, "expert": 0.2619597911834717 }
37,136
Spawn in area unity
6e94b424e23909e237f1ad7896d10c02
{ "intermediate": 0.3947395086288452, "beginner": 0.33784255385398865, "expert": 0.2674179673194885 }
37,137
Spawn in area around point unity
9f64372e590fcf117ae0cd4c4257193f
{ "intermediate": 0.3599681556224823, "beginner": 0.3325955271720886, "expert": 0.30743634700775146 }
37,138
//Fear System by Caleb Bernatchez using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Linq; using ShadowDetect; public class FearSystem : MonoBehaviour, IDataPersistence { public bool _surroundedLight; [Separator("Radius Detection")] public float radiusDetection = 15f; [Separator("Layer to Fear")] public LayerMask fearMask; public LayerMask obstacleMask; public Transform playerHead; [Separator("Audio Source")] public AudioSource fearBreathing; [Separator("Decrepitude")] public List<Transform> decrepitudeList = new List<Transform>(); [Separator("Fear Amount")] public float currentFear = 0; public float maxFear = 100f; [Separator("Fear Slider")] public Slider fearSlider; public Slider sanitySlider; [Separator("Number Of Enemies")] public int currentEnemy; public int enemyMax = 15; public bool maxreached = false; [Separator("Intensity")] public int normal = 5; public int medium = 10; public int high = 15; [Separator("Sanity")] public float resetTimer; public float timerToSuicide; public bool timerIsRunning; public bool isInsane; [Separator("Shadow People Prefab")] public GameObject shadowPeoplePrefab; public GameObject shadowPeopleInsaneModePrefab; [Separator("Shadow People Listing")] private List<GameObject> listOfAllNearbyShadow = new List<GameObject>(); private List<GameObject> listOfAllAwayShadow = new List<GameObject>(); private CameraFilterPack_3D_Anomaly fearAnomaly; private PlayerVitals playerVitals; private RaycastHit hit; private float spawnMeleeNext = 0.0f; private float spawnMeleeRate = 0.8f; private LightFlickerEffect lightFlickerEffect; public GameObject[] fires; private void Awake() { if (menuScript1.PlayerSelected == 1) { resetTimer = 20; } else if (menuScript1.PlayerSelected == 2) { resetTimer = 30; } else if (menuScript1.PlayerSelected == 3) { resetTimer = 15; } } private void Start() { fearSlider.interactable = false; fearSlider.maxValue = maxFear; fearSlider.value = currentFear; sanitySlider.value = currentFear; playerVitals = GetComponent<PlayerVitals>(); lightFlickerEffect = GetComponentInChildren<LightFlickerEffect>(); fearAnomaly = Camera.main.GetComponent<CameraFilterPack_3D_Anomaly>(); timerToSuicide = resetTimer; timerIsRunning = false; isInsane = false; StartCoroutine(FearDetection()); fires = GameObject.FindGameObjectsWithTag("Fire"); } void Update() { foreach (GameObject fire in fires) { if (timerToSuicide < resetTimer) { if (Vector3.Distance(transform.position, fire.transform.position) <= 4 ) { timerToSuicide += 0.05f; } } } fearSlider.value = 100 * (timerToSuicide / resetTimer); sanitySlider.value = currentFear; fearAnomaly.Intensity = currentFear / 50; if (currentEnemy <= 0) { currentEnemy = 0; lightFlickerEffect.enabled = false; } maxreached = currentEnemy >= enemyMax; timerIsRunning = currentFear >= maxFear; currentEnemy = listOfAllNearbyShadow.Count + listOfAllAwayShadow.Count; if (maxreached) { if (currentEnemy > enemyMax) { currentEnemy = enemyMax; } } if (currentFear >= 50 && currentFear < 75) { enemyMax = normal; lightFlickerEffect.enabled = true; } else if (currentFear >= 75 && currentFear < 90) { enemyMax = medium; lightFlickerEffect.enabled = true; } else if (currentFear >= 90) { enemyMax = high; lightFlickerEffect.enabled = true; } if (decrepitudeList.Count >= 1) { currentFear += (decrepitudeList.Count * Time.deltaTime); if (currentFear > maxFear) { currentFear = maxFear; } if (currentFear < 0) { currentFear = 0; } } else { currentFear -= (2.5f * Time.deltaTime); if (currentFear > maxFear) { currentFear = maxFear; } if (currentFear < 0) { currentFear = 0; } } currentFear = Mathf.Clamp(currentFear, 0, 100); if (currentFear > maxFear) { currentFear = maxFear; } if (currentFear < 0) { currentFear = 0; } if (timerIsRunning) { if (timerToSuicide > 0) { timerToSuicide -= Time.deltaTime; } else { if (!playerVitals.isSuiciding && !playerVitals.isDead) { timerIsRunning = false; timerToSuicide = resetTimer; playerVitals.isSuiciding = true; playerVitals.StartCoroutine(playerVitals.CharacterSuicide()); StartCoroutine(DestroyWithTag("ShadowPeople")); } } } if (timerToSuicide <= 0) { timerIsRunning = false; timerToSuicide = resetTimer; playerVitals.isSuiciding = true; playerVitals.StartCoroutine(playerVitals.CharacterSuicide()); StartCoroutine(DestroyWithTag("ShadowPeople")); } if (currentFear >= maxFear) { isInsane = true; } else { isInsane = false; } if (!playerVitals.isDead || !playerVitals.isSuiciding) { if (currentFear > 10 && !fearBreathing.isPlaying) { fearBreathing.Play(); fearBreathing.loop = true; } else if (currentFear < 10 && fearBreathing.isPlaying) { fearBreathing.Stop(); fearBreathing.loop = false; } } else { fearBreathing.Stop(); fearBreathing.loop = false; } if (currentFear > 50) { SpawnEnemy(); ListShadowPeople(); GetObjectsOutSideOftheSpehere(); } else if (currentFear < 50) { if (listOfAllNearbyShadow != null) { foreach (GameObject shadow in listOfAllNearbyShadow) { StartCoroutine(DestroyWithTag("ShadowPeople")); currentEnemy--; } } } } IEnumerator FearDetection() { while (true) { decrepitudeList.Clear(); ListDecrepitude(); /*foreach (Transform decrepitude in decrepitudeList) { Debug.DrawLine(playerHead.position, decrepitude.position, Color.yellow); }*/ yield return new WaitForSeconds(1f); } } List<Transform> ListDecrepitude() { decrepitudeList.Clear(); Collider[] colliders = Physics.OverlapSphere(transform.position, radiusDetection, fearMask); foreach (Collider col in colliders) { if (colliders.Length >= 1) { if (!Physics.Linecast(playerHead.position, col.transform.position, out hit, obstacleMask)) { //Debug.DrawLine(playerHead.position, col.transform.position, Color.green); if (!playerVitals.LightOn || playerVitals.flashlightSlider.value <= 0 || !playerVitals.GlowStickON || !_surroundedLight) { //Debug.Log("Fear"); decrepitudeList.Add(col.transform); } if ((playerVitals.LightOn && playerVitals.flashlightSlider.value >= 1) || playerVitals.GlowStickON || _surroundedLight) { //Debug.Log("Light Reduces Fear"); decrepitudeList.Remove(col.transform); } } else if (Physics.Linecast(playerHead.position, col.transform.position, out hit, obstacleMask)) { //Debug.Log("Obstacle Reduces Fear"); //Debug.Log(hit.collider.transform.name); decrepitudeList.Remove(col.transform); } } else if (colliders.Length < 1) { decrepitudeList.Remove(col.transform); //Debug.Log("No Decrepitude Around"); } else if (colliders.Length < 1 && (playerVitals.LightOn && playerVitals.flashlightSlider.value >= 1) || playerVitals.GlowStickON || _surroundedLight) { decrepitudeList.Remove(col.transform); //Debug.Log("No Decrepitude Around + Light"); } } return decrepitudeList; } List<GameObject> ListShadowPeople() { if (!maxreached) { listOfAllNearbyShadow.Clear(); GameObject[] allObjects = GameObject.FindGameObjectsWithTag("ShadowPeople"); for (int i = 0; i < allObjects.Length; i++) { if (Vector3.Distance(allObjects[i].transform.position, transform.position) < radiusDetection) { listOfAllNearbyShadow.Add(allObjects[i]); } } } return listOfAllNearbyShadow; } List<GameObject> GetObjectsOutSideOftheSpehere() { listOfAllAwayShadow.Clear(); GameObject[] allObjects = GameObject.FindGameObjectsWithTag("ShadowPeople"); for (int i = 0; i < allObjects.Length; i++) { if (Vector3.Distance(allObjects[i].transform.position, transform.position) > radiusDetection) { listOfAllAwayShadow.Add(allObjects[i]); } } return listOfAllAwayShadow; } private void SpawnEnemy() { if (Time.time > spawnMeleeNext && !maxreached) { spawnMeleeNext = Time.time + spawnMeleeRate; Vector3 spawnPos = GameObject.Find("Player").transform.position; //Spawning an enemy spawnPos.x += Random.insideUnitSphere.x * radiusDetection; spawnPos.z += Random.insideUnitSphere.z * radiusDetection; if(timerToSuicide > 10) { Instantiate(shadowPeoplePrefab, spawnPos, Quaternion.identity); currentEnemy+=1; } else if (timerToSuicide <= 10) { Instantiate(shadowPeopleInsaneModePrefab, spawnPos, Quaternion.identity); currentEnemy += 1; } } foreach (GameObject shadow in listOfAllAwayShadow) { Vector3 spawnPos = GameObject.Find("Player").transform.position; //Spawning an enemy spawnPos.x += Random.insideUnitSphere.x * radiusDetection; spawnPos.z += Random.insideUnitSphere.z * radiusDetection; DestroyObject(shadow); currentEnemy=-1; if (listOfAllNearbyShadow.Count < enemyMax && !maxreached) { if (timerToSuicide > 10) { Instantiate(shadowPeoplePrefab, spawnPos, Quaternion.identity); currentEnemy += 1; } else if (timerToSuicide <= 10) { Instantiate(shadowPeopleInsaneModePrefab, spawnPos, Quaternion.identity); currentEnemy += 1; } } } } IEnumerator DestroyWithTag(string destroyTag) { GameObject[] shadowPeople; shadowPeople = GameObject.FindGameObjectsWithTag(destroyTag); foreach (GameObject oneObject in shadowPeople) Destroy(oneObject); yield return new WaitForSeconds(1); } public void OnShadow() { _surroundedLight = false; } public void OutShadow() { _surroundedLight = true; } private void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, radiusDetection); } public void LoadData(GameData data) { this.currentFear = data.fearLevel; this.timerToSuicide = data.sanityLevel; } public void SaveData(GameData data) { data.fearLevel = this.currentFear; data.sanityLevel = this.timerToSuicide; } }
3027f365ee2325edf53d26b8707bc36e
{ "intermediate": 0.3311706483364105, "beginner": 0.4769327640533447, "expert": 0.19189658761024475 }
37,139
Şu arama widgettimi tasarımını daha güzel hale getir ve ara butonu ayrı durması kötü olmuş daha birleşik ve modern tasarım yap @override Widget build(BuildContext context) { return Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Material( elevation: 5.0, // Arama çubuğuna gölge efekti verir. borderRadius: BorderRadius.circular(30.0), // Kenarları yuvarlar. child: TextFormField( onChanged: (value) { setState(() { query = value; }); }, decoration: InputDecoration( labelText: 'Arama', prefixIcon: Icon(Icons.search), border: OutlineInputBorder( borderRadius: BorderRadius.circular(30.0), borderSide: BorderSide.none, ), filled: false, fillColor: Colors.transparent.withOpacity(0.8), contentPadding: EdgeInsets.symmetric(horizontal: 35.0, vertical: 1.0), ), ), ), ), ElevatedButton( onPressed: searchVideos, child: Text('Ara'), ), Expanded( child: videos == null ? Container() : ListView.builder( itemCount: videos!.length, itemBuilder: (context, index) { var video = videos![index]; return ListTile( title: Text(video.title), subtitle: Text(video.author), ); }, ), ), ], ); }
a6926b702384f992c8fe414b1b908e2e
{ "intermediate": 0.2952137291431427, "beginner": 0.4843856990337372, "expert": 0.22040049731731415 }
37,140
//±-----------------------------------------------------------------+ //| ZZ_EA.mq4 | //| Copyright © 2023, Gabriele Bassi | //| Added LotSize & Spread | //| Added MagicNumber & Custom OrdersTotal | //±-----------------------------------------------------------------+ #property copyright "Gabriele Bassi" string version = "ZZ_EA v.0.1"; // External input parameters for the EA input double LotSize = 0.1; // Fixed lot size for each trade input double TakeProfitPips = 400; // Take profit in pips input double StopLossPips = 150; // Stop loss in pips input double TrailingStopPips = 10; // Trailing stop in pips input int MagicNumber = 12345; // Magic number to identify trades by this EA input double MaximumSpread = 3; // Maximum allowed spread in pips // External input parameters for the indicator input int CCI_Period = 12; input int Momentum_Period = 21; input int RSI_Period = 14; input double SAR_Step = 0.01; input double SAR_Maximum = 0.2; // OnInit is called when the expert is loaded onto a chart int OnInit() { // Initialization code here return INIT_SUCCEEDED; } int deinit() { // Deinitialization code here return(0); } // Custom function to count only our own trades with the MagicNumber and on the current symbol int CountOrdersByMagicAndSymbol() { int count = 0; for (int i = 0; i < OrdersTotal(); i++) { if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue; if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) { count++; } } return count; } // OnTick is called on every new tick void OnTick() { // Get the current spread in pips double spread = (Ask - Bid) / Point; // Check the spread against the maximum allowable spread before trading if (spread > MaximumSpread) { // Spread is too high, do not place the trade // Print("Spread is too high: ", spread); // Uncomment this line to print to the log return; // Exit the OnTick function } // Get last bar index in the chart (0 is the currently forming bar, 1 is the last fully formed bar) int lastBarIndex = 1; // Retrieve the last known values for the indicator signals double arrowUp = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 0, lastBarIndex); double arrowDown = iCustom(Symbol(), 0, "ZZZZZ", CCI_Period, Momentum_Period, RSI_Period, SAR_Step, SAR_Maximum, 1, lastBarIndex); // If there are no current orders with our MagicNumber, check for a buy or sell signal if (CountOrdersByMagicAndSymbol() == 0) { if (arrowUp != EMPTY_VALUE) { // If an up arrow (buy signal) is present, send a buy order double sl = NormalizeDouble(Bid - StopLossPips * Point, Digits); double tp = NormalizeDouble(Bid + TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy order based on ZZZZZ", MagicNumber, 0, clrGreen); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } else if (arrowDown != EMPTY_VALUE) { // If a down arrow (sell signal) is present, send a sell order double sl = NormalizeDouble(Ask + StopLossPips * Point, Digits); double tp = NormalizeDouble(Ask - TakeProfitPips * Point, Digits); int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell order based on ZZZZZ", MagicNumber, 0, clrRed); if (ticket < 0) { Print("OrderSend error: ", GetLastError()); } } } else { // Update the trailing stop for existing orders TrailingStopFunc(); } } // TrailingStopFunc adjusts the stop loss to enable a trailing stop void TrailingStopFunc() { for (int i = OrdersTotal() - 1; i >= 0; --i) { if (!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue; // Verify that the selected order is for the current symbol with our MagicNumber if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) { double newStopLoss; if (OrderType() == OP_BUY) { // Current price is far enough from the opening price to move stop loss if (Bid - OrderOpenPrice() > TrailingStopPips * Point) { newStopLoss = Bid - TrailingStopPips * Point; // Update the stop loss if it is less than the current stop loss if (newStopLoss > OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrGreen); } } } else if (OrderType() == OP_SELL) { // Current price is far enough from the opening price to move stop loss if (OrderOpenPrice() - Ask > TrailingStopPips * Point) { newStopLoss = Ask + TrailingStopPips * Point; // Update the stop loss if it is greater than the current stop loss if (newStopLoss < OrderStopLoss()) { OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, clrRed); } } } } } } //±-----------------------------------------------------------------+ ho questo errore: 'ticket' - variable already defined zzz_ea4.mq4 82 17
ce93d2c2047c9c08bd7db5ef05f25617
{ "intermediate": 0.28350773453712463, "beginner": 0.46349698305130005, "expert": 0.2529953122138977 }
37,141
can you provide valid c++ or expression that state either r8 or r9 is one of 0xff48, 0xbf68 , 0x58 ?
d8e1b05b6f969eb919148855c2feef5c
{ "intermediate": 0.30168718099594116, "beginner": 0.4821806848049164, "expert": 0.21613208949565887 }
37,142
Write a C# script for unity in which the player can make enemy disappear upon litting them with the flashlight actual light
c12c2e2c855c0cd4deebe5ecda56e801
{ "intermediate": 0.4040221869945526, "beginner": 0.2661709487438202, "expert": 0.3298068642616272 }
37,143
can you write me an edge detaection shader for Godot 4.2
f4c6f308de55d0e552b71bf71f090c90
{ "intermediate": 0.37655946612358093, "beginner": 0.23234902322292328, "expert": 0.391091525554657 }
37,144
error line 46 invalid arguments vec3 float
628c6133b68acbcc7388ec400ada8b4d
{ "intermediate": 0.3144760727882385, "beginner": 0.515605092048645, "expert": 0.16991885006427765 }