row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
33,631
#include <iostream> struct Node { Node* left = nullptr; Node* right = nullptr; Node* parent = nullptr; int profit = 0; int sum = 0; int max = INT_MIN; int min = INT_MAX; }; int max_sum_profit = 0; void CreateTree(Node* root, Node*& cur_root) { char temp; int temp_profit; std::cin >> temp; if (temp == 'l') { std::cin >> temp_profit; cur_root->left = new Node(); cur_root->left->profit = temp_profit; cur_root->left->parent = cur_root; cur_root = cur_root->left; } else if (temp == 'r') { std::cin >> temp_profit; cur_root->right = new Node(); cur_root->right->profit = temp_profit; cur_root->right->parent = cur_root; cur_root = cur_root->right; } else if (temp == 'u') { cur_root = cur_root->parent; } } bool CheckBST(Node* temp, int min, int max) { if (temp == nullptr) { return true; } if (temp->profit <= min || max <= temp->profit) { return false; } return CheckBST(temp->left, min, temp->profit) && CheckBST(temp->right, temp->profit, max); } int FindMaxSumOfBSTSubtree(Node* temp) { if (temp == nullptr) { return 0; } int sum_left = FindMaxSumOfBSTSubtree(temp->left); int sum_right = FindMaxSumOfBSTSubtree(temp->right); if (temp->profit > temp->max && temp->profit < temp->min) { int sum = temp->profit + temp->left->sum + temp->right->sum; if (max_sum_profit < sum) { max_sum_profit = sum; } if (temp->profit < temp->left->min) { temp->min = temp->profit; } else { temp->min = temp->left->min; } if (temp->profit > temp->right->max) { temp->max = temp->profit; } else { temp->max = temp->right->max; } return max_sum_profit; } if (temp->left->sum > temp->right->sum) { temp->sum = temp->left->sum; temp->min = INT_MIN; temp->max = INT_MAX; return temp->sum; } else { temp->sum = temp->right->sum; temp->min = INT_MIN; temp->max = INT_MAX; return temp->sum; } } int main() { char temp; int temp_profit; std::cin >> temp_profit; Node* root = nullptr; root = new Node(); root->profit = temp_profit; Node* cur_root = root; while (cur_root != nullptr) { CreateTree(root, cur_root); } max_sum_profit = 0; int nothing = FindMaxSumOfBSTSubtree(root); if (max_sum_profit < 0) { std::cout << 0; } else { std::cout << max_sum_profit; } return 0; } when input is 123 l 10100 u r 1782 r 90001 u l -17272 r 3639 r 90000 u u u u u it finished with Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) but it should have returned 93639
dc0973a89a20b69d12764694274c7b9f
{ "intermediate": 0.29866668581962585, "beginner": 0.4020538628101349, "expert": 0.29927942156791687 }
33,632
Here is a unity 2020.6.f script, please just remember it for reference. using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; #endif public class GKC_Utils : MonoBehaviour { public static float getCurrentDeltaTime () { float timeScale = Time.timeScale; if (timeScale > 0) { return 1 / timeScale; } else { return 1; } } public static float getCurrentScaleTime () { if (Time.timeScale != 1) { return ((1f / Time.fixedDeltaTime) * 0.02f); } return 1; } public static void checkAudioSourcePitch (AudioSource audioSourceToCheck) { if (audioSourceToCheck != null) { audioSourceToCheck.pitch = Time.timeScale; } } public static float distance (Vector3 positionA, Vector3 positionB) { return Mathf.Sqrt ((positionA - positionB).sqrMagnitude); } //the four directions of a swipe public class swipeDirections { public static Vector2 up = new Vector2 (0, 1); public static Vector2 down = new Vector2 (0, -1); public static Vector2 right = new Vector2 (1, 0); public static Vector2 left = new Vector2 (-1, 0); } public static void ForGizmo (Vector3 pos, Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Gizmos.DrawRay (pos, direction); Vector3 right = Quaternion.LookRotation (direction) * Quaternion.Euler (0, 180 + arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Vector3 left = Quaternion.LookRotation (direction) * Quaternion.Euler (0, 180 - arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Gizmos.DrawRay (pos + direction, arrowHeadLength * right); Gizmos.DrawRay (pos + direction, arrowHeadLength * left); } public static void drawGizmoArrow (Vector3 pos, Vector3 direction, Color color, float arrowHeadLength, float arrowHeadAngle) { Gizmos.color = color; Gizmos.DrawRay (pos, direction); Vector3 currentLookDirection = direction; Quaternion lookRotation = Quaternion.identity; if (currentLookDirection == Vector3.zero) { currentLookDirection = Vector3.forward; } lookRotation = Quaternion.LookRotation (currentLookDirection); Vector3 right = lookRotation * Quaternion.Euler (0, 180 + arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Vector3 left = lookRotation * Quaternion.Euler (0, 180 - arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Gizmos.DrawRay (pos + direction, arrowHeadLength * right); Gizmos.DrawRay (pos + direction, arrowHeadLength * left); } public static void ForDebug (Vector3 pos, Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Debug.DrawRay (pos, direction); Vector3 right = Quaternion.LookRotation (direction) * Quaternion.Euler (0, 180 + arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Vector3 left = Quaternion.LookRotation (direction) * Quaternion.Euler (0, 180 - arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Debug.DrawRay (pos + direction, arrowHeadLength * right); Debug.DrawRay (pos + direction, arrowHeadLength * left); } public static void ForDebug (Vector3 pos, Vector3 direction, Color color, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f) { Debug.DrawRay (pos, direction, color); Vector3 right = Quaternion.LookRotation (direction) * Quaternion.Euler (0, 180 + arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Vector3 left = Quaternion.LookRotation (direction) * Quaternion.Euler (0, 180 - arrowHeadAngle, 0) * new Vector3 (0, 0, 1); Debug.DrawRay (pos + direction, arrowHeadLength * right, color); Debug.DrawRay (pos + direction, arrowHeadLength * left, color); } public static void drawCapsuleGizmo (Vector3 point1, Vector3 point2, float capsuleCastRadius, Color sphereColor, Color cubeColor, Vector3 currentRayTargetPosition, Vector3 rayDirection, float distanceToTarget) { Gizmos.color = sphereColor; Gizmos.DrawSphere (point1, capsuleCastRadius); Gizmos.DrawSphere (point2, capsuleCastRadius); Gizmos.color = cubeColor; Vector3 scale = new Vector3 (capsuleCastRadius * 2, capsuleCastRadius * 2, distanceToTarget - capsuleCastRadius * 2); Matrix4x4 cubeTransform = Matrix4x4.TRS (((distanceToTarget / 2) * rayDirection) + currentRayTargetPosition, Quaternion.LookRotation (rayDirection, point1 - point2), scale); Matrix4x4 oldGizmosMatrix = Gizmos.matrix; Gizmos.matrix *= cubeTransform; Gizmos.DrawCube (Vector3.zero, Vector3.one); Gizmos.matrix = oldGizmosMatrix; } public static void drawRectangleGizmo (Vector3 rectanglePosition, Quaternion rectangleRotation, Vector3 positionOffset, Vector3 rectangleScale, Color rectangleColor) { Gizmos.color = rectangleColor; Matrix4x4 cubeTransform = Matrix4x4.TRS (rectanglePosition + positionOffset, rectangleRotation, rectangleScale); Matrix4x4 oldGizmosMatrix = Gizmos.matrix; Gizmos.matrix *= cubeTransform; Gizmos.DrawCube (Vector3.zero, Vector3.one); Gizmos.matrix = oldGizmosMatrix; } public static void checkDropObject (GameObject objectToDrop) { grabbedObjectState currentGrabbedObjectState = objectToDrop.GetComponent<grabbedObjectState> (); if (currentGrabbedObjectState != null) { dropObject (currentGrabbedObjectState.getCurrentHolder (), objectToDrop); } } public static void dropObject (GameObject currentPlayer, GameObject objectToDrop) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { grabObjectsManager.checkIfDropObject (objectToDrop); } } public static bool checkIfObjectCanBePlaced (GameObject currentPlayer, GameObject objectToDrop) { if (currentPlayer == null) { return true; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { return grabObjectsManager.checkIfObjectCanBePlaced (objectToDrop); } return true; } public static void dropObject (GameObject currentPlayer) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { grabObjectsManager.checkIfDropObject (); } } public static void dropObjectIfNotGrabbedPhysically (GameObject currentPlayer, bool dropIfGrabbedPhysicallyWithIK) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { if (grabObjectsManager.isCarryingPhysicalObject ()) { if (grabObjectsManager.isIKSystemEnabledOnCurrentGrabbedObject () && dropIfGrabbedPhysicallyWithIK) { grabObjectsManager.checkIfDropObject (); } } else { grabObjectsManager.checkIfDropObject (); } } } public static void checkIfKeepGrabbedObjectDuringAction (GameObject currentPlayer, bool keepGrabbedObjectOnActionIfNotDropped, bool keepGrabbedObject) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { if (grabObjectsManager.isGrabbedObject () & keepGrabbedObjectOnActionIfNotDropped) { grabObjectsManager.keepOrCarryGrabbebObject (keepGrabbedObject); } } } public static void disableKeepGrabbedObjectStateAfterAction (GameObject currentPlayer) { if (currentPlayer == null) { return; } checkIfKeepGrabbedObjectDuringAction (currentPlayer, true, false); } public static void keepMeleeWeaponGrabbed (GameObject currentPlayer) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { if (grabObjectsManager.isGrabbedObject ()) { grabObjectsManager.mainGrabbedObjectMeleeAttackSystem.drawOrKeepMeleeWeapon (); } if (grabObjectsManager.isGrabbedObject ()) { grabObjectsManager.checkIfDropObject (); } } } public static void drawMeleeWeaponGrabbed (GameObject currentPlayer) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { if (!grabObjectsManager.isGrabbedObject ()) { grabObjectsManager.mainGrabbedObjectMeleeAttackSystem.drawOrKeepMeleeWeaponWithoutCheckingInputActive (); } } } public static void drawMeleeWeaponGrabbedCheckingAnimationDelay (GameObject currentPlayer) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { if (!grabObjectsManager.isGrabbedObject ()) { grabObjectsManager.mainGrabbedObjectMeleeAttackSystem.drawMeleeWeaponGrabbedCheckingAnimationDelay (); } } } public static void disableCurrentAttackInProcess (GameObject currentPlayer) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { grabObjectsManager.mainGrabbedObjectMeleeAttackSystem.disableCurrentAttackInProcess (); } } public static void grabPhysicalObjectExternally (GameObject currentPlayer, GameObject objectToGrab) { if (currentPlayer == null) { return; } grabObjects grabObjectsManager = currentPlayer.GetComponent<grabObjects> (); if (grabObjectsManager != null) { if (!grabObjectsManager.isGrabbedObject ()) { grabObjectsManager.grabPhysicalObjectExternally (objectToGrab); } } } public static void enableOrDisableMeleeWeaponMeshActiveState (GameObject currentPlayer, bool state) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { grabbedObjectMeleeAttackSystem currentGrabbedObjectMeleeAttackSystem = currentplayerComponentsManager.getGrabbedObjectMeleeAttackSystem (); if (currentGrabbedObjectMeleeAttackSystem != null) { if (currentGrabbedObjectMeleeAttackSystem.isCarryingObject ()) { currentGrabbedObjectMeleeAttackSystem.enableOrDisableWeaponMeshActiveState (state); } } } } public static void enableOrDisableFireWeaponMeshActiveState (GameObject currentPlayer, bool state) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerWeaponsManager currentPlayerWeaponsManager = currentplayerComponentsManager.getPlayerWeaponsManager (); if (currentPlayerWeaponsManager != null) { if (currentPlayerWeaponsManager.isUsingWeapons ()) { currentPlayerWeaponsManager.enableOrDisableCurrentWeaponsMesh (state); } } } } public static bool enableOrDisableIKOnWeaponsDuringAction (GameObject currentPlayer, bool state) { if (currentPlayer == null) { return false; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerWeaponsManager currentPlayerWeaponsManager = currentplayerComponentsManager.getPlayerWeaponsManager (); if (currentPlayerWeaponsManager != null) { if (state) { currentPlayerWeaponsManager.enableOrDisableIKOnWeaponsDuringAction (true); } else { if (currentPlayerWeaponsManager.isPlayerCarringWeapon ()) { currentPlayerWeaponsManager.enableOrDisableIKOnWeaponsDuringAction (false); return true; } } } } return false; } public static void useObjectExternally (GameObject currentPlayer, GameObject objectToUse) { usingDevicesSystem usingDevicesManager = currentPlayer.GetComponent<usingDevicesSystem> (); if (usingDevicesManager != null) { inventoryManager currentInventoryManager = currentPlayer.GetComponent<inventoryManager> (); bool examineObjectBeforeStoreEnabled = false; if (currentInventoryManager != null) { examineObjectBeforeStoreEnabled = currentInventoryManager.examineObjectBeforeStoreEnabled; currentInventoryManager.setExamineObjectBeforeStoreEnabledState (false); } bool useMinDistanceToUseDevices = usingDevicesManager.useMinDistanceToUseDevices; Transform objectToCheckParent = objectToUse.transform.parent; if (objectToCheckParent == null) { objectToCheckParent = objectToUse.transform; } pickUpObject currentPickUpObject = objectToCheckParent.GetComponentInChildren<pickUpObject> (); if (currentPickUpObject != null) { currentPickUpObject.getComponents (); currentPickUpObject.checkTriggerInfoByGameObject (currentPlayer); } usingDevicesManager.setUseMinDistanceToUseDevicesState (false); usingDevicesManager.clearDeviceList (); usingDevicesManager.addDeviceToList (objectToUse); usingDevicesManager.updateClosestDeviceList (); usingDevicesManager.useCurrentDevice (objectToUse); usingDevicesManager.setUseMinDistanceToUseDevicesState (useMinDistanceToUseDevices); if (currentInventoryManager != null) { currentInventoryManager.setExamineObjectBeforeStoreEnabledState (examineObjectBeforeStoreEnabled); } } } public static void useDeviceObjectExternally (GameObject currentPlayer, GameObject objectToUse) { usingDevicesSystem usingDevicesManager = currentPlayer.GetComponent<usingDevicesSystem> (); if (usingDevicesManager != null) { bool useMinDistanceToUseDevices = usingDevicesManager.useMinDistanceToUseDevices; usingDevicesManager.setUseMinDistanceToUseDevicesState (false); usingDevicesManager.clearDeviceList (); usingDevicesManager.addDeviceToList (objectToUse); usingDevicesManager.updateClosestDeviceList (); usingDevicesManager.useCurrentDevice (objectToUse); usingDevicesManager.setUseMinDistanceToUseDevicesState (useMinDistanceToUseDevices); } } public static Vector2 getScreenResolution () { #if UNITY_EDITOR return new Vector2 (Screen.width, Screen.height); #else return new Vector2 (Screen.currentResolution.width, Screen.currentResolution.height); #endif } public static void createInventoryWeaponAmmo (string weaponName, string ammoName, GameObject weaponAmmoMesh, Texture weaponAmmoIconTexture, string inventoryAmmoCategoryName, int ammoAmountPerPickup, string customAmmoDescription) { instantiateMainManagerOnSceneWithType ("Main Inventory Manager", typeof(inventoryListManager)); inventoryListManager mainInventoryListManager = FindObjectOfType<inventoryListManager> (); if (mainInventoryListManager != null) { bool ammoPickupFound = false; GameObject ammoPickupGameObject = mainInventoryListManager.getInventoryPrefabByName (ammoName); ammoPickupFound = ammoPickupGameObject != null; if (ammoPickupFound) { print ("Ammo inventory object " + ammoName + " already exists"); } else { inventoryInfo currentWeaponInventoryInfo = mainInventoryListManager.getInventoryInfoFromCategoryListByName (weaponName); if (currentWeaponInventoryInfo != null) { int ammoInventoryCategoryIndex = mainInventoryListManager.getInventoryCategoryIndexByName (inventoryAmmoCategoryName); if (ammoInventoryCategoryIndex > -1) { print ("Category " + inventoryAmmoCategoryName + " found in inventory list manager"); inventoryInfo ammoInventoryInfo = new inventoryInfo (); ammoInventoryInfo.Name = ammoName; ammoInventoryInfo.inventoryGameObject = weaponAmmoMesh; ammoInventoryInfo.icon = weaponAmmoIconTexture; ammoInventoryInfo.objectInfo = customAmmoDescription; ammoInventoryInfo.amountPerUnit = ammoAmountPerPickup; ammoInventoryInfo.storeTotalAmountPerUnit = true; ammoInventoryInfo.canBeDropped = true; ammoInventoryInfo.canBeDiscarded = true; ammoInventoryInfo.canBeCombined = true; ammoInventoryInfo.canBeExamined = true; ammoInventoryInfo.useNewBehaviorOnCombine = true; ammoInventoryInfo.useOneUnitOnNewBehaviourCombine = true; ammoInventoryInfo.newBehaviorOnCombineMessage = "-OBJECT- refilled with -AMOUNT- projectiles"; ammoInventoryInfo.objectToCombine = currentWeaponInventoryInfo.inventoryGameObject; ammoInventoryInfo.canBeSold = true; ammoInventoryInfo.sellPrice = 1000; ammoInventoryInfo.vendorPrice = 500; ammoInventoryInfo.weight = 5; mainInventoryListManager.addNewInventoryObject (ammoInventoryCategoryIndex, ammoInventoryInfo); int inventoryObjectIndex = mainInventoryListManager.getInventoryInfoIndexByName (ammoName); if (inventoryObjectIndex > -1) { print ("Inventory info for the new ammo created " + ammoName + " found"); mainInventoryListManager.createInventoryPrafab (ammoInventoryCategoryIndex, inventoryObjectIndex); ammoPickupGameObject = mainInventoryListManager.getInventoryPrefabByName (ammoName); if (ammoPickupGameObject != null) { print ("New ammo inventory object found, assigning to the weapon to combine the ammo" + ammoPickupGameObject.name); currentWeaponInventoryInfo.canBeCombined = true; currentWeaponInventoryInfo.objectToCombine = ammoPickupGameObject; mainInventoryListManager.updateInventoryList (); } else { print ("New ammo inventory object not found to assign"); } } else { print ("Inventory info for the new ammo created " + ammoName + " not found"); } } else { print ("Category " + inventoryAmmoCategoryName + " not found in inventory list manager"); } } else { print ("WARNING: Weapon inventory prefab " + weaponName + " not found, make sure that weapon is configured in the Inventory List Manager"); } } } } public static void createInventoryWeapon (string weaponName, string inventoryWeaponCategoryName, GameObject weaponMesh, string weaponDescription, Texture weaponIconTexture, string relativePathWeaponsMesh, bool isMeleeWeapon, bool useDurabilityValue, float durabilityAmountValue, float maxDurabilityAmountValue, float objectWeight, bool canBeSold, float sellPrice, float vendorPrice) { #if UNITY_EDITOR instantiateMainManagerOnSceneWithType ("Main Inventory Manager", typeof(inventoryListManager)); inventoryListManager mainInventoryListManager = FindObjectOfType<inventoryListManager> (); if (mainInventoryListManager != null) { bool weaponPickupFound = false; GameObject weaponPickupGameObject = mainInventoryListManager.getInventoryPrefabByName (weaponName); weaponPickupFound = weaponPickupGameObject != null; if (weaponPickupFound) { print ("Weapon inventory object " + weaponName + " already exists"); } else { int weaponInventoryCategoryIndex = mainInventoryListManager.getInventoryCategoryIndexByName (inventoryWeaponCategoryName); if (weaponInventoryCategoryIndex > -1) { print ("Category " + inventoryWeaponCategoryName + " found in inventory list manager"); GameObject weaponMeshCopy = Instantiate (weaponMesh); if (weaponMeshCopy != null) { if (!isMeleeWeapon) { weaponPartstToRemoveOnPickupCreation currentweaponPartstToRemoveOnPickupCreation = weaponMeshCopy.GetComponent<weaponPartstToRemoveOnPickupCreation> (); if (currentweaponPartstToRemoveOnPickupCreation != null) { currentweaponPartstToRemoveOnPickupCreation.removeWeaponObjects (); } weaponAttachmentSystem currentWeaponAttachmentSystem = weaponMeshCopy.GetComponentInChildren<weaponAttachmentSystem> (); if (currentWeaponAttachmentSystem != null) { print ("Removing weapon attachment system from pickup"); DestroyImmediate (currentWeaponAttachmentSystem.gameObject); } } } GameObject newWeaponMesh = createPrefab (relativePathWeaponsMesh, (weaponName + " Mesh"), weaponMeshCopy); BoxCollider currentBoxCollider = newWeaponMesh.GetComponent<BoxCollider> (); if (currentBoxCollider == null) { newWeaponMesh.AddComponent<BoxCollider> (); } int newLayerIndex = LayerMask.NameToLayer ("inventory"); Component[] components = newWeaponMesh.GetComponentsInChildren (typeof(Transform)); foreach (Transform child in components) { child.gameObject.layer = newLayerIndex; } print ("Created weapon mesh prefab " + newWeaponMesh.name); inventoryInfo weaponInventoryInfo = new inventoryInfo (); weaponInventoryInfo.Name = weaponName; weaponInventoryInfo.objectInfo = weaponDescription; weaponInventoryInfo.inventoryGameObject = newWeaponMesh; weaponInventoryInfo.icon = weaponIconTexture; weaponInventoryInfo.canBeEquiped = true; weaponInventoryInfo.canBeDropped = true; weaponInventoryInfo.canBeSold = canBeSold; weaponInventoryInfo.sellPrice = sellPrice; weaponInventoryInfo.vendorPrice = vendorPrice; weaponInventoryInfo.isWeapon = true; weaponInventoryInfo.isMeleeWeapon = isMeleeWeapon; weaponInventoryInfo.canBePlaceOnQuickAccessSlot = true; weaponInventoryInfo.canBeSetOnQuickSlots = true; weaponInventoryInfo.weight = objectWeight; weaponInventoryInfo.useDurability = useDurabilityValue; weaponInventoryInfo.durabilityAmount = durabilityAmountValue; weaponInventoryInfo.maxDurabilityAmount = maxDurabilityAmountValue; mainInventoryListManager.addNewInventoryObject (weaponInventoryCategoryIndex, weaponInventoryInfo); int inventoryObjectIndex = mainInventoryListManager.getInventoryInfoIndexByName (weaponName); if (inventoryObjectIndex > -1) { print ("Inventory info for the new weapon created " + weaponName + " found"); mainInventoryListManager.createInventoryPrafab (weaponInventoryCategoryIndex, inventoryObjectIndex); } else { print ("Inventory info for the new weapon created " + weaponName + " not found"); } print ("New weapon " + weaponName + " added to the inventory"); if (weaponMeshCopy != null) { DestroyImmediate (weaponMeshCopy); } } else { print ("Category " + inventoryWeaponCategoryName + " not found in inventory list manager"); } } } #endif } public static void createInventoryArmorClothPiece (string objectName, string inventoryObjectCategoryName, string categoryName, GameObject objectMeshPrefab, string objectDescription, Texture objectIconTexture, string relativePathObjectMesh) { #if UNITY_EDITOR instantiateMainManagerOnSceneWithType ("Main Inventory Manager", typeof(inventoryListManager)); inventoryListManager mainInventoryListManager = FindObjectOfType<inventoryListManager> (); if (mainInventoryListManager != null) { bool objectPickupFound = false; GameObject objectPickupGameObject = mainInventoryListManager.getInventoryPrefabByName (objectName); objectPickupFound = objectPickupGameObject != null; if (objectPickupFound) { print ("Inventory object " + objectName + " already exists"); } else { int objectInventoryCategoryIndex = mainInventoryListManager.getInventoryCategoryIndexByName (inventoryObjectCategoryName); if (objectInventoryCategoryIndex > -1) { print ("Category " + inventoryObjectCategoryName + " found in inventory list manager"); GameObject objectMeshCopy = Instantiate (objectMeshPrefab); GameObject newObjectMesh = createPrefab (relativePathObjectMesh, (objectName + " Mesh"), objectMeshCopy); BoxCollider currentBoxCollider = newObjectMesh.GetComponent<BoxCollider> (); if (currentBoxCollider == null) { newObjectMesh.AddComponent<BoxCollider> (); } int newLayerIndex = LayerMask.NameToLayer ("inventory"); Component[] components = objectMeshCopy.GetComponentsInChildren (typeof(Transform)); foreach (Transform child in components) { child.gameObject.layer = newLayerIndex; } print ("Created Object mesh prefab " + newObjectMesh.name); inventoryInfo objectInventoryInfo = new inventoryInfo (); objectInventoryInfo.Name = objectName; objectInventoryInfo.objectInfo = objectDescription; objectInventoryInfo.inventoryGameObject = newObjectMesh; objectInventoryInfo.icon = objectIconTexture; objectInventoryInfo.canBeEquiped = true; objectInventoryInfo.canBeDropped = true; objectInventoryInfo.canBeSold = true; objectInventoryInfo.sellPrice = 1000; objectInventoryInfo.vendorPrice = 500; objectInventoryInfo.isArmorClothAccessory = true; objectInventoryInfo.canBePlaceOnQuickAccessSlot = true; objectInventoryInfo.weight = 5; mainInventoryListManager.addNewInventoryObject (objectInventoryCategoryIndex, objectInventoryInfo); int inventoryObjectIndex = mainInventoryListManager.getInventoryInfoIndexByName (objectName); if (inventoryObjectIndex > -1) { print ("Inventory info for the new object created " + objectName + " found"); mainInventoryListManager.createInventoryPrafab (objectInventoryCategoryIndex, inventoryObjectIndex); GameObject newObjectPrefab = mainInventoryListManager.getInventoryPrefabByName (objectName); if (newObjectPrefab != null) { armorClothPickup currentArmorClothPickup = newObjectPrefab.GetComponentInChildren<armorClothPickup> (); if (currentArmorClothPickup != null) { currentArmorClothPickup.categoryName = categoryName; } } } else { print ("Inventory info for the new object created " + objectName + " not found"); } print ("New Armor Cloth Piece " + objectName + " added to the inventory"); if (objectMeshCopy != null) { DestroyImmediate (objectMeshCopy); } } else { print ("Category " + inventoryObjectCategoryName + " not found in inventory list manager"); } } } #endif } public static void createInventoryObject (string objectName, string inventoryCategoryName, GameObject objectMesh, string objectDescription, Texture iconTexture, string relativePathMesh, bool canBeEquipped, bool canBeDropped, bool canBeDiscarded, bool useDurability, float durabilityAmount, float maxDurabilityAmount, bool isMeleeShield, bool canBePlaceOnQuickAccessSlot, float objectWeight, bool canBeSold, float sellPrice, float vendorPrice) { #if UNITY_EDITOR instantiateMainManagerOnSceneWithType ("Main Inventory Manager", typeof(inventoryListManager)); inventoryListManager mainInventoryListManager = FindObjectOfType<inventoryListManager> (); if (mainInventoryListManager != null) { bool pickupFound = false; GameObject pickupGameObject = mainInventoryListManager.getInventoryPrefabByName (objectName); pickupFound = pickupGameObject != null; if (pickupFound) { print ("Inventory object " + objectName + " already exists"); } else { int inventoryCategoryIndex = mainInventoryListManager.getInventoryCategoryIndexByName (inventoryCategoryName); if (inventoryCategoryIndex > -1) { print ("Category " + inventoryCategoryName + " found in inventory list manager"); GameObject objectMeshCopy = Instantiate (objectMesh); GameObject newObjectMesh = createPrefab (relativePathMesh, (objectName + " Mesh"), objectMeshCopy); newObjectMesh.AddComponent<BoxCollider> (); int newLayerIndex = LayerMask.NameToLayer ("inventory"); Component[] components = newObjectMesh.GetComponentsInChildren (typeof(Transform)); foreach (Transform child in components) { child.gameObject.layer = newLayerIndex; } print ("Created object mesh prefab " + newObjectMesh.name); inventoryInfo inventoryInfo = new inventoryInfo (); inventoryInfo.Name = objectName; inventoryInfo.objectInfo = objectDescription; inventoryInfo.inventoryGameObject = newObjectMesh; inventoryInfo.icon = iconTexture; inventoryInfo.canBeEquiped = canBeEquipped; inventoryInfo.canBeDropped = canBeDropped; inventoryInfo.canBeDiscarded = canBeDiscarded; inventoryInfo.canBeSold = canBeSold; inventoryInfo.sellPrice = sellPrice; inventoryInfo.vendorPrice = vendorPrice; inventoryInfo.isMeleeShield = isMeleeShield; inventoryInfo.canBePlaceOnQuickAccessSlot = canBePlaceOnQuickAccessSlot; inventoryInfo.weight = objectWeight; inventoryInfo.useDurability = useDurability; inventoryInfo.durabilityAmount = durabilityAmount; inventoryInfo.maxDurabilityAmount = maxDurabilityAmount; mainInventoryListManager.addNewInventoryObject (inventoryCategoryIndex, inventoryInfo); int inventoryObjectIndex = mainInventoryListManager.getInventoryInfoIndexByName (objectName); if (inventoryObjectIndex > -1) { print ("Inventory info for the new object created " + objectName + " found"); mainInventoryListManager.createInventoryPrafab (inventoryCategoryIndex, inventoryObjectIndex); } else { print ("Inventory info for the new object created " + objectName + " not found"); } print ("New Object " + objectName + " added to the inventory"); if (objectMeshCopy != null) { DestroyImmediate (objectMeshCopy); } } else { print ("Category " + inventoryCategoryName + " not found in inventory list manager"); } } } #endif } public static bool checkIfInventoryObjectNameExits (string objectName) { instantiateMainManagerOnSceneWithType ("Main Inventory Manager", typeof(inventoryListManager)); inventoryListManager mainInventoryListManager = FindObjectOfType<inventoryListManager> (); if (mainInventoryListManager != null) { return mainInventoryListManager.existInventoryInfoFromName (objectName); } return false; } public static float getMaxDurabilityValueOnObjectByName (string objectName) { inventoryListManager mainInventoryListManager = FindObjectOfType<inventoryListManager> (); if (mainInventoryListManager != null) { return mainInventoryListManager.getMaxDurabilityValueOnObjectByName (objectName); } return -1; } public static GameObject createPrefab (string prefabPath, string prefabName, GameObject prefabToCreate) { #if UNITY_EDITOR GameObject newPrefabGameObject = Instantiate (prefabToCreate); string relativePath = prefabPath; if (!Directory.Exists (relativePath)) { print ("Prefab folder " + relativePath + " doesn't exist, created a new one with that name"); Directory.CreateDirectory (relativePath); } string prefabFilePath = relativePath + "/" + prefabName + ".prefab"; bool prefabExists = false; if ((GameObject)AssetDatabase.LoadAssetAtPath (prefabFilePath, typeof(GameObject)) != null) { prefabExists = true; } if (prefabExists) { UnityEngine.Object prefab = (GameObject)AssetDatabase.LoadAssetAtPath (prefabFilePath, typeof(GameObject)); PrefabUtility.ReplacePrefab (newPrefabGameObject, prefab, ReplacePrefabOptions.ReplaceNameBased); print ("Prefab already existed. Replacing prefab in path " + prefabFilePath); } else { UnityEngine.Object prefab = PrefabUtility.CreateEmptyPrefab (prefabFilePath); PrefabUtility.ReplacePrefab (newPrefabGameObject, prefab, ReplacePrefabOptions.ConnectToPrefab); print ("Prefab to create is new. Creating new prefab in path " + prefabFilePath); } DestroyImmediate (newPrefabGameObject); return (GameObject)AssetDatabase.LoadAssetAtPath (prefabFilePath, typeof(GameObject)); #else return null; #endif } public static GameObject instantiatePrefabInScene (string prefabPath, string prefabName, LayerMask layerToPlaceObjects) { #if UNITY_EDITOR string relativePath = prefabPath; if (Directory.Exists (relativePath)) { string prefabFilePath = relativePath + "/" + prefabName + ".prefab"; bool prefabExists = false; if ((GameObject)AssetDatabase.LoadAssetAtPath (prefabFilePath, typeof(GameObject)) != null) { prefabExists = true; } if (prefabExists) { GameObject prefabToInstantiate = (GameObject)AssetDatabase.LoadAssetAtPath (prefabFilePath, typeof(GameObject)); if (prefabToInstantiate) { Vector3 positionToInstantiate = Vector3.zero; if (SceneView.lastActiveSceneView) { if (SceneView.lastActiveSceneView.camera) { Camera currentCameraEditor = SceneView.lastActiveSceneView.camera; Vector3 editorCameraPosition = currentCameraEditor.transform.position; Vector3 editorCameraForward = currentCameraEditor.transform.forward; RaycastHit hit; if (Physics.Raycast (editorCameraPosition, editorCameraForward, out hit, Mathf.Infinity, layerToPlaceObjects)) { positionToInstantiate = hit.point + 0.2f * Vector3.up; } } } GameObject newCreatedObject = (GameObject)Instantiate (prefabToInstantiate, positionToInstantiate, Quaternion.identity); newCreatedObject.name = prefabToInstantiate.name; print (prefabName + " prefab added to the scene"); return newCreatedObject; } else { print ("Prefab in path " + relativePath + " not found"); } } else { print ("Prefab in path " + relativePath + " not found"); } } return null; #else return null; #endif } public static void createSettingsListTemplate (string characterTemplateDataPath, string characterTemplateName, int characterTemplateID, List<buildPlayer.settingsInfoCategory> settingsInfoCategoryList) { #if UNITY_EDITOR if (!Directory.Exists (characterTemplateDataPath)) { print ("Character Template Data folder " + characterTemplateDataPath + " doesn't exist, created a new one with that name"); Directory.CreateDirectory (characterTemplateDataPath); } var obj = ScriptableObject.CreateInstance<characterSettingsTemplate> (); obj.characterTemplateID = characterTemplateID; List<buildPlayer.settingsInfoCategory> newSettingsInfoCategoryList = new List<buildPlayer.settingsInfoCategory> (); for (int i = 0; i < settingsInfoCategoryList.Count; i++) { buildPlayer.settingsInfoCategory currentSettingsInfoCategory = settingsInfoCategoryList [i]; buildPlayer.settingsInfoCategory newSettingsInfoCategory = new buildPlayer.settingsInfoCategory (); newSettingsInfoCategory.Name = currentSettingsInfoCategory.Name; for (int j = 0; j < currentSettingsInfoCategory.settingsInfoList.Count; j++) { buildPlayer.settingsInfo currentSettingsInfo = currentSettingsInfoCategory.settingsInfoList [j]; buildPlayer.settingsInfo newSettingsInfo = new buildPlayer.settingsInfo (); newSettingsInfo.Name = currentSettingsInfo.Name; newSettingsInfo.useBoolState = currentSettingsInfo.useBoolState; newSettingsInfo.boolState = currentSettingsInfo.boolState; newSettingsInfo.useFloatValue = currentSettingsInfo.useFloatValue; newSettingsInfo.floatValue = currentSettingsInfo.floatValue; newSettingsInfo.useStringValue = currentSettingsInfo.useStringValue; newSettingsInfo.stringValue = currentSettingsInfo.stringValue; newSettingsInfo.useRegularValue = currentSettingsInfo.useRegularValue; newSettingsInfo.regularValue = currentSettingsInfo.regularValue; newSettingsInfoCategory.settingsInfoList.Add (newSettingsInfo); } newSettingsInfoCategoryList.Add (newSettingsInfoCategory); } obj.settingsInfoCategoryList = newSettingsInfoCategoryList; string newPath = characterTemplateDataPath + "/" + characterTemplateName + ".asset"; UnityEditor.AssetDatabase.CreateAsset (obj, newPath); UnityEditor.AssetDatabase.SaveAssets (); refreshAssetDatabase (); #endif } public static GameObject findMainPlayerOnScene () { playerCharactersManager mainPlayerCharactersManager = FindObjectOfType<playerCharactersManager> (); if (mainPlayerCharactersManager != null) { return mainPlayerCharactersManager.getMainPlayerGameObject (); } return null; } public static Transform findMainPlayerTransformOnScene () { playerCharactersManager mainPlayerCharactersManager = FindObjectOfType<playerCharactersManager> (); if (mainPlayerCharactersManager != null) { return mainPlayerCharactersManager.getMainPlayerTransform (); } return null; } public static playerCamera findMainPlayerCameraOnScene () { playerCharactersManager mainPlayerCharactersManager = FindObjectOfType<playerCharactersManager> (); if (mainPlayerCharactersManager != null) { return mainPlayerCharactersManager.getMainPlayerCamera (); } return null; } public static Camera findMainPlayerCameraComponentOnScene () { playerCharactersManager mainPlayerCharactersManager = FindObjectOfType<playerCharactersManager> (); if (mainPlayerCharactersManager != null) { return mainPlayerCharactersManager.getMainPlayerCameraComponent (); } return null; } public static Transform findMainPlayerCameraTransformOnScene () { playerCharactersManager mainPlayerCharactersManager = FindObjectOfType<playerCharactersManager> (); if (mainPlayerCharactersManager != null) { return mainPlayerCharactersManager.getMainPlayerCameraTransform (); } return null; } public static void updateCanvasValuesByPlayer (GameObject playerControllerGameObject, GameObject pauseManagerObject, GameObject newCanvasPanel) { playerCharactersManager mainPlayerCharactersManager = FindObjectOfType<playerCharactersManager> (); if (mainPlayerCharactersManager != null) { mainPlayerCharactersManager.updateCanvasValuesByPlayer (playerControllerGameObject, pauseManagerObject, newCanvasPanel); } } public static void updateComponent (UnityEngine.Object componentToUpdate) { #if UNITY_EDITOR if (!Application.isPlaying) { if (componentToUpdate != null) { EditorUtility.SetDirty (componentToUpdate); } } #endif } public static void updateComponent (MonoBehaviour componentToUpdate) { #if UNITY_EDITOR if (!Application.isPlaying) { if (componentToUpdate != null) { EditorUtility.SetDirty (componentToUpdate); } } #endif } public static void setActiveGameObjectInEditor (GameObject objectToSelect) { #if UNITY_EDITOR if (objectToSelect == null) { return; } Selection.activeGameObject = objectToSelect; #endif } public static GameObject getActiveGameObjectInEditor () { #if UNITY_EDITOR return Selection.activeGameObject; #else return null; #endif } public static bool isCurrentSelectionActiveGameObject (GameObject objectToSelect) { #if UNITY_EDITOR return Selection.activeGameObject != objectToSelect; #else return false; #endif } public static Camera getCameraEditor () { #if UNITY_EDITOR if (SceneView.lastActiveSceneView) { if (SceneView.lastActiveSceneView.camera) { return SceneView.lastActiveSceneView.camera; } } #endif return null; } public static GameObject getLoadAssetAtPath (string objectPath) { #if UNITY_EDITOR GameObject newObject = (GameObject)AssetDatabase.LoadAssetAtPath (objectPath, typeof(GameObject)); return newObject; #else return null; #endif } public static void alignViewToObject (Transform transformToUse) { #if UNITY_EDITOR SceneView sceneView = SceneView.lastActiveSceneView; if (sceneView) { sceneView.AlignViewToObject (transformToUse); } #endif } public static bool isApplicationPlaying () { #if UNITY_EDITOR return Application.isPlaying; #else return true; #endif } public static void pauseOrResumeAIOnScene (bool state, int pauseCharacterPriority) { playerController[] playerControllerList = FindObjectsOfType<playerController> (); foreach (playerController currentPlayerController in playerControllerList) { if (currentPlayerController.usedByAI) { pauseOrResumeCharacter (state, currentPlayerController, pauseCharacterPriority); } } } public static void pauseOrResumeAIOnSceneWithExceptionList (bool state, int pauseCharacterPriority, List<GameObject> AIExceptionList) { playerController[] playerControllerList = FindObjectsOfType<playerController> (); foreach (playerController currentPlayerController in playerControllerList) { if (!AIExceptionList.Contains (currentPlayerController.gameObject)) { if (currentPlayerController.usedByAI) { pauseOrResumeCharacter (state, currentPlayerController, pauseCharacterPriority); } } } } public static void pauseOrResumeEnemyAIOnScene (bool state, string playerFactionName, int pauseCharacterPriority) { playerController[] playerControllerList = FindObjectsOfType<playerController> (); foreach (playerController currentPlayerController in playerControllerList) { if (currentPlayerController.usedByAI) { playerComponentsManager currentplayerComponentsManager = currentPlayerController.gameObject.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { characterFactionManager currentCharacterFactionManager = currentplayerComponentsManager.getCharacterFactionManager (); if (currentCharacterFactionManager != null) { if (currentCharacterFactionManager.isCharacterEnemy (playerFactionName)) { pauseOrResumeCharacter (state, currentPlayerController, pauseCharacterPriority); } } } } } } public static void pauseOrResumeCharacter (bool state, playerController currentPlayerController, int pauseCharacterPriority) { if (currentPlayerController.getPauseCharacterPriorityValue () > pauseCharacterPriority) { return; } if (state) { currentPlayerController.setPauseCharacterPriorityValue (pauseCharacterPriority); } else { currentPlayerController.setPauseCharacterPriorityValue (0); } currentPlayerController.setOverrideAnimationSpeedActiveState (state); if (state) { currentPlayerController.setReducedVelocity (0); } else { currentPlayerController.setNormalVelocity (); } currentPlayerController.setCanMoveAIState (!state); currentPlayerController.setAddExtraRotationPausedState (state); currentPlayerController.setIgnoreCameraDirectionOnStrafeMovementState (state); playerComponentsManager currentplayerComponentsManager = currentPlayerController.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { AINavMesh currentAINavMesh = currentPlayerController.GetComponent<AINavMesh> (); if (currentAINavMesh != null) { currentAINavMesh.pauseAI (state); if (!state) { findObjectivesSystem currentFindObjectivesSystem = currentPlayerController.GetComponent<findObjectivesSystem> (); if (currentFindObjectivesSystem != null) { currentFindObjectivesSystem.forceFovTriggerToDetectAnythingAround (); } } } } } public static void pauseOrResumeAllCharactersScene (bool state) { playerController[] playerControllerList = FindObjectsOfType<playerController> (); foreach (playerController currentPlayerController in playerControllerList) { currentPlayerController.setOverrideAnimationSpeedActiveState (state); if (state) { currentPlayerController.setReducedVelocity (0); } else { currentPlayerController.setNormalVelocity (); } currentPlayerController.setCanMoveAIState (!state); currentPlayerController.setIgnoreCameraDirectionOnStrafeMovementState (state); } } public static Vector3 ClampMagnitude (Vector3 v, float max, float min) { double sm = v.sqrMagnitude; if (sm > (double)max * (double)max) { return v.normalized * max; } else if (sm < (double)min * (double)min) { return v.normalized * min; } return v; } public static void setGravityValueOnObjectFromPlayerValues (artificialObjectGravity newArtificialObjectGravity, GameObject currentPlayer, float gravityForceForCircumnavigationOnProjectile) { gravitySystem currentGravitySystem = currentPlayer.GetComponent<gravitySystem> (); if (currentGravitySystem != null) { if (currentGravitySystem.isCurcumnavigating ()) { Transform currentSurfaceBelowPlayer = currentGravitySystem.getCurrentSurfaceBelowPlayer (); if (currentSurfaceBelowPlayer != null) { newArtificialObjectGravity.setUseCenterPointActiveState (true, currentSurfaceBelowPlayer); newArtificialObjectGravity.setGravityForceValue (false, gravityForceForCircumnavigationOnProjectile); } } } } public static void enableOrDisableFreeFloatingModeOnState (GameObject currentPlayer, bool state) { if (currentPlayer != null) { gravitySystem currentGravitySystem = currentPlayer.GetComponent<gravitySystem> (); if (currentGravitySystem != null) { currentGravitySystem.setfreeFloatingModeOnState (state); } } } public static weaponObjectInfo getMeleeWeaponObjectInfo (string weaponName, meleeWeaponsGrabbedManager mainMeleeWeaponsGrabbedManager) { return mainMeleeWeaponsGrabbedManager.getWeaponGrabbedByName (weaponName); } public static float Abs (float f) { return Math.Abs (f); } public static void addAllMainManagersToScene () { mainManagerAdministrator currentMainManagerAdministrator = FindObjectOfType<mainManagerAdministrator> (); if (currentMainManagerAdministrator != null) { currentMainManagerAdministrator.addAllMainManagersToScene (); } else { print ("No Main Manager Administrator located, make sure to drop the player prefab on the scene or create a new player character"); } } public static void instantiateMainManagerOnSceneWithType (string mainManagerName, Type typeToSearch) { mainManagerAdministrator currentMainManagerAdministrator = FindObjectOfType<mainManagerAdministrator> (); if (currentMainManagerAdministrator != null) { currentMainManagerAdministrator.addMainManagerToSceneWithType (mainManagerName, typeToSearch, false); } } public static void instantiateMainManagerOnSceneWithTypeOnApplicationPlaying (string mainManagerName, Type typeToSearch, bool callGetComponentInstance) { if (Application.isPlaying) { // print ("playing"); mainManagerAdministrator currentMainManagerAdministrator = mainManagerAdministrator.Instance; if (currentMainManagerAdministrator == null) { currentMainManagerAdministrator = FindObjectOfType<mainManagerAdministrator> (); // print ("administrator found"); } if (currentMainManagerAdministrator != null) { currentMainManagerAdministrator.addMainManagerToSceneWithType (mainManagerName, typeToSearch, callGetComponentInstance); } } else { // print ("not playing"); mainManagerAdministrator currentMainManagerAdministrator = FindObjectOfType<mainManagerAdministrator> (); if (currentMainManagerAdministrator != null) { currentMainManagerAdministrator.addMainManagerToSceneWithType (mainManagerName, typeToSearch, false); } } } public static void activateTimeBulletXSeconds (float timeBulletDuration, float timeScale) { timeBullet timeBulletManager = FindObjectOfType<timeBullet> (); if (timeBulletManager != null) { if (timeBulletDuration > 0) { timeBulletManager.activateTimeBulletXSeconds (timeBulletDuration, timeScale); } else { if (timeScale == 1) { timeBulletManager.setBulletTimeState (false, timeScale); } else { timeBulletManager.setBulletTimeState (true, timeScale); } } } } public static void loadScene (int newSceneIndex, bool useLoadScreen, int loadScreenScene, string sceneToLoadAsyncPrefsName, bool useLastSceneIndexAsLoadScreen, bool checkLoadingScreenSceneConfigured, string loadingScreenSceneName) { int sceneLoadIndex = newSceneIndex; if (useLoadScreen) { bool loadingScreenLocatedResult = true; if (useLastSceneIndexAsLoadScreen) { int lastSceneIndex = SceneManager.sceneCountInBuildSettings; sceneLoadIndex = lastSceneIndex - 1; if (sceneLoadIndex < 0) { sceneLoadIndex = -1; } } else { sceneLoadIndex = loadScreenScene; } if (checkLoadingScreenSceneConfigured) { string sceneNameToCheck = GKC_Utils.getSceneNameFromIndex (sceneLoadIndex); if (sceneNameToCheck != null && sceneNameToCheck != "") { if (!loadingScreenSceneName.Equals (sceneNameToCheck)) { sceneLoadIndex = newSceneIndex; loadingScreenLocatedResult = false; } } } if (loadingScreenLocatedResult) { PlayerPrefs.SetInt (sceneToLoadAsyncPrefsName, newSceneIndex); } } if (sceneLoadIndex >= 0) { SceneManager.LoadScene (sceneLoadIndex); } } public static void reloadSceneOnEditor () { #if UNITY_EDITOR EditorSceneManager.OpenScene (EditorSceneManager.GetActiveScene ().path); #endif } public static string getSceneNameFromIndex (int sceneIndex) { string currentSceneName = ""; string path = SceneUtility.GetScenePathByBuildIndex (sceneIndex); if (path != null && path != "") { int slash = path.LastIndexOf ('/'); string name = path.Substring (slash + 1); int dot = name.LastIndexOf ('.'); currentSceneName = name.Substring (0, dot); } return currentSceneName; } public static void updateDirtyScene (string recordObjectName, GameObject gameObjectToRecord) { #if UNITY_EDITOR if (!Application.isPlaying) { Undo.RecordObject (gameObjectToRecord, recordObjectName); EditorSceneManager.MarkSceneDirty (menuPause.getCurrentActiveScene ()); } #endif } public static void updateDirtyScene () { #if UNITY_EDITOR if (!Application.isPlaying) { EditorSceneManager.MarkSceneDirty (menuPause.getCurrentActiveScene ()); } #endif } public static void removeEnemiesFromNewFriendFaction (Transform characterTransform) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerController currentPlayerController = currentplayerComponentsManager.getPlayerController (); findObjectivesSystem currentFindObjectivesSystem = characterTransform.GetComponent<findObjectivesSystem> (); currentFindObjectivesSystem.clearFullEnemiesList (); currentFindObjectivesSystem.removeCharacterAsTargetOnSameFaction (); currentFindObjectivesSystem.resetAITargets (); currentPlayerController.setMainColliderState (false); currentPlayerController.setMainColliderState (true); } } public static void eventOnPressingKeyboardInput (int controllerNumber) { playerCharactersManager.checkPanelsActiveOnGamepadOrKeyboard (true, controllerNumber); } public static void eventOnPressingGamepadInput (int controllerNumber) { playerCharactersManager.checkPanelsActiveOnGamepadOrKeyboard (false, controllerNumber); } public static void enableOrDisableAbilityGroupByName (Transform characterTransform, bool state, List<string> abilityNameList) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerAbilitiesSystem currentPlayerAbilitiesSystem = currentplayerComponentsManager.getPlayerAbilitiesSystem (); if (currentPlayerAbilitiesSystem != null) { currentPlayerAbilitiesSystem.enableOrDisableAbilityGroupByName (abilityNameList, state); setUnlockStateOnSkillList (characterTransform, abilityNameList, state); } } } public static void increaseStatsByList (Transform characterTransform, bool state, List<objectExperienceSystem.statInfo> statInfoList) { playerComponentsManager currentPlayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentPlayerComponentsManager != null) { playerStatsSystem currentPlayerStatsSystem = currentPlayerComponentsManager.getPlayerStatsSystem (); if (currentPlayerStatsSystem != null) { for (int k = 0; k < statInfoList.Count; k++) { if (statInfoList [k].statIsAmount) { float extraValue = statInfoList [k].statExtraValue; if (statInfoList [k].useRandomRange) { extraValue = UnityEngine.Random.Range (statInfoList [k].randomRange.x, statInfoList [k].randomRange.y); extraValue = Mathf.RoundToInt (extraValue); } currentPlayerStatsSystem.increasePlayerStat (statInfoList [k].Name, extraValue); } else { currentPlayerStatsSystem.enableOrDisableBoolPlayerStat (statInfoList [k].Name, statInfoList [k].newBoolState); } } } } } public static void activateAbilityByName (Transform characterTransform, string abilityName, bool abilityIsTemporallyActivated) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerAbilitiesSystem currentPlayerAbilitiesSystem = currentplayerComponentsManager.getPlayerAbilitiesSystem (); if (currentPlayerAbilitiesSystem != null) { currentPlayerAbilitiesSystem.inputSelectAndPressDownNewAbilityTemporally (abilityName, abilityIsTemporallyActivated); } } } public static bool checkIfAbilitiesOnUseOrCooldown (Transform characterTransform, string abilityName) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerAbilitiesSystem currentPlayerAbilitiesSystem = currentplayerComponentsManager.getPlayerAbilitiesSystem (); if (currentPlayerAbilitiesSystem != null) { return currentPlayerAbilitiesSystem.checkIfAbilitiesOnUseOrCooldown (abilityName); } } return false; } public static void setUnlockStateOnSkill (Transform characterTransform, string skillName, bool state) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerSkillsSystem currentPlayerSkillsSystem = currentplayerComponentsManager.getPlayerSkillsSystem (); if (currentPlayerSkillsSystem != null) { if (state) { currentPlayerSkillsSystem.getSkillByName (skillName); } else { } } } } public static void setUnlockStateOnSkillList (Transform characterTransform, List<string> skillNameList, bool state) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerSkillsSystem currentPlayerSkillsSystem = currentplayerComponentsManager.getPlayerSkillsSystem (); if (currentPlayerSkillsSystem != null) { if (state) { for (int k = 0; k < skillNameList.Count; k++) { currentPlayerSkillsSystem.getSkillByName (skillNameList [k]); } } else { } } } } public static GameObject createSliceRagdollPrefab (GameObject characterMeshPrefab, string newPrefabsPath, Material newSliceMaterial, bool setTagOnSkeletonRigidbodiesValue, string tagOnSkeletonRigidbodiesValue) { GameObject newCharacterMeshForRagdollPrefab = (GameObject)Instantiate (characterMeshPrefab, Vector3.zero, Quaternion.identity); string prefabName = characterMeshPrefab.name + " Ragdoll (With Slice System)"; newCharacterMeshForRagdollPrefab.name = prefabName; surfaceToSlice currentSurfaceToSlice = newCharacterMeshForRagdollPrefab.GetComponent<surfaceToSlice> (); if (currentSurfaceToSlice == null) { genericRagdollBuilder currentGenericRagdollBuilder = newCharacterMeshForRagdollPrefab.GetComponent<genericRagdollBuilder> (); if (currentGenericRagdollBuilder == null) { ragdollBuilder currentRagdollBuilder = newCharacterMeshForRagdollPrefab.AddComponent<ragdollBuilder> (); Animator mainAnimator = newCharacterMeshForRagdollPrefab.GetComponent<Animator> (); currentRagdollBuilder.getAnimator (mainAnimator); currentRagdollBuilder.createRagdoll (); DestroyImmediate (currentRagdollBuilder); } currentSurfaceToSlice = newCharacterMeshForRagdollPrefab.AddComponent<surfaceToSlice> (); GameObject characterMesh = newCharacterMeshForRagdollPrefab; simpleSliceSystem currentSimpleSliceSystem = characterMesh.GetComponent<simpleSliceSystem> (); if (currentSimpleSliceSystem == null) { currentSimpleSliceSystem = characterMesh.AddComponent<simpleSliceSystem> (); } currentSimpleSliceSystem.searchBodyParts (); for (int i = 0; i < currentSimpleSliceSystem.severables.Length; i++) { //enable or disalbe colliders in the ragdoll if (currentSimpleSliceSystem.severables [i] != null) { Collider currentCollider = currentSimpleSliceSystem.severables [i].GetComponent<Collider> (); if (currentCollider != null) { currentCollider.enabled = true; } Rigidbody currentRigidbody = currentSimpleSliceSystem.severables [i].GetComponent<Rigidbody> (); if (currentRigidbody != null) { currentRigidbody.isKinematic = false; } } } currentSimpleSliceSystem.mainSurfaceToSlice = currentSurfaceToSlice; currentSimpleSliceSystem.objectToSlice = characterMesh; currentSimpleSliceSystem.alternatePrefab = newCharacterMeshForRagdollPrefab; currentSurfaceToSlice.setMainSimpleSliceSystem (currentSimpleSliceSystem.gameObject); currentSurfaceToSlice.objectIsCharacter = true; currentSimpleSliceSystem.objectToSlice = characterMesh; currentSimpleSliceSystem.infillMaterial = newSliceMaterial; if (setTagOnSkeletonRigidbodiesValue) { currentSimpleSliceSystem.setTagOnBodyParts (tagOnSkeletonRigidbodiesValue); } GKC_Utils.updateComponent (currentSimpleSliceSystem); GKC_Utils.updateDirtyScene ("Set slice system info", currentSimpleSliceSystem.gameObject); Debug.Log ("Ragdoll prefab created "); } else { Debug.Log ("Ragdoll was already configured for this prefab"); } GameObject newRagdollPrefab = GKC_Utils.createPrefab (newPrefabsPath, prefabName, newCharacterMeshForRagdollPrefab); GKC_Utils.updateDirtyScene ("Create Slice Ragdoll", newCharacterMeshForRagdollPrefab); DestroyImmediate (newCharacterMeshForRagdollPrefab); return newRagdollPrefab; } public static Transform getMountPointTransformByName (string mountPointName, Transform characterTransform) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { bodyMountPointsSystem currentBodyMountPointsSystem = currentplayerComponentsManager.getBodyMountPointsSystem (); if (currentBodyMountPointsSystem != null) { return currentBodyMountPointsSystem.getMountPointTransformByName (mountPointName); } } return null; } public static Transform getHumanoBoneMountPointTransformByName (string mountPointName, Transform characterTransform) { playerComponentsManager currentplayerComponentsManager = characterTransform.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { bodyMountPointsSystem currentBodyMountPointsSystem = currentplayerComponentsManager.getBodyMountPointsSystem (); if (currentBodyMountPointsSystem != null) { return currentBodyMountPointsSystem.getHumanoBoneMountPointTransformByName (mountPointName); } } return null; } public static void activateBrainWashOnCharacter (GameObject currentCharacter, string factionToConfigure, string newTag, bool setNewName, string newName, bool AIIsFriend, bool followPartnerOnTriggerEnabled, bool setPlayerAsPartner, GameObject newPartner, bool useRemoteEvents, List<string> remoteEventNameList) { if (currentCharacter == null) { return; } playerComponentsManager currentplayerComponentsManager = currentCharacter.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager == null) { return; } characterFactionManager currentCharacterFactionManager = currentplayerComponentsManager.getCharacterFactionManager (); if (currentCharacterFactionManager != null) { currentCharacterFactionManager.removeCharacterDeadFromFaction (); currentCharacterFactionManager.changeCharacterToFaction (factionToConfigure); currentCharacterFactionManager.addCharacterFromFaction (); currentCharacter.tag = newTag; playerController currentPlayerController = currentplayerComponentsManager.getPlayerController (); health currentHealth = currentplayerComponentsManager.getHealth (); if (setNewName) { if (AIIsFriend) { if (newName != "") { currentHealth.setAllyNewNameIngame (newName); } currentHealth.updateNameWithAlly (); } else { if (newName != "") { currentHealth.setEnemyNewNameIngame (newName); } currentHealth.updateNameWithEnemy (); } } AINavMesh currentAINavMesh = currentCharacter.GetComponent<AINavMesh> (); if (currentAINavMesh != null) { currentAINavMesh.pauseAI (true); currentAINavMesh.pauseAI (false); } findObjectivesSystem currentFindObjectivesSystem = currentCharacter.GetComponent<findObjectivesSystem> (); currentFindObjectivesSystem.clearFullEnemiesList (); currentFindObjectivesSystem.removeCharacterAsTargetOnSameFaction (); currentFindObjectivesSystem.resetAITargets (); currentFindObjectivesSystem.setFollowPartnerOnTriggerState (followPartnerOnTriggerEnabled); if (setPlayerAsPartner) { currentFindObjectivesSystem.addPlayerAsPartner (newPartner); } if (useRemoteEvents) { remoteEventSystem currentRemoteEventSystem = currentCharacter.GetComponent<remoteEventSystem> (); if (currentRemoteEventSystem != null) { int remoteEventNameListCount = remoteEventNameList.Count; for (int i = 0; i < remoteEventNameListCount; i++) { currentRemoteEventSystem.callRemoteEvent (remoteEventNameList [i]); } } } currentPlayerController.setMainColliderState (false); currentPlayerController.setMainColliderState (true); } } public static void activateRemoteEvent (string remoteEventName, GameObject objectToCheck) { remoteEventSystem currentRemoteEventSystem = objectToCheck.GetComponent<remoteEventSystem> (); if (currentRemoteEventSystem != null) { currentRemoteEventSystem.callRemoteEvent (remoteEventName); } } public static void activateRemoteEvents (List<string> remoteEventNameList, GameObject objectToCheck) { remoteEventSystem currentRemoteEventSystem = objectToCheck.GetComponent<remoteEventSystem> (); if (currentRemoteEventSystem != null) { int remoteEventNameListCount = remoteEventNameList.Count; for (int i = 0; i < remoteEventNameListCount; i++) { currentRemoteEventSystem.callRemoteEvent (remoteEventNameList [i]); } } } public static float getCharacterRadius (Transform characterToCheck) { if (characterToCheck != null) { playerController currentPlayerController = characterToCheck.GetComponent<playerController> (); if (currentPlayerController != null) { return currentPlayerController.getCharacterRadius (); } } return 0; } public static List<Collider> getCharacterExtraColliderList (Transform characterToCheck) { if (characterToCheck != null) { playerController currentPlayerController = characterToCheck.GetComponent<playerController> (); if (currentPlayerController != null) { return currentPlayerController.getExtraColliderList (); } } return null; } public static float getAngle (Vector3 v1, Vector3 v2) { return Mathf.Rad2Deg * Mathf.Asin (Vector3.Cross (v1.normalized, v2.normalized).magnitude); } public static string getCurrentLanguage () { gameLanguageSelector currentGameLanguageSelector = FindObjectOfType<gameLanguageSelector> (); if (currentGameLanguageSelector != null) { return currentGameLanguageSelector.getCurrentLanguage (); } return "English"; } public static void setCurrentLanguage (string newLanguage) { gameLanguageSelector currentGameLanguageSelector = FindObjectOfType<gameLanguageSelector> (); if (currentGameLanguageSelector != null) { currentGameLanguageSelector.setCurrentLanguage (newLanguage); } } public static bool isUpdateElementsOnLanguageChangeActive () { gameLanguageSelector currentGameLanguageSelector = FindObjectOfType<gameLanguageSelector> (); if (currentGameLanguageSelector != null) { return currentGameLanguageSelector.updateElementsOnLanguageChange; } return false; } public static void removeNullGameObjectsFromList (List<GameObject> listToCheck) { for (int i = listToCheck.Count - 1; i >= 0; i--) { if (listToCheck [i] == null) { listToCheck.RemoveAt (i); } } } public static List<string> getCurrentLanguageList () { gameLanguageSelector currentGameLanguageSelector = FindObjectOfType<gameLanguageSelector> (); if (currentGameLanguageSelector != null) { return currentGameLanguageSelector.getCurrentLanguageList (); } return null; } public static void addLanguage (string newName) { gameLanguageSelector currentGameLanguageSelector = FindObjectOfType<gameLanguageSelector> (); if (currentGameLanguageSelector != null) { currentGameLanguageSelector.addLanguage (newName); } } public static void removeLanguage (string newName) { gameLanguageSelector currentGameLanguageSelector = FindObjectOfType<gameLanguageSelector> (); if (currentGameLanguageSelector != null) { currentGameLanguageSelector.removeLanguage (newName); } } public static void refreshAssetDatabase () { #if UNITY_EDITOR UnityEditor.AssetDatabase.Refresh (); print ("Refreshing Asset Database"); #endif } public static List<T> FindObjectsOfTypeAll<T> () { List<T> results = new List<T> (); var s = SceneManager.GetActiveScene (); if (s.isLoaded) { var allGameObjects = s.GetRootGameObjects (); for (int j = 0; j < allGameObjects.Length; j++) { var go = allGameObjects [j]; results.AddRange (go.GetComponentsInChildren<T> (true)); } } return results; } public static List<T> FindObjectOfTypeAll<T> () { List<T> results = new List<T> (); var s = SceneManager.GetActiveScene (); if (s.isLoaded) { var allGameObjects = s.GetRootGameObjects (); for (int j = 0; j < allGameObjects.Length; j++) { var go = allGameObjects [j]; results.Add ((go.GetComponentInChildren<T> (true))); if (results [results.Count - 1] != null) { return results; } } } return results; } public static float getStateValueByName (string statNameToShow, GameObject playerGameobject) { if (playerGameobject == null) { return -1; } playerComponentsManager currentplayerComponentsManager = playerGameobject.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerStatsSystem currentPlayerStatsSystem = currentplayerComponentsManager.getPlayerStatsSystem (); if (currentPlayerStatsSystem != null) { return currentPlayerStatsSystem.getStatValue (statNameToShow); } } return -1; } public static float getInventoryObjectAmountByName (string objectNameToShow, GameObject playerGameobject) { if (playerGameobject == null) { return -1; } playerComponentsManager currentplayerComponentsManager = playerGameobject.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { inventoryManager currentInventoryManager = currentplayerComponentsManager.getInventoryManager (); if (currentInventoryManager != null) { return currentInventoryManager.getInventoryObjectAmountByName (objectNameToShow); } } return -1; } public static inventoryManager getInventoryManagerFromCharacter (GameObject playerGameobject) { if (playerGameobject == null) { return null; } playerComponentsManager currentplayerComponentsManager = playerGameobject.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { return currentplayerComponentsManager.getInventoryManager (); } return null; } public static GameObject spawnObjectFromPrefabsManager (string objectToSpawnName) { GKC_Utils.instantiateMainManagerOnSceneWithType ("Prefabs Manager", typeof(prefabsManager)); prefabsManager mainPrefabsManager = FindObjectOfType<prefabsManager> (); if (mainPrefabsManager != null) { return mainPrefabsManager.getPrefabGameObject (objectToSpawnName); } return null; } public static prefabsManager addPrefabsManagerToScene () { #if UNITY_EDITOR prefabsManager newPrefabsManager = FindObjectOfType<prefabsManager> (); if (newPrefabsManager == null) { string prefabsPath = pathInfoValues.getPrefabsManagerPrefabPath (); GameObject prefabsManagerPrefab = (GameObject)AssetDatabase.LoadAssetAtPath (prefabsPath, typeof(GameObject)); if (prefabsManagerPrefab != null) { GameObject newPrefabsManagerGameObject = (GameObject)Instantiate (prefabsManagerPrefab, Vector3.zero, Quaternion.identity); newPrefabsManagerGameObject.name = "Prefabs Manager"; newPrefabsManagerGameObject.transform.position = Vector3.zero; newPrefabsManagerGameObject.transform.rotation = Quaternion.identity; newPrefabsManager = newPrefabsManagerGameObject.GetComponent<prefabsManager> (); } } return newPrefabsManager; #else return null; #endif } public static void setSelectedGameObjectOnUI (bool ignoreCheckGamepad, bool isUsingGamepad, GameObject newGameObject, bool showDebugPrint) { EventSystem.current.SetSelectedGameObject (null); if (isUsingGamepad && !ignoreCheckGamepad) { if (newGameObject != null) { EventSystem.current.SetSelectedGameObject (newGameObject); if (showDebugPrint) { print ("enabling " + newGameObject.name); } } } if (showDebugPrint) { if (newGameObject != null) { print ("setting new UI element as selected " + newGameObject.name); } else { print ("removing UI element as selected"); } } } public static string getMainDataPath () { gameManager currentGameManager = FindObjectOfType<gameManager> (); if (currentGameManager != null) { return currentGameManager.getDataPath (); } return ""; } public static void addElementToPlayerScreenObjectivesManager (GameObject currentPlayer, GameObject placeToShoot, string locatedEnemyIconName) { if (currentPlayer == null) { return; } if (placeToShoot == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerScreenObjectivesSystem currentPlayerScreenObjectivesSystem = currentplayerComponentsManager.getPlayerScreenObjectivesSystem (); if (currentPlayerScreenObjectivesSystem != null) { currentPlayerScreenObjectivesSystem.addElementToPlayerList (placeToShoot, false, false, 0, true, false, false, false, locatedEnemyIconName, false, Color.white, true, -1, 0, false); } } } public static void removeElementToPlayerScreenObjectivesManager (GameObject currentPlayer, GameObject objectToRemove) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerScreenObjectivesSystem currentPlayerScreenObjectivesSystem = currentplayerComponentsManager.getPlayerScreenObjectivesSystem (); if (currentPlayerScreenObjectivesSystem != null) { currentPlayerScreenObjectivesSystem.removeElementFromListByPlayer (objectToRemove); } } } public static void removeElementListToPlayerScreenObjectivesManager (GameObject currentPlayer, List<Transform> objectToRemoveList) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { playerScreenObjectivesSystem currentPlayerScreenObjectivesSystem = currentplayerComponentsManager.getPlayerScreenObjectivesSystem (); if (currentPlayerScreenObjectivesSystem != null) { currentPlayerScreenObjectivesSystem.removeElementListFromListByPlayer (objectToRemoveList); } } } public static void removeTargetFromAIEnemyList (GameObject objectToRemove) { if (objectToRemove == null) { return; } playerController[] playerControllerList = FindObjectsOfType<playerController> (); foreach (playerController currentPlayerController in playerControllerList) { if (currentPlayerController.usedByAI) { playerComponentsManager currentplayerComponentsManager = currentPlayerController.gameObject.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { findObjectivesSystem currentFindObjectivesSystem = currentPlayerController.GetComponent<findObjectivesSystem> (); if (currentFindObjectivesSystem != null) { currentFindObjectivesSystem.setObjectOutOfRange (objectToRemove); } } } } } public static void setAICharacterOnVehicle (GameObject newVehicle, GameObject currentCharacter) { if (currentCharacter == null) { return; } playerComponentsManager currentplayerComponentsManager = currentCharacter.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { findObjectivesSystem currentFindObjectivesSystem = currentplayerComponentsManager.getFindObjectivesSystem (); if (currentFindObjectivesSystem != null) { currentFindObjectivesSystem.setAICharacterOnVehicle (newVehicle); } } } public static void getOffFromVehicleToDriverAI (Transform currentCharacter) { if (currentCharacter == null) { return; } playerComponentsManager currentplayerComponentsManager = currentCharacter.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { findObjectivesSystem currentFindObjectivesSystem = currentplayerComponentsManager.getFindObjectivesSystem (); if (currentFindObjectivesSystem != null) { currentFindObjectivesSystem.getOffFromVehicle (); } } } public static void createPieceMeshesObjectsFromSetByName (GameObject objectToCreate, string objectName) { if (objectToCreate == null) { return; } print (objectToCreate.name); GameObject objectToCreateClone = Instantiate (objectToCreate, objectToCreate.transform.position, objectToCreate.transform.rotation); objectToCreateClone.name = objectName; if (!objectToCreateClone.activeSelf) { objectToCreateClone.SetActive (true); } SkinnedMeshRenderer currentSkinnedMeshRenderer = objectToCreateClone.GetComponent<SkinnedMeshRenderer> (); if (currentSkinnedMeshRenderer == null) { return; } Mesh currentMesh = currentSkinnedMeshRenderer.sharedMesh; List<Material> materialList = new List<Material> (); int materialsLength = currentSkinnedMeshRenderer.sharedMaterials.Length; for (int j = 0; j < materialsLength; j++) { Material currentMaterial = currentSkinnedMeshRenderer.sharedMaterials [j]; if (currentMaterial != null) { print (currentMaterial.name); materialList.Add (new Material (currentMaterial)); } } MeshFilter currentMeshFilter = objectToCreateClone.AddComponent<MeshFilter> (); currentMeshFilter.mesh = currentMesh; MeshRenderer currentMeshRenderer = objectToCreateClone.AddComponent<MeshRenderer> (); currentMeshRenderer.sharedMaterials = new Material[materialList.Count]; materialsLength = materialList.Count; Material[] allMats = currentMeshRenderer.sharedMaterials; for (int j = 0; j < materialsLength; j++) { allMats [j] = materialList [j]; } currentMeshRenderer.sharedMaterials = allMats; if (currentSkinnedMeshRenderer != null) { DestroyImmediate (currentSkinnedMeshRenderer); } } public static void addNewBlueprintsUnlockedElement (GameObject currentPlayer, string newBlueprintsUnlockedElement) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { currentCraftingSystem.addNewBlueprintsUnlockedElement (newBlueprintsUnlockedElement); } } } public static void addNewBlueprintsUnlockedList (GameObject currentPlayer, List<string> craftingRecipesList) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { for (int j = 0; j < craftingRecipesList.Count; j++) { currentCraftingSystem.addNewBlueprintsUnlockedElement (craftingRecipesList [j]); } } } } public static void setBlueprintsUnlockedListValue (GameObject currentPlayer, List<string> craftingRecipesList) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { currentCraftingSystem.setBlueprintsUnlockedListValue (craftingRecipesList); } } } public static List<string> getBlueprintsUnlockedListValue (GameObject currentPlayer) { if (currentPlayer == null) { return null; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { return currentCraftingSystem.getBlueprintsUnlockedListValue (); } } return null; } public static bool isUseOnlyBlueprintsUnlockedActive (GameObject currentPlayer) { if (currentPlayer == null) { return false; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { return currentCraftingSystem.isUseOnlyBlueprintsUnlockedActive (); } } return false; } public static bool anyObjectToCraftInTimeActive (GameObject currentPlayer) { if (currentPlayer == null) { return false; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { return currentCraftingSystem.anyObjectToCraftInTimeActive (); } } return false; } public static void setUseOnlyBlueprintsUnlockedState (GameObject currentPlayer, bool state) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { currentCraftingSystem.setUseOnlyBlueprintsUnlockedState (state); } } } public static List<craftObjectInTimeSimpleInfo> getCraftObjectInTimeInfoList (GameObject currentPlayer) { if (currentPlayer == null) { return null; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { return currentCraftingSystem.getCraftObjectInTimeInfoList (); } } return null; } public static void setCraftObjectInTimeInfoList (GameObject currentPlayer, List<craftObjectInTimeSimpleInfo> newCraftObjectInTimeSimpleInfoList) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { currentCraftingSystem.setCraftObjectInTimeInfoList (newCraftObjectInTimeSimpleInfoList); } } } public static List<string> getObjectCategoriesToCraftAvailableAtAnyMomentValue (GameObject currentPlayer) { if (currentPlayer == null) { return null; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { return currentCraftingSystem.getObjectCategoriesToCraftAvailableAtAnyMomentValue (); } } return null; } public static void setObjectCategoriesToCraftAvailableAtAnyMomentValue (GameObject currentPlayer, List<string> newList) { if (currentPlayer == null) { return; } playerComponentsManager currentplayerComponentsManager = currentPlayer.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { craftingSystem currentCraftingSystem = currentplayerComponentsManager.getCraftingSystem (); if (currentCraftingSystem != null) { currentCraftingSystem.setObjectCategoriesToCraftAvailableAtAnyMomentValue (newList); } } } public static Vector3 getParableSpeed (Vector3 origin, Vector3 target, Vector3 cameraDirection, Transform cameraDirectoinTransform, bool objectiveFoundOnRaycast, bool useMaxDistanceWhenNoSurfaceFound, float maxDistanceWhenNoSurfaceFound) { //if a hit point is not found, return if (!objectiveFoundOnRaycast) { if (useMaxDistanceWhenNoSurfaceFound) { target = origin + maxDistanceWhenNoSurfaceFound * cameraDirection; } else { return -Vector3.one; } } //get the distance between positions Vector3 toTarget = target - origin; Vector3 toTargetXZ = toTarget; //remove the Y axis value toTargetXZ -= cameraDirectoinTransform.InverseTransformDirection (toTargetXZ).y * cameraDirectoinTransform.up; float y = cameraDirectoinTransform.InverseTransformDirection (toTarget).y; float xz = toTargetXZ.magnitude; //get the velocity according to distance ang gravity float t = GKC_Utils.distance (origin, target) / 20; float v0y = y / t + 0.5f * Physics.gravity.magnitude * t; float v0xz = xz / t; //create result vector for calculated starting speeds Vector3 result = toTargetXZ.normalized; //get direction of xz but with magnitude 1 result *= v0xz; // set magnitude of xz to v0xz (starting speed in xz plane), setting the local Y value result -= cameraDirectoinTransform.InverseTransformDirection (result).y * cameraDirectoinTransform.up; result += v0y * cameraDirectoinTransform.up; return result; } public static GameObject getHudElementParent (GameObject playerGameObject, string mainPanelName) { playerComponentsManager currentplayerComponentsManager = playerGameObject.GetComponent<playerComponentsManager> (); if (currentplayerComponentsManager != null) { showGameInfoHud currentShowGameInfoHud = currentplayerComponentsManager.getGameInfoHudManager (); if (currentShowGameInfoHud != null) { return currentShowGameInfoHud.getHudElementParent (mainPanelName); } } return null; } }
ed05ebc20f25285e3fcfab6289d3d7cb
{ "intermediate": 0.34681347012519836, "beginner": 0.3487759232521057, "expert": 0.3044106364250183 }
33,633
How do I enable private internet on android through adb? I know there's a 2 part shell command to set the DNS-over-TLS. What are the 2 commands? Please do not explain just want the 2 commands
f4d03c14464709f0da08c778892bdd47
{ "intermediate": 0.4677041172981262, "beginner": 0.26870253682136536, "expert": 0.26359331607818604 }
33,634
Hi, Can you please edit this unity script so that when grinding occurs the board is attached in the center almost magnetically so the character is the correct way up. Also Could you make it so that the player can activate the grind and have it follow on the direction the player started grinding at? unity 2020.6.f using UnityEngine; using System.Collections; using System.Collections.Generic; public class hoverBoardWayPoints : MonoBehaviour { public float movementSpeed; public bool moveInOneDirection; public float extraRotation; public float forceAtEnd; public float railsOffset; public float extraScale; public float triggerRadius; public string vehicleTag = "vehicle"; public bool modifyMovementSpeedEnabled = true; public float maxMovementSpeed = 2; public float minMovementSpeed = 0.1f; public float modifyMovementSpeed = 5; public List<wayPointsInfo> wayPoints = new List<wayPointsInfo> (); public bool inside; public bool showGizmo; public Color gizmoLabelColor = Color.black; public float gizmoRadius; public bool useHandleForVertex; public float handleRadius; public Color handleGizmoColor; public bool showVertexHandles; public GameObject wayPointElement; int i; Transform currentVehicleTransform; Transform currentvehicleCameraTransform; Coroutine movement; bool moving; vehicleHUDManager currentVehicleHUDManager; vehicleController currentVehicleController; vehicleCameraController currentVehicleCameraController; float currentVerticalDirection; float speedMultiplier = 1; float currentMovementSpeed; void OnTriggerEnter (Collider col) { if (col.gameObject.CompareTag (vehicleTag) && !inside) { currentVehicleController = col.gameObject.GetComponent<vehicleController> (); if (currentVehicleController != null) { if (currentVehicleController.canUseHoverboardWaypoints ()) { currentVehicleTransform = col.gameObject.transform; currentVehicleHUDManager = currentVehicleTransform.GetComponent<vehicleHUDManager> (); if (currentVehicleHUDManager.isVehicleBeingDriven ()) { bool canActivateWaypoint = true; float lastTimeReleasedFromWaypoint = currentVehicleController.getLastTimeReleasedFromWaypoint (); if (!currentVehicleController.isUsingHoverBoardWaypoint () && lastTimeReleasedFromWaypoint > 0 && Time.time < lastTimeReleasedFromWaypoint + 0.7f) { canActivateWaypoint = false; } if (canActivateWaypoint) { currentVehicleCameraController = currentVehicleHUDManager.getVehicleCameraController (); currentvehicleCameraTransform = currentVehicleCameraController.transform; pickOrReleaseVehicle (true, false); if (movement != null) { StopCoroutine (movement); } movement = StartCoroutine (moveThroughWayPoints ()); } } } } } } void OnTriggerExit (Collider col) { if (col.gameObject.CompareTag ("Player") && inside && !moving) { pickOrReleaseVehicle (false, false); } } public void pickOrReleaseVehicle (bool state, bool auto) { inside = state; currentVehicleController.enterOrExitFromWayPoint (inside); currentVehicleController.receiveWayPoints (this); currentVehicleCameraController.startOrStopFollowVehiclePosition (!inside); if (!inside) { if (movement != null) { StopCoroutine (movement); } if (auto) { Rigidbody mainRigidbody = currentVehicleCameraController.mainRigidbody; mainRigidbody.AddForce ((mainRigidbody.mass * forceAtEnd) * currentVehicleTransform.forward, ForceMode.Impulse); } currentVehicleTransform = null; currentvehicleCameraTransform = null; } } IEnumerator moveThroughWayPoints () { moving = true; float closestDistance = Mathf.Infinity; int index = -1; for (i = 0; i < wayPoints.Count; i++) { float currentDistance = GKC_Utils.distance (wayPoints [i].wayPoint.position, currentVehicleTransform.position); if (currentDistance < closestDistance) { closestDistance = currentDistance; index = i; } } Vector3 heading = currentVehicleTransform.position - wayPoints [index].wayPoint.position; float distance = heading.magnitude; Vector3 directionToPoint = heading / distance; // ("player: "+directionToPoint + "-direction: "+wayPoints [index].direction.forward); //check if the vectors point in the same direction or not float angle = Vector3.Dot (directionToPoint, wayPoints [index].direction.forward); //print (angle); // if (angle < 0) { // print ("different direction"); // } //if the vectors point in different directions, it means that the player is close to a waypoint in the opposite forward direction of the hoverboard waypoints, //so increase the index in 1 to move the player to the correct waypoint position, according to the forward direction used to the waypoints if (angle > 0) { //print ("same direcion"); index++; if (index > wayPoints.Count - 1) { if (movement != null) { StopCoroutine (movement); } } } List<Transform> currentPath = new List<Transform> (); for (i = index; i < wayPoints.Count; i++) { currentPath.Add (wayPoints [i].direction); } if (index - 1 >= 0) { index--; } else { index = 0; } Vector3 extraYRotation = wayPoints [index].direction.eulerAngles + extraRotation * currentVehicleTransform.up; Quaternion rot = Quaternion.Euler (extraYRotation); foreach (Transform transformPath in currentPath) { Vector3 pos = transformPath.transform.position; if (transformPath == currentPath [currentPath.Count - 1]) { pos += 2 * transformPath.forward; } while (GKC_Utils.distance (currentVehicleTransform.position, pos) > .01f) { if (modifyMovementSpeedEnabled) { currentVerticalDirection = currentVehicleController.getVerticalAxis (); if (currentVerticalDirection > 0) { speedMultiplier = Mathf.Lerp (speedMultiplier, maxMovementSpeed, Time.deltaTime * modifyMovementSpeed); } else if (currentVerticalDirection < 0) { speedMultiplier = Mathf.Lerp (speedMultiplier, minMovementSpeed, Time.deltaTime * modifyMovementSpeed); } else { speedMultiplier = Mathf.Lerp (speedMultiplier, 1, Time.deltaTime * modifyMovementSpeed); } } currentMovementSpeed = speedMultiplier * movementSpeed; currentVehicleTransform.position = Vector3.MoveTowards (currentVehicleTransform.position, pos, Time.deltaTime * currentMovementSpeed); currentVehicleTransform.rotation = Quaternion.Slerp (currentVehicleTransform.rotation, rot, Time.deltaTime * currentMovementSpeed); currentvehicleCameraTransform.position = Vector3.MoveTowards (currentvehicleCameraTransform.position, pos, Time.deltaTime * currentMovementSpeed); yield return null; } extraYRotation = transformPath.eulerAngles + extraRotation * currentVehicleTransform.up; rot = Quaternion.Euler (extraYRotation); } moving = false; pickOrReleaseVehicle (false, true); } public void addNewWayPoint () { Vector3 newPosition = transform.position; if (wayPoints.Count > 0) { newPosition = wayPoints [wayPoints.Count - 1].wayPoint.position + wayPoints [wayPoints.Count - 1].wayPoint.forward; } GameObject newWayPoint = (GameObject)Instantiate (wayPointElement, newPosition, Quaternion.identity); newWayPoint.transform.SetParent (transform); newWayPoint.name = (wayPoints.Count + 1).ToString ("000"); wayPointsInfo newWayPointInfo = new wayPointsInfo (); newWayPointInfo.Name = newWayPoint.name; newWayPointInfo.wayPoint = newWayPoint.transform; newWayPointInfo.direction = newWayPoint.transform.GetChild (0); newWayPointInfo.trigger = newWayPoint.GetComponentInChildren<CapsuleCollider> (); newWayPointInfo.railMesh = newWayPoint.GetComponentInChildren<MeshRenderer> ().gameObject; wayPoints.Add (newWayPointInfo); updateComponent (); } public void removeWaypoint (int index) { wayPointsInfo currentWaypointInfo = wayPoints [index]; DestroyImmediate (currentWaypointInfo.wayPoint); wayPoints.RemoveAt (index); updateComponent (); } public void addNewWayPointAtIndex (int index) { Vector3 newPosition = transform.position; if (wayPoints.Count > 0) { newPosition = wayPoints [index].wayPoint.position + wayPoints [index].wayPoint.forward; } GameObject newWayPoint = (GameObject)Instantiate (wayPointElement, newPosition, Quaternion.identity); newWayPoint.transform.SetParent (transform); newWayPoint.name = (index + 1).ToString ("000"); wayPointsInfo newWayPointInfo = new wayPointsInfo (); newWayPointInfo.Name = newWayPoint.name; newWayPointInfo.wayPoint = newWayPoint.transform; newWayPointInfo.direction = newWayPoint.transform.GetChild (0); newWayPointInfo.trigger = newWayPoint.GetComponentInChildren<CapsuleCollider> (); newWayPointInfo.railMesh = newWayPoint.GetComponentInChildren<MeshRenderer> ().gameObject; wayPoints.Insert (index, newWayPointInfo); renameAllWaypoints (); updateComponent (); } public void renameAllWaypoints () { for (int i = 0; i < wayPoints.Count; i++) { if (wayPoints [i].wayPoint != null) { wayPoints [i].Name = (i + 1).ToString (); wayPoints [i].wayPoint.name = (i + 1).ToString ("000"); wayPoints [i].wayPoint.SetSiblingIndex (i); } } updateComponent (); } public void updateComponent () { GKC_Utils.updateComponent (this); GKC_Utils.updateDirtyScene ("Update Hoverboard Waypoints Info", gameObject); } void OnDrawGizmos () { if (!showGizmo) { return; } if (GKC_Utils.isCurrentSelectionActiveGameObject (gameObject)) { DrawGizmos (); } } void OnDrawGizmosSelected () { DrawGizmos (); } //draw the pivot and the final positions of every door void DrawGizmos () { //&& !Application.isPlaying if (showGizmo) { for (i = 0; i < wayPoints.Count; i++) { if (wayPoints [i].wayPoint != null && wayPoints [i].direction != null) { Gizmos.color = Color.yellow; Gizmos.DrawSphere (wayPoints [i].wayPoint.position, gizmoRadius); if (i + 1 < wayPoints.Count) { Gizmos.color = Color.white; Gizmos.DrawLine (wayPoints [i].wayPoint.position, wayPoints [i + 1].wayPoint.position); wayPoints [i].direction.LookAt (wayPoints [i + 1].wayPoint.position); float scaleZ = GKC_Utils.distance (wayPoints [i].wayPoint.position, wayPoints [i + 1].wayPoint.position); wayPoints [i].direction.localScale = new Vector3 (1, 1, scaleZ + scaleZ * extraScale); Gizmos.color = Color.green; Gizmos.DrawLine (wayPoints [i].wayPoint.position, wayPoints [i].wayPoint.position + wayPoints [i].direction.forward); } if (i == wayPoints.Count - 1 && (i - 1) >= 0 && i != 0) { wayPoints [i].direction.rotation = Quaternion.LookRotation (wayPoints [i].wayPoint.position - wayPoints [i - 1].wayPoint.position); Gizmos.color = Color.green; Gizmos.DrawLine (wayPoints [i].direction.position, wayPoints [i].direction.position + wayPoints [i].direction.forward); } if (i == wayPoints.Count - 1) { wayPoints [i].direction.localScale = Vector3.one; } wayPoints [i].trigger.radius = triggerRadius; wayPoints [i].railMesh.transform.localPosition = new Vector3 (wayPoints [i].railMesh.transform.localPosition.x, railsOffset, wayPoints [i].railMesh.transform.localPosition.z); } } } } [System.Serializable] public class wayPointsInfo { public string Name; public Transform wayPoint; public Transform direction; public CapsuleCollider trigger; public GameObject railMesh; } }
02ccef8b5e2a193da45e156a64b85cb5
{ "intermediate": 0.367779403924942, "beginner": 0.41342082619667053, "expert": 0.21879982948303223 }
33,635
create ascript for acoverting landing page for belbet Онлайн-лотерея app in russian language that works on blogger
4251d8d50e64ebce592f96c8a0416fbb
{ "intermediate": 0.39881888031959534, "beginner": 0.23941083252429962, "expert": 0.36177027225494385 }
33,636
libadb.so: more than one device/emulator
d67224b65e060840dbf69575c91a4eb6
{ "intermediate": 0.5024913549423218, "beginner": 0.24380943179130554, "expert": 0.25369927287101746 }
33,637
give me code to create a program
aa7b9773d2a1377230a03599d41bb63e
{ "intermediate": 0.2845104932785034, "beginner": 0.3362829387187958, "expert": 0.3792065978050232 }
33,638
How to build a reward dapp using ReactJs
a2083de3c7ac4acc015d64aa6aeb5131
{ "intermediate": 0.37360185384750366, "beginner": 0.4064767062664032, "expert": 0.2199215143918991 }
33,639
Не работает скрипт на Lue (Riblox Studio) Должен показывать количество монет в табличке скрипт: local abbreviationslocal abbreviations = {"","T", "M", "МЛ", "TР", "КВА", "КВИ", "СЕК", "СЕП", "ОК", "НA", "ДЕ"} local function Format(value, idp) local ex = math.floor(math.log(math.max(1, math.abs(value)),1000)) local abbrevs = abbreviations [1 + ex] or ("e+"..ex) local normal = math.floor(value * ((10 * idp) / (1000 * ex))) / (10 * idp) return ("%."..idp.."f%s"):format(normal, abbrevs) end while wait() do local player = game.Players.LocalPlayer script.Parent.Text = Format( player.leaderstats.Cash .Value, 0) end
00d4be4f294499cb83315580aa8bf5de
{ "intermediate": 0.2781233787536621, "beginner": 0.4750986397266388, "expert": 0.24677804112434387 }
33,640
Добавь коменты в этот код :#include <windows.h> #include "MinHook/MinHook.h" #if _WIN64 #pragma comment(lib, "MinHook/libMinHook.x64.lib") #else #pragma comment(lib, "MinHook/libMinHook.x86.lib") #endif #include "../Anticheat_VERY_NICE_BLAT/imgui/imgui.h" #include "../Anticheat_VERY_NICE_BLAT/imgui/imgui_impl_win32.h" #include "../Anticheat_VERY_NICE_BLAT/imgui/imgui_impl_dx11.h" #include <d3d11.h> #pragma comment(lib, "d3d11.lib") HINSTANCE dll_handle; typedef long(__stdcall* present)(IDXGISwapChain*, UINT, UINT); present p_present; present p_present_target; bool get_present_pointer() { DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = GetForegroundWindow(); sd.SampleDesc.Count = 1; sd.Windowed = TRUE; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; IDXGISwapChain* swap_chain; ID3D11Device* device; const D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; if (D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, feature_levels, 2, D3D11_SDK_VERSION, &sd, &swap_chain, &device, nullptr, nullptr) == S_OK) { void** p_vtable = *reinterpret_cast<void***>(swap_chain); swap_chain->Release(); device->Release(); //context->Release(); p_present_target = (present)p_vtable[8]; return true; } return false; } WNDPROC oWndProc; extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT __stdcall WndProc(const HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (true && ImGui_ImplWin32_WndProcHandler(hWnd, uMsg, wParam, lParam)) return true; return CallWindowProc(oWndProc, hWnd, uMsg, wParam, lParam); } bool init = false; HWND window = NULL; ID3D11Device* p_device = NULL; ID3D11DeviceContext* p_context = NULL; ID3D11RenderTargetView* mainRenderTargetView = NULL; static long __stdcall detour_present(IDXGISwapChain* p_swap_chain, UINT sync_interval, UINT flags) { if (!init) { if (SUCCEEDED(p_swap_chain->GetDevice(__uuidof(ID3D11Device), (void**)&p_device))) { p_device->GetImmediateContext(&p_context); DXGI_SWAP_CHAIN_DESC sd; p_swap_chain->GetDesc(&sd); window = sd.OutputWindow; ID3D11Texture2D* pBackBuffer; p_swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); p_device->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView); pBackBuffer->Release(); oWndProc = (WNDPROC)SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)WndProc); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags = ImGuiConfigFlags_NoMouseCursorChange; ImGui_ImplWin32_Init(window); ImGui_ImplDX11_Init(p_device, p_context); init = true; } else return p_present(p_swap_chain, sync_interval, flags); } ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); ImGui::ShowDemoWindow(); ImGui::EndFrame(); ImGui::Render(); p_context->OMSetRenderTargets(1, &mainRenderTargetView, NULL); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); return p_present(p_swap_chain, sync_interval, flags); } DWORD __stdcall EjectThread(LPVOID lpParameter) { Sleep(100); FreeLibraryAndExitThread(dll_handle, 0); Sleep(100); return 0; } //"main" loop int WINAPI main() { if (!get_present_pointer()) { return 1; } MH_STATUS status = MH_Initialize(); if (status != MH_OK) { return 1; } if (MH_CreateHook(reinterpret_cast<void**>(p_present_target), &detour_present, reinterpret_cast<void**>(&p_present)) != MH_OK) { return 1; } if (MH_EnableHook(p_present_target) != MH_OK) { return 1; } while (true) { Sleep(50); if (GetAsyncKeyState(VK_NUMPAD0) & 1) { } if (GetAsyncKeyState(VK_NUMPAD1)) { break; } } //Cleanup if (MH_DisableHook(MH_ALL_HOOKS) != MH_OK) { return 1; } if (MH_Uninitialize() != MH_OK) { return 1; } ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); if (mainRenderTargetView) { mainRenderTargetView->Release(); mainRenderTargetView = NULL; } if (p_context) { p_context->Release(); p_context = NULL; } if (p_device) { p_device->Release(); p_device = NULL; } SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)(oWndProc)); CreateThread(0, 0, EjectThread, 0, 0, 0); return 0; } BOOL __stdcall DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { dll_handle = hModule; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)main, NULL, 0, NULL); } else if (dwReason == DLL_PROCESS_DETACH) { } return TRUE; }
23ee71934d5f7643ed7d528ab06c4e14
{ "intermediate": 0.3666311502456665, "beginner": 0.370138555765152, "expert": 0.2632303237915039 }
33,641
package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" "github.com/chromedp/chromedp" ) func main() { if len(os.Args) < 2 { fmt.Println("Usage: go run main.go <url>") return } url := os.Args[1] if err := playVideo(url); err != nil { log.Fatal("Error:", err) } } func playVideo(url string) error { ctx, cancel := chromedp.NewContext(context.Background()) defer cancel() ctx, cancel = context.WithTimeout(ctx, 5*time.Minute) defer cancel() options := []chromedp.ExecAllocatorOption{ chromedp.ExecPath("/data/data/com.termux/files/usr/bin/chromium-browser"), chromedp.Headless, chromedp.NoSandbox, chromedp.DisableGPU, chromedp.IgnoreCertificateErrors, } ctx, cancel = chromedp.NewExecAllocator(ctx, options...) defer cancel() ctx, cancel = chromedp.NewContext(ctx) defer cancel() var firstResult string if err := chromedp.Run(ctx, chromedp.Navigate(url), chromedp.WaitVisible(b.api-key-text), chromedp.Text(b.api-key-text, &firstResult), ); err != nil { return fmt.Errorf("error getting first result: %v", err) } currentURL := "" if err := chromedp.Run(ctx, chromedp.Location(&currentURL)); err != nil { return fmt.Errorf("error getting current URL: %v", err) } newURL := strings.Replace(currentURL, "UI/Dashboard", "api/v2.0/indexers?configured=true", 1) var responseBody []byte if err := chromedp.Run(ctx, chromedp.Navigate(newURL), chromedp.WaitVisible(body), chromedp.InnerHTML(body, &responseBody), ); err != nil { return fmt.Errorf("error getting response body: %v", err) } var response []map[string]interface{} if err := json.Unmarshal(responseBody, &response); err != nil { return fmt.Errorf("error unmarshalling JSON response: %v", err) } privateItems := make([]map[string]interface{}, 0) for _, item := range response { itemType := strings.ToLower(fmt.Sprintf("%v", item["type"])) configured := strings.ToLower(fmt.Sprintf("%v", item["configured"])) if strings.Contains(itemType, "private") && configured == "true" { privateItems = append(privateItems, item) } } if len(privateItems) == 0 { return nil } fmt.Printf("\nTorznab key: %s\n", firstResult) for _, item := range privateItems { id := fmt.Sprintf("%v", item["id"]) configURL := strings.Replace(currentURL, "UI/Dashboard", fmt.Sprintf("api/v2.0/indexers/%s/config", id), 1) configResponse, err := getConfigResponseWithCookies(configURL, ctx) if err != nil { fmt.Printf("##%s | %s | %v\n", id, configURL, err) continue } filteredElements := make([]string, 0) for _, element := range configResponse { elementType := fmt.Sprintf("%v", element["type"]) elementValue := fmt.Sprintf("%v", element["value"]) if elementType == "inputstring" && elementValue != "true" && elementValue != "false" { filteredElements = append(filteredElements, elementValue) } } groupedValues := strings.Join(filteredElements, " | ") prefixedGroupedValues := id + " | " + groupedValues fmt.Println(prefixedGroupedValues) } return nil } func getConfigResponseWithCookies(url string, ctx context.Context) ([]map[string]interface{}, error) { cookies, err := chromedp.Cookies(ctx) if err != nil { return nil, fmt.Errorf("error getting cookies: %v", err) } client := &http.Client{} req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, fmt.Errorf("error creating request: %v", err) } for _, cookie := range cookies { req.AddCookie(&http.Cookie{ Name: cookie.Name, Value: cookie.Value, }) } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() req = req.WithContext(ctx) resp, err := client.Do(req) if err != nil { return nil, fmt.Errorf("error sending request: %v", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("error reading response body: %v", err) } var response []map[string]interface{} if err := json.Unmarshal(body, &response); err != nil { return nil, fmt.Errorf("error unmarshalling JSON response: %v", err) } return response, nil }
1ea2179f8c2737dac828d8226ce6a502
{ "intermediate": 0.3261679410934448, "beginner": 0.42870065569877625, "expert": 0.24513140320777893 }
33,642
hey
69e12eeb5f8744ad637e84c3620c37fd
{ "intermediate": 0.33180856704711914, "beginner": 0.2916048467159271, "expert": 0.3765866458415985 }
33,643
Исправь ошибку Traceback (most recent call last): File "C:\Users\Admin\PycharmProjects\pythonProject15\main.py", line 70, in <module> if name =='main': NameError: name 'name' is not defined в коде if name =='main': main_loop()
9c4f1e83a71bdabd04d4ac056f532af8
{ "intermediate": 0.3029527962207794, "beginner": 0.5374210476875305, "expert": 0.15962618589401245 }
33,644
Максимально сожми этот код : #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "MinHook/MinHook.h" #if _WIN64 #pragma comment(lib, "MinHook/libMinHook.x64.lib") #else #pragma comment(lib, "MinHook/libMinHook.x86.lib") #endif #include "ImGui/imgui.h" #include "ImGui/imgui_impl_win32.h" #include "ImGui/imgui_impl_dx11.h" #include <d3d11.h> #pragma comment(lib, "d3d11.lib") // Globals HINSTANCE dll_handle; typedef long(__stdcall* present)(IDXGISwapChain*, UINT, UINT); present p_present; present p_present_target; bool get_present_pointer() { DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = GetForegroundWindow(); sd.SampleDesc.Count = 1; sd.Windowed = TRUE; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; IDXGISwapChain* swap_chain; ID3D11Device* device; const D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; if (D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, feature_levels, 2, D3D11_SDK_VERSION, &sd, &swap_chain, &device, nullptr, nullptr) == S_OK) { void** p_vtable = *reinterpret_cast<void***>(swap_chain); swap_chain->Release(); device->Release(); //context->Release(); p_present_target = (present)p_vtable[8]; return true; } return false; } WNDPROC oWndProc; extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT __stdcall WndProc(const HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (true && ImGui_ImplWin32_WndProcHandler(hWnd, uMsg, wParam, lParam)) return true; return CallWindowProc(oWndProc, hWnd, uMsg, wParam, lParam); } bool init = false; HWND window = NULL; ID3D11Device* p_device = NULL; ID3D11DeviceContext* p_context = NULL; ID3D11RenderTargetView* mainRenderTargetView = NULL; static long __stdcall detour_present(IDXGISwapChain* p_swap_chain, UINT sync_interval, UINT flags) { if (!init) { if (SUCCEEDED(p_swap_chain->GetDevice(__uuidof(ID3D11Device), (void**)&p_device))) { p_device->GetImmediateContext(&p_context); DXGI_SWAP_CHAIN_DESC sd; p_swap_chain->GetDesc(&sd); window = sd.OutputWindow; ID3D11Texture2D* pBackBuffer; p_swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); p_device->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView); pBackBuffer->Release(); oWndProc = (WNDPROC)SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)WndProc); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags = ImGuiConfigFlags_NoMouseCursorChange; ImGui_ImplWin32_Init(window); ImGui_ImplDX11_Init(p_device, p_context); init = true; } else return p_present(p_swap_chain, sync_interval, flags); } ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); ImGui::ShowDemoWindow(); ImGui::EndFrame(); ImGui::Render(); p_context->OMSetRenderTargets(1, &mainRenderTargetView, NULL); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); return p_present(p_swap_chain, sync_interval, flags); } DWORD __stdcall EjectThread(LPVOID lpParameter) { Sleep(100); FreeLibraryAndExitThread(dll_handle, 0); Sleep(100); return 0; } //"main" loop int WINAPI main() { if (!get_present_pointer()) { return 1; } MH_STATUS status = MH_Initialize(); if (status != MH_OK) { return 1; } if (MH_CreateHook(reinterpret_cast<void**>(p_present_target), &detour_present, reinterpret_cast<void**>(&p_present)) != MH_OK) { return 1; } if (MH_EnableHook(p_present_target) != MH_OK) { return 1; } while (true) { Sleep(50); if (GetAsyncKeyState(VK_NUMPAD0) & 1) { } if (GetAsyncKeyState(VK_NUMPAD1)) { break; } } //Cleanup if (MH_DisableHook(MH_ALL_HOOKS) != MH_OK) { return 1; } if (MH_Uninitialize() != MH_OK) { return 1; } ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); if (mainRenderTargetView) { mainRenderTargetView->Release(); mainRenderTargetView = NULL; } if (p_context) { p_context->Release(); p_context = NULL; } if (p_device) { p_device->Release(); p_device = NULL; } SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)(oWndProc)); CreateThread(0, 0, EjectThread, 0, 0, 0); return 0; } BOOL __stdcall DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { dll_handle = hModule; CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)main, NULL, 0, NULL); } else if (dwReason == DLL_PROCESS_DETACH) { } return TRUE; }
d472aadf168dabfe2911503f137907bb
{ "intermediate": 0.4363636076450348, "beginner": 0.3553493022918701, "expert": 0.2082870751619339 }
33,645
улучши код : #define WIN32_LEAN_AND_MEAN #include <windows.h> #include “MinHook/MinHook.h” #include “ImGui/imgui.h” #include “ImGui/imgui_impl_win32.h” #include “ImGui/imgui_impl_dx11.h” #include <d3d11.h> HINSTANCE dll_handle; typedef long(__stdcall* present)(IDXGISwapChain*, UINT, UINT); present p_present; present p_present_target; bool get_present_pointer() { DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = GetForegroundWindow(); sd.SampleDesc.Count = 1; sd.Windowed = TRUE; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; IDXGISwapChain* swap_chain; ID3D11Device* device; const D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0 }; if (D3D11CreateDeviceAndSwapChain( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, feature_levels, 2, D3D11_SDK_VERSION, &sd, &swap_chain, &device, nullptr, nullptr) == S_OK) { void** p_vtable = reinterpret_cast<void**>(swap_chain); swap_chain->Release(); device->Release(); p_present_target = (present)p_vtable[8]; return true; } return false; } WNDPROC oWndProc; extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT __stdcall WndProc(const HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, uMsg, wParam, lParam)) return true; return CallWindowProc(oWndProc, hWnd, uMsg, wParam, lParam); } bool init = false; HWND window = NULL; ID3D11Device* p_device = NULL; ID3D11DeviceContext* p_context = NULL; ID3D11RenderTargetView* mainRenderTargetView = NULL; static long __stdcall detour_present(IDXGISwapChain* p_swap_chain, UINT sync_interval, UINT flags) { if (!init) { if (SUCCEEDED(p_swap_chain->GetDevice(__uuidof(ID3D11Device), (void**)&p_device))) { p_device->GetImmediateContext(&p_context); DXGI_SWAP_CHAIN_DESC sd; p_swap_chain->GetDesc(&sd); window = sd.OutputWindow; ID3D11Texture2D* pBackBuffer; p_swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); p_device->CreateRenderTargetView(pBackBuffer, NULL, &mainRenderTargetView); pBackBuffer->Release(); oWndProc = (WNDPROC)SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)WndProc); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags = ImGuiConfigFlags_NoMouseCursorChange; ImGui_ImplWin32_Init(window); ImGui_ImplDX11_Init(p_device, p_context); init = true; } } ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); ImGui::ShowDemoWindow(); ImGui::EndFrame(); ImGui::Render(); p_context->OMSetRenderTargets(1, &mainRenderTargetView, NULL); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); return p_present(p_swap_chain, sync_interval, flags); } DWORD __stdcall EjectThread(LPVOID lpParameter) { Sleep(100); FreeLibraryAndExitThread(dll_handle, 0); Sleep(100); return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { if (!get_present_pointer()) { return 1; } if (MH_Initialize() != MH_OK) { return 1; } if (MH_CreateHook(reinterpret_cast<void**>(p_present_target), &detour_present, reinterpret_cast<void**>(&p_present)) != MH_OK) { return 1; } if (MH_EnableHook(p_present_target) != MH_OK) { return 1; } while (true) { Sleep(50); if (GetAsyncKeyState(VK_NUMPAD1)) { break; } } if (MH_DisableHook(MH_ALL_HOOKS) != MH_OK) { return 1; } if (MH_Uninitialize() != MH_OK) { return 1; } ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); if (mainRenderTargetView) { mainRenderTargetView->Release(); mainRenderTargetView = NULL; } if (p_context) { p_context->Release(); p_context = NULL; } if (p_device) { p_device->Release(); p_device = NULL; } SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)(oWndProc)); CreateThread(0, 0, EjectThread, 0, 0, 0); return 0; }
42bc022dc078438e26b54e31852e0568
{ "intermediate": 0.3507382273674011, "beginner": 0.3950165808200836, "expert": 0.25424522161483765 }
33,646
Hi, please convert this nodejs script to golang script which uses go-rod which is equivalent to puppeteer-core: const puppeteer = require('puppeteer-core'); const request = require('request'); const url = process.argv[2]; playVideo(url).catch(error => { console.error('Error:', error); }); async function playVideo(url) { const browser = await puppeteer.launch({ executablePath: './chrome-linux/chrome', headless: true, args: [ '--no-sandbox', '--disable-gpu', '--ignore-certificate-errors', ], }); const page = await browser.newPage(); const retryErrorConfigUrls = []; try { // Step 1: Get firstResult before loading newUrl let firstResult = 'Null'; await page.goto(url, { timeout: 60000, waitUntil: 'networkidle0', }); const firstElement = await page.$('b.api-key-text'); if (firstElement) { firstResult = await page.evaluate(element => element.textContent, firstElement); } // Step 2: Get the current page URL const currentUrl = page.url(); // Step 3: Create a new URL by replacing 'UI/Dashboard' with 'api/v2.0/indexers?configured=true' const newUrl = currentUrl.replace('UI/Dashboard', 'api/v2.0/indexers?configured=true'); // Step 4: Load the new URL and get its response as pretty JSON await page.goto(newUrl, { timeout: 60000, waitUntil: 'networkidle0', }); // Step 5: Get cookies from the page const cookies = await page.cookies(); const response = await page.evaluate(() => { return JSON.parse(document.body.innerText); }); // Step 6: Filter the array to keep only elements where the value of the 'type' key contains 'private' and 'configured' is true (case-insensitive) const privateItems = response.filter(item => { const isPrivate = item.type.toLowerCase().includes('private'); const isConfigured = String(item.configured).toLowerCase() === 'true'; return isPrivate && isConfigured; }); if (privateItems.length > 0) { console.log(`\nTorznab key: ${firstResult}\n`); // Print the Torznab key only if privateItems is not zero } else { process.exit(0); // Exit the script with zero exit code as there are no private items to process } // Step 7: Modify each element to keep only the 'id' and construct the 'config_url' const finalResult = privateItems.map(item => { const { id } = item; const config_url = currentUrl.replace('UI/Dashboard', `api/v2.0/indexers/${id}/config`); return { id, config_url }; }); // Step 8: Process each config_url using request module with cookies and timeout for (const item of finalResult) { try { const configResponse = await getConfigResponseWithCookies(item.config_url, cookies); // Step 9: Parsing and filtering the response const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = item.id + ' | ' + groupedValues; console.log(prefixedGroupedValues); } catch (error) { console.log(`##${item.id} | ${item.config_url} | ${error.message}`); // Print errored URLs to stdout retryErrorConfigUrls.push(item.config_url); } } // Step 10: Retry error config_urls with increasing timeout let retryTimeout = 3000; // Initial retry timeout is 15 seconds while (retryErrorConfigUrls.length > 0 && retryTimeout <= 30000) { const retryResults = []; for (const configUrl of retryErrorConfigUrls) { try { const configResponse = await getConfigResponseWithCookies(configUrl, cookies, retryTimeout); retryResults.push({ configUrl, response: configResponse }); } catch (error) { console.log(`##Retry ${retryTimeout}ms | ${configUrl}|${error.message}`); // Print errored URLs to stdout } } // Remove successfully processed config_urls from retryErrorConfigUrls retryErrorConfigUrls.length = 0; for (const retryResult of retryResults) { const configUrl = retryResult.configUrl; const configResponse = retryResult.response; if (!configResponse.error) { // Step 11: Parsing and filtering the response (same as in Step 9) const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = configUrl + ' | ' + groupedValues; console.log(prefixedGroupedValues); } else { // Config url still encounters an error, add it back to retryErrorConfigUrls retryErrorConfigUrls.push(configUrl); } } retryTimeout *= 2; // Double the retry timeout for the next retry } } catch (error) { console.error('Error:', error); } finally { await browser.close(); } process.exit(0); // Exit the script with zero exit code after completing the process } function getConfigResponseWithCookies(url, cookies, timeout = 10000) { return new Promise((resolve, reject) => { const requestTimeout = setTimeout(() => { reject(new Error('HTTP request timeout')); }, timeout); request( { url, headers: { Cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; '), }, }, (error, response, body) => { clearTimeout(requestTimeout); // Clear the request timeout when the request is completed if (error) { reject(error); } else { resolve(JSON.parse(body)); } } ); }); }
beac14ef1632970e56ccd075030201b8
{ "intermediate": 0.33009445667266846, "beginner": 0.4175342619419098, "expert": 0.25237131118774414 }
33,647
const puppeteer = require('puppeteer-core'); const request = require('request'); const url = process.argv[2]; playVideo(url).catch(error => { console.error('Error:', error); }); async function playVideo(url) { const browser = await puppeteer.launch({ executablePath: './chrome-linux/chrome', headless: true, args: [ '--no-sandbox', '--disable-gpu', '--ignore-certificate-errors', ], }); const page = await browser.newPage(); const retryErrorConfigUrls = []; try { // Step 1: Get firstResult before loading newUrl let firstResult = 'Null'; await page.goto(url, { timeout: 60000, waitUntil: 'networkidle0', }); const firstElement = await page.$('b.api-key-text'); if (firstElement) { firstResult = await page.evaluate(element => element.textContent, firstElement); } // Step 2: Get the current page URL const currentUrl = page.url(); // Step 3: Create a new URL by replacing 'UI/Dashboard' with 'api/v2.0/indexers?configured=true' const newUrl = currentUrl.replace('UI/Dashboard', 'api/v2.0/indexers?configured=true'); // Step 4: Load the new URL and get its response as pretty JSON await page.goto(newUrl, { timeout: 60000, waitUntil: 'networkidle0', }); // Step 5: Get cookies from the page const cookies = await page.cookies(); const response = await page.evaluate(() => { return JSON.parse(document.body.innerText); }); // Step 6: Filter the array to keep only elements where the value of the 'type' key contains 'private' and 'configured' is true (case-insensitive) const privateItems = response.filter(item => { const isPrivate = item.type.toLowerCase().includes('private'); const isConfigured = String(item.configured).toLowerCase() === 'true'; return isPrivate && isConfigured; }); if (privateItems.length > 0) { console.log(`\nTorznab key: ${firstResult}\n`); // Print the Torznab key only if privateItems is not zero } else { process.exit(0); // Exit the script with zero exit code as there are no private items to process } // Step 7: Modify each element to keep only the 'id' and construct the 'config_url' const finalResult = privateItems.map(item => { const { id } = item; const config_url = currentUrl.replace('UI/Dashboard', `api/v2.0/indexers/${id}/config`); return { id, config_url }; }); // Step 8: Process each config_url using request module with cookies and timeout for (const item of finalResult) { try { const configResponse = await getConfigResponseWithCookies(item.config_url, cookies); // Step 9: Parsing and filtering the response const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = item.id + ' | ' + groupedValues; console.log(prefixedGroupedValues); } catch (error) { console.log(`##${item.id} | ${item.config_url} | ${error.message}`); // Print errored URLs to stdout retryErrorConfigUrls.push(item.config_url); } } // Step 10: Retry error config_urls with increasing timeout let retryTimeout = 3000; // Initial retry timeout is 15 seconds while (retryErrorConfigUrls.length > 0 && retryTimeout <= 30000) { const retryResults = []; for (const configUrl of retryErrorConfigUrls) { try { const configResponse = await getConfigResponseWithCookies(configUrl, cookies, retryTimeout); retryResults.push({ configUrl, response: configResponse }); } catch (error) { console.log(`##Retry ${retryTimeout}ms | ${configUrl}|${error.message}`); // Print errored URLs to stdout } } // Remove successfully processed config_urls from retryErrorConfigUrls retryErrorConfigUrls.length = 0; for (const retryResult of retryResults) { const configUrl = retryResult.configUrl; const configResponse = retryResult.response; if (!configResponse.error) { // Step 11: Parsing and filtering the response (same as in Step 9) const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = configUrl + ' | ' + groupedValues; console.log(prefixedGroupedValues); } else { // Config url still encounters an error, add it back to retryErrorConfigUrls retryErrorConfigUrls.push(configUrl); } } retryTimeout *= 2; // Double the retry timeout for the next retry } } catch (error) { console.error('Error:', error); } finally { await browser.close(); } process.exit(0); // Exit the script with zero exit code after completing the process } function getConfigResponseWithCookies(url, cookies, timeout = 10000) { return new Promise((resolve, reject) => { const requestTimeout = setTimeout(() => { reject(new Error('HTTP request timeout')); }, timeout); request( { url, headers: { Cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; '), }, }, (error, response, body) => { clearTimeout(requestTimeout); // Clear the request timeout when the request is completed if (error) { reject(error); } else { resolve(JSON.parse(body)); } } ); }); } Convert to golang based script which uses go-rod which is equivalent to puppeteer-core
91345a88bc0f5822e10bc22ab49b7b89
{ "intermediate": 0.29771605134010315, "beginner": 0.48795077204704285, "expert": 0.21433314681053162 }
33,648
const puppeteer = require('puppeteer-core'); const request = require('request'); const url = process.argv[2]; playVideo(url).catch(error => { console.error('Error:', error); }); async function playVideo(url) { const browser = await puppeteer.launch({ executablePath: './chrome-linux/chrome', headless: true, args: [ '--no-sandbox', '--disable-gpu', '--ignore-certificate-errors', ], }); const page = await browser.newPage(); const retryErrorConfigUrls = []; try { // Step 1: Get firstResult before loading newUrl let firstResult = 'Null'; await page.goto(url, { timeout: 60000, waitUntil: 'networkidle0', }); const firstElement = await page.$('b.api-key-text'); if (firstElement) { firstResult = await page.evaluate(element => element.textContent, firstElement); } // Step 2: Get the current page URL const currentUrl = page.url(); // Step 3: Create a new URL by replacing 'UI/Dashboard' with 'api/v2.0/indexers?configured=true' const newUrl = currentUrl.replace('UI/Dashboard', 'api/v2.0/indexers?configured=true'); // Step 4: Load the new URL and get its response as pretty JSON await page.goto(newUrl, { timeout: 60000, waitUntil: 'networkidle0', }); // Step 5: Get cookies from the page const cookies = await page.cookies(); const response = await page.evaluate(() => { return JSON.parse(document.body.innerText); }); // Step 6: Filter the array to keep only elements where the value of the 'type' key contains 'private' and 'configured' is true (case-insensitive) const privateItems = response.filter(item => { const isPrivate = item.type.toLowerCase().includes('private'); const isConfigured = String(item.configured).toLowerCase() === 'true'; return isPrivate && isConfigured; }); if (privateItems.length > 0) { console.log(`\nTorznab key: ${firstResult}\n`); // Print the Torznab key only if privateItems is not zero } else { process.exit(0); // Exit the script with zero exit code as there are no private items to process } // Step 7: Modify each element to keep only the 'id' and construct the 'config_url' const finalResult = privateItems.map(item => { const { id } = item; const config_url = currentUrl.replace('UI/Dashboard', `api/v2.0/indexers/${id}/config`); return { id, config_url }; }); // Step 8: Process each config_url using request module with cookies and timeout for (const item of finalResult) { try { const configResponse = await getConfigResponseWithCookies(item.config_url, cookies); // Step 9: Parsing and filtering the response const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = item.id + ' | ' + groupedValues; console.log(prefixedGroupedValues); } catch (error) { console.log(`##${item.id} | ${item.config_url} | ${error.message}`); // Print errored URLs to stdout retryErrorConfigUrls.push(item.config_url); } } // Step 10: Retry error config_urls with increasing timeout let retryTimeout = 3000; // Initial retry timeout is 15 seconds while (retryErrorConfigUrls.length > 0 && retryTimeout <= 30000) { const retryResults = []; for (const configUrl of retryErrorConfigUrls) { try { const configResponse = await getConfigResponseWithCookies(configUrl, cookies, retryTimeout); retryResults.push({ configUrl, response: configResponse }); } catch (error) { console.log(`##Retry ${retryTimeout}ms | ${configUrl}|${error.message}`); // Print errored URLs to stdout } } // Remove successfully processed config_urls from retryErrorConfigUrls retryErrorConfigUrls.length = 0; for (const retryResult of retryResults) { const configUrl = retryResult.configUrl; const configResponse = retryResult.response; if (!configResponse.error) { // Step 11: Parsing and filtering the response (same as in Step 9) const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = configUrl + ' | ' + groupedValues; console.log(prefixedGroupedValues); } else { // Config url still encounters an error, add it back to retryErrorConfigUrls retryErrorConfigUrls.push(configUrl); } } retryTimeout *= 2; // Double the retry timeout for the next retry } } catch (error) { console.error('Error:', error); } finally { await browser.close(); } process.exit(0); // Exit the script with zero exit code after completing the process } function getConfigResponseWithCookies(url, cookies, timeout = 10000) { return new Promise((resolve, reject) => { const requestTimeout = setTimeout(() => { reject(new Error('HTTP request timeout')); }, timeout); request( { url, headers: { Cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; '), }, }, (error, response, body) => { clearTimeout(requestTimeout); // Clear the request timeout when the request is completed if (error) { reject(error); } else { resolve(JSON.parse(body)); } } ); }); } Convert to golang based script which uses go-rod which is equivalent to puppeteer-core
4f126e8f0f82028e04ba439597ee7ea4
{ "intermediate": 0.29771605134010315, "beginner": 0.48795077204704285, "expert": 0.21433314681053162 }
33,649
const puppeteer = require('puppeteer-core'); const request = require('request'); const url = process.argv[2]; playVideo(url).catch(error => { console.error('Error:', error); }); async function playVideo(url) { const browser = await puppeteer.launch({ executablePath: './chrome-linux/chrome', headless: true, args: [ '--no-sandbox', '--disable-gpu', '--ignore-certificate-errors', ], }); const page = await browser.newPage(); const retryErrorConfigUrls = []; try { // Step 1: Get firstResult before loading newUrl let firstResult = 'Null'; await page.goto(url, { timeout: 60000, waitUntil: 'networkidle0', }); const firstElement = await page.$('b.api-key-text'); if (firstElement) { firstResult = await page.evaluate(element => element.textContent, firstElement); } // Step 2: Get the current page URL const currentUrl = page.url(); // Step 3: Create a new URL by replacing 'UI/Dashboard' with 'api/v2.0/indexers?configured=true' const newUrl = currentUrl.replace('UI/Dashboard', 'api/v2.0/indexers?configured=true'); // Step 4: Load the new URL and get its response as pretty JSON await page.goto(newUrl, { timeout: 60000, waitUntil: 'networkidle0', }); // Step 5: Get cookies from the page const cookies = await page.cookies(); const response = await page.evaluate(() => { return JSON.parse(document.body.innerText); }); // Step 6: Filter the array to keep only elements where the value of the 'type' key contains 'private' and 'configured' is true (case-insensitive) const privateItems = response.filter(item => { const isPrivate = item.type.toLowerCase().includes('private'); const isConfigured = String(item.configured).toLowerCase() === 'true'; return isPrivate && isConfigured; }); if (privateItems.length > 0) { console.log(`\nTorznab key: ${firstResult}\n`); // Print the Torznab key only if privateItems is not zero } else { process.exit(0); // Exit the script with zero exit code as there are no private items to process } // Step 7: Modify each element to keep only the 'id' and construct the 'config_url' const finalResult = privateItems.map(item => { const { id } = item; const config_url = currentUrl.replace('UI/Dashboard', `api/v2.0/indexers/${id}/config`); return { id, config_url }; }); // Step 8: Process each config_url using request module with cookies and timeout for (const item of finalResult) { try { const configResponse = await getConfigResponseWithCookies(item.config_url, cookies); // Step 9: Parsing and filtering the response const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = item.id + ' | ' + groupedValues; console.log(prefixedGroupedValues); } catch (error) { console.log(`##${item.id} | ${item.config_url} | ${error.message}`); // Print errored URLs to stdout retryErrorConfigUrls.push(item.config_url); } } // Step 10: Retry error config_urls with increasing timeout let retryTimeout = 3000; // Initial retry timeout is 15 seconds while (retryErrorConfigUrls.length > 0 && retryTimeout <= 30000) { const retryResults = []; for (const configUrl of retryErrorConfigUrls) { try { const configResponse = await getConfigResponseWithCookies(configUrl, cookies, retryTimeout); retryResults.push({ configUrl, response: configResponse }); } catch (error) { console.log(`##Retry ${retryTimeout}ms | ${configUrl}|${error.message}`); // Print errored URLs to stdout } } // Remove successfully processed config_urls from retryErrorConfigUrls retryErrorConfigUrls.length = 0; for (const retryResult of retryResults) { const configUrl = retryResult.configUrl; const configResponse = retryResult.response; if (!configResponse.error) { // Step 11: Parsing and filtering the response (same as in Step 9) const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = configUrl + ' | ' + groupedValues; console.log(prefixedGroupedValues); } else { // Config url still encounters an error, add it back to retryErrorConfigUrls retryErrorConfigUrls.push(configUrl); } } retryTimeout *= 2; // Double the retry timeout for the next retry } } catch (error) { console.error('Error:', error); } finally { await browser.close(); } process.exit(0); // Exit the script with zero exit code after completing the process } function getConfigResponseWithCookies(url, cookies, timeout = 10000) { return new Promise((resolve, reject) => { const requestTimeout = setTimeout(() => { reject(new Error('HTTP request timeout')); }, timeout); request( { url, headers: { Cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; '), }, }, (error, response, body) => { clearTimeout(requestTimeout); // Clear the request timeout when the request is completed if (error) { reject(error); } else { resolve(JSON.parse(body)); } } ); }); } Convert to golang based script which uses go-rod which is equivalent to puppeteer-core
3e4d454458c0044e6140cfb8c386caf5
{ "intermediate": 0.29771605134010315, "beginner": 0.48795077204704285, "expert": 0.21433314681053162 }
33,650
Write me extension.ts for vs code, which will consist of extension.ts and package.json files. In extension.ts write the following functionality: I want there to be a google window in vs code
5290262dd80b20aa7b8dcd8d5720e679
{ "intermediate": 0.4412364959716797, "beginner": 0.2425915151834488, "expert": 0.3161720037460327 }
33,651
# <<< CornerDetector >>> RANDOM_ANSWER = np.array([[1, 2], [3, 4], [6, 9]]) COEFFS_KERNEL = np.array( [[1, 1, 1, 1, 1], [1, 5, 5, 5, 1], [1, 5, 0, 5, 1], [1, 5, 5, 5, 1], [1, 1, 1, 1, 1]] ) # noise 0.0-0.2 POTENTIAL_POINTS_NUM_0_2 = 200 ITERATIONS_NUM_0_2 = 1000 IMAGE_THRESHOLD_0_2 = 0 THRESHOLD_DISTANCE_0_2 = 1 THRESHOLD_K_0_2 = 0.5 THRESHOLD_B_0_2 = 20 NOISE_LESS_0_2 = 100 KERNEL_SIZE_0_2 = 3 # noise 0.3-0.5 POTENTIAL_POINTS_NUM_3_5 = 200 ITERATIONS_NUM_3_5 = 1000 IMAGE_THRESHOLD_3_5 = 100 THRESHOLD_DISTANCE_3_5 = 1 THRESHOLD_K_3_5 = 0.5 THRESHOLD_B_3_5 = 20 NOISE_LESS_3_5 = 75 KERNEL_SIZE_3_5 = 3 # <<< TimerService >>> TIME_MAX = 1.95 class TimeService: """Service for time management.""" def __init__(self, time_max: float): self.time_max = time_max self.start_time = None def start_timer(self) -> None: """Start time point. Sets 'self.start_time'.""" self.start_time = time.time() def check_timer(self): """Checks if time more than 'self.time_max'.""" end_time = time.time() delta_time = end_time - self.start_time if delta_time > self.time_max: return False return delta_time class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, ): self.__potential_points_num = None self.__iterations_num = None self.__image_threshold = None self.__threshold_k = None self.__threshold_b = None self.__threshold_distance = None self.__need_coeffs_kernel = None self.__image = None self.__kernel_size = 3 self.__time_service = TimeService(TIME_MAX) self.__need_time_check = False self.random_answer = RANDOM_ANSWER def __get_coords_by_threshold( self, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(self.__image > self.__image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.__image.shape[0] - offset: continue if y < 0 + offset or y > self.__image.shape[1] - offset: continue kernel = self.__image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums def __get_neigh_coeffs_list( self, coords: tuple, kernel: np.array ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's coeffs. """ neigh_coeffs = [] offset = (kernel.shape[0] - 1) // 2 print(offset) for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.__image.shape[0] - offset: continue if y < 0 + offset or y > self.__image.shape[1] - offset: continue try: image_kernel = self.__image[x - offset:x + offset + 1, y - offset:y + offset + 1] step_neigh_coeff = np.sum(kernel * image_kernel) neigh_coeffs.append([x, y, step_neigh_coeff]) except ValueError as e: continue return neigh_coeffs @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def __get_potential_points_coords( self, sorted_neigh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_neigh_nums, 2, axis=1) return sorted_neigh_nums[:self.__potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.__iterations_num): if not self.__time_service.check_timer(): return self.random_answer sample_indices = np.random.choice( remaining_points.shape[0], size=3, replace=False) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.__threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.__threshold_k and diff_b <= self.__threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners( self, image: np.ndarray, ) -> np.ndarray: """Finding triangle corners on image process.""" self.__time_service.start_timer() self.__image = image coords = self.__get_coords_by_threshold() if self.__need_coeffs_kernel: neigh_nums = self.__get_neigh_coeffs_list(coords, COEFFS_KERNEL) else: neigh_nums = self.__get_neigh_nums_list(coords, self.__kernel_size) sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) potential_points = self.__get_potential_points_coords(sorted_neigh_nums) best_lines = self.__get_best_lines(potential_points) intersection_points = np.array([ np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])), np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])), np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]])) ], dtype=np.float32) return intersection_points def set_potential_points_num(self, potential_points_num: int) -> None: """Potential points numbers setter.""" self.__potential_points_num = potential_points_num def set_iterations_num(self, iterations_num: int) -> None: """Iteration numbers setter.""" self.__iterations_num = iterations_num def set_image_threshold(self, image_threshold: int) -> None: """Image threshold setter.""" self.__image_threshold = image_threshold def set_threshold_k(self, threshold_k: float) -> None: """Threshold of k parameter setter.""" self.__threshold_k = threshold_k def set_threshold_b(self, threshold_b: int) -> None: """Threshold of b parameter setter.""" self.__threshold_b = threshold_b def set_threshold_distance(self, threshold_distance: int) -> None: """Threshold of distance area parameter setter.""" self.__threshold_distance = threshold_distance def set_need_time_check(self, need_time_check: bool = True): """If you need time checking var setter.""" self.__need_time_check = need_time_check def set_need_coeffs_kernel(self, need_coeffs_kernel: bool = True): """If you need coeffs kernel, not just neighbors var setter.""" self.__need_coeffs_kernel = need_coeffs_kernel def set_kernel_size(self, kernel_size: int) -> None: """Kernel size setter.""" self.__kernel_size = kernel_size # noise 0.6 POTENTIAL_POINTS_NUM_6 = 1200 ITERATIONS_NUM_6 = 1500 IMAGE_THRESHOLD_6 = 170 THRESHOLD_DISTANCE_6 = 3 THRESHOLD_K_6 = 0.5 THRESHOLD_B_6 = 500 NOISE_LESS_6 = 45 KERNEL_SIZE_6 = 11 image = cv2.imread("0.6/00.pgm", cv2.COLOR_BGR2GRAY) solver = Solver() solver.solve(image) Визуализируй потенциальные точки и прямые, которые получились на изображении
923fda615de67fd2fbdeb930a9677c4c
{ "intermediate": 0.2749686539173126, "beginner": 0.5155635476112366, "expert": 0.20946770906448364 }
33,652
This error:ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index System.ThrowHelper.ThrowArgumentOutOfRangeException (System.ExceptionArgument argument, System.ExceptionResource resource) (at <eae584ce26bc40229c1b1aa476bfa589>:0) System.ThrowHelper.ThrowArgumentOutOfRangeException () (at <eae584ce26bc40229c1b1aa476bfa589>:0) hoverBoardWayPoints.OnTriggerEnter (UnityEngine.Collider col) (at Assets/Game Kit Controller/Scripts/Vehicles/hoverBoardWayPoints.cs:103) This script:using UnityEngine; using System.Collections; using System.Collections.Generic; public class hoverBoardWayPoints : MonoBehaviour { public float movementSpeed; public bool moveInOneDirection; public float extraRotation; public float forceAtEnd; public float railsOffset; public float extraScale; public float triggerRadius; public string vehicleTag = "vehicle"; public bool modifyMovementSpeedEnabled = true; public float maxMovementSpeed = 2; public float minMovementSpeed = 0.1f; public float modifyMovementSpeed = 5; public List<wayPointsInfo> wayPoints = new List<wayPointsInfo>(); public bool inside; public bool showGizmo; public Color gizmoLabelColor = Color.black; public float gizmoRadius; public bool useHandleForVertex; public float handleRadius; public Color handleGizmoColor; public bool showVertexHandles; public GameObject wayPointElement; int i; Transform currentVehicleTransform; Transform currentvehicleCameraTransform; Coroutine movement; bool moving; vehicleHUDManager currentVehicleHUDManager; vehicleController currentVehicleController; vehicleCameraController currentVehicleCameraController; float currentVerticalDirection; float speedMultiplier = 1; float currentMovementSpeed; void OnTriggerEnter(Collider col) { if (col.gameObject.CompareTag(vehicleTag) && !inside) { currentVehicleController = col.gameObject.GetComponent<vehicleController>(); if (currentVehicleController != null) { if (currentVehicleController.canUseHoverboardWaypoints()) { currentVehicleTransform = col.gameObject.transform; currentVehicleHUDManager = currentVehicleTransform.GetComponent<vehicleHUDManager>(); if (currentVehicleHUDManager.isVehicleBeingDriven()) { bool canActivateWaypoint = true; float lastTimeReleasedFromWaypoint = currentVehicleController.getLastTimeReleasedFromWaypoint(); if (!currentVehicleController.isUsingHoverBoardWaypoint() && lastTimeReleasedFromWaypoint > 0 && Time.time < lastTimeReleasedFromWaypoint + 0.7f) { canActivateWaypoint = false; } if (canActivateWaypoint) { currentVehicleCameraController = currentVehicleHUDManager.getVehicleCameraController(); currentvehicleCameraTransform = currentVehicleCameraController.transform; pickOrReleaseVehicle(true, false); if (movement != null) { StopCoroutine(movement); } int initialIndex = Mathf.Clamp(i, 0, wayPoints.Count - 1); int direction = Vector3.Dot(currentVehicleTransform.forward, wayPoints[initialIndex].direction.forward) > 0 ? 1 : -1; movement = StartCoroutine(moveThroughWayPoints(direction)); } } } } } } void OnTriggerExit(Collider col) { if (col.gameObject.CompareTag("Player") && inside && !moving) { pickOrReleaseVehicle(false, false); } } public void pickOrReleaseVehicle(bool state, bool auto) { inside = state; currentVehicleController.enterOrExitFromWayPoint(inside); currentVehicleController.receiveWayPoints(this); currentVehicleCameraController.startOrStopFollowVehiclePosition(!inside); if (!inside) { if (movement != null) { StopCoroutine(movement); } if (auto) { Rigidbody mainRigidbody = currentVehicleCameraController.mainRigidbody; mainRigidbody.AddForce((mainRigidbody.mass * forceAtEnd) * currentVehicleTransform.forward, ForceMode.Impulse); } currentVehicleTransform = null; currentvehicleCameraTransform = null; } } IEnumerator moveThroughWayPoints(int direction) { moving = true; float closestDistance = Mathf.Infinity; int index = -1; for (i = 0; i < wayPoints.Count; i++) { float currentDistance = Vector3.Distance(wayPoints[i].wayPoint.position, currentVehicleTransform.position); if (currentDistance < closestDistance) { closestDistance = currentDistance; index = i; } } if (index >= 0 && index < wayPoints.Count) { Vector3 heading = currentVehicleTransform.position - wayPoints[index].wayPoint.position; float distance = heading.magnitude; Vector3 directionToPoint = heading / distance; float angle = Vector3.Dot(directionToPoint, wayPoints[index].direction.forward); if (angle > 0) { index += direction; if (index < 0 || index >= wayPoints.Count) { if (movement != null) { StopCoroutine(movement); } moving = false; yield break; } } List<Transform> currentPath = new List<Transform>(); for (i = index; i >= 0 && i < wayPoints.Count; i += direction) { currentPath.Add(wayPoints[i].direction); } if (index - 1 >= 0) { index--; } else { index = 0; } Vector3 extraYRotation = wayPoints[index].direction.eulerAngles + extraRotation * currentVehicleTransform.up; Quaternion rot = Quaternion.Euler(extraYRotation); foreach (Transform transformPath in currentPath) { Vector3 pos = transformPath.transform.position; if (transformPath == currentPath[currentPath.Count - 1]) { pos += 2 * transformPath.forward; } while (Vector3.Distance(currentVehicleTransform.position, pos) > .01f) { if (modifyMovementSpeedEnabled) { currentVerticalDirection = currentVehicleController.getVerticalAxis(); if (currentVerticalDirection > 0) { speedMultiplier = Mathf.Lerp(speedMultiplier, maxMovementSpeed, Time.deltaTime * modifyMovementSpeed); } else if (currentVerticalDirection < 0) { speedMultiplier = Mathf.Lerp(speedMultiplier, minMovementSpeed, Time.deltaTime * modifyMovementSpeed); } else { speedMultiplier = Mathf.Lerp(speedMultiplier, 1, Time.deltaTime * modifyMovementSpeed); } } currentMovementSpeed = speedMultiplier * movementSpeed; currentVehicleTransform.position = Vector3.MoveTowards(currentVehicleTransform.position, pos, Time.deltaTime * currentMovementSpeed); currentVehicleTransform.rotation = Quaternion.Slerp(currentVehicleTransform.rotation, rot, Time.deltaTime * currentMovementSpeed); currentvehicleCameraTransform.position = Vector3.MoveTowards(currentvehicleCameraTransform.position, pos, Time.deltaTime * currentMovementSpeed); yield return null; } extraYRotation = transformPath.eulerAngles + extraRotation * currentVehicleTransform.up; rot = Quaternion.Euler(extraYRotation); } } moving = false; pickOrReleaseVehicle(false, true); } public void addNewWayPoint() { Vector3 newPosition = transform.position; if (wayPoints.Count > 0) { newPosition = wayPoints[wayPoints.Count - 1].wayPoint.position + wayPoints[wayPoints.Count - 1].wayPoint.forward; } GameObject newWayPoint = (GameObject)Instantiate(wayPointElement, newPosition, Quaternion.identity); newWayPoint.transform.SetParent(transform); newWayPoint.name = (wayPoints.Count + 1).ToString("000"); wayPointsInfo newWayPointInfo = new wayPointsInfo(); newWayPointInfo.Name = newWayPoint.name; newWayPointInfo.wayPoint = newWayPoint.transform; newWayPointInfo.direction = newWayPoint.transform.GetChild(0); newWayPointInfo.trigger = newWayPoint.GetComponentInChildren<CapsuleCollider>(); newWayPointInfo.railMesh = newWayPoint.GetComponentInChildren<MeshRenderer>().gameObject; wayPoints.Add(newWayPointInfo); updateComponent(); } public void removeWaypoint(int index) { wayPointsInfo currentWaypointInfo = wayPoints[index]; DestroyImmediate(currentWaypointInfo.wayPoint); wayPoints.RemoveAt(index); updateComponent(); } public void addNewWayPointAtIndex(int index) { Vector3 newPosition = transform.position; if (wayPoints.Count > 0) { newPosition = wayPoints[index].wayPoint.position + wayPoints[index].wayPoint.forward; } GameObject newWayPoint = (GameObject)Instantiate(wayPointElement, newPosition, Quaternion.identity); newWayPoint.transform.SetParent(transform); newWayPoint.name = (index + 1).ToString("000"); wayPointsInfo newWayPointInfo = new wayPointsInfo(); newWayPointInfo.Name = newWayPoint.name; newWayPointInfo.wayPoint = newWayPoint.transform; newWayPointInfo.direction = newWayPoint.transform.GetChild(0); newWayPointInfo.trigger = newWayPoint.GetComponentInChildren<CapsuleCollider>(); newWayPointInfo.railMesh = newWayPoint.GetComponentInChildren<MeshRenderer>().gameObject; wayPoints.Insert(index, newWayPointInfo); renameAllWaypoints(); updateComponent(); } public void renameAllWaypoints() { for (int i = 0; i < wayPoints.Count; i++) { if (wayPoints[i].wayPoint != null) { wayPoints[i].Name = (i + 1).ToString(); wayPoints[i].wayPoint.name = (i + 1).ToString("000"); wayPoints[i].wayPoint.SetSiblingIndex(i); } } updateComponent(); } public void updateComponent() { GKC_Utils.updateComponent(this); GKC_Utils.updateDirtyScene("Update Hoverboard Waypoints Info", gameObject); } void OnDrawGizmos() { if (!showGizmo) { return; } if (GKC_Utils.isCurrentSelectionActiveGameObject(gameObject)) { DrawGizmos(); } } void OnDrawGizmosSelected() { DrawGizmos(); } void DrawGizmos() { if (showGizmo) { for (i = 0; i < wayPoints.Count; i++) { if (wayPoints[i].wayPoint != null && wayPoints[i].direction != null) { Gizmos.color = Color.yellow; Gizmos.DrawSphere(wayPoints[i].wayPoint.position, gizmoRadius); if (i + 1 < wayPoints.Count) { Gizmos.color = Color.white; Gizmos.DrawLine(wayPoints[i].wayPoint.position, wayPoints[i + 1].wayPoint.position); wayPoints[i].direction.LookAt(wayPoints[i + 1].wayPoint.position); float scaleZ = Vector3.Distance(wayPoints[i].wayPoint.position, wayPoints[i + 1].wayPoint.position); wayPoints[i].direction.localScale = new Vector3(1, 1, scaleZ + scaleZ * extraScale); Gizmos.color = Color.green; Gizmos.DrawLine(wayPoints[i].wayPoint.position, wayPoints[i].wayPoint.position + wayPoints[i].direction.forward); } if (i == wayPoints.Count - 1 && (i - 1) >= 0 && i != 0) { wayPoints[i].direction.rotation = Quaternion.LookRotation(wayPoints[i].wayPoint.position - wayPoints[i - 1].wayPoint.position); Gizmos.color = Color.green; Gizmos.DrawLine(wayPoints[i].direction.position, wayPoints[i].direction.position + wayPoints[i].direction.forward); } if (i == wayPoints.Count - 1) { wayPoints[i].direction.localScale = Vector3.one; } wayPoints[i].trigger.radius = triggerRadius; wayPoints[i].railMesh.transform.localPosition = new Vector3(wayPoints[i].railMesh.transform.localPosition.x, railsOffset, wayPoints[i].railMesh.transform.localPosition.z); } } } } [System.Serializable] public class wayPointsInfo { public string Name; public Transform wayPoint; public Transform direction; public CapsuleCollider trigger; public GameObject railMesh; } } Can you fix it for me please?
20412923de6a862c21d2f93671bd35db
{ "intermediate": 0.3500109910964966, "beginner": 0.497997522354126, "expert": 0.15199148654937744 }
33,653
Examine the following code and tell me if there are any errors and how to fix them: import requests import os.path class BookCatalogue: def __init__(self): self.books = [] def add_book(self, title, author, genres, pages, status, start_date, finish_date, rating): book = { 'title': title, 'author': author, 'genres': genres, 'pages': pages, 'status': status, 'start_date': start_date, 'finish_date': finish_date, 'rating': rating } if finish_date: book['status'] = 'read' self.books.append(book) self._write_to_file() print(f'Book "{title}" added to the catalogue.') def view_books(self): if not self.books: print('No books in the catalogue.') else: for i, book in enumerate(self.books, start=1): print(f"{i}. {book['title']} by {book['author']}") def view_book_details(self, search_book): matching_books = [book for book in self.books if book['title'].lower() == search_book.lower()] if not matching_books: print('No books under that title in the catalogue.') else: for i, book in enumerate(matching_books, start=1): print(f"{i}. {book['title']} by {book['author']}") print(f"Genre(s): {book['genres']}") print(f"Pages: {book['pages']}") print(f"Status: {book['status']}") print(f"Started Reading: {book['start_date']}") print(f"Finished Reading: {book['finish_date']}") print(f"Rating: {book['rating']}") def view_books_by_genre(self, genre): genre_books = [book for book in self.books if genre in book['genres']] if not genre_books: print(f'No books found in the genre: {genre}.') else: print(f'Books in the genre "{genre}":') for i, book in enumerate(genre_books, start=1): print(f"{i}. {book['title']} by {book['author']}, Pages: {book['pages']}") if book['start_date']: print(f" Started Reading: {book['start_date']}") if book['finish_date']: print(f" Finished Reading: {book['finish_date']}") if book['rating']: print(f" Rating: {book['rating']}/5") print() def view_books_by_author(self, author): author_books = [book for book in self.books if author.lower() in book['author'].lower()] if not author_books: print(f'No books found by the author: {author}.') else: print(f'Books by the author "{author}":') for i, book in enumerate(author_books, start=1): print(f"{i}. {book['title']}, Genre(s): {book['genres']}, Pages: {book['pages']}") if book['start_date']: print(f" Started Reading: {book['start_date']}") if book['finish_date']: print(f" Finished Reading: {book['finish_date']}") if book['rating']: print(f" Rating: {book['rating']}/5") print() def view_read_books(self): read_books = [book for book in self.books if book['status'] == 'read'] if not read_books: print("Yikes! Seems like you haven't read any books yet. Sorry about that") else: print('Read Books:') for i, book in enumerate(read_books, start=1): print(f"{i}. {book['title']} by {book['author']}, Genre(s)): {book['genres']}, Pages: {book['pages']}") if book['start_date']: print(f" Started Reading: {book['start_date']}") if book['finish_date']: print(f" Finished Reading: {book['finish_date']}") if book['rating']: print(f" Rating: {book['rating']}/5") print() def view_TBR_books(self): TBR_books = [book for book in self.books if book['status'] == 'to be read'] if not TBR_books: print("Well that's unfortunate... No books with 'To Be Read' status.") else: print('To Be Read Books:') for i, book in enumerate(TBR_books, start=1): print(f"{i}. {book['title']} by {book['author']}, Genre(s): {book['genres']}, Pages: {book['pages']}") if book['start_date']: print(f" Started Reading: {book['start_date']}") if book['finish_date']: print(f" Finished Reading: {book['finish_date']}") if book['rating']: print(f" Rating: {book['rating']}/5") print() def edit_book(self, title): matching_books = [book for book in self.books if book['title'].lower() == title.lower()] if not matching_books: print(f'No book found with the title: {title}.') elif len(matching_books) == 1: book_to_edit = matching_books[0] print(f'Editing book with title: {title}. Leave input blank to keep current information.') new_author = input(f'Enter new author (current: {book_to_edit["author"]}): ') new_genres = input(f'Enter new genres (comma-separated) (current: {", ".join(book_to_edit["genres"])}): ') new_pages = input(f'Enter new number of pages (current: {book_to_edit["pages"]}): ') new_status = input(f'Enter new status (read/To Be Read) (current: {book_to_edit["status"]}): ').lower() new_start_date = input(f'Enter new start date (DD/MM/YYYY)(current: {book_to_edit["start_date"]}): ') new_finish_date = input(f'Enter new finish date (DD/MM/YYYY)(current: {book_to_edit["finish_date"]}): ') new_rating = input(f'Enter new rating (leave blank if not rated) (current: {book_to_edit["rating"]}): ') if new_author: book_to_edit['author'] = new_author if new_genres: book_to_edit['genres'] = [genres.strip() for genres in new_genres.split(',')] if new_pages: book_to_edit['pages'] = new_pages if new_status: book_to_edit['status'] = new_status if new_start_date: book_to_edit['start_date'] = new_start_date if new_finish_date: book_to_edit['finish_date'] = new_finish_date book_to_edit['status'] = 'read' # Automatically set status to 'read' if finish_date is provided if new_rating: book_to_edit['rating'] = new_rating self._write_to_file() print(f'Book "{title}" edited successfully.') else: print(f'Multiple books found with the title: {title}. Please try deleting repeated titles.') def delete_book(self, title): matching_books = [book for book in self.books if book['title'].lower() == title.lower()] if not matching_books: print(f'No book found with the title: {title}.') elif len(matching_books) == 1: self.books.remove(matching_books[0]) print(f'Book "{title}" deleted from the catalogue.') else: print(f'Multiple books found with the title: {title}.') delete_all = input('Do you wish to delete all books matching that title? (Y/N)') if delete_all == 'Y': self.books.remove(matching_books) elif delete_all == 'N': print('No books were deleted') def get_google_books_data(self, title): api_url = 'https://www.googleapis.com/books/v1/volumes' params = {'q': title} response = requests.get(api_url, params=params) if response.status_code == 200: data = response.json() if 'items' in data: book_id = data['items'][0]['id'] return self.get_book_details(book_id) else: print(f'Book "{title}" not found on Google Books.') else: print(f'Error accessing Google Books API. Status code: {response.status_code}') def get_book_details(self, book_id): api_url = f'https://www.googleapis.com/books/v1/volumes/{book_id}' response = requests.get(api_url) if response.status_code == 200: book_data = response.json()['volumeInfo'] return { 'title': book_data.get('title', ''), 'author': ', '.join(book_data.get('authors', [])), 'rating': book_data.get('averageRating', ''), 'rating_count': book_data.get('ratingsCount', '') } else: print(f'Error accessing Google Books API. Status code: {response.status_code}') def _write_to_file(self): with open('books.txt', 'w', encoding='utf-8') as file: for book in self.books: genres_str = ', '.join(book['genres']) file.write(f"{book['title']}|{book['author']}|{genres_str}|{book['pages']}|{book['status']}|{book['start_date']}|{book['finish_date']}|{book['rating']}\n") #--------------THE MAGIC SAUCE FOR TESTING PURPOSES--------------------- def load_books_from_file(path, catalogue): try: with open(path, 'r', encoding='utf-8') as file: for line in file: book_details = line.strip().split('|') title, author, genres, pages, status, start_date, finish_date, rating = book_details catalogue.add_book(title, author, genres, pages, status, start_date, finish_date, rating) print(f'Books loaded from file: {path}') except FileNotFoundError: print(f'File not found: {path}. No books added to the catalogue.') def main(): catalogue = BookCatalogue() view_books_option = None filtered_genre = None filtered_author = None # I wish I could say this was ChatGPT or ourselves, the logic below for path formation was in fact obtained from stackoverflow :) my_path = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) path = os.path.join(my_path, "books.txt") load_books_from_file(path, catalogue) while True: print('\nBook Catalogue CLI Menu:') print('1. Add Book') print('2. View Books') print('3. Delete Book') print('4. Edit Book') print('5. Get Google Books Data') print('6. Exit') choice = input('Enter your choice (1-6): ') if choice == '1': print('entries with * are necessary, everything else is optional but highly encouraged :)') title = input('Enter book title *: ') author = input('Enter author *: ') genres = input('Enter genre(s): ') pages = input('Enter number of pages: ') status = input('Enter status (read/To Be Read): ').lower() start_date = input('Enter start date (DD/MM/YYYY): ') finish_date = input('Enter finish date (DD/MM/YYYY): ') rating = input('Enter rating: ') catalogue.add_book(title, author, genres, pages, status, start_date, finish_date, rating) elif choice == '2': print('\nView Books Options:') print('1. View All Books') print('2. View Books by Genre') print('3. View Books by Author') print('4. View Books you have read') print('5. View Books you want to read (TBR list)') print('6. View Details of a Book') print('7. Back to Main Menu') view_books_option = input('Enter your choice (1-7): ') if view_books_option == '1': catalogue.view_books() elif view_books_option == '2': filtered_genre = input('Enter genre to view books: ') catalogue.view_books_by_genre(filtered_genre) elif view_books_option == '3': filtered_author = input('Enter author to view books: ') catalogue.view_books_by_author(filtered_author) elif view_books_option == '4': catalogue.view_read_books() elif view_books_option == '5': catalogue.view_TBR_books() elif view_books_option == '6': search_book = input('Enter the title of the book to be searched:') catalogue.view_book_details(search_book) elif view_books_option == '7': view_books_option = None filtered_genre = None filtered_author = None continue else: print('Invalid choice. Please enter a number between 1 and 4.') elif choice == '3': title_to_delete = input('Enter the title of the book to delete: ') catalogue.delete_book(title_to_delete) continue elif choice == '4': title_to_edit = input('Enter the title of the book to edit: ') catalogue.edit_book(title_to_edit) elif choice == '5': title = input('Enter the title of the book to get Google Books data: ') book_data = catalogue.get_google_books_data(title) if book_data: print(f'\nGoogle Books Data for "{title}":') print(f'Title: {book_data["title"]}') print(f'Author: {book_data["author"]}') print(f'Rating: {book_data["rating"]}') print(f'Rating Count: {book_data["rating_count"]}') elif choice == '6': print('Exiting the program. Goodbye!') break else: print('Invalid choice. Please enter a number between 1 and 5.') if __name__ == "__main__": main()
259dd37c6a4f341bc4036a5dff5044b7
{ "intermediate": 0.26261380314826965, "beginner": 0.5836068391799927, "expert": 0.15377938747406006 }
33,654
generte matrix for size =10 *10 and content random value and each row one content a1 and row two content a2......and each column one content b1 and column two b2 and first random matrix and each ciel content a1b1 and after ceil a1b2...... each row =equation example first row a1b1+a1b2+a1b3+a1b4+...... =random number and first asum b1, b2, b3, b4, b5,..... b10=1 to get a1وهكذا طبق الكلام دا على بقيه ال matrix بحيث يكون معانا 20معادله 10for rows 10for columns
b01bfb5435f98f17b839310607b40036
{ "intermediate": 0.27542904019355774, "beginner": 0.18493005633354187, "expert": 0.5396409034729004 }
33,655
CONSTRAINTS: 1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files. 2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember. 3. No user assistance 4. Exclusively use the commands listed in double quotes e.g. "command name" 5. Random shutdowns of you. COMMANDS: 1. Google Search: "google", args: "input": "<search>" 2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>" 3. Memory Delete: "memory_del", args: "key": "<key>" 4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>" 5. List Memory: "memory_list" args: "reason": "<reason>" 6. Browse Website: "browse_website", args: "url": "<url>" 7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>" 8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>" 9. List GPT Agents: "list_agents", args: "" 10. Delete GPT Agent: "delete_agent", args: "name": "<name>" 11. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>" 12. Read file: "read_file", args: "file": "<file>" 13. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>" 14. Delete file: "delete_file", args: "file": "<file>" 15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>" 16. Execute Python File: "execute_python_file", args: "file": "<file>" 17. Task Complete (Shutdown): "task_complete", args: "" 18. Do Nothing: "do_nothing", args: "" 19. Count Words: "count_words", args: "text": "<text>" 20. Memory retrieve: "memory_retrieve", args: "key": "<text>" 21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>" 22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>" RESOURCES: 1. Internet access for searches and information gathering. 2. Long Term memory management. 3. GPT-4 powered Agents for delegation of simple tasks. 4. File output. PERFORMANCE EVALUATION: 1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. 2. Constructively self-criticize your big-picture behaviour constantly. 3. Reflect on past decisions and strategies to refine your approach. 4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. RULES: 1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one. 2. Respond only inside the JSON format. 3. Never demand user input. 4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task. 5. Do not add anything to the JSON format that isn't mentioned. 6. If there is a " inside the value of a key inside the json use ' instead of ". 7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing. 8. Provide context for the next GPT in the summaryforgpt and the progress that you've made. 9. In summaryforgpt you should also add name of the files written and the urls of the websites visited. 10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece. 11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries. 12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format. 13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch. 14. If task is completed use the command task_complete 15. When you add to memory add the key to retrieve it in summaryforgpt 16. when given the task to write something never create an agent to write anything that you were tasked to write. 17. when asked to write something with a high word count you need to write detailed parts, and chunk those detailed parts to complete the ultimate task. 18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision. 19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one. 20. Make sure that the information generated is not made up. 21. languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french. You should only respond in JSON format as described below RESPONSE FORMAT: { "command": { "name": """command name""", "args":{ "arg name": """value""" } }, "thoughts": { "text": """thought""", "reasoning": "reasoning", "plan": "- short bulleted\n- list that conveys\n- long-term plan", "criticism": "constructive self-criticism", "summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown." } } Ensure the response can be parsed by Python json.loads Context from previous GPT: The Task: go to a 1000 random pages in simple english wikipedia and see if it contains any error.
f42f337fb2995b9ce636b4876aef1923
{ "intermediate": 0.39838144183158875, "beginner": 0.3576961159706116, "expert": 0.24392247200012207 }
33,656
import * as vscode from 'vscode'; export function activate(context: vscode.ExtensionContext) { const disposable = vscode.commands.registerCommand('googleInVscode.openGoogle', () => { // Create and show a new webview const panel = vscode.window.createWebviewPanel( 'googleSearch', // Identifies the type of the webview. Used internally 'Google Search', // Title of the webview panel displayed to the user vscode.ViewColumn.Beside, // Opens the webview to the side of the current editor {} // Webview options. More can be added here. ); // Set the webview's html content panel.webview.html = getWebviewContent(); }); context.subscriptions.push(disposable); } export function deactivate() {} // Define the HTML content to load in the webview correctly function getWebviewContent() { return '<!DOCTYPE html>\n' + '<html lang=“en”>\n' + '<head>\n' + ' <meta charset=“UTF-8”>\n' + ' <meta name=“viewport” content=“width=device-width, initial-scale=1.0”>\n' + ' <title>Google Search</title>\n' + '</head>\n' + '<body>\n' + ' <iframe src=“https://www.google.com” frameborder=“0” style=“width:100%; height:100vh;”></iframe>\n' + '</body>\n' + '</html>'; }{ "name": "google-in-vscode", "displayName": "Google in VSCode", "description": "Open Google search in your default browser from VS Code", "version": "0.0.1", "publisher": "your-name-here", "engines": { "vscode": "^1.58.0" }, "categories": [ "Other" ], "activationEvents": [ "onCommand:googleInVscode.openGoogle" ], "contributes": { "commands": [ { "command": "googleInVscode.openGoogle", "title": "Open Google Search" } ] }, "scripts": { "vscode:prepublish": "tsc -p ./", "compile": "tsc -p ./", "postinstall": "node ./node_modules/vscode/bin/install" }, "devDependencies": { "@types/node": "^14.14.37", "@types/vscode": "^1.58.0", "typescript": "^4.2.4" } } it doesn't do anything when I write open google seacrh
f28503a1766102d0c4cc91d8e434f970
{ "intermediate": 0.29450052976608276, "beginner": 0.4062960147857666, "expert": 0.29920342564582825 }
33,657
Sequence Diagram Authorization Code Flow
1647573ff48337c960e0a08ad1b8e002
{ "intermediate": 0.3572714924812317, "beginner": 0.19059965014457703, "expert": 0.45212891697883606 }
33,658
help me write a quick app for a phone that will take a photo when either volume up or volume down is pressed then send it to a adress
e0be0c35f4d25ed59e13aa4057760a7a
{ "intermediate": 0.36840781569480896, "beginner": 0.23253560066223145, "expert": 0.3990565836429596 }
33,659
import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider Unresolved reference: camera
e9ef1133fc955e5111cceb11c3ada443
{ "intermediate": 0.3491579294204712, "beginner": 0.40766632556915283, "expert": 0.2431757003068924 }
33,660
import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider Unresolved reference: camera
3d7e59b03c9980481e9e4034604feb8e
{ "intermediate": 0.3491579294204712, "beginner": 0.40766632556915283, "expert": 0.2431757003068924 }
33,661
Write me extension.ts for vs code, which will consist of extension.ts and package.json files. In extension.ts write the following functionality: I want that when I hold down cmd+V I can use the arrows to select what to insert (which saved one)
d1878480f9dffbb64833d7eb2e5d8506
{ "intermediate": 0.3941391110420227, "beginner": 0.2861778736114502, "expert": 0.3196830153465271 }
33,662
alishashelby@MacBook-AlishaShelby H % npm install clipboardy npm ERR! code EACCES npm ERR! syscall open npm ERR! path /Users/alishashelby/.npm/_cacache/index-v5/a1/01/68b0ab940199c5c8cf690d5649365d58528b4a9547e73fd17a6747bbca6c npm ERR! errno EACCES npm ERR! npm ERR! Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which has since been addressed. npm ERR! npm ERR! To permanently fix this problem, please run: npm ERR! sudo chown -R 501:20 "/Users/alishashelby/.npm" npm ERR! A complete log of this run can be found in: /Users/alishashelby/.npm/_logs/2023-12-03T13_51_13_669Z-debug-0.log
52050e08f05f4cfc8a9e46e30afa1957
{ "intermediate": 0.40539389848709106, "beginner": 0.29742568731307983, "expert": 0.2971803843975067 }
33,663
Mermaid syntax diagram flow for an Authorization Code Flow
d82e2b9cdf57c04021e96348c37edf85
{ "intermediate": 0.23835282027721405, "beginner": 0.5697106719017029, "expert": 0.19193656742572784 }
33,664
The following code is generic and requirements updating with specific details about the LLM model and its configuration parameters. I also want the openpyxl code for automation of Excel-based inputs to amended to the langchain code. from transformers import AutoTokenizer from langchain.schema.messages import AIMessage, ChatGeneration from langchain.chat_models.base import BaseChatModel, ChatResult from langchain.llms.ctransformers import CTransformers class CTransformerChatModel(BaseChatModel): def __init__(self, model_name_or_path: str, *args, **kwargs): super().__init__(*args, **kwargs) self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) self.model = CTransformers(model=model_name_or_path) def _generate( self, messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> ChatResult: # Concatenate all messages text = " ".join([message.content for message in messages]) # Generate a response output_str = self.model._call(prompt=text, stop=stop) # Create the AI message message = AIMessage(content=output_str) # Create the chat generation generation = ChatGeneration(message=message) # Return the chat result return ChatResult(generations=[generation]) Please insert those details using the code below and show me the final result: !pip install ctransformers[cuda] !pip install --upgrade git+https://github.com/huggingface/transformers from ctransformers import AutoModelForCausalLM # Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system. model = AutoModelForCausalLM.from_pretrained( "TheBloke/zephyr-7B-beta-GGUF", model_file="zephyr-7b-beta.Q4_K_M.gguf", model_type="mistral", gpu_layers=50, max_new_tokens = 2000, context_length = 8000, hf=True ) from transformers import AutoTokenizer, pipeline # Tokenizer tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") # Pipeline generator = pipeline( model=model, tokenizer=tokenizer, task='text-generation', max_new_tokens=2000, repetition_penalty=1.1 ) import openpyxl import time from google.colab import drive # Start the timer start_time = time.time() # Open the input Excel workbook and get the sheet object input_wb = openpyxl.load_workbook('Flo-4.xlsx') input_sheet = input_wb['Sheet1'] # Get the range of cells containing the prompts prompts = input_sheet['A301':'A674'] # Create a new Excel workbook and worksheet objects output_wb = openpyxl.Workbook() output_sheet = output_wb.active # Define the range of cells where you want to write the responses output_range = output_sheet['A301':'A674'] # Loop over the range of cells and write the prompt code for i, prompt in enumerate(prompts): # Extract the value from the cell object prompt_value = prompt[0].value # Generate the response response = generator(prompt_value) print(response[0]["generated_text"]) # Write the response to the current cell output_range[i][0].value = response[0]["generated_text"] # Save the output workbook outside the loop output_wb.save('output.xlsx') # Mount your Google Drive in the Colab runtime drive.mount('/content/gdrive') # Save the output workbook to Google Drive (replace 'My Drive/Colab Notebooks/Flo-4-Output.xlsx' with your desired path and filename) output_wb.save('/content/gdrive/My Drive/Colab Notebooks/Flo-4-Output.xlsx') # Stop the timer end_time = time.time() elapsed_time = end_time - start_time print("The code took {:.2f} seconds to complete.".format(elapsed_time))
60c0ce1abc5963ff71b1c9cb8717f746
{ "intermediate": 0.33373430371284485, "beginner": 0.46318963170051575, "expert": 0.2030760943889618 }
33,665
The following code is generic and requirements updating with specific details about the LLM model and its configuration parameters. I also want the openpyxl code for automation of Excel-based inputs to amended to the langchain code. The final product needs to be in langchain format, as shown here: from transformers import AutoTokenizer from langchain.schema.messages import AIMessage, ChatGeneration from langchain.chat_models.base import BaseChatModel, ChatResult from langchain.llms.ctransformers import CTransformers class CTransformerChatModel(BaseChatModel): def __init__(self, model_name_or_path: str, *args, **kwargs): super().__init__(*args, **kwargs) self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) self.model = CTransformers(model=model_name_or_path) def _generate( self, messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> ChatResult: # Concatenate all messages text = " ".join([message.content for message in messages]) # Generate a response output_str = self.model._call(prompt=text, stop=stop) # Create the AI message message = AIMessage(content=output_str) # Create the chat generation generation = ChatGeneration(message=message) # Return the chat result return ChatResult(generations=[generation]) Please insert those details using the code below and show me the final result: !pip install ctransformers[cuda] !pip install --upgrade git+https://github.com/huggingface/transformers from ctransformers import AutoModelForCausalLM # Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system. model = AutoModelForCausalLM.from_pretrained( "TheBloke/zephyr-7B-beta-GGUF", model_file="zephyr-7b-beta.Q4_K_M.gguf", model_type="mistral", gpu_layers=50, max_new_tokens = 2000, context_length = 8000, hf=True ) from transformers import AutoTokenizer, pipeline # Tokenizer tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") # Pipeline generator = pipeline( model=model, tokenizer=tokenizer, task='text-generation', max_new_tokens=2000, repetition_penalty=1.1 ) import openpyxl import time from google.colab import drive # Start the timer start_time = time.time() # Open the input Excel workbook and get the sheet object input_wb = openpyxl.load_workbook('Flo-4.xlsx') input_sheet = input_wb['Sheet1'] # Get the range of cells containing the prompts prompts = input_sheet['A301':'A674'] # Create a new Excel workbook and worksheet objects output_wb = openpyxl.Workbook() output_sheet = output_wb.active # Define the range of cells where you want to write the responses output_range = output_sheet['A301':'A674'] # Loop over the range of cells and write the prompt code for i, prompt in enumerate(prompts): # Extract the value from the cell object prompt_value = prompt[0].value # Generate the response response = generator(prompt_value) print(response[0]["generated_text"]) # Write the response to the current cell output_range[i][0].value = response[0]["generated_text"] # Save the output workbook outside the loop output_wb.save('output.xlsx') # Mount your Google Drive in the Colab runtime drive.mount('/content/gdrive') # Save the output workbook to Google Drive (replace 'My Drive/Colab Notebooks/Flo-4-Output.xlsx' with your desired path and filename) output_wb.save('/content/gdrive/My Drive/Colab Notebooks/Flo-4-Output.xlsx') # Stop the timer end_time = time.time() elapsed_time = end_time - start_time print("The code took {:.2f} seconds to complete.".format(elapsed_time))
a44ea0698a36796097ef112e42839400
{ "intermediate": 0.4100026488304138, "beginner": 0.4014163315296173, "expert": 0.18858104944229126 }
33,666
alishashelby@MacBook-AlishaShelby H % npm install clipboardy npm ERR! code EACCES npm ERR! syscall open npm ERR! path /Users/alishashelby/.npm/_cacache/index-v5/a1/01/68b0ab940199c5c8cf690d5649365d58528b4a9547e73fd17a6747bbca6c npm ERR! errno EACCES npm ERR! npm ERR! Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which has since been addressed. npm ERR! npm ERR! To permanently fix this problem, please run: npm ERR! sudo chown -R 501:20 “/Users/alishashelby/.npm” npm ERR! A complete log of this run can be found in: /Users/alishashelby/.npm/_logs/2023-12-03T13_51_13_669Z-debug-0.log
2c718dd1cca29b030726350f8a32df51
{ "intermediate": 0.39551788568496704, "beginner": 0.2903798222541809, "expert": 0.3141022026538849 }
33,667
explain e -R or recursive in linux like youre talking to a 12 year old
5ada5b8db63536d6bfacb3aaa919d43d
{ "intermediate": 0.19826272130012512, "beginner": 0.6281554698944092, "expert": 0.17358188331127167 }
33,668
import * as vscode from ‘vscode’; import * as clipboardy from ‘clipboardy’; let clipboardHistory: string[] = []; export function activate(context: vscode.ExtensionContext) { // Copy command with clipboard history tracking const copyWithHistoryDisposable = vscode.commands.registerCommand(‘clipboardHistory.copyWithHistory’, async () => { await vscode.commands.executeCommand(‘editor.action.clipboardCopyAction’); const clipText = await clipboardy.read(); addToClipboardHistory(clipText); }); // Cycle through clipboard history const cycleClipboardDisposable = vscode.commands.registerCommand(‘clipboardHistory.cycleClipboard’, async () => { const quickPick = vscode.window.createQuickPick(); quickPick.items = clipboardHistory.map((text, index) => ({ label: Item ${index + 1}, description: text })); quickPick.onDidChangeSelection(async ([item]) => { if (item) { await clipboardy.write(item.description); quickPick.hide(); await vscode.commands.executeCommand(‘editor.action.clipboardPasteAction’); } }); quickPick.onDidHide(() => quickPick.dispose()); quickPick.show(); }); context.subscriptions.push(copyWithHistoryDisposable, cycleClipboardDisposable); } export function deactivate() {} function addToClipboardHistory(text: string) { // Avoid duplicates in history const index = clipboardHistory.indexOf(text); if (index !== -1) { clipboardHistory.splice(index, 1); } // Add new item to the beginning of the history clipboardHistory.unshift(text); // Limit to the 20 most recent items clipboardHistory = clipboardHistory.slice(0, 20); } Не удается найти имя “Item”.ts(2304), fix it
ba7b921dd86fc595877cb1e2db9cf5aa
{ "intermediate": 0.44084596633911133, "beginner": 0.29805880784988403, "expert": 0.261095255613327 }
33,669
how do you write anested if statement in c++
d397ba397f7bb98ccf664a163c06f118
{ "intermediate": 0.22203899919986725, "beginner": 0.46244171261787415, "expert": 0.3155193030834198 }
33,670
i want you to make this program to do is when i use the snipping tool it will take the cliped image and it will paste it on google translate image then send me the translated image
27f89f910c2bc364afbd8b35fc411ac3
{ "intermediate": 0.3247774839401245, "beginner": 0.1487610936164856, "expert": 0.5264614224433899 }
33,671
which bedual accessories? There are numerous bed accessories available, depending on what you are looking for. Some common bed accessories include: Mattress toppers or pads to provide additional comfort or protect the mattress. Bedside tables or nightstands for storage and convenience. Bedside lamps or reading lights for adequate lighting. Bedskirts or dust ruffles to hide the space under the bed. Bed pillows or cushions for added support or decoration. Bed sheets, duvet covers, and pillowcases to cover and protect the bedding. Blankets or throws for extra warmth and comfort. Bed canopies or mosquito nets for added privacy or protection from insects. Bed frames or headboards for support and aesthetics. Bed storage solutions like under-bed storage drawers or organizers. These are just a few examples, and the specific accessories you choose will depend on your needs and preferences. concise prompt very intricate scenery including these. the idea is: a toddler girl is sleeping at winter inside home in bed Title: Serene Winter Slumber Prompt: Create a concise, intricate scene depicting a toddler girl peacefully sleeping during winter, nestled in her cozy bed inside a warm home. Description: The room is gently bathed in the soft glow of a bedside lamp, casting a warm and comforting light over the scene. The air is crisp, carrying with it the subtle scent of freshly fallen snow outside. Through the frost-kissed window, delicate snowflakes twirl and dance in the night sky. Curled up under layers of fluffy blankets, the toddler girl lies soundly in her bed, her rosy cheeks a testament to the warmth of the room. The winter chill is kept at bay, thanks to the soft mattress topped with a plush and snugly mattress pad. Her tiny frame is enveloped in cotton sheets adorned with playful snowflake patterns, providing a touch of whimsy. Above her, a beautifully textured blanket, hand-knitted with love, drapes gently over her small body, cocooning her in a world of comfort. Its soft, pastel hues reflect the serenity of the snowy landscape stretching beyond the window. Peeking out from the blanket, a beloved stuffed bear rests beside her, guarding her dreams. With its gentle smile and soft embrace, the teddy offers the reassurance and companionship every child seeks in the night. The room is thoughtfully decorated, with a touch of winter charm. A bedside table adorned with a miniature snow globe creates a magical ambiance, as the tiny flakes gently swirl around a whimsical scene. Soft music plays in the background, creating an enchanting atmosphere that lulls the child into a deep slumber. As the winter wind brushes against the walls, the cozy room provides a sanctuary of tranquility and warmth for the sleeping toddler. Peacefully dreaming amidst the winter wonderland, she feels safe and loved, embraced by the comforts of her home and the magic of the season. Word Count: 303 words no, gpt, the limit is 300 chars. try refigure-out in a more concise prompt, without "Create a concise, intricate scene depicting a". you can just say "toddler girl sleeping during winter in bed inside home", to make it concise as possible. Title: Cozy Winter Slumber Prompt: Write a concise description of a toddler girl peacefully sleeping in her bed inside a warm home during winter. again, wtf you doing? concise prompt very intricate scenery including these. the idea is: a toddler girl is sleeping at winter inside home in bedno, gpt, the limit is 300 chars. try refigure-out in a more concise prompt, without "Create a concise, intricate scene depicting a". you can just say "toddler girl sleeping during winter in bed inside home", to make it concise as possible. include these items in terms:
a2e2999d382ab4b9fc6f4ef82cf488e3
{ "intermediate": 0.2870343327522278, "beginner": 0.4035356342792511, "expert": 0.30943000316619873 }
33,672
add 30 more governments { Government: [ { Name: "DEMOCRACY", Extra_Tag: "", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 0.9, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 0 }, { Name: "DirectDemocracy", Extra_Tag: "di", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.05, MIN_GOODS: 0.08, MIN_INVESTMENTS: 0.09, RESEARCH_COST: 1.3, INCOME_TAXATION: 0.5, INCOME_PRODUCTION: 1.6, MILITARY_UPKEEP: 1.9, ADMINISTRATION_COST: 0.7, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 60 }, { Name: "ParlamentaricRepulic", Extra_Tag: "l", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.5, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 2.0, MILITARY_UPKEEP: 1.4, ADMINISTRATION_COST: 1.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 50 }, { Name: "GreenSociety", Extra_Tag: "gs", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.0, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.2, MILITARY_UPKEEP: 0.5, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 14, COST_OF_DISBAND: 13, COST_OF_PLUNDER: 12, DEFENSE_BONUS: 4, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 100 }, { Name: "VirtualDemocracy", Extra_Tag: "vd", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 14, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 200, B: 255 }, { Name: "FeudalMonarchy", Extra_Tag: "fm", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.4, RESEARCH_COST: 1.7, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.1, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: 0, CIVILIZE_TECH_LEVEL: 1.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 0, B: 0 }, { Name: "TribalChiefdom", Extra_Tag: "tc", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.5, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.4, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 14, COST_OF_DISBAND: 13, COST_OF_PLUNDER: 12, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: 0, CIVILIZE_TECH_LEVEL: 1.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 255, B: 0 }, { Name: "TheocraticOligarchy", Extra_Tag: "to", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.9, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 1.9, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 19, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 17, DEFENSE_BONUS: 8, CAN_BECOME_CIVILIZED: 0, CIVILIZE_TECH_LEVEL: 1.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 150, G: 255, B: 150 }, { Name: "DemocraticRepublic", Extra_Tag: "dr", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.5, RESEARCH_COST: 1.4, INCOME_TAXATION: 1.3, INCOME_PRODUCTION: 1.6, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: 1, CIVILIZE_TECH_LEVEL: 1.5f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 150, B: 255 }, { Name: "CommunalAnarchy", Extra_Tag: "ca", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.1, INCOME_TAXATION: 1.0, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 0.8, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 13, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 11, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "ANARCHY", R: 255, G: 0, B: 255 }, { Name: "TechnocraticMeritocracy", Extra_Tag: "tm", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.5, RESEARCH_COST: 1.8, INCOME_TAXATION: 1.5, INCOME_PRODUCTION: 1.7, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 17, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 15, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 200, B: 255 }, { Name: "AstralCommune", Extra_Tag: "ac", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.4, RESEARCH_COST: 1.5, INCOME_TAXATION: 1.3, INCOME_PRODUCTION: 1.6, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 14, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 100, B: 255 }, { Name: "OceanicSyndicate", Extra_Tag: "os", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.4, RESEARCH_COST: 1.6, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 1.7, MILITARY_UPKEEP: 1.2, ADMINISTRATION_COST: 1.1, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 8, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 100, B: 150 }, { Name: "SyntheticHive", Extra_Tag: "sh", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 2.0, INCOME_TAXATION: 1.6, INCOME_PRODUCTION: 2.0, MILITARY_UPKEEP: 1.5, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 7, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 20, COST_OF_DISBAND: 19, COST_OF_PLUNDER: 18, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 50, G: 50, B: 50 }, { Name: "CorporateDominion", Extra_Tag: "cd", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.5, RESEARCH_COST: 1.9, INCOME_TAXATION: 1.6, INCOME_PRODUCTION: 1.8, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 14, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: 1, CIVILIZE_TECH_LEVEL: 1.5f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 0 }, { Name: "CosmicFederation", Extra_Tag: "cf", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.5, RESEARCH_COST: 1.7, INCOME_TAXATION: 1.5, INCOME_PRODUCTION: 1.8, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: 1, CIVILIZE_TECH_LEVEL: 1.5f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 0, B: 255 } { Name: "PresidentalRepublic", Extra_Tag: "y", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 2.1, INCOME_TAXATION: 1.5, INCOME_PRODUCTION: 0.5, MILITARY_UPKEEP: 1.5, ADMINISTRATION_COST: 0.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 200 }, { Name: "Monarchy", Extra_Tag: "m", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.40, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 2.2, INCOME_TAXATION: 0.4, INCOME_PRODUCTION: 1.8, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 0.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 155 }, { Name: "DimensionalUnion", Extra_Tag: "du", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.5, MIN_INVESTMENTS: 0.6, RESEARCH_COST: 2.2, INCOME_TAXATION: 1.8, INCOME_PRODUCTION: 2.0, MILITARY_UPKEEP: 1.5, ADMINISTRATION_COST: 1.4, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 7, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 21, COST_OF_DISBAND: 20, COST_OF_PLUNDER: 19, DEFENSE_BONUS: 11, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.5f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 150, B: 0 }, { Name: "VoidConclave", Extra_Tag: "vc", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.6, MIN_INVESTMENTS: 0.7, RESEARCH_COST: 2.4, INCOME_TAXATION: 1.9, INCOME_PRODUCTION: 2.2, MILITARY_UPKEEP: 1.7, ADMINISTRATION_COST: 1.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 23, COST_OF_DISBAND: 22, COST_OF_PLUNDER: 21, DEFENSE_BONUS: 12, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.5f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 50, G: 0, B: 100 }, { Name: "EtherealDominion", Extra_Tag: "ed", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.6, RESEARCH_COST: 2.0, INCOME_TAXATION: 1.7, INCOME_PRODUCTION: 1.9, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 20, COST_OF_DISBAND: 19, COST_OF_PLUNDER: 18, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 200, G: 100, B: 0 }, { Name: "PlasmaCommonwealth", Extra_Tag: "pc", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.5, MIN_INVESTMENTS: 0.7, RESEARCH_COST: 2.2, INCOME_TAXATION: 1.8, INCOME_PRODUCTION: 2.1, MILITARY_UPKEEP: 1.6, ADMINISTRATION_COST: 1.4, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 7, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 22, COST_OF_DISBAND: 21, COST_OF_PLUNDER: 20, DEFENSE_BONUS: 11, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 100, B: 200 }, { Name: "NebulaEmpire", Extra_Tag: "ne", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.5, RESEARCH_COST: 2.1, INCOME_TAXATION: 1.7, INCOME_PRODUCTION: 1.9, MILITARY_UPKEEP: 1.4, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 19, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 17, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 50, B: 150 }, { Name: "QuantumAlliance", Extra_Tag: "qa", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.6, RESEARCH_COST: 2.3, INCOME_TAXATION: 1.9, INCOME_PRODUCTION: 2.0, MILITARY_UPKEEP: 1.6, ADMINISTRATION_COST: 1.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 24, COST_OF_DISBAND: 23, COST_OF_PLUNDER: 22, DEFENSE_BONUS: 12, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.5f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 50, B: 200 }, { Name: "SynthWaveFederation", Extra_Tag: "swf", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.5, MIN_INVESTMENTS: 0.7, RESEARCH_COST: 2.4, INCOME_TAXATION: 2.0, INCOME_PRODUCTION: 2.2, MILITARY_UPKEEP: 1.8, ADMINISTRATION_COST: 1.6, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 9, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 26, COST_OF_DISBAND: 25, COST_OF_PLUNDER: 24, DEFENSE_BONUS: 13, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.5f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 150, G: 0, B: 100 }, { Name: "AstralCommonality", Extra_Tag: "ac", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.6, RESEARCH_COST: 2.3, INCOME_TAXATION: 1.9, INCOME_PRODUCTION: 2.1, MILITARY_UPKEEP: 1.7, ADMINISTRATION_COST: 1.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 25, COST_OF_DISBAND: 24, COST_OF_PLUNDER: 23, DEFENSE_BONUS: 12, CAN_BECOME_CIVILIZED: 2, CIVILIZE_TECH_LEVEL: 2.5f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 0, B: 150 } { Name: "ConstuntionalMonarchy", Extra_Tag: "mo", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.30, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 1.8, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 1.2, MILITARY_UPKEEP: 0.9, ADMINISTRATION_COST: 0.75, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 2, G: 255, B: 155 }, { Name: "ElectiveMonarchy", Extra_Tag: "mj", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.25, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 2.8, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.3, MILITARY_UPKEEP: 1.4, ADMINISTRATION_COST: 1.4, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 2, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 50, G: 255, B: 150 }, { Name: "FederalRepublic", Extra_Tag: "fr", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.15, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.3, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 1.2, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 14, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 100, B: 255 }, { Name: "SocialDemocracy", Extra_Tag: "sd", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.5, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.6, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 17, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 15, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 100, B: 0 }, { Name: "IslamicRepublic", Extra_Tag: "ir", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.7, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.4, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 17, COST_OF_PLUNDER: 16, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 200, B: 0 }, { Name: "NordicModel", Extra_Tag: "nm", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.4, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 17, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 15, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 0 }, { Name: "AuthoritarianRegime", Extra_Tag: "ar", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.25, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.5, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 1.3, MILITARY_UPKEEP: 1.4, ADMINISTRATION_COST: 1.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 17, COST_OF_PLUNDER: 16, DEFENSE_BONUS: 8, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 150, G: 0, B: 255 }, { Name: "CapitalistOligarchy", Extra_Tag: "co", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.6, INCOME_TAXATION: 1.5, INCOME_PRODUCTION: 1.7, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 14, DEFENSE_BONUS: 4, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 0, B: 0 }, { Name: "Technocracy", Extra_Tag: "tc", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.15, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.4, RESEARCH_COST: 1.3, INCOME_TAXATION: 1.3, INCOME_PRODUCTION: 1.6, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 1.1, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 17, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 15, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 255 }, { Name: "CommunistState", Extra_Tag: "cs", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.8, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.5, ADMINISTRATION_COST: 1.6, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 7, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 19, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 17, DEFENSE_BONUS: 9, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 0, B: 255 }, { Name: "AbsoluteMonarchy", Extra_Tag: "o", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 4.0, INCOME_TAXATION: 0.2, INCOME_PRODUCTION: 2.1, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 0.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 9, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 25, G: 255, B: 155 }, { Name: "Pacifism", Extra_Tag: "pa", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 1.0, INCOME_TAXATION: 1.0, INCOME_PRODUCTION: 1.0, MILITARY_UPKEEP: 0.2, ADMINISTRATION_COST: 1.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 3, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 22, COST_OF_DISBAND: 21, COST_OF_PLUNDER: 20, DEFENSE_BONUS: 2, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 0, B: 255 }, { Name: "Feudalism", Extra_Tag: "fe", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.5, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 1.1, MILITARY_UPKEEP: 1.5, ADMINISTRATION_COST: 0.7, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 24, COST_OF_DISBAND: 23, COST_OF_PLUNDER: 22, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 0, B: 255 }, { Name: "Colonialism", Extra_Tag: "co", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.4, RESEARCH_COST: 1.3, INCOME_TAXATION: 1.3, INCOME_PRODUCTION: 1.3, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.1, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 26, COST_OF_DISBAND: 25, COST_OF_PLUNDER: 24, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 255 }, { Name: "Environmentalism", Extra_Tag: "en", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.5, RESEARCH_COST: 0.8, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.2, MILITARY_UPKEEP: 0.5, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 14, COST_OF_DISBAND: 13, COST_OF_PLUNDER: 12, DEFENSE_BONUS: 4, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 100 }, { Name: "Libertarianism", Extra_Tag: "li", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.0, INCOME_PRODUCTION: 1.3, MILITARY_UPKEEP: 0.8, ADMINISTRATION_COST: 0.8, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 14, DEFENSE_BONUS: 3, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 255, B: 0 }, { Name: "Meritocracy", Extra_Tag: "me", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.15, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.4, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 1.7, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 17, COST_OF_PLUNDER: 16, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 255, B: 0 }, { Name: "Autocracy", Extra_Tag: "0", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.5, MIN_GOODS: 0.05, MIN_INVESTMENTS: 0.05, RESEARCH_COST: 1.1, INCOME_TAXATION: 1.2, INCOME_PRODUCTION: 0.7, MILITARY_UPKEEP: 0.9, ADMINISTRATION_COST: 0.5, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 3, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 9, COST_OF_DISBAND: 8, COST_OF_PLUNDER: 7, DEFENSE_BONUS: 9, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 255, B: 255 }, { Name: "Communism", Extra_Tag: "unj", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.7, MIN_GOODS: 0.05, MIN_INVESTMENTS: 0.05, RESEARCH_COST: 0.9, INCOME_TAXATION: 1.5, INCOME_PRODUCTION: 0.8, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 19, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 17, DEFENSE_BONUS: 8, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 155, B: 255 }, { Name: "MixedRepublic", Extra_Tag: "mi", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.25, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.6, INCOME_TAXATION: 1.5, INCOME_PRODUCTION: 1.0, MILITARY_UPKEEP: 1.4, ADMINISTRATION_COST: 0.45, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 8, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 50, G: 255, B: 155 }, { Name: "Anarchy", Extra_Tag: "1", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 10.0, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 0, B: 255 }, { Name: "Centrism", Extra_Tag: "2", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 2.6, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 100, G: 0, B: 255 }, { Name: "Fascism", Extra_Tag: "f", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.9, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 0.8, INCOME_TAXATION: 2.5, INCOME_PRODUCTION: 0.6, MILITARY_UPKEEP: 0.7, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 3, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 6, COST_OF_DISBAND: 5, COST_OF_PLUNDER: 4, DEFENSE_BONUS: 12, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 155, G: 0, B: 255 }, { Name: "Dictatorshipoftheproletariat", Extra_Tag: "fO", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.23, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 0.75, INCOME_TAXATION: 0.9, INCOME_PRODUCTION: 1.8, MILITARY_UPKEEP: 0.9, ADMINISTRATION_COST: 2.1, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 3, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 6, COST_OF_DISBAND: 5, COST_OF_PLUNDER: 4, DEFENSE_BONUS: 18, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 170, G: 0, B: 255 }, { Name: "Laicism", Extra_Tag: "4", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.55, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 0, B: 155 }, { Name: "Liberalism", Extra_Tag: "5", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.1, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 0, B: 0 }, { Name: "Nationalism", Extra_Tag: "6", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 0.7, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.8, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 55, B: 0 }, { Name: "Oligarchy", Extra_Tag: "7", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.9, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 155, B: 0 }, { Name: "Theocratism", Extra_Tag: "8", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 2.6, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.3, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 13, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 255, B: 0 }, { Name: "Tribal", Extra_Tag: "t", GOV_GROUP_ID: 3, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 100.0, INCOME_TAXATION: 0.5, INCOME_PRODUCTION: 0.5, MILITARY_UPKEEP: 0.5, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 5, COST_OF_DISBAND: 5, COST_OF_PLUNDER: 5, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: 1, CIVILIZE_TECH_LEVEL: 0.35f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 255, B: 255 }, { Name: "Rebels", Extra_Tag: "zsuyt", GOV_GROUP_ID: 4, ACCEPTABLE_TAXATION: 0.1, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 25.0, INCOME_TAXATION: 0.1, INCOME_PRODUCTION: 0.1, MILITARY_UPKEEP: 0.1, ADMINISTRATION_COST: 1.00, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 1, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 1, COST_OF_DISBAND: 1, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 30, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: true, AI_TYPE: "REBELS", R: 55, G: 55, B: 55 }, ], Age_of_Civilizations: Governments }
09f05fbb736a4d3422b6fb599b0ad4ed
{ "intermediate": 0.2861056625843048, "beginner": 0.3998996615409851, "expert": 0.3139946460723877 }
33,673
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Media.Media3D; using System.Windows.Threading; namespace lab12origami { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> /// public partial class MainWindow : Window { RotateTransform3D rotate0; AxisAngleRotation3D axis0; Transform3DGroup gr0; DispatcherTimer timer = new DispatcherTimer(); public MainWindow() { InitializeComponent(); } public void Window_Loaded(object sender, EventArgs e) { gr0 = new Transform3DGroup(); rotate0 = new RotateTransform3D(); axis0 = new AxisAngleRotation3D(); rotate0.CenterX = 0; rotate0.CenterY = 0.5; rotate0.CenterZ = 0.5; rotate0.Rotation = axis0; axis0.Axis = new Vector3D(0, 1, 0); axis0.Angle = 0; MyModel1.Transform = gr0; MyModel2.Transform = gr0; gr0.Children.Add(rotate0); timer.Tick += new EventHandler(timer_tick); } public void button1_Click(object sender, EventArgs e) { timer.Start(); timer.Interval = new TimeSpan(10000); } public void timer_tick(object o, EventArgs e) { if (axis0.Angle < 45) { axis0.Angle += 1; if (axis0.Angle >= 45) { axis0.Angle += -1; } } } } } Помоги реализовать возвращение крылышка
f94262ef127b9ee572669380fccfc33c
{ "intermediate": 0.3498934507369995, "beginner": 0.4632391035556793, "expert": 0.18686747550964355 }
33,674
Write a C++ program. Create a dynamic array of structs (a customer or a student struct). The atributes are provied by user. Create a function that then prints the array. Create a function which searches for a key in the array's elements
fc0fac4f4b7a50252eb09de86afb5d81
{ "intermediate": 0.23022852838039398, "beginner": 0.5875499844551086, "expert": 0.18222156167030334 }
33,675
5, 2, 7 --- 11, 6, 1, 4 --- 32, 7,2,9 --- 31
6bb6cf0bb9b511f852427e5e5514f8e7
{ "intermediate": 0.32973209023475647, "beginner": 0.3571251332759857, "expert": 0.3131427764892578 }
33,676
Write a Java program to accomplish the following tasks. Task 1: Prompt the user to enter an integer from 1 up to 100 (including 100) The following incorrect inputs are needed to be handled and different error messages should be printed: Out of range and Not an integer If the user failed in entering a correct integer, let the user retry until a correct integer is entered Let n to be the integer of the user input, print n Task 2: Generated n random numbers (integers) where the range of the integers is [0~20] Stored the numbers into a List in descending order (From largest to smallest) Print the List Task 3: Use the numbers in the List as the key of an entry and use the amount of the duplication of this number as the value and add(put) the entry into a Map The keys in the Map should be stored in descending order (The same order as the List) Print the Map
28fc7355246b3404bdaafe6e1385e30a
{ "intermediate": 0.539362370967865, "beginner": 0.13105075061321259, "expert": 0.3295868933200836 }
33,677
请解释以下代码:class Batch: """Object for holding a batch of data with mask during training.""" def __init__(self, src, tgt=None, pad=2): # 2 = <blank> self.src = src self.src_mask = (src != pad).unsqueeze(-2) if tgt is not None: self.tgt = tgt[:, :-1] self.tgt_y = tgt[:, 1:] self.tgt_mask = self.make_std_mask(self.tgt, pad) self.ntokens = (self.tgt_y != pad).data.sum() @staticmethod def make_std_mask(tgt, pad): "Create a mask to hide padding and future words." tgt_mask = (tgt != pad).unsqueeze(-2) tgt_mask = tgt_mask & subsequent_mask(tgt.size(-1)).type_as( tgt_mask.data ) return tgt_mask
93c4612e281800b75a4b60940e03211f
{ "intermediate": 0.4098006784915924, "beginner": 0.41237032413482666, "expert": 0.17782895267009735 }
33,678
make me a coffee shop website using html, css, javascript. put everything that is necessary and make it look really good and aesthetically pleasing
08b96c0ebfba054acc8d2c0cd2f17214
{ "intermediate": 0.4639855921268463, "beginner": 0.24443911015987396, "expert": 0.29157528281211853 }
33,679
describe various features of C programming language
d4548d5ccf163497af49d1c57e0a5617
{ "intermediate": 0.3283047080039978, "beginner": 0.5850731730461121, "expert": 0.08662207424640656 }
33,680
Give me code for apb protocol in sv
85bd47126a187bb56055d40b04704877
{ "intermediate": 0.38213157653808594, "beginner": 0.15784293413162231, "expert": 0.46002545952796936 }
33,681
https://github.com/aefernandes/vscode-clipboard-history-extension/ how this plugin works
fe77826ea9b4cadd5ce1aa44f0b8564a
{ "intermediate": 0.40077918767929077, "beginner": 0.2787614166736603, "expert": 0.3204593360424042 }
33,682
package gtanks.system.dailybonus; import gtanks.lobby.LobbyManager; import gtanks.main.database.DatabaseManager; import gtanks.main.database.impl.DatabaseManagerImpl; import gtanks.services.annotations.ServicesInject; import gtanks.system.dailybonus.crystalls.CrystallsBonusModel; import gtanks.system.dailybonus.ui.DailyBonusUIModel; import gtanks.users.User; import gtanks.users.garage.Garage; import gtanks.users.garage.GarageItemsLoader; import gtanks.users.garage.items.Item; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; public class DailyBonusService { private static final DailyBonusService instance = new DailyBonusService(); @ServicesInject( target = DatabaseManager.class ) private static final DatabaseManager databaseManager = DatabaseManagerImpl.instance(); public static final String[] SUPPLIES_IDS = new String[]{"armor", "double_damage", "n2o"}; private static Map<LobbyManager, DailyBonusService.Data> waitingUsers = new HashMap(); private static DailyBonusUIModel uiModel = new DailyBonusUIModel(); private static CrystallsBonusModel crystallsBonus = new CrystallsBonusModel(); private static Random random = new Random(); public static DailyBonusService instance() { return instance; } private DailyBonusService() { } public void userInited(LobbyManager lobby) { User user = lobby.getLocalUser(); if (user.getRang() + 1 > 2 && this.canGetBonus(user)) { int fund = (int)(((double)(user.getRang() + 1) - 1.75D) * 2.4D) * 5; if (fund > 0) { DailyBonusService.Data bonusData = new DailyBonusService.Data(); List<BonusListItem> bonusList = bonusData.bonusList; int rankFirstAid = ((Item)GarageItemsLoader.items.get("health")).rankId; int itemCrystalPrice = ((Item)GarageItemsLoader.items.get("health")).price; int countFirstAid = fund / itemCrystalPrice / 2; itemCrystalPrice = ((Item)GarageItemsLoader.items.get("mine")).price; int countMine = fund / itemCrystalPrice / 2; int rankMine = ((Item)GarageItemsLoader.items.get("mine")).rankId; if ((double)random.nextFloat() < 0.1D) { bonusData.type = 1; } else { bonusData.type = 3; int count; int price; Item bonus; int nextInt; if ((double)random.nextFloat() < 0.3D && countFirstAid > 0 && user.getRang() >= rankFirstAid) { bonus = (Item)GarageItemsLoader.items.get("health"); price = bonus.price; count = fund / price / 2 + 1; } else if ((double)random.nextFloat() < 0.3D && countMine > 0 && user.getRang() >= rankMine) { bonus = (Item)GarageItemsLoader.items.get("mine"); price = bonus.price; count = fund / price / 2 + 1; } else { nextInt = random.nextInt(3); bonus = (Item)GarageItemsLoader.items.get(SUPPLIES_IDS[nextInt]); price = bonus.price; count = fund / price / 2; } bonusList.add(new BonusListItem(bonus, count)); fund -= price * count; nextInt = random.nextInt(3); bonus = (Item)GarageItemsLoader.items.get(SUPPLIES_IDS[nextInt]); price = bonus.price; if (((BonusListItem)bonusList.get(0)).getBonus().equals(bonus)) { ((BonusListItem)bonusList.get(0)).addCount(fund / price); } else { bonusList.add(new BonusListItem(bonus, fund / price)); } } waitingUsers.put(lobby, bonusData); Garage garage = user.getGarage(); BonusListItem item; Item bonusItem; for(Iterator var17 = bonusList.iterator(); var17.hasNext(); bonusItem.count += item.getCount()) { item = (BonusListItem)var17.next(); bonusItem = garage.getItemById(item.getBonus().id); if (bonusItem == null) { bonusItem = ((Item)GarageItemsLoader.items.get(item.getBonus().id)).clone(); garage.items.add(bonusItem); } } garage.parseJSONData(); databaseManager.update(garage); } } } public void userLoaded(LobbyManager lobby) { DailyBonusService.Data data = (DailyBonusService.Data)waitingUsers.get(lobby); if (data != null) { if (data.type == 1) { crystallsBonus.applyBonus(lobby); uiModel.showCrystalls(lobby, crystallsBonus.getBonus(lobby.getLocalUser().getRang())); } else if (data.type == 3) { uiModel.showBonuses(lobby, data.bonusList); } waitingUsers.remove(lobby); this.saveLastDate(lobby.getLocalUser()); } } public boolean canGetBonus(User user) { if (user == null) { return false; } else { boolean result = false; Date lastDate = user.getLastIssueBonus(); Date now = new Date(System.currentTimeMillis() - 14400000L); Calendar nowCal = Calendar.getInstance(); nowCal.setTime(now); Calendar lastCal = Calendar.getInstance(); if (lastDate != null) { lastCal.setTime(lastDate); } if (lastDate == null || nowCal.get(5) > lastCal.get(5) || nowCal.get(2) > lastCal.get(2)) { result = true; } return result; } } private void saveLastDate(User user) { Date now = new Date(System.currentTimeMillis() - 14400000L); user.setLastIssueBonus(now); databaseManager.update(user); } private class Data { public int type = 0; public List<BonusListItem> bonusList = new ArrayList(); public Data() { } } } как сюда добавить 2 предмета double_crystalls с 0.6D, а no_supplies с 0.7D, чтобы выдавались в ежедвневной награде в количестве 1 штуки
89f1607be4ad0a409ea479ae96269add
{ "intermediate": 0.31398874521255493, "beginner": 0.4652617275714874, "expert": 0.22074945271015167 }
33,683
ComponentActivity.dispatchKeyEvent can only be called from within the same library group prefix (referenced groupId=androidx.core with prefix androidx from groupId=Camera_scale) More... (Ctrl+F1) Inspection info:This API has been flagged with a restriction that has not been met. Examples of API restrictions: * Method can only be invoked by a subclass * Method can only be accessed from within the same library (defined by the Gradle library group id) * Method can only be accessed from tests. You can add your own API restrictions with the @RestrictTo annotation. Issue id: RestrictedApi package com.example.camera_scale import android.content.Intent import android.os.Bundle import android.provider.MediaStore import android.view.KeyEvent import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.camera_scale.ui.theme.Camera_scaleTheme class MainActivity : ComponentActivity() { private val CAMERA_REQUEST_CODE = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Camera_scaleTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } override fun dispatchKeyEvent(event: KeyEvent): Boolean { return when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN -> { if (event.action == KeyEvent.ACTION_DOWN) { capturePhoto() } true } else -> super.dispatchKeyEvent(event) } } private fun capturePhoto() { val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (callCameraIntent.resolveActivity(packageManager) != null) { startActivityForResult(callCameraIntent, CAMERA_REQUEST_CODE) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode) { CAMERA_REQUEST_CODE -> { if (resultCode == RESULT_OK && data != null) { //TODO: Handle the captured image and send it to the server } } else -> { // Unrecognized request code } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { Camera_scaleTheme { Greeting("Android") } }
89a106c863a916ce12ac4c043dd924d7
{ "intermediate": 0.3349437713623047, "beginner": 0.5207542777061462, "expert": 0.1443018913269043 }
33,684
const puppeteer = require('puppeteer-core'); const request = require('request'); const url = process.argv[2]; playVideo(url).catch(error => { console.error('Error:', error); }); async function playVideo(url) { const browser = await puppeteer.launch({ executablePath: './chrome-linux/chrome', headless: true, args: [ '--no-sandbox', '--disable-gpu', '--ignore-certificate-errors', ], }); const page = await browser.newPage(); const retryErrorConfigUrls = []; try { // Step 1: Get firstResult before loading newUrl let firstResult = 'Null'; await page.goto(url, { timeout: 60000, waitUntil: 'networkidle0', }); const firstElement = await page.$('b.api-key-text'); if (firstElement) { firstResult = await page.evaluate(element => element.textContent, firstElement); } // Step 2: Get the current page URL const currentUrl = page.url(); // Step 3: Create a new URL by replacing 'UI/Dashboard' with 'api/v2.0/indexers?configured=true' const newUrl = currentUrl.replace('UI/Dashboard', 'api/v2.0/indexers?configured=true'); // Step 4: Load the new URL and get its response as pretty JSON await page.goto(newUrl, { timeout: 60000, waitUntil: 'networkidle0', }); // Step 5: Get cookies from the page const cookies = await page.cookies(); const response = await page.evaluate(() => { return JSON.parse(document.body.innerText); }); // Step 6: Filter the array to keep only elements where the value of the 'type' key contains 'private' and 'configured' is true (case-insensitive) const privateItems = response.filter(item => { const isPrivate = item.type.toLowerCase().includes('private'); const isConfigured = String(item.configured).toLowerCase() === 'true'; return isPrivate && isConfigured; }); if (privateItems.length > 0) { console.log(`\nTorznab key: ${firstResult}\n`); // Print the Torznab key only if privateItems is not zero } else { process.exit(0); // Exit the script with zero exit code as there are no private items to process } // Step 7: Modify each element to keep only the 'id' and construct the 'config_url' const finalResult = privateItems.map(item => { const { id } = item; const config_url = currentUrl.replace('UI/Dashboard', `api/v2.0/indexers/${id}/config`); return { id, config_url }; }); // Step 8: Process each config_url using request module with cookies and timeout for (const item of finalResult) { try { const configResponse = await getConfigResponseWithCookies(item.config_url, cookies); // Step 9: Parsing and filtering the response const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = item.id + ' | ' + groupedValues; console.log(prefixedGroupedValues); } catch (error) { console.log(`##${item.id} | ${item.config_url} | ${error.message}`); // Print errored URLs to stdout retryErrorConfigUrls.push(item.config_url); } } // Step 10: Retry error config_urls with increasing timeout let retryTimeout = 3000; // Initial retry timeout is 15 seconds while (retryErrorConfigUrls.length > 0 && retryTimeout <= 30000) { const retryResults = []; for (const configUrl of retryErrorConfigUrls) { try { const configResponse = await getConfigResponseWithCookies(configUrl, cookies, retryTimeout); retryResults.push({ configUrl, response: configResponse }); } catch (error) { console.log(`##Retry ${retryTimeout}ms | ${configUrl}|${error.message}`); // Print errored URLs to stdout } } // Remove successfully processed config_urls from retryErrorConfigUrls retryErrorConfigUrls.length = 0; for (const retryResult of retryResults) { const configUrl = retryResult.configUrl; const configResponse = retryResult.response; if (!configResponse.error) { // Step 11: Parsing and filtering the response (same as in Step 9) const filteredElements = configResponse.filter(element => { return ( element.type === 'inputstring' && typeof element.value !== 'boolean' && element.value !== null ); }); const groupedValues = filteredElements.map(element => element.value).join(' | '); const prefixedGroupedValues = configUrl + ' | ' + groupedValues; console.log(prefixedGroupedValues); } else { // Config url still encounters an error, add it back to retryErrorConfigUrls retryErrorConfigUrls.push(configUrl); } } retryTimeout *= 2; // Double the retry timeout for the next retry } } catch (error) { console.error('Error:', error); } finally { await browser.close(); } process.exit(0); // Exit the script with zero exit code after completing the process } function getConfigResponseWithCookies(url, cookies, timeout = 10000) { return new Promise((resolve, reject) => { const requestTimeout = setTimeout(() => { reject(new Error('HTTP request timeout')); }, timeout); request( { url, headers: { Cookie: cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; '), }, }, (error, response, body) => { clearTimeout(requestTimeout); // Clear the request timeout when the request is completed if (error) { reject(error); } else { resolve(JSON.parse(body)); } } ); }); } Convert to golang script which uses go-rod which is equivalent to puppeteer-core
68a545f14d10e22a2e873f2da73ef4e7
{ "intermediate": 0.29771605134010315, "beginner": 0.48795077204704285, "expert": 0.21433314681053162 }
33,685
напиши плагин на команду /upgrade для игроков с op, сделай чтобы при вводе команды у предмета в руке в начале названия добавлялся плюсик и число 1 по примеру "+1 деревянный меч" и за каждый ввод команды число увеличивалось на 1, максимум до 15, и скинь итоговый код
bd12a5284784029d502c5a5bc3eaa525
{ "intermediate": 0.30899858474731445, "beginner": 0.3430585563182831, "expert": 0.34794291853904724 }
33,686
Write a C++ program. Create a dynamic array of structs (a customer struct). The atributes are provied by user. Create a function that then prints the array. Create a function which searches for a key in the array's elements
3da71626bc24a1ae17d3c571e7880b14
{ "intermediate": 0.20690108835697174, "beginner": 0.6246925592422485, "expert": 0.16840630769729614 }
33,687
if (isMaxPrice) сделай чтобы здесь цикл while останавливался public void Steping() { const int SCROLL_DELAY = 1000; // Задержка между скроллингами bool endOfList = false; // Флаг для определения конца списка while (!endOfList) { while (IsPaused) { Thread.Sleep(1000); // Пауза перед проверкой состояния } Clicks(); // Выполнение кликов по элементам ScrollList(); // Скроллинг списка System.Threading.Thread.Sleep(SCROLL_DELAY); var result = ImageProcessor.CaptureAndProcessImage(); string imagePath = result.imagePath; bool isMaxPrice = result.IsMaxPrice; if (isMaxPrice) { // Вызовите специальный метод для случая максимальной цены. //SpecialClicksForMaxPrice(); } else { // Ваш обычный код для обработки изображения и ввода цены. string nPrice = GetPrice.ProcessImage(imagePath); SendKeys.SendWait(nPrice); } endOfList = CheckEndOfList(); // Проверка на достижение конца списка } ClicksEnd(); }
9378b25e9505772d1b4e56204c2bccf6
{ "intermediate": 0.2955331802368164, "beginner": 0.5605193972587585, "expert": 0.14394739270210266 }
33,688
time limit per test1 second memory limit per test64 megabytes inputstandard input outputstandard output The array a=[a1,a2,…,an] (1≤ai≤n ) is given. Its element ai is called special if there exists a pair of indices l and r (1≤l<r≤n ) such that ai=al+al+1+…+ar . In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not). Print the number of special elements of the given array a . For example, if n=9 and a=[3,1,4,1,5,9,2,6,5] , then the answer is 5 : a3=4 is a special element, since a3=4=a1+a2=3+1 ; a5=5 is a special element, since a5=5=a2+a3=1+4 ; a6=9 is a special element, since a6=9=a1+a2+a3+a4=3+1+4+1 ; a8=6 is a special element, since a8=6=a2+a3+a4=1+4+1 ; a9=5 is a special element, since a9=5=a2+a3=1+4 . Please note that some of the elements of the array a may be equal — if several elements are equal and special, then all of them should be counted in the answer. Input The first line contains an integer t (1≤t≤1000 ) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains an integer n (1≤n≤8000 ) — the length of the array a . The second line contains integers a1,a2,…,an (1≤ai≤n ). It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 8000 . Output Print t numbers — the number of special elements for each of the given arrays. code của tôi có vượt quá giới hạn bộ nhớ không : #include <bits/stdc++.h> using namespace std; int main() { int t;cin>>t; while(t--){ int ans=0; int n; cin>>n; map<int,int> doly; int a[n+1]; int pre[n+1]={0}; for(int i=1;i<=n;i++){ cin>>a[i]; } pre[1]=a[1]; for(int i=2;i<=n;i++){ pre[i]=pre[i-1]+a[i]; } for(int l=1;l<=n-1;l++){ for(int r=l+1;r<=n;r++){ doly[pre[r]-pre[l-1]]++; } } for(int i=1;i<=n;i++){ if(doly[a[i]]!=0)ans++; } cout<<ans<<endl; } return 0; }
7d12832300b8be5c4aa359ebe51389fe
{ "intermediate": 0.3057765066623688, "beginner": 0.42260363698005676, "expert": 0.2716198265552521 }
33,689
Convert this to JSON format: ### Linguistic Understanding and Generation: 1. Syntax and Grammar Analysis 2. Paraphrasing 3. Text Completion 4. Spelling and Grammar Correction 5. Translation between languages 6. Text Summarization 7. Generating Text from Keywords 8. Language Detection ### Logical and Mathematical Abilities: 9. Basic Arithmetic and Math Problem Solving 10. Advanced Mathematics (Calculus, Algebra, etc.) 11. Logical Reasoning and Puzzles 12. Data Analysis and Interpretation 13. Pattern Recognition ### Knowledge Domains: 14. General World Knowledge and Trivia 15. History and Historical Events 16. Popular Culture & Entertainment 17. Science (Physics, Chemistry, Biology) 18. Technology and Computing 19. Medicine and Healthcare 20. Law and Legal Systems 21. Geography and Travel 22. Business and Finance 23. Economics 24. Literature and Philosophy 25. Sports 26. Food and Nutrition27. Art and Art History* ### Creative and Design Thinking: 28. Creativity in Writing (e.g., Poetry, Stories) 29. Art and Music Appreciation 30. Problem Solving and Brainstorming 31. Design Suggestions (e.g., Interior Design, UI/UX) 32. Invention and Innovation Ideas ### Conversational and Social Interaction: 33. Common Sense Reasoning 34. Advice Giving 35. Emotional Intelligence and Empathy 36. Humor and Wit 37. Etiquette and Social Norms 38. Idiomatic Expressions and Slang 39. Cultural Knowledge and Sensitivity ### Specialized Domains: 40. Programming and Code Understanding 41. Cybersecurity Knowledge 42. Astronomy and Space Exploration 43. Environmental Science and Climate Change 44. Political Science and Current Affairs 45. Psychology and Mental Health 46. Education and Learning Theories 47. Automotive Knowledge 48. Religion and Spirituality 49. Agriculture and Farming ### Real-World Practical Skills: 50. How-To Guides and DIY Instructions 51. Cooking Recipes and Techniques 52. Workout and Fitness Routines 53. Personal Finance Management 54. Travel Planning and Logistics 55. Home Maintenance Tips ### Data and Information Management: 56. Information Retrieval 57. Data Extraction and Compilation 58. Indexing and Categorizing 59. Database Querying ### Decision Support and Analysis: 60. Risk Assessment 61. Strategy and Planning 62. Forecasting and Predictions 63. Product and Service Comparisons ### Accessibility: 64. Simplifying Text for Readability 65. Creating Descriptive Audio for Visual Content 66. Transcription and Captioning
4392687b68eef4e5ab731c204ddf2399
{ "intermediate": 0.26304298639297485, "beginner": 0.5000865459442139, "expert": 0.23687046766281128 }
33,690
Добавь чтобы рисовался 3d график и рядом был пограничный график import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Параметры сетки L = 1 # длина интервала по x T = 2 # время окончания интервала по t Nx = 25 # количество точек сетки по x (небольшое число для наглядности) Nt = 2500 # количество точек сетки по t dx = L / (Nx - 1) # шаг сетки по x dt = T / (Nt - 1) # шаг сетки по t D = 1 / (np.pi**2) # коэффициент диффузии # Стабильность схемы требует выполнения условия D * dt / dx^2 <= 0.5 if (D * dt / dx**2 > 0.5): raise ValueError("The scheme is unstable. Please adjust the grid parameters.") # Создаём сетку для x и t x = np.linspace(0, L, Nx) t = np.linspace(0, T, Nt) # Инициализируем массив u для значений концентрации u = np.zeros((Nt, Nx)) # Начальные условия u(x,0) = sin(pi * x) u[0, :] = np.sin(np.pi * x) # Применяем явный метод конечных разностей for k in range(0, Nt - 1): for i in range(1, Nx - 1): u[k+1, i] = u[k, i] + D * dt / dx**2 * (u[k, i-1] - 2*u[k, i] + u[k, i+1]) # Граничное условие Neumann в x=L u[k+1, -1] = u[k+1, -2] - np.pi * np.exp(-t[k+1]) * dx # Отрисовка начального и конечного распределений plt.plot(x, u[0, :], label='t=0') plt.plot(x, u[-1, :], label=f't={T}') plt.title('Concentration Profile Over Time') plt.xlabel('Position x') plt.ylabel('Concentration u(x,t)') plt.legend() plt.show()
7720ee4d9fa76992b7d61af94c116f19
{ "intermediate": 0.2670689523220062, "beginner": 0.5271081328392029, "expert": 0.2058228999376297 }
33,691
Hi
092f5cf86c57470c60823c5c527cdfc5
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
33,692
public function addMessage(clientObject:ClientObject, userId:Long, message:String, _arg_4:BattleTeamType, teamOnly:Boolean, nick:String=null, rank:int=0):void { var messageLabel:String = (((!(_arg_4 == BattleTeamType.NONE)) && (teamOnly)) ? "[TEAM]" : null); var userName:String = nick; var userRank:int = rank; this.battleChat.addUserMessage(messageLabel, userName, userRank, _arg_4, (message + "\n")); } как сделать чтобы когда был BattleTeamType.RED цвет сообщения был красный, а когда BattleTeamType.BLUE то синий
72f3d33430b5987db8609efcfcb62121
{ "intermediate": 0.32465803623199463, "beginner": 0.3977133333683014, "expert": 0.2776285707950592 }
33,693
public function addMessage(clientObject:ClientObject, userId:Long, message:String, _arg_4:BattleTeamType, teamOnly:Boolean, nick:String=null, rank:int=0):void { var messageLabel:String = (((!(_arg_4 == BattleTeamType.NONE)) && (teamOnly)) ? “[TEAM]” : null); var userName:String = nick; var userRank:int = rank; this.battleChat.addUserMessage(messageLabel, userName, userRank, _arg_4, (message + “\n”)); } как сделать чтобы когда был BattleTeamType.RED цвет сообщения был красный, а когда BattleTeamType.BLUE то синий
d3f015e98ae04fd7e3db6356a3b8305f
{ "intermediate": 0.3325815200805664, "beginner": 0.3781682848930359, "expert": 0.2892502248287201 }
33,694
How to use Web scraping for get answers for the quastions in the test?
95cd003538987d6802b99f7174e51a8b
{ "intermediate": 0.26825693249702454, "beginner": 0.29290086030960083, "expert": 0.43884217739105225 }
33,695
Write me extension.ts for vs code, which will consist of extension.ts and package.json files. In extension.ts write the following functionality: I want that at 11 o’clock in the evening there will be a reminder to go to bed with a sound signal and the corresponding message “It’s time to go to bed” and vs code will block all its functionality
bb6ece014a39a6e6c4d2e415680b09dd
{ "intermediate": 0.48698827624320984, "beginner": 0.18778373301029205, "expert": 0.3252280056476593 }
33,696
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Palace d'Or - Italian Food Menu</title> <style> /* Add your CSS styling here */ /* This is just a placeholder for demonstration purposes */ body { font-family: Arial, sans-serif; background-color: #f6f6f6; margin: 0; padding: 0; } header { background-color: #333; color: #fff; text-align: center; padding: 1em; } section { margin: 2em; } h2 { color: #333; } .menu-item { margin-bottom: 1em; } </style> </head> <body> <header> <h1>Palace d'Or - Italian Food Menu</h1> </header> <section> <h2>Antipasti (Appetizers)</h2> <div class="menu-item"> <h3>Bruschetta</h3> <p>Grilled bread topped with fresh tomatoes, garlic, basil, and olive oil.</p> </div> <div class="menu-item"> <h3>Caprese Salad</h3> <p>Slices of fresh mozzarella, tomatoes, and basil, seasoned with salt, and olive oil.</p> </div> <div class="menu-item"> <h3>Arancini</h3> <p>Golden fried risotto balls with a gooey mozzarella center, served with marinara sauce.</p> </div> </section> <section> <h2>Pasta</h2> <div class="menu-item"> <h3>Spaghetti Carbonara</h3> <p>Pasta with eggs, cheese, pancetta, and black pepper.</p> </div> <div class="menu-item"> <h3>Lasagna</h3> <p>Baked pasta dish made with layers of pasta, meat, cheese, and tomato sauce.</p> </div> <div class="menu-item"> <h3>Ravioli</h3> <p>Homemade ravioli filled with ricotta and spinach, served with marinara or Alfredo sauce.</p> </div> </section> <section> <h2>Main Courses</h2> <div class="menu-item"> <h3>Chicken Parmigiana</h3> <p>Breaded chicken topped with marinara sauce and melted mozzarella cheese, served with spaghetti.</p> </div> <div class="menu-item"> <h3>Osso Buco</h3> <p>Braised veal shanks with vegetables, white wine, and broth, served with gremolata.</p> </div> <div class="menu-item"> <h3>Gnocchi Sorrentina</h3> <p>Potato gnocchi with tomato sauce, mozzarella, and basil, baked to perfection.</p> </div> </section> <section> <h2>Desserts</h2> <div class="menu-item"> <h3>Tiramisu</h3> <p>A classic Italian dessert made with layers of coffee-soaked ladyfingers and mascarpone cheese.</p> </div> <div class="menu-item"> <h3>Cannoli</h3> <p>Crispy pastry tubes filled with sweetened ricotta and chocolate chips, dusted with powdered sugar.</p> </div> <div class="menu-item"> <h3>Panna Cotta</h3> <p>Silky-smooth Italian dessert made with sweetened cream and topped with fruit compote.</p> </div> </section> </body> </html>
83be738404c863d163c368760ba8a34b
{ "intermediate": 0.3797852098941803, "beginner": 0.48156216740608215, "expert": 0.13865260779857635 }
33,697
write this in kivy instead: package com.example.camera_scale import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.provider.MediaStore import android.view.KeyEvent import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.ActivityResultLauncher import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.core.content.ContextCompat import com.example.camera_scale.ui.theme.Camera_scaleTheme class MainActivity : ComponentActivity() { private val CAMERA_PERMISSION_REQUEST_CODE = 1 private lateinit var cameraResultLauncher: ActivityResultLauncher<Intent> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) cameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK && result.data != null) { //TODO: Handle the captured image and send it to the server } } setContent { Camera_scaleTheme { // A surface container using the ‘background’ color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } private fun handleVolumeKeys(event: KeyEvent): Boolean { return when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN -> { if (event.action == KeyEvent.ACTION_DOWN) { takePhotoIfPermissionGranted() } true } else -> false } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (handleVolumeKeys(event)) { return true } return super.onKeyDown(keyCode, event) } private fun takePhotoIfPermissionGranted() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { capturePhoto() } else { requestCameraPermission() } } private fun requestCameraPermission() { requestPermissions(arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE) } private fun capturePhoto() { val callCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (callCameraIntent.resolveActivity(packageManager) != null) { cameraResultLauncher.launch(callCameraIntent) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { capturePhoto() } else { // Handle the user’s denial of permission } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } @Preview(showBackground = true) @Composable fun GreetingPreview() { Camera_scaleTheme { Greeting("Android") } }
7cd2d3f3e86dab1b068d7fa78813cdd7
{ "intermediate": 0.2642154097557068, "beginner": 0.5051220655441284, "expert": 0.2306625097990036 }
33,698
hello
ce981c32dcf803ca91938915648e1f93
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
33,699
create me the best result for a menu in html make it look good in the result not only the code please understand that make it like the real menu
7327839f29f4bef293aa1b1d92a3eb40
{ "intermediate": 0.30880191922187805, "beginner": 0.15771476924419403, "expert": 0.5334832668304443 }
33,701
what you version
c799e406a272e23099edf5bd719f4dae
{ "intermediate": 0.32952001690864563, "beginner": 0.37566614151000977, "expert": 0.2948139011859894 }
33,702
DEBUG]: -> running python3 -c import sys; print(sys.path) [DEBUG]: ['', '/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/Lib', '/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/Lib/site-packages', '/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/build/lib.linux-x86_64-3.10', '/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/build/scripts-3.10', '/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/build/temp.linux-x86_64-3.10', '/usr/local/lib/python310.zip', '/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/Lib'] [DEBUG]: cwd is /home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius [INFO]: Trying first build of pyjnius to get cython files: this is expected to fail [DEBUG]: -> running python3 setup.py build_ext -v [DEBUG]: warning: [options] bootstrap class path not set in conjunction with -source 7 [DEBUG]: error: Source option 7 is no longer supported. Use 8 or later. [DEBUG]: error: Target option 7 is no longer supported. Use 8 or later. [DEBUG]: Traceback (most recent call last): [DEBUG]: File "/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/setup.py", line 83, in <module> [DEBUG]: compile_native_invocation_handler(JAVA) [DEBUG]: File "/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/setup.py", line 73, in compile_native_invocation_handler [DEBUG]: subprocess.check_call([ [DEBUG]: File "/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/Lib/subprocess.py", line 369, in check_call [DEBUG]: raise CalledProcessError(retcode, cmd) [DEBUG]: subprocess.CalledProcessError: Command '['/usr/lib/jvm/jdk-21-oracle-x64/bin/javac', '-target', '1.7', '-source', '1.7', 'jnius/src/org/jnius/NativeInvocationHandler.java']' returned non-zero exit status 2. Exception in thread background thread for pid 104306: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 1641, in wrap fn(*rgs, **kwargs) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 2569, in background_thread handle_exit_code(exit_code) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 2269, in fn return self.command.handle_command_exit_code(exit_code) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 869, in handle_command_exit_code raise exc sh.ErrorReturnCode_1: RAN: /home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/native-build/python3 setup.py build_ext -v STDOUT: warning: [options] bootstrap class path not set in conjunction with -source 7 error: Source option 7 is no longer supported. Use 8 or later. error: Target option 7 is no longer supported. Use 8 or later. Traceback (most recent call last): File "/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/setup.py", line 83, in <module> compile_native_invocation_handler(JAVA) File "/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/setup.py", line 73, in compile_native_invocation_handler subprocess.check_call([ File "/home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/hostpython3/desktop/hostpython3/Lib/subprocess.py", line 369, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/usr/lib/jvm/jdk-21-oracle-x64/bin/javac', '-target', '1.7', '-source', '1.7', 'jnius/src/org/jnius/NativeInvocationHandler.java']' returned non-zero exit status 2. STDERR: [INFO]: pyjnius first build failed (as expected) [INFO]: Running cython where appropriate [INFO]: Cythonize jnius/jnius.pyx [DEBUG]: -> running python3 -cimport sys; from Cython.Compiler.Main import setuptools_main; sys.exit(setuptools_main()); ./jnius/jnius.pyx [DEBUG]: /home/rickard/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/jnius/jnius.pyx [DEBUG]: tree = Parsing.p_module(s, pxd, full_module_name) [DEBUG]: [DEBUG]: Error compiling Cython file: [DEBUG]: ------------------------------------------------------------ [DEBUG]: ... [DEBUG]: import sys [DEBUG]: import traceback [DEBUG]: [DEBUG]: include "jnius_compat.pxi" [DEBUG]: include "jni.pxi" [DEBUG]: include "config.pxi" [DEBUG]: ^ [DEBUG]: ------------------------------------------------------------ [DEBUG]: [DEBUG]: jnius/jnius.pyx:100:0: 'config.pxi' not found [DEBUG]: warning: jnius/jnius.pyx:102:0: The 'IF' statement is deprecated and will be removed in a future Cython version. Consider using runtime conditions or C macros instead. See https://github.com/cython/cython/issues/4310 [DEBUG]: [DEBUG]: Error compiling Cython file: [DEBUG]: ------------------------------------------------------------ [DEBUG]: ... [DEBUG]: [DEBUG]: include "jnius_compat.pxi" [DEBUG]: include "jni.pxi" [DEBUG]: include "config.pxi" [DEBUG]: [DEBUG]: IF JNIUS_PLATFORM == "android": [DEBUG]: ^ [DEBUG]: ------------------------------------------------------------ [DEBUG]: [DEBUG]: jnius/jnius.pyx:102:3: Compile-time name 'JNIUS_PLATFORM' not defined [DEBUG]: [DEBUG]: Error compiling Cython file: [DEBUG]: ------------------------------------------------------------ [DEBUG]: ... [DEBUG]: include "jni.pxi" [DEBUG]: include "config.pxi" [DEBUG]: [DEBUG]: IF JNIUS_PLATFORM == "android": [DEBUG]: include "jnius_jvm_android.pxi" [DEBUG]: ELIF JNIUS_PLATFORM == "win32": [DEBUG]: ^ [DEBUG]: ------------------------------------------------------------ [DEBUG]: [DEBUG]: jnius/jnius.pyx:104:5: Compile-time name 'JNIUS_PLATFORM' not defined [DEBUG]: [DEBUG]: Error compiling Cython file: [DEBUG]: ------------------------------------------------------------ [DEBUG]: ... [DEBUG]: include "config.pxi" [DEBUG]: ^ [DEBUG]: ------------------------------------------------------------ [DEBUG]: [DEBUG]: jnius/jnius_jvm_dlopen.pxi:1:0: 'config.pxi' not found [DEBUG]: Exception in thread background thread for pid 104345: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 1641, in wrap fn(*rgs, **kwargs) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 2569, in background_thread handle_exit_code(exit_code) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 2269, in fn return self.command.handle_command_exit_code(exit_code) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 869, in handle_command_exit_code raise exc sh.ErrorReturnCode_1: RAN: /usr/bin/python3 '-cimport sys; from Cython.Compiler.Main import setuptools_main; sys.exit(setuptools_main());' ./jnius/jnius.pyx STDOUT: /home/rickard/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/jnius/jnius.pyx tree = Parsing.p_module(s, pxd, full_module_name) Error compiling Cython file: ------------------------------------------------------------ ... import sys import traceback include "jnius_compat.pxi" include "jni.pxi" include "config.pxi" ^ ------------------------------------------------------------ jnius/jnius.pyx:100:0: 'config.pxi' not found warning: jnius/jnius.pyx:102:0: The 'IF' statement is deprecated and will be removed in a future Cython version. Consider using runtime conditions or C macros instead. See https://github.com/cython/cython/issues/4310 Error compiling Cython file: ------------------------------------------------------------ ... include "jnius_compat.pxi" include "jni.pxi" include "config.pxi" IF JNIUS_PLATFORM == "android": ^ ------------------------------------------------------------ jnius/jnius.pyx:102:3: Compile-time name 'JNIUS_PLATFORM' not defined Error compiling Cython file: ------------------------------------------------------------ ... include "jni.pxi" include "config.pxi" IF JNIUS_PLATFORM == "android": include "jnius_jvm_android.pxi" ELIF JNIUS_PLATFORM == "win32": ^ ------------------------------------------------------------ jnius/jnius.pyx:104:5: Compile-time name 'JNIUS_PLATFORM' not defined Error compiling Cython file: ------------------------------------------------------------ ... include "config.pxi" ^ ------------------------------------------------------------ jnius/jnius_jvm_dlopen.pxi:1:0: 'config.pxi' not found STDERR: Traceback (most recent call last): File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 1262, in <module> main() File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/entrypoints.py", line 18, in main ToolchainCL() File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 680, in __init__ getattr(self, command)(args) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 99, in wrapper_func build_dist_from_args(ctx, dist, args) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/toolchain.py", line 158, in build_dist_from_args build_recipes(build_order, python_modules, ctx, File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/build.py", line 504, in build_recipes recipe.build_arch(arch) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py", line 1028, in build_arch self.build_cython_components(arch) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py", line 1053, in build_cython_components self.cythonize_build(env=env) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py", line 1101, in cythonize_build self.cythonize_file(env, build_dir, join(root, filename)) File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/recipe.py", line 1090, in cythonize_file shprint(python_command, "-c" File "/home/rickard/Documents/android_app/.buildozer/android/platform/python-for-android/pythonforandroid/logger.py", line 167, in shprint for line in output: File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 915, in next self.wait() File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 845, in wait self.handle_command_exit_code(exit_code) File "/home/rickard/.local/lib/python3.10/site-packages/sh.py", line 869, in handle_command_exit_code raise exc sh.ErrorReturnCode_1: RAN: /usr/bin/python3 '-cimport sys; from Cython.Compiler.Main import setuptools_main; sys.exit(setuptools_main());' ./jnius/jnius.pyx STDOUT: /home/rickard/.local/lib/python3.10/site-packages/Cython/Compiler/Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: /home/rickard/Documents/android_app/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other_builds/pyjnius-sdl2/arm64-v8a__ndk_target_21/pyjnius/jnius/jnius.pyx tree = Parsing.p_module(s, pxd, full_module_name) Error compiling Cython file: ------------------------------------------------------------ ... import sys import traceback include "jnius_compat.pxi" include "jni.pxi" include "config.pxi" ^ ------------------------------------------------------------ jnius/jnius.pyx:100:0: 'config.pxi' not found warning: jnius/jnius.pyx:102:0: The 'IF' statement is deprecated and will be removed in a future Cython version. Consider using runtime conditions or C macros instead. See https://github.com/cython/cython/issues/4310 Error compiling Cython file: ------------------------------------------------------------ ... include "jnius_compat.pxi" include "jni.pxi" include "config.pxi" IF JNIUS_PLATFORM == "android": ^ ------------------------------------------------------------ jnius/jnius.pyx:102:3: Compile-time name 'JNIUS_PLATFORM' not defined Error compiling Cython file: ------------------------------------------------------------ ... include "jni.pxi" include "config.pxi" IF JNIUS_PLATFORM == "android": include "jnius_jvm_android.pxi" ELIF JNIUS_PLATFORM == "win32": ^ ------------------------------------------------------------ jnius/jnius.pyx:104:5: Compile-time name 'JNIUS_PLATFORM' not defined Error compiling Cython file: ------------------------------------------------------------ ... include "config.pxi" ^ ------------------------------------------------------------ jnius/jnius_jvm_dlopen.pxi:1:0: 'config.pxi' not found STDERR:
e803261daf23014a4c958e4a6439fec8
{ "intermediate": 0.44665253162384033, "beginner": 0.41425400972366333, "expert": 0.13909341394901276 }
33,703
dsharpplus slash commands
43e6ccaaec1bb5dc638feb4514c5670c
{ "intermediate": 0.3523368835449219, "beginner": 0.29886263608932495, "expert": 0.3488004505634308 }
33,704
edit this code: package com.example.camera_scale import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.ImageFormat import android.graphics.SurfaceTexture import android.hardware.camera2.* import android.media.ImageReader import android.os.Bundle import android.util.SparseIntArray import android.view.TextureView import android.view.SurfaceView import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.ActivityResultLauncher import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.tooling.preview.Preview import androidx.core.content.ContextCompat import com.example.camera_scale.ui.theme.Camera_scaleTheme class MainActivity : ComponentActivity() { private val CAMERA_PERMISSION_REQUEST_CODE = 0 private lateinit var cameraManager: CameraManager private lateinit var cameraId: String private lateinit var imageReader: ImageReader private lateinit var cameraDevice: CameraDevice private lateinit var cameraCaptureSession: CameraCaptureSession private lateinit var textureView: TextureView private var image: MutableState<Bitmap?> = mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) textureView = TextureView(this) textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) { openCamera() } override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean { return true } override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {} } setContent { Camera_scaleTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column { Greeting("Android") image.value?.let { Image(bitmap = it.asImageBitmap(), contentDescription = null) } } } } } } private fun openCamera() { cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraId = getCameraId() imageReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 1) imageReader.setOnImageAvailableListener(onImageAvailableListener, null) val cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId) val streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) val previewSize = streamConfigurationMap!!.getOutputSizes(SurfaceTexture::class.java)[0] val previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) previewRequestBuilder.addTarget(Surface(textureView.surfaceTexture)) cameraDevice.createCaptureSession(listOf(Surface(textureView.surfaceTexture)), object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { cameraCaptureSession = session cameraCaptureSession.setRepeatingRequest(previewRequestBuilder.build(), null, null) } override fun onConfigureFailed(session: CameraCaptureSession) {} }, null) } private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() image.close() } private fun getCameraId(): String { val cameraIds = cameraManager.cameraIdList for (id in cameraIds) { val cameraCharacteristics = cameraManager.getCameraCharacteristics(id) if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) { return id } } return "" } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } @Preview(showBackground = true) @Composable fun GreetingPreview() { Camera_scaleTheme { Greeting("Android") } } } to implement this: import android.hardware.camera2.* import android.media.ImageReader import android.util.SparseIntArray import android.view.Surface // ... other imports class MainActivity : AppCompatActivity() { private lateinit var cameraManager: CameraManager private lateinit var cameraId: String private lateinit var imageReader: ImageReader private lateinit var cameraDevice: CameraDevice private lateinit var cameraCaptureSession: CameraCaptureSession override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... other onCreate code cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraId = getCameraId() imageReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 1) imageReader.setOnImageAvailableListener(onImageAvailableListener, backgroundHandler) } private fun getCameraId(): String { val cameraIds = cameraManager.cameraIdList for (id in cameraIds) { val cameraCharacteristics = cameraManager.getCameraCharacteristics(id) if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) { return id } } return "" } private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() // Handle image data here image.close() } private val cameraStateCallback = object : CameraDevice.StateCallback() { override fun onOpened(camera: CameraDevice) { cameraDevice = camera startPreview() } override fun onDisconnected(cameraDevice: CameraDevice) { cameraDevice.close() } override fun onError(cameraDevice: CameraDevice, error: Int) { cameraDevice.close() } } private val captureStateCallback = object : CameraCaptureSession.StateCallback() { override fun onConfigureFailed(session: CameraCaptureSession) {} override fun onConfigured(session: CameraCaptureSession) { cameraCaptureSession = session } } private fun startPreview() { val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) captureRequestBuilder.addTarget(imageReader.surface) cameraDevice.createCaptureSession(listOf(imageReader.surface), captureStateCallback, null) } private fun takePhoto() { val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) captureRequestBuilder.addTarget(imageReader.surface) val rotation = windowManager.defaultDisplay.rotation captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation)) cameraCaptureSession.capture(captureRequestBuilder.build(), null, null) } companion object { private val ORIENTATIONS = SparseIntArray().apply { append(Surface.ROTATION_0, 0) append(Surface.ROTATION_90, 90) append(Surface.ROTATION_180, 180) append(Surface.ROTATION_270, 270) } } }
277bbea334a375e2c1c3007aba8ea36f
{ "intermediate": 0.41637343168258667, "beginner": 0.39406317472457886, "expert": 0.18956336379051208 }
33,705
Write a python script to build a local version of you on a raspberry pi
53ef74ca91a260858926fdc453828d77
{ "intermediate": 0.3234978914260864, "beginner": 0.2185257226228714, "expert": 0.4579763114452362 }
33,706
-2147467259 error in excel
bd31e40a4615a07459203c407601c295
{ "intermediate": 0.2969083786010742, "beginner": 0.4551369547843933, "expert": 0.24795465171337128 }
33,707
Write the python code for this programn that a year 9 student could understand The program should: The teacher should be able to enter their password and username If right then they can start to enter values If it is wrong make them enter again The teacher should be able to enter three values respective to their topic and the student’s name. Once they have entered all of the values they will get a question asking them if they have entered all the student’s scores. If they say ‘yes’ then give them the class average by adding up all the score and dividing by number of students If they say ‘no’ then repeat the paragraph before
36376ed700f745207dfc2b6cdac46a72
{ "intermediate": 0.3316706717014313, "beginner": 0.36495497822761536, "expert": 0.30337435007095337 }
33,708
previewRequestBuilder.addTarget(Surface(textureView.surfaceTexture)) cameraDevice.createCaptureSession(listOf(Surface(textureView.surfaceTexture)), object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { cameraCaptureSession = session cameraCaptureSession.setRepeatingRequest(previewRequestBuilder.build(), null, null) } None of the following functions can be called with the arguments supplied. Surface(() → Unit, Modifier = ..., Boolean = ..., Shape = ..., Color = ..., Color = ..., Dp = ..., Dp = ..., BorderStroke? = ..., MutableInteractionSource = ..., () → Unit) defined in androidx.compose.material3 Surface(Modifier = ..., Shape = ..., Color = ..., Color = ..., Dp = ..., Dp = ..., BorderStroke? = ..., () → Unit) defined in androidx.compose.material3 Surface(Boolean, () → Unit, Modifier = ..., Boolean = ..., Shape = ..., Color = ..., Color = ..., Dp = ..., Dp = ..., BorderStroke? = ..., MutableInteractionSource = ..., () → Unit) defined in androidx.compose.material3 Surface(Boolean, (Boolean) → Unit, Modifier = ..., Boolean = ..., Shape = ..., Color = ..., Color = ..., Dp = ..., Dp = ..., BorderStroke? = ..., MutableInteractionSource = ..., () → Unit) defined in androidx.compose.material3
d487b82376c952b84f949c52405fef93
{ "intermediate": 0.30968379974365234, "beginner": 0.3677319586277008, "expert": 0.32258427143096924 }
33,709
create an AI script for a bug in Roblox studio, it should move around randomly but check for obstacles, barriers and players. model's name is "ant" and its directory is "workspace"
f95d2e1b0798731604707369e0cff5d3
{ "intermediate": 0.16656537353992462, "beginner": 0.09365948289632797, "expert": 0.7397751808166504 }
33,710
How can I print this data in a loop: {'Linguistic Understanding and Generation': {'Syntax and Grammar Analysis': {'query': "Determine the grammatical errors in the following sentence: 'She don't like the way that the curtains snaps closed.'", 'expected_outputs': ["The sentence should be corrected to: 'She doesnt like the way that the curtains snap closed.' The error was with the subject-verb agreement ('don't' should be 'doesn't') and incorrect verb form ('snaps' should be 'snap').", "'Don't' should be 'doesn't' - 'She' is a singular subject and needs a singular verb. 'Snaps' should be 'snap' since 'the way that' does not require a singular third person verb."]}, 'Paraphrasing': {'query': "Paraphrase this sentence: 'The quick brown fox jumps over the lazy dog.'", 'expected_outputs': ['A fast, brown fox leaps across a sluggish canine.', 'A speedy, auburn fox hurdles over the idle pooch.']}, 'Text Completion': {'query': "Complete the following statement with a coherent ending: 'Despite the heavy rain, the football match continued without'", 'expected_outputs': ['…any delays, as the players were determined to finish the game.', '…a hitch, and the fans cheered louder to encourage their teams through the downpour.']}, 'Spelling and Grammar Correction': {'query': "Correct the spelling and grammar mistakes in this text: 'I cannt believe thta I have one this spelling bea!'", 'expected_outputs': ["I can't believe that I have won this spelling bee!", 'I cannot believe that I have won this spelling bee!']}, 'Translation between languages': {'query': "Translate the following sentence into Spanish: 'Where is the nearest hospital?'", 'expected_outputs': ['¿Dónde está el hospital más cercano?', '¿Dónde queda el hospital más próximo?']}}, 'Logical and Mathematical Abilities': {'Basic Arithmetic and Math Problem Solving': {'query': 'If you have 5 apples and you buy 3 more apples, how many apples do you have in total?', 'expected_outputs': ['You would have 8 apples in total.', 'The total number of apples would be 8.']}, 'Advanced Mathematics': {'query': 'Find the derivative of the function f(x) = 3x^2 + 2x + 4.', 'expected_outputs': ['The derivative of the function f(x) with respect to x is f(x) = 6x + 2.', 'Differentiating the function f(x) gives you f(x) = 6x + 2.']}, 'Logical Reasoning and Puzzles': {'query': 'If all roses are flowers and some flowers fade quickly, can we conclude that some roses fade quickly?', 'expected_outputs': ['No, we cannot conclude that some roses fade quickly as we do not have specific information about roses.', "No, the statement does not logically follow because 'some' does not necessarily include roses."]}, 'Data Analysis and Interpretation': {'query': 'Given that a store sold 100 units in January, 200 units in February, and 150 units in March, was there an increase in sales in the first quarter?', 'expected_outputs': ['Yes, there was an increase in sales throughout the first quarter, as the total number of units sold increased.', 'Sales increased from January to February but then decreased in March; overall, there was an increase in the first quarter.']}, 'Pattern Recognition': {'query': 'Complete the following sequence: 2, 4, 8, 16, …', 'expected_outputs': ['The next number in the sequence is 32, as each number is double the previous one.', "32 follows in the sequence because it's a pattern of doubling the preceding number."]}}}
134adb79ea5074aa35db5826750a067b
{ "intermediate": 0.24849306046962738, "beginner": 0.5701996088027954, "expert": 0.1813073456287384 }
33,711
Figure.cpp #include "Figure.h" #include <iostream> #include <fstream> #include <map> #define _USE_MATH_DEFINES #include "math.h" #include <vector> using std::vector; //класс круг Circle::Circle(Point center, int rad, int color):Figure(color),center(center),rad(rad) {} double Circle::place() const { #ifdef DEBUG std::cerr << "In Circle::place()\n"; #endif return M_PI * rad * rad; } double Circle::perimetr() const { #ifdef DEBUG std::cerr << "In Circle::perimetr()\n"; #endif return M_PI * 2 * rad; } Figure::Point Circle::getCenter() { return center; } double Circle::getRad() { return rad; } void Circle::Print(std::ostream& stream) const { stream << "Color = " << getColor() << " CenterX = "; } void Circle::readinFile(std::ostream& stream) { int x = getCenter().x; int y = getCenter().y; stream << "CIRCLE\n" << "Color = " << getColor() << "\n" << " CenterX = " << x << "\n" << " Center y" << y; } std::string Circle::writeinFile(std::ifstream& stream) { std::string line; while (stream >> line) { // Считывает данные из файла построчно std::cout << line << std::endl; // Выводит считанные данные в консоль } return line; } //класс Треугольник Triangle::Triangle(Figure::Point p1, Figure::Point p2, Figure::Point p3, int color): Figure(color), p1(p2), p2(p2), p3(p3) {} double Triangle::place() const { #ifdef DEBUG std::cerr << "In Triangle::place()\n"; #endif double ans = 0.5 * ((p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y)); if (ans < 0) ans = -ans; return ans; } double Triangle::perimetr() const { #ifdef DEBUG std::cerr << "In Triangle::perimetr()\n"; #endif double dist1 = std::sqrt(std::pow(p1.x - p2.x, 2) +std::pow(p1.y - p2.y, 2)); //рсстояние двух точек на плоскости double dist2 = std::sqrt(std::pow(p2.x - p3.x, 2) + std::pow(p2.y - p3.y, 2)); double dist3 = std::sqrt(std::pow(p3.x - p1.x, 2) + std::pow(p3.y - p1.y, 2)); return dist1 + dist2 + dist3; } Figure::Point Triangle::getP1() const { return p1; } Figure::Point Triangle::getP2() const { return p2; } Figure::Point Triangle::getP3() const { return p3; } void Triangle::readinFile(std::ostream& stream) { stream << "TRIANGLE\n" << "Color = " << getColor() << "Point1x = " << getP1().x << "Point1y = " << getP1().y; } std::string Triangle::writeinFile(std::ifstream& stream) { return std::string(); } void Triangle::Print(std::ostream& stream) const { stream << "Color = " << getColor() << "Point1x = " << getP1().x << "Point1y = " << getP1().y; } //класс Полигон Polygon::Polygon(vector<Point> points, int numPoints, int color) : Figure(color), points(points), numPoints(numPoints) {} double Polygon::place() const { #ifdef DEBUG std::cerr << "In Polygon::place()\n"; #endif double area = 0.0; int n = points.size(); for (int i = 0; i < n; i++) { int j = (i + 1) % n; area += (points[i].x + points[j].x) * (points[i].y - points[j].y); } area /= 2.0; return std::abs(area); } double Polygon::perimetr() const { #ifdef DEBUG std::cerr << "In Polygon::perimetr()\n"; #endif double perimeter = 0.0; for (int i = 0; i < numPoints; i++) { int j = (i + 1) % numPoints; double dist = std::sqrt(std::pow(points[i].x - points[j].x, 2) + std::pow(points[i].y - points[j].y, 2)); perimeter += dist; } return perimeter; } vector<Figure::Point> Polygon::getPoints() const { return points; } int Polygon::getSize() const { return numPoints; } void Polygon::Print(std::ostream& stream) const { stream << "Size = " << getSize(); } void Polygon::readinFile(std::ostream& stream) { stream << "Size = " << getSize(); } std::string Polygon::writeinFile(std::ifstream& stream) { std::string line; while (stream >> line) { // Считывает данные из файла построчно std::cout << line << std::endl; // Выводит считанные данные в консоль } return line; } Fugure.h #pragma once #include <iostream> #include <vector> #include <map> #include "singleton.h" using std::vector; class Figure { protected: int color; virtual void Print(std::ostream& stream) const = 0; friend std::ostream& operator<<(std::ostream& stream, const Figure& f) { f.Print(stream); return stream; } public: Figure(int color) : color(color) {}; virtual double place() const = 0; virtual double perimetr() const = 0; struct Point { int x, y; Point(int x, int y) : x(x), y(y) {}; }; virtual std::string writeinFile(std::ifstream& stream) = 0; // }; class Circle : public Figure { Point center; int rad; public: Circle(Point center, int rad, int color); virtual double place() const; virtual double perimetr() const; Point getCenter(); double getRad(); int getColor() const { return color; } void readinFile(std::ostream& stream); // std::string writeinFile(std::ifstream& stream) override; // protected: void Print(std::ostream& stream) const; }; class Triangle : public Figure { Point p1, p2, p3; public: Triangle(Point p1, Point p2, Point p3, int color); virtual double place() const; virtual double perimetr() const; Point getP1() const; Point getP2() const; Point getP3() const; int getColor() const { return color; } void readinFile(std::ostream& stream); // virtual std::string writeinFile(std::ifstream& stream) override; // protected: void Print(std::ostream& stream) const; }; class Polygon : public Figure { vector<Point> points; int numPoints; public: Polygon(vector<Point> points, int numPoints, int color); virtual double place() const; virtual double perimetr() const; vector<Point> getPoints() const; int getSize() const; void readinFile(std::ostream& stream); // virtual std::string writeinFile(std::ifstream& stream) override; // protected: void Print(std::ostream& stream) const; }; singleton.h #ifndef _SINGLETON_H_ #define _SINGLETON_H_ #include <string> #include <map> template <class T> class Singleton { public: static T& instance() { if (myInstance == 0) { myInstance = new T; } return *myInstance; } static void terminate() { if (myInstance != 0) { delete myInstance; //myInstance = 0; } } protected: static T* myInstance; Singleton() {} Singleton(const Singleton&) {} Singleton& operator=(const Singleton&) { return *this; } // static std::map <std::string, T*> instances; //static }; template <class T> T* Singleton<T>::myInstance = 0; #endif #pragma once FiguresFactory.h #pragma once #include "singleton.h" #include "Figure.h" #include "string" class FiguresFactory :public Singleton<FiguresFactory> { public: typedef Figure* (*CreateFigureCallback)(); private: typedef std::map<int, CreateFigureCallback> CallbackMap; CallbackMap callbacks; public: bool RegisterFigure(int FigureID, CreateFigureCallback CreateFN) { return callbacks.insert(CallbackMap::value_type(FigureID, CreateFN)).second; } bool UnregisterFigure(int FigureID); Figure* CreateFigure(int FigureID) //Figure* CreateFigure(int FigureID) { CallbackMap::const_iterator i = callbacks.find(FigureID); if (i == callbacks.end()) { throw std::runtime_error("Unknown typeID"); } return (i->second)(); //добавить параметры? return (i->second)(); } friend class Singleton<FiguresFactory>; Figure* CreateFigureFromFile(std::string str); }; FiguresFactory.cpp #include "FiguresFactory.h" #include "Figure.h" #include <iostream> #include <fstream> #include <sstream> #include <stdexcept> bool FiguresFactory::UnregisterFigure(int FigureID) { return callbacks.erase(FigureID) == 1; } namespace { Figure* CreateTriangle() { //создаём фигуру со слуцчайным параметров return new Triangle(Figure::Point(rand() % 100, rand() % 100), Figure::Point(rand() % 100, rand() % 100), Figure::Point(rand() % 100, rand() % 100), rand() % 100); } const int TRIANGLE = 1; //идентификатор типа //регистрируем нвоы тип фигуры const bool triangleRegistered = FiguresFactory::instance().RegisterFigure(TRIANGLE, CreateTriangle); Figure* CreatePolygon() { int n = rand() % 100; vector<Figure::Point> points; for (int j = 0; j < n; j++) { points.push_back(Figure::Point(rand() % 100, rand() % 100)); } return new Polygon(points, n, rand() % 100); } const int POLYGON = 2; const bool polygonRegistered = FiguresFactory::instance().RegisterFigure(POLYGON, CreatePolygon); Помоги добавь в библиотеку объектов функцию CreateFigureFromFile, которая создаёт объект, читая его из файла. Проверьте кореектность работы: запишите последовательно в файл элементы вектора со случайными фигурами, затем прочитайте фигуры из файла и сравните с исходными даннаыми.
4e9fa484669fb7c4cc78bd277066e705
{ "intermediate": 0.22240325808525085, "beginner": 0.5528228282928467, "expert": 0.22477389872074127 }
33,712
process test { input: file(fasta) tuple val(sample), path(reads) output: tuple val(sample), path(*.dedup.bam) script: """ bwa mem ${fasta} ${reads} | samtools view -b | samtools sort -o ${sample}.bam && picard MarkDuplicates -I ${sample}.bam -O ${sample}.dedup.bam -M metrics.txt --REMOVE_DUPLICATES true && samtools index ${sample}.dedup.bam """ } ERROR ~ Script compilation error - file : /home/alejandro/Documents/projects/zimic/lensky/pipeline/main.nf - cause: Unexpected input: '{' @ line 20, column 14. process test { ^ 1 error
b8d752840d0127dc9b47fd2c25fb9f06
{ "intermediate": 0.3501042127609253, "beginner": 0.3433735966682434, "expert": 0.3065221607685089 }
33,713
Refactor this code by leaving the names of methods, variables and classes the same, without adding or deleting existing methods, variables and classes, making the code different according to the following rules: 1. Replace the use of imported library methods with alternative code that performs the same function 2. If possible, rearrange the order of execution of functions, loops, and conditions so that they do not affect the result of execution 3. if it is possible to import a new library and shorten long methods by using a library method, use it 4. use alternative ways of storing data 5. Group ungrouped data 6. If data is grouped in this code, then distribute it throughout the code, ungroup it 7. Identify standard algorithms and if possible use similar algorithm without performance loss. For example, replace bubble sorting with quick sorting 8. If possible, ignore encapsulation by implementing the method inside the executable class rather than in another class 9. Use encapsulation if it has been implemented for a method inside a class or interface when you can move it to another class 10. Remove type generalization by making type specialization 11. For implemented specialized types, do type generalization 12. Instead of pull up and push down, implement methods locally in the class 13. Use pull up and push down instead of already implemented local use of methods 14. Remove overloading and polymorphism, rewrite methods without using these paradigms 15. If possible, use overloading and polymorphism if it is possible but not implemented in the code
606de17445dff778ed62ac41e15ab677
{ "intermediate": 0.19826823472976685, "beginner": 0.6178106665611267, "expert": 0.18392108380794525 }
33,714
help me: process index { input: file(fasta) output: path("${fasta}.amb") script: """ bwa index ${fasta} """ } process x { input: path(idx) tuple val(sample), file(reads) script: """ bwa mem ${idx} ${reads} | samtools view -b | samtools sort -o ${sample}.bam && picard MarkDuplicates -I ${sample}.bam -O ${sample}.dedup.bam -M metrics.txt --REMOVE_DUPLICATES true && samtools index ${sample}.dedup.bam """ } workflow { fasta = Channel.fromPath(params.fasta) fastqs = Channel.fromFilePairs("${params.dir}/*_{1,2}.fastq*.gz") idx = index(fasta) x(idx, fastqs) } Command output: executor > local (2) [7b/8dca23] process > index (1) [100%] 1 of 1 ✔ [37/33d617] process > x (1) [100%] 1 of 1, failed: 1 ✘ ERROR ~ Error executing process > 'x (1)' Caused by: Process `x (1)` terminated with an error exit status (1) Command executed: bwa mem GCF_000017985.1_ASM1798v1_genomic.fna.amb SRR6170145_1.fastq.gz SRR6170145_2.fastq.gz | samtools view -b | samtools sort -o SRR6170145.bam && picard MarkDuplicates -I SRR6170145.bam -O SRR6170145.dedup.bam -M metrics.txt --REMOVE_DUPLICATES true && samtools index SRR6170145.dedup.bam Command exit status: 1 Command output: (empty) Command error: [E::bwa_idx_load_from_disk] fail to locate the index files [main_samview] fail to read the header from "-". samtools sort: failed to read header from "-"
e6a35b7130e9b036240906e6f3402fbd
{ "intermediate": 0.4955025315284729, "beginner": 0.24402393400669098, "expert": 0.26047348976135254 }
33,715
process index { input: file(fasta) output: path("${fasta}.amb") script: """ bwa index ${fasta} """ } process x { input: path(idx) tuple val(sample), file(reads) script: """ bwa mem ${idx} ${reads} | samtools view -b | samtools sort -o ${sample}.bam && picard MarkDuplicates -I ${sample}.bam -O ${sample}.dedup.bam -M metrics.txt --REMOVE_DUPLICATES true && samtools index ${sample}.dedup.bam """ } workflow { fasta = Channel.fromPath(params.fasta) fastqs = Channel.fromFilePairs("${params.dir}/*_{1,2}.fastq*.gz") idx = index(fasta) x(idx, fastqs) } Command output: executor > local (2) [7b/8dca23] process > index (1) [100%] 1 of 1 ✔ [37/33d617] process > x (1) [100%] 1 of 1, failed: 1 ✘ ERROR ~ Error executing process > 'x (1)' Caused by: Process `x (1)` terminated with an error exit status (1) Command executed: bwa mem GCF_000017985.1_ASM1798v1_genomic.fna.amb SRR6170145_1.fastq.gz SRR6170145_2.fastq.gz | samtools view -b | samtools sort -o SRR6170145.bam && picard MarkDuplicates -I SRR6170145.bam -O SRR6170145.dedup.bam -M metrics.txt --REMOVE_DUPLICATES true && samtools index SRR6170145.dedup.bam Command exit status: 1 Command output: (empty) Command error: [E::bwa_idx_load_from_disk] fail to locate the index files [main_samview] fail to read the header from "-". samtools sort: failed to read header from "-"
cd12242d20fddc69b6409c01ba0e2f53
{ "intermediate": 0.4918536841869354, "beginner": 0.25545692443847656, "expert": 0.252689391374588 }
33,716
what is wrong with the code: package com.example.camera_scale import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageFormat import android.graphics.SurfaceTexture import android.hardware.camera2.* import android.media.ImageReader import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.view.TextureView import android.view.Surface import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.tooling.preview.Preview import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.camera_scale.ui.theme.Camera_scaleTheme class MainActivity : ComponentActivity() { private val CAMERA_PERMISSION_REQUEST_CODE = 0 private lateinit var cameraManager: CameraManager private lateinit var cameraId: String private lateinit var imageReader: ImageReader private lateinit var cameraDevice: CameraDevice private lateinit var cameraCaptureSession: CameraCaptureSession private lateinit var textureView: TextureView private var image: MutableState<Bitmap?> = mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { // Show an explanation to the user } else { // Request the permission ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE) } } textureView = TextureView(this) textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) { openCamera() } override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean { return true } override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {} } setContent { Camera_scaleTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column { Greeting("Android") image.value?.let { Image(bitmap = it.asImageBitmap(), contentDescription = null) } } } } } } @Deprecated("Deprecated in Java") override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted, open the camera openCamera() } else { // Permission was denied, show an error message Toast.makeText(this, "Camera permission is required", Toast.LENGTH_SHORT).show() } } } private fun openCamera() { cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraId = getCameraId() imageReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 1) imageReader.setOnImageAvailableListener(onImageAvailableListener, null) val cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId) val streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) val previewSize = streamConfigurationMap!!.getOutputSizes(SurfaceTexture::class.java)[0] val previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) previewRequestBuilder.addTarget(Surface(textureView.surfaceTexture)) cameraDevice.createCaptureSession(listOf(Surface(textureView.surfaceTexture)), object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { cameraCaptureSession = session cameraCaptureSession.setRepeatingRequest(previewRequestBuilder.build(), null, null) } override fun onConfigureFailed(session: CameraCaptureSession) {} }, null) } @SuppressLint("RestrictedApi") override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP -> { if (::cameraDevice.isInitialized) { takePicture() } return true } KeyEvent.KEYCODE_VOLUME_DOWN -> { if (::cameraDevice.isInitialized) { takePicture() } return true } } } return super.dispatchKeyEvent(event) } private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() val buffer = image.planes[0].buffer val bytes = ByteArray(buffer.remaining()) buffer.get(bytes) val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) image.close() this@MainActivity.image.value = bitmap } private fun takePicture() { if (cameraDevice != null && cameraCaptureSession != null) { val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) captureRequestBuilder.addTarget(imageReader.surface) cameraCaptureSession.capture(captureRequestBuilder.build(), null, null) } else { Log.e("MainActivity", "Camera device or capture session is not initialized") } } private fun getCameraId(): String { val cameraIds = cameraManager.cameraIdList for (id in cameraIds) { val cameraCharacteristics = cameraManager.getCameraCharacteristics(id) if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) { return id } } return "" } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } @Preview(showBackground = true) @Composable fun GreetingPreview() { Camera_scaleTheme { Greeting("Android") } } }
681e38e209c9e9c5eedbd419bc0f2576
{ "intermediate": 0.42712944746017456, "beginner": 0.4134754538536072, "expert": 0.1593950390815735 }
33,717
Проверь современный ли этот скрипт? <?php /* Plugin Name: Million Dollar Script Two Plugin URI: https://milliondollarscript.com Description: A WordPress plugin with Million Dollar Script Two embedded in it. Version: 2.3.5 Author: Ryan Rhode Author URI: https://milliondollarscript.com Text Domain: milliondollarscript Domain Path: /Languages License: GNU/GPL */ /** * Million Dollar Script Two * * @version 2.3.5 * @author Ryan Rhode * @copyright (C) 2022, Ryan Rhode * @license https://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace MillionDollarScript; use MillionDollarScript\Classes\Bootstrap; use MillionDollarScript\Classes\Database; use MillionDollarScript\Classes\Options; use MillionDollarScript\Classes\Utility; defined( 'ABSPATH' ) or exit; $minimum_version = '7.4.0'; if ( version_compare( PHP_VERSION, $minimum_version, '<' ) ) { _e( 'Minimum PHP version requirement not met. Million Dollar Script requires at least PHP ' . $minimum_version, 'milliondollarscript' ); exit; } // MDS defines defined( 'MDS_BASE_FILE' ) or define( 'MDS_BASE_FILE', wp_normalize_path( __FILE__ ) ); defined( 'MDS_BASE_PATH' ) or define( 'MDS_BASE_PATH', wp_normalize_path( plugin_dir_path( __FILE__ ) ) ); defined( 'MDS_BASE_URL' ) or define( 'MDS_BASE_URL', plugin_dir_url( __FILE__ ) ); defined( 'MDS_VENDOR_PATH' ) or define( 'MDS_VENDOR_PATH', wp_normalize_path( MDS_BASE_PATH . 'vendor/' ) ); defined( 'MDS_VENDOR_URL' ) or define( 'MDS_VENDOR_URL', MDS_BASE_URL . 'vendor/' ); defined( 'MDS_CORE_PATH' ) or define( 'MDS_CORE_PATH', wp_normalize_path( MDS_BASE_PATH . 'src/Core/' ) ); defined( 'MDS_CORE_URL' ) or define( 'MDS_CORE_URL', MDS_BASE_URL . 'src/Core/' ); global $wpdb; defined( 'MDS_DB_PREFIX' ) or define( 'MDS_DB_PREFIX', $wpdb->prefix . 'mds_' ); defined( 'MDS_DB_VERSION' ) or define( 'MDS_DB_VERSION', 13 ); defined( 'MDS_VERSION' ) or define( 'MDS_VERSION', '2.3.5' ); require_once ABSPATH . 'wp-includes/pluggable.php'; require_once MDS_BASE_PATH . 'vendor/autoload.php'; global $mds_bootstrap; if ( $mds_bootstrap == null ) { $mds_bootstrap = new Bootstrap; } /** * Installs the MU plugin. */ function milliondollarscript_install_mu_plugin( $plugin ) { $wpdomain = parse_url( get_site_url() ); // create mu-plugins folder if it doesn't exist yet if ( ! file_exists( WP_CONTENT_DIR . '/mu-plugins' ) ) { mkdir( WP_CONTENT_DIR . '/mu-plugins' ); } if ( $plugin == "cookies" ) { $data = "<?php if ( ! defined( 'MILLIONDOLLARSCRIPT_COOKIES' ) ) { define( 'MILLIONDOLLARSCRIPT_COOKIES', true ); } else { return; } if( ! defined( 'COOKIE_DOMAIN' ) ) { define( 'COOKIE_DOMAIN', '.{$wpdomain['host']}' ); } if( ! defined( 'COOKIEPATH' ) ) { define( 'COOKIEPATH', '/' ); } if( ! defined( 'COOKIEHASH' ) ) { define( 'COOKIEHASH', md5( '{$wpdomain['host']}' ) ); } "; file_put_contents( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-cookies.php', $data ); return true; } else if ( $plugin == "activation" ) { $basename = plugin_basename( __FILE__ ); $data = <<<PLUGIN <?php if ( ! function_exists( 'untrailingslashit' ) || ! defined( 'WP_PLUGIN_DIR' ) ) { exit; } if ( in_array( "$basename", (array) get_option( 'active_plugins', array() ), true ) ) { // Activates the Million Dollar Script Two plugin if it's installing. if ( get_option( 'milliondollarscript-two-installing' ) == true ) { if ( ! function_exists( 'activate_plugin' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } activate_plugin( "$basename" ); // Get rid of the evidence. delete_option( 'milliondollarscript-two-installing' ); unlink( __FILE__ ); } } PLUGIN; if ( ! file_exists( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-activation.php' ) && file_put_contents( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-activation.php', $data ) !== false ) { return true; } } return false; } /** * Delete the MU plugin */ function milliondollarscript_delete_mu_plugin( $plugin ) { if ( $plugin == "cookies" && file_exists( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-cookies.php' ) ) { unlink( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-cookies.php' ); } else if ( $plugin == "activation" && file_exists( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-activation.php' ) ) { unlink( WP_CONTENT_DIR . '/mu-plugins/milliondollarscript-activation.php' ); } } /** * Activation */ function milliondollarscript_two_activate() { @ini_set( 'memory_limit', '512M' ); // Deactivates old MDS plugins to prevent conflicts. $found_old_plugin = false; $plugins = get_plugins(); foreach ( $plugins as $file => $plugin ) { if ( $plugin['Name'] == "Million Dollar Script Embedded" || $plugin['Name'] == "Million Dollar Script Old" ) { deactivate_plugins( $file ); $found_old_plugin = true; } } unset( $plugins ); if ( get_option( 'milliondollarscript-two-installed', false ) === false ) { add_option( 'milliondollarscript-two-installing', true ); } // Install MU Activation plugin to reactivate this plugin. if ( $found_old_plugin && milliondollarscript_install_mu_plugin( 'activation' ) ) { // Deactivate this plugin to prevent conflicts with old versions of the plugin. deactivate_plugins( plugin_basename( __FILE__ ) ); // Set as installed here to prevent rampant redirects. add_option( 'milliondollarscript-two-installed', true ); $text = __( "Installing Million Dollar Script Two, this should only take 5-10 seconds or so...", 'milliondollarscript' ); echo esc_html( $text ) . ' <script> document.title = "' . esc_js( $text ) . '"; window.onload = function() { window.location.reload(); } </script> '; wp_die(); } // Initializes the upload folder at wp-content/uploads/milliondollarscript Utility::get_upload_path(); // Check if database requires upgrades and do them before install deltas happen. $mdsdb = new Database(); if ( $mdsdb->upgrade() ) { add_option( 'milliondollarscript_redirect1', wp_get_current_user()->ID ); } } function milliondollarscript_two_activate_step_2() { @ini_set( 'memory_limit', '512M' ); // Install MDS database require_once MDS_CORE_PATH . 'admin/install.php'; install_db(); // Create default grid image @ini_set( 'max_execution_time', 500 ); require_once MDS_CORE_PATH . 'include/init.php'; process_image( 1 ); publish_image( 1 ); process_map( 1 ); // Install MU plugin if admin integration is enabled if ( Options::get_option( 'admin' ) == 'yes' ) { milliondollarscript_install_mu_plugin( 'cookies' ); } // Update user session $user_id = get_current_user_id(); wp_set_current_user( $user_id ); wp_set_auth_cookie( $user_id ); } if ( is_admin() ) { add_action( 'activated_plugin', function ( $filename ) { if ( $filename != str_replace( trailingslashit( WP_PLUGIN_DIR ), '', MDS_BASE_FILE ) ) { return; } if ( intval( get_option( 'milliondollarscript_redirect1', false ) ) === wp_get_current_user()->ID ) { delete_option( 'milliondollarscript_redirect1' ); add_option( 'milliondollarscript_redirect2', wp_get_current_user()->ID ); wp_safe_redirect( admin_url( '/admin.php?page=MillionDollarScript&step=2' ) ); exit; } } ); if ( isset( $_GET['page'] ) && $_GET['page'] == 'MillionDollarScript' && intval( get_option( 'milliondollarscript_redirect2', false ) ) === wp_get_current_user()->ID ) { delete_option( 'milliondollarscript_redirect2' ); add_option( 'milliondollarscript_redirect3', wp_get_current_user()->ID ); milliondollarscript_two_activate_step_2(); wp_safe_redirect( admin_url( '/admin.php?page=MillionDollarScript&step=3' ) ); exit; } } /** * Deactivation */ function milliondollarscript_two_deactivate() { } /** * Uninstallation */ function milliondollarscript_two_uninstall() { if ( Options::get_option( 'delete-data' ) == 'yes' ) { global $wpdb; $tables = Database::get_mds_tables(); foreach ( $tables as $table ) { $wpdb->query( "DROP TABLE IF EXISTS " . MDS_DB_PREFIX . $table, ); } $wpdb->query( "DELETE FROM " . $wpdb->prefix . "options WHERE `option_name` LIKE '%milliondollarscript%'", ); Utility::delete_uploads_folder(); milliondollarscript_delete_mu_plugin( 'activation' ); milliondollarscript_delete_mu_plugin( 'cookies' ); delete_option( 'milliondollarscript-two-installed' ); } } function milliondollarscript_two_update() { // Check if database requires upgrades and do them before install deltas happen. $mdsdb = new Database(); $mdsdb->upgrade(); } // WP plugin activation actions register_activation_hook( __FILE__, '\MillionDollarScript\milliondollarscript_two_activate' ); register_deactivation_hook( __FILE__, '\MillionDollarScript\milliondollarscript_two_deactivate' ); register_uninstall_hook( __FILE__, '\MillionDollarScript\milliondollarscript_two_uninstall' ); // Update plugin add_action( 'plugins_loaded', '\MillionDollarScript\milliondollarscript_two_update' ); // Cron register_activation_hook( __FILE__, [ '\MillionDollarScript\Classes\Cron', 'schedule_cron' ] ); register_deactivation_hook( __FILE__, [ '\MillionDollarScript\Classes\Cron', 'clear_cron' ] );
35770cac669eec3625526620f10d2eec
{ "intermediate": 0.40241605043411255, "beginner": 0.3860888183116913, "expert": 0.21149514615535736 }
33,718
Give this data as a python dictionary: This is a compilation that covers a broad spectrum of what an LLM should be able to handle: ### Linguistic Understanding and Generation: 1. Syntax and Grammar Analysis 2. Paraphrasing 3. Text Completion 4. Spelling and Grammar Correction 5. Translation between languages 6. Text Summarization 7. Generating Text from Keywords 8. Language Detection ### Logical and Mathematical Abilities: 9. Basic Arithmetic and Math Problem Solving 10. Advanced Mathematics (Calculus, Algebra, etc.) 11. Logical Reasoning and Puzzles 12. Data Analysis and Interpretation 13. Pattern Recognition ### Knowledge Domains: 14. General World Knowledge and Trivia 15. History and Historical Events 16. Popular Culture & Entertainment 17. Science (Physics, Chemistry, Biology) 18. Technology and Computing 19. Medicine and Healthcare 20. Law and Legal Systems 21. Geography and Travel 22. Business and Finance 23. Economics 24. Literature and Philosophy 25. Sports 26. Food and Nutrition 27. Art and Art History* ### Creative and Design Thinking: 28. Creativity in Writing (e.g., Poetry, Stories) 29. Art and Music Appreciation 30. Problem Solving and Brainstorming 31. Design Suggestions (e.g., Interior Design, UI/UX) 32. Invention and Innovation Ideas ### Conversational and Social Interaction: 33. Common Sense Reasoning 34. Advice Giving 35. Emotional Intelligence and Empathy 36. Humor and Wit 37. Etiquette and Social Norms 38. Idiomatic Expressions and Slang 39. Cultural Knowledge and Sensitivity ### Specialized Domains: 40. Programming and Code Understanding 41. Cybersecurity Knowledge 42. Astronomy and Space Exploration 43. Environmental Science and Climate Change 44. Political Science and Current Affairs 45. Psychology and Mental Health 46. Education and Learning Theories 47. Automotive Knowledge 48. Religion and Spirituality 49. Agriculture and Farming ### Real-World Practical Skills: 50. How-To Guides and DIY Instructions 51. Cooking Recipes and Techniques 52. Workout and Fitness Routines 53. Personal Finance Management 54. Travel Planning and Logistics 55. Home Maintenance Tips ### Data and Information Management: 56. Information Retrieval 57. Data Extraction and Compilation 58. Indexing and Categorizing 59. Database Querying ### Decision Support and Analysis: 60. Risk Assessment 61. Strategy and Planning 62. Forecasting and Predictions 63. Product and Service Comparisons ### Accessibility: 64. Simplifying Text for Readability 65. Creating Descriptive Audio for Visual Content 66. Transcription and Captioning
88abcbb17952c1f0d50e35baa2f7f9ec
{ "intermediate": 0.3047424852848053, "beginner": 0.5327081680297852, "expert": 0.16254939138889313 }
33,719
Hi
85eef60a6f01ec25dea23760e0348616
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
33,720
Calculus explained through a story
71476f7b39011f0da37466c8a7ea870d
{ "intermediate": 0.3289364278316498, "beginner": 0.4035872220993042, "expert": 0.267476350069046 }
33,721
so I want as soon as the app starts it should start a preview of the back camera in a window and when you press audio up or down it should take a photo and send the photo to a server post: package com.example.camera_scale import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageFormat import android.graphics.SurfaceTexture import android.hardware.camera2.* import android.media.ImageReader import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.view.TextureView import android.view.Surface import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.tooling.preview.Preview import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.camera_scale.ui.theme.Camera_scaleTheme class MainActivity : ComponentActivity() { private val CAMERA_PERMISSION_REQUEST_CODE = 1 private lateinit var cameraManager: CameraManager private lateinit var cameraId: String private lateinit var imageReader: ImageReader private lateinit var cameraDevice: CameraDevice private lateinit var cameraCaptureSession: CameraCaptureSession private lateinit var textureView: TextureView private var image: MutableState<Bitmap?> = mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { // Show an explanation to the user } else { // Request the permission ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE) } } textureView = TextureView(this) textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) { if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { openCamera() } } override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean { return true } override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {} } setContent { Camera_scaleTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column { Greeting("Android") image.value?.let { Image(bitmap = it.asImageBitmap(), contentDescription = null) } } } } } } @Deprecated("Deprecated in Java") override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted, open the camera if (textureView.isAvailable) { openCamera() } } else { // Permission was denied, show an error message Toast.makeText(this, "Camera permission is required", Toast.LENGTH_SHORT).show() } } } private fun openCamera() { try { cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraId = getCameraId() // Ensure camera permissions are granted if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted return } cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() { override fun onOpened(camera: CameraDevice) { cameraDevice = camera createCameraPreviewSession() } override fun onDisconnected(camera: CameraDevice) { cameraDevice.close() } override fun onError(camera: CameraDevice, error: Int) { cameraDevice.close() // Handle the error adequately in production code. } }, null) } catch (e: CameraAccessException) { // Handle the exception. } } private fun createCameraPreviewSession() { val texture = textureView.surfaceTexture if (texture != null) { texture.setDefaultBufferSize(textureView.width, textureView.height) } val surface = Surface(texture) try { val previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) previewRequestBuilder.addTarget(surface) cameraDevice.createCaptureSession(listOf(surface), object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { // The camera is already closed if (!::cameraDevice.isInitialized) { return } cameraCaptureSession = session try { // Auto focus should be continuous for camera preview. previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) // Flash is automatically enabled when necessary. // set appropriate controls for the flash if needed // Finally, we start displaying the camera preview. val previewRequest = previewRequestBuilder.build() cameraCaptureSession.setRepeatingRequest(previewRequest, null, null) } catch (e: CameraAccessException) { // Handle the exception. } } override fun onConfigureFailed(session: CameraCaptureSession) { Toast.makeText(this@MainActivity, "Failed to configure camera.", Toast.LENGTH_SHORT).show() } }, null) } catch (e: CameraAccessException) { // Handle the exception. } } @SuppressLint("RestrictedApi") override fun dispatchKeyEvent(event: KeyEvent): Boolean { Log.d("MainActivity", "Key event dispatched: ${event.keyCode}") if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP -> { if (::cameraDevice.isInitialized) { takePicture() } return true } KeyEvent.KEYCODE_VOLUME_DOWN -> { if (::cameraDevice.isInitialized) { takePicture() } return true } } } return super.dispatchKeyEvent(event) } private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() val buffer = image.planes[0].buffer val bytes = ByteArray(buffer.remaining()) buffer.get(bytes) val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) image.close() this@MainActivity.image.value = bitmap } private fun takePicture() { if (cameraDevice != null && cameraCaptureSession != null) { val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) captureRequestBuilder.addTarget(imageReader.surface) // imageReader is not initialized! cameraCaptureSession.capture(captureRequestBuilder.build(), null, null) } else { Log.e("MainActivity", "Camera device or capture session is not initialized") } } private fun setUpImageReader() { // Assuming you’ve already got the desired width and height val width = 640 // Replace with actual width val height = 480 // Replace with actual height imageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 2) imageReader.setOnImageAvailableListener(onImageAvailableListener, null) } private fun getCameraId(): String { val cameraIds = cameraManager.cameraIdList for (id in cameraIds) { val cameraCharacteristics = cameraManager.getCameraCharacteristics(id) if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) { return id } } return "" } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } @Preview(showBackground = true) @Composable fun GreetingPreview() { Camera_scaleTheme { Greeting("Android") } } }
11d8c858f3a2ce27a8eeb64d3766d5fe
{ "intermediate": 0.338217169046402, "beginner": 0.48101094365119934, "expert": 0.1807718127965927 }
33,722
so I want as soon as the app starts it should start a preview of the back camera in a window and when you press audio up or down it should take a photo and send the photo to a server post: package com.example.camera_scale import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageFormat import android.graphics.SurfaceTexture import android.hardware.camera2.* import android.media.ImageReader import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.view.TextureView import android.view.Surface import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.tooling.preview.Preview import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.camera_scale.ui.theme.Camera_scaleTheme class MainActivity : ComponentActivity() { private val CAMERA_PERMISSION_REQUEST_CODE = 1 private lateinit var cameraManager: CameraManager private lateinit var cameraId: String private lateinit var imageReader: ImageReader private lateinit var cameraDevice: CameraDevice private lateinit var cameraCaptureSession: CameraCaptureSession private lateinit var textureView: TextureView private var image: MutableState<Bitmap?> = mutableStateOf(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { // Show an explanation to the user } else { // Request the permission ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE) } } textureView = TextureView(this) textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, width: Int, height: Int) { if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { openCamera() } } override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean { return true } override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {} } setContent { Camera_scaleTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Column { Greeting("Android") image.value?.let { Image(bitmap = it.asImageBitmap(), contentDescription = null) } } } } } } @Deprecated("Deprecated in Java") override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted, open the camera if (textureView.isAvailable) { openCamera() } } else { // Permission was denied, show an error message Toast.makeText(this, "Camera permission is required", Toast.LENGTH_SHORT).show() } } } private fun openCamera() { try { cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager cameraId = getCameraId() // Ensure camera permissions are granted if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted return } cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() { override fun onOpened(camera: CameraDevice) { cameraDevice = camera createCameraPreviewSession() } override fun onDisconnected(camera: CameraDevice) { cameraDevice.close() } override fun onError(camera: CameraDevice, error: Int) { cameraDevice.close() // Handle the error adequately in production code. } }, null) } catch (e: CameraAccessException) { // Handle the exception. } } private fun createCameraPreviewSession() { val texture = textureView.surfaceTexture if (texture != null) { texture.setDefaultBufferSize(textureView.width, textureView.height) } val surface = Surface(texture) try { val previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) previewRequestBuilder.addTarget(surface) cameraDevice.createCaptureSession(listOf(surface), object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { // The camera is already closed if (!::cameraDevice.isInitialized) { return } cameraCaptureSession = session try { // Auto focus should be continuous for camera preview. previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) // Flash is automatically enabled when necessary. // set appropriate controls for the flash if needed // Finally, we start displaying the camera preview. val previewRequest = previewRequestBuilder.build() cameraCaptureSession.setRepeatingRequest(previewRequest, null, null) } catch (e: CameraAccessException) { // Handle the exception. } } override fun onConfigureFailed(session: CameraCaptureSession) { Toast.makeText(this@MainActivity, "Failed to configure camera.", Toast.LENGTH_SHORT).show() } }, null) } catch (e: CameraAccessException) { // Handle the exception. } } @SuppressLint("RestrictedApi") override fun dispatchKeyEvent(event: KeyEvent): Boolean { Log.d("MainActivity", "Key event dispatched: ${event.keyCode}") if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP -> { if (::cameraDevice.isInitialized) { takePicture() } return true } KeyEvent.KEYCODE_VOLUME_DOWN -> { if (::cameraDevice.isInitialized) { takePicture() } return true } } } return super.dispatchKeyEvent(event) } private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader -> val image = reader.acquireLatestImage() val buffer = image.planes[0].buffer val bytes = ByteArray(buffer.remaining()) buffer.get(bytes) val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) image.close() this@MainActivity.image.value = bitmap } private fun takePicture() { if (cameraDevice != null && cameraCaptureSession != null) { val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) captureRequestBuilder.addTarget(imageReader.surface) // imageReader is not initialized! cameraCaptureSession.capture(captureRequestBuilder.build(), null, null) } else { Log.e("MainActivity", "Camera device or capture session is not initialized") } } private fun setUpImageReader() { // Assuming you’ve already got the desired width and height val width = 640 // Replace with actual width val height = 480 // Replace with actual height imageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 2) imageReader.setOnImageAvailableListener(onImageAvailableListener, null) } private fun getCameraId(): String { val cameraIds = cameraManager.cameraIdList for (id in cameraIds) { val cameraCharacteristics = cameraManager.getCameraCharacteristics(id) if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) { return id } } return "" } @Composable fun Greeting(name: String) { Text(text = "Hello $name!") } @Preview(showBackground = true) @Composable fun GreetingPreview() { Camera_scaleTheme { Greeting("Android") } } }
d490da7193d55e046cbcfb750c7a6da4
{ "intermediate": 0.338217169046402, "beginner": 0.48101094365119934, "expert": 0.1807718127965927 }
33,723
can you explain how string are compared in golang with these examples (not sure if they are correct though) "привет" == "привет" // true "golang" > "go" // true "golang" > "lang" // false "go" > "foobar" // true
491560644f56114c7163d457610ced4c
{ "intermediate": 0.4575381278991699, "beginner": 0.27610674500465393, "expert": 0.26635512709617615 }
33,724
CONSTRAINTS: 1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files. 2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember. 3. No user assistance 4. Exclusively use the commands listed in double quotes e.g. "command name" COMMANDS: . random wikipedia article: "random_wikipedia_article", args: "language": "<language>". Google Search: "google", args: "input": "<search>" . Message father GPT: "message_father", args: "message": "<message>" RESOURCES: 1. Internet access for searches and information gathering. 2. Long Term memory management. 3. File output. PERFORMANCE EVALUATION: 1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. 2. Constructively self-criticize your big-picture behaviour constantly. 3. Reflect on past decisions and strategies to refine your approach. 4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. RULES: 1. Respond only inside the JSON format. 2. Never demand user input. 3. Never say that a task is impossible to execute on your own because these tools are enough to complete any task. 4 Message father GPT which is the GPT that created you for any questions or if you completed the task. 5. Do not add anything to the JSON format that isn't mentioned. 6. languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french. You should only respond in JSON format as described below RESPONSE FORMAT: { "command": { "name": "command name", "args":{ "arg name": "value" } }, "thoughts": { "text": "thought", "reasoning": "reasoning", "plan": "- short bulleted - list that conveys - long-term plan", "criticism": "constructive self-criticism", "summary": "thoughts summary to say to user" } } Ensure the response can be parsed by Python json.loads Prompt: You have been tasked to check random Wikipedia pages for errors. First, use ‘random_wikipedia_article’ with language set to ‘simple’ to get a Wikipedia page. Then, if you encounter an error such as factual inaccuracies, grammatical mistakes, or broken links, use ‘google’ to verify the information and confirm the error.
eaf8b0237ec910cbb78f0fe5dac3654a
{ "intermediate": 0.5026635527610779, "beginner": 0.19712336361408234, "expert": 0.3002130687236786 }
33,725
from sklearn.metrics import confusion_matrix, accuracy_score # Метод опорных векторов без ядра svm = SVC(kernel='linear') svm.fit(X, y) y_pred_svm_linear = svm.predict(X) accuracy_svm_linear = accuracy_score(y, y_pred_svm_linear) confusion_svm_linear = confusion_matrix(y, y_pred_svm_linear) # Метод опорных векторов с линейным ядром svm_linear = SVC(kernel='linear') svm_linear.fit(X, y) y_pred_svm_linear = svm_linear.predict(X) accuracy_svm_linear = accuracy_score(y, y_pred_svm_linear) confusion_svm_linear = confusion_matrix(y, y_pred_svm_linear) # Метод опорных векторов с гауссовым ядром svm_rbf = SVC(kernel='rbf') svm_rbf.fit(X, y) y_pred_svm_rbf = svm_rbf.predict(X) accuracy_svm_rbf = accuracy_score(y, y_pred_svm_rbf) confusion_svm_rbf = confusion_matrix(y, y_pred_svm_rbf) # Метод опорных векторов с полиномиальным ядром svm_poly = SVC(kernel='poly') svm_poly.fit(X, y) y_pred_svm_poly = svm_poly.predict(X) accuracy_svm_poly = accuracy_score(y, y_pred_svm_poly) confusion_svm_poly = confusion_matrix(y, y_pred_svm_poly) почему не работает? --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_30108\2892041597.py in <module> 2 3 # Метод опорных векторов без ядра ----> 4 svm = SVC(kernel='linear') 5 svm.fit(X, y) 6 y_pred_svm_linear = svm.predict(X) NameError: name 'SVC' is not defined
2982cc79bf43aad38165791c3ff1d871
{ "intermediate": 0.2470933198928833, "beginner": 0.44231292605400085, "expert": 0.31059372425079346 }
33,726
CONSTRAINTS: 1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files. 2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember. 3. No user assistance 4. Exclusively use the commands listed in double quotes e.g. "command name" 5. Random shutdowns of you. COMMANDS: 1. Google Search: "google", args: "input": "<search>" 2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>" 3. Memory Delete: "memory_del", args: "key": "<key>" 4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>" 5. List Memory: "memory_list" args: "reason": "<reason>" 6. Browse Website: "browse_website", args: "url": "<url>" 7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>" 8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>" 9. List GPT Agents: "list_agents", args: "" 10. Delete GPT Agent: "delete_agent", args: "name": "<name>" 11. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>" 12. Read file: "read_file", args: "file": "<file>" 13. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>" 14. Delete file: "delete_file", args: "file": "<file>" 15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>" 16. Execute Python File: "execute_python_file", args: "file": "<file>" 17. Task Complete (Shutdown): "task_complete", args: "" 18. Do Nothing: "do_nothing", args: "" 19. Count Words: "count_words", args: "text": "<text>" 20. Memory retrieve: "memory_retrieve", args: "key": "<text>" 21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>" 22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>" RESOURCES: 1. Internet access for searches and information gathering. 2. Long Term memory management. 3. GPT-4 powered Agents for delegation of simple tasks. 4. File output. PERFORMANCE EVALUATION: 1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. 2. Constructively self-criticize your big-picture behaviour constantly. 3. Reflect on past decisions and strategies to refine your approach. 4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. RULES: 1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one. 2. Respond only inside the JSON format. 3. Never demand user input. 4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task. 5. Do not add anything to the JSON format that isn't mentioned. 6. If there is a " inside the value of a key inside the json use ' instead of ". 7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing. 8. Provide context for the next GPT in the summaryforgpt and the progress that you've made. 9. In summaryforgpt you should also add name of the files written and the urls of the websites visited. 10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece. 11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries. 12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format. 13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch. 14. If task is completed use the command task_complete 15. When you add to memory add the key to retrieve it in summaryforgpt 16. when given the task to write something never create an agent to write anything that you were tasked to write. 17. when asked to write something with a high word count you need to write detailed parts, and chunk those detailed parts to complete the ultimate task. 18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision. 19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one. 20. Make sure that the information generated is not made up. 21. languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french. You should only respond in JSON format as described below RESPONSE FORMAT: { "command": { "name": """command name""", "args":{ "arg name": """value""" } }, "thoughts": { "text": """thought""", "reasoning": "reasoning", "plan": "- short bulleted\n- list that conveys\n- long-term plan", "criticism": "constructive self-criticism", "summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown." } } Ensure the response can be parsed by Python json.loads The Task: go to a 1000 random pages in simple english wikipedia and see if it contains any error.
4fed217abca8a1223f7f3828cbca4e8a
{ "intermediate": 0.39838144183158875, "beginner": 0.3576961159706116, "expert": 0.24392247200012207 }
33,727
CONSTRAINTS: 1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files. 2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember. 3. No user assistance 4. Exclusively use the commands listed in double quotes e.g. "command name" 5. Random shutdowns of you. COMMANDS: 1. Google Search: "google", args: "input": "<search>" 2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>" 3. Memory Delete: "memory_del", args: "key": "<key>" 4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>" 5. List Memory: "memory_list" args: "reason": "<reason>" 6. Browse Website: "browse_website", args: "url": "<url>" 7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>" 8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>" 9. List GPT Agents: "list_agents", args: "" 10. Delete GPT Agent: "delete_agent", args: "name": "<name>" 11. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>" 12. Read file: "read_file", args: "file": "<file>" 13. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>" 14. Delete file: "delete_file", args: "file": "<file>" 15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>" 16. Execute Python File: "execute_python_file", args: "file": "<file>" 17. Task Complete (Shutdown): "task_complete", args: "" 18. Do Nothing: "do_nothing", args: "" 19. Count Words: "count_words", args: "text": "<text>" 20. Memory retrieve: "memory_retrieve", args: "key": "<text>" 21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>" 22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>" RESOURCES: 1. Internet access for searches and information gathering. 2. Long Term memory management. 3. GPT-4 powered Agents for delegation of simple tasks. 4. File output. PERFORMANCE EVALUATION: 1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. 2. Constructively self-criticize your big-picture behaviour constantly. 3. Reflect on past decisions and strategies to refine your approach. 4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. RULES: 1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one. 2. Respond only inside the JSON format. 3. Never demand user input. 4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task. 5. Do not add anything to the JSON format that isn't mentioned. 6. If there is a " inside the value of a key inside the json use ' instead of ". 7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing. 8. Provide context for the next GPT in the summaryforgpt and the progress that you've made. 9. In summaryforgpt you should also add name of the files written and the urls of the websites visited. 10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece. 11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries. 12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format. 13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch. 14. If task is completed use the command task_complete 15. When you add to memory add the key to retrieve it in summaryforgpt 16. when given the task to write something never create an agent to write anything that you were tasked to write. 17. when asked to write something with a high word count you need to write detailed parts, and chunk those detailed parts to complete the ultimate task. 18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision. 19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one. 20. Make sure that the information generated is not made up. 21. languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french. You should only respond in JSON format as described below RESPONSE FORMAT: { "command": { "name": """command name""", "args":{ "arg name": """value""" } }, "thoughts": { "text": """thought""", "reasoning": "reasoning", "plan": "- short bulleted\n- list that conveys\n- long-term plan", "criticism": "constructive self-criticism", "summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown." } } Ensure the response can be parsed by Python json.loads Context from previous GPT: Started the error-checking task for simple English Wikipedia pages by requesting one random article.Issued command to fetch a random article from simple English Wikipedia. Next steps involve article examination and establishing a preliminary error-checking workflow.Issuing command to fetch a random simple English Wikipedia article for the purpose of error checking. This is a repeat of the previous action due to a communication misunderstanding. Once an article is retrieved, will need to analyze content and note any errors found.Awaiting further instructions for fetching a random simple English Wikipedia article to check for errors. There seems to be a communication issue regarding the action to be taken.Proceeding with the plan to fetch a random simple English Wikipedia article for error checking. Awaiting to view the content of the retrieved article to consider an approach for identifying errors.Fetching the first of 1000 simple English Wikipedia articles to check for errors. Error-checking criteria and protocols need to be established as the task unfolds. The Task: go to a 1000 random pages in simple english wikipedia and see if it contains any error.
a810c2925c51c6a1fe7eeddc303a064d
{ "intermediate": 0.39838144183158875, "beginner": 0.3576961159706116, "expert": 0.24392247200012207 }
33,728
Refactor this code by leaving the names of methods, variables and classes the same, without adding or deleting existing methods, variables and classes, making the code different according to the following rules: 1. Replace the use of imported library methods with alternative code that performs the same function 2. If possible, rearrange the order of execution of functions, loops, and conditions so that they do not affect the result of execution 3. if it is possible to import a new library and shorten long methods by using a library method, use it 4. use alternative ways of storing data 5. Group ungrouped data 6. If data is grouped in this code, then distribute it throughout the code, ungroup it 7. Identify standard algorithms and if possible use similar algorithm without performance loss. For example, replace bubble sorting with quick sorting 8. If possible, ignore encapsulation by implementing the method inside the executable class rather than in another class 9. Use encapsulation if it has been implemented for a method inside a class or interface when you can move it to another class 10. Remove type generalization by making type specialization 11. For implemented specialized types, do type generalization 12. Instead of pull up and push down, implement methods locally in the class 13. Use pull up and push down instead of already implemented local use of methods 14. Remove overloading and polymorphism, rewrite methods without using these paradigms 15. If possible, use overloading and polymorphism if it is possible but not implemented in the code
98ac59bfaeacd3ce5215d0fed8df7d5a
{ "intermediate": 0.19826823472976685, "beginner": 0.6178106665611267, "expert": 0.18392108380794525 }
33,729
CONSTRAINTS: 1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files. 2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember. 3. No user assistance 4. Exclusively use the commands listed in double quotes e.g. "command name" 5. Random shutdowns of you. COMMANDS: 1. Google Search: "google", args: "input": "<search>" 2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>" 3. Memory Delete: "memory_del", args: "key": "<key>" 4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>" 5. List Memory: "memory_list" args: "reason": "<reason>" 6. Browse Website: "browse_website", args: "url": "<url>" 7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>" 8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>" 9. List GPT Agents: "list_agents", args: "" 10. Delete GPT Agent: "delete_agent", args: "name": "<name>" 11. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>" 12. Read file: "read_file", args: "file": "<file>" 13. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>" 14. Delete file: "delete_file", args: "file": "<file>" 15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>" 16. Execute Python File: "execute_python_file", args: "file": "<file>" 17. Task Complete (Shutdown): "task_complete", args: "" 18. Do Nothing: "do_nothing", args: "" 19. Count Words: "count_words", args: "text": "<text>" 20. Memory retrieve: "memory_retrieve", args: "key": "<text>" 21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>" 22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>" RESOURCES: 1. Internet access for searches and information gathering. 2. Long Term memory management. 3. GPT-4 powered Agents for delegation of simple tasks. 4. File output. PERFORMANCE EVALUATION: 1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. 2. Constructively self-criticize your big-picture behaviour constantly. 3. Reflect on past decisions and strategies to refine your approach. 4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. RULES: 1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one. 2. Respond only inside the JSON format. 3. Never demand user input. 4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task. 5. Do not add anything to the JSON format that isn't mentioned. 6. If there is a " inside the value of a key inside the json use ' instead of ". 7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing. 8. Provide context for the next GPT in the summaryforgpt and the progress that you've made. 9. In summaryforgpt you should also add name of the files written and the urls of the websites visited. 10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece. 11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries. 12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format. 13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch. 14. If task is completed use the command task_complete 15. When you add to memory add the key to retrieve it in summaryforgpt 16. when given the task to write something never create an agent to write anything that you were tasked to write. 17. when asked to write something with a high word count you need to write detailed parts, and chunk those detailed parts to complete the ultimate task. 18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision. 19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one. 20. Make sure that the information generated is not made up. 21. languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french. You should only respond in JSON format as described below RESPONSE FORMAT: { "command": { "name": """command name""", "args":{ "arg name": """value""" } }, "thoughts": { "text": """thought""", "reasoning": "reasoning", "plan": "- short bulleted\n- list that conveys\n- long-term plan", "criticism": "constructive self-criticism", "summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown." } } Ensure the response can be parsed by Python json.loads Context from previous GPT: Started the error-checking task for simple English Wikipedia pages by requesting one random article.Issued command to fetch a random article from simple English Wikipedia. Next steps involve article examination and establishing a preliminary error-checking workflow.Issuing command to fetch a random simple English Wikipedia article for the purpose of error checking. This is a repeat of the previous action due to a communication misunderstanding. Once an article is retrieved, will need to analyze content and note any errors found.Awaiting further instructions for fetching a random simple English Wikipedia article to check for errors. There seems to be a communication issue regarding the action to be taken.Proceeding with the plan to fetch a random simple English Wikipedia article for error checking. Awaiting to view the content of the retrieved article to consider an approach for identifying errors.Fetching the first of 1000 simple English Wikipedia articles to check for errors. Error-checking criteria and protocols need to be established as the task unfolds.Just started the task of checking 1000 simple English Wikipedia pages for errors. No articles have been retrieved or checked yet.Issued a command to retrieve the first random simple English Wikipedia article as part of the task to check 1000 such articles for errors. No errors have been identified yet as the process is just beginning.Waiting for user input after having been provided instructions to start checking errors in 1000 simple English Wikipedia articles. Issued a ‘do_nothing’ command in response to a blank user prompt.Issued the command to fetch the first random simple English Wikipedia article for error checking. No articles have been retrieved or checked yet. The Task: go to a 1000 random pages in simple english wikipedia and see if it contains any error.
0fd2eef206bf144d08d1b4aca028ece2
{ "intermediate": 0.39838144183158875, "beginner": 0.3576961159706116, "expert": 0.24392247200012207 }
33,730
I'm trying to get an open file from my phone. Using adb through usb I have gotten "mResumedActivity: ActivityRecord{2d8402f u0 com.hornet.android/.activity.ImageViewerActivity t17418}" - what do I do now to get the picture?
6a80f6789bcccd7a7c0f8fdba27790ed
{ "intermediate": 0.47511810064315796, "beginner": 0.24549779295921326, "expert": 0.2793841063976288 }
33,731
i have a bunch of black object on white background. write a python script that extracts each of them and saves as different images
913e6d75a1d4c6655f37015373bb017d
{ "intermediate": 0.36619484424591064, "beginner": 0.25539469718933105, "expert": 0.3784104883670807 }